結果

問題 No.1769 Don't Stop the Game
ユーザー polylogK
提出日時 2021-11-06 13:45:53
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 310 ms / 3,000 ms
コード長 1,235 bytes
コンパイル時間 748 ms
コンパイル使用メモリ 72,960 KB
最終ジャッジ日時 2025-01-25 14:08:24
ジャッジサーバーID
(参考情報)
judge9 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 28
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.cpp: In function ‘int main()’:
main.cpp:7:21: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
    7 |         int n; scanf("%d", &n);
      |                ~~~~~^~~~~~~~~~
main.cpp:11:22: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   11 |                 scanf("%d%d%d", &a[i], &b[i], &c[i]); a[i]--; b[i]--;
      |                 ~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

ソースコード

diff #

#include <stdio.h>
#include <algorithm>
#include <vector>
#include <unordered_map>

int main() {
	int n; scanf("%d", &n);
	std::vector<std::vector<int>> g(n);
	std::vector<int> a(n - 1), b(n - 1), c(n - 1);
	for(int i = 0; i < n - 1; i++) {
		scanf("%d%d%d", &a[i], &b[i], &c[i]); a[i]--; b[i]--;

		g[a[i]].push_back(i);
		g[b[i]].push_back(i);
	}

	using i64 = long long;

	i64 ans = (i64)n * (n - 1);
	std::vector<int> x(n), root(n), size(n), count(n);
	std::unordered_map<int, int> count_root; {
		std::unordered_map<int, int> map;
		auto dfs = [&](auto&& dfs, int v, int par, int xor_val) -> void {
			auto [it, _] = map.try_emplace(xor_val, -1);
			int tmp = it->second;

			if(tmp == -1) count_root[xor_val]++;
			else count[tmp]++;

			x[v] = xor_val;
			root[v] = tmp;
			size[v] = 1;
			for(int id: g[v]) {
				int to = a[id] ^ b[id] ^ v;
				if(to == par) continue;

				map[xor_val] = to;
				dfs(dfs, to, v, xor_val ^ c[id]);

				size[v] += size[to];
				ans -= (i64)count[to] * (n - size[to]);
			}
			map[xor_val] = tmp;
		}; dfs(dfs, 0, -1, 0);
	}
	for(int v = 0; v < n; v++) {
		if(root[v] == -1) ans -= (i64)(count_root[x[v]] - 1) * size[v];
		else ans -= (i64)count[root[v]] * size[v];
	}
	printf("%lld\n", ans);
}
0