結果

問題 No.1843 Tree ANDistance
ユーザー yudedako
提出日時 2022-02-28 18:46:05
言語 C++17(clang)
(17.0.6 + boost 1.87.0)
結果
AC  
実行時間 240 ms / 2,000 ms
コード長 1,753 bytes
コンパイル時間 1,560 ms
コンパイル使用メモリ 152,580 KB
実行使用メモリ 12,216 KB
最終ジャッジ日時 2024-07-06 21:56:36
合計ジャッジ時間 7,085 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 38
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <vector>
#include <numeric>
#include <algorithm>
#include <queue>
#include <string>
#include <random>
#include <array>
#include <climits>
#include <map>
#include <cassert>
#include <stack>
#include <iomanip>
#include <cfloat>
#include <bitset>
#include <fstream>
#include <chrono>


int main() {
	constexpr int MOD = 1000000007;
	int n; std::cin >> n;
	std::vector<std::tuple<int, int, int>> edges(n - 1);
	for (auto& [a, b, c] : edges) {
		std::cin >> a >> b >> c; --a; --b;
	}
	std::vector<std::vector<std::pair<int, int>>> graph(n);
	for (const auto [a, b, c] : edges) {
		graph[a].emplace_back(b, c);
		graph[b].emplace_back(a, c);
	}
	std::vector<int> depth(n, -1); depth[0] = 0;
	std::queue<int> queue; queue.push(0);
	while (!queue.empty()) {
		const auto top = queue.front(); queue.pop();
		for (const auto [next, _] : graph[top]) {
			if (depth[next] == -1) {
				depth[next] = depth[top] + 1;
				queue.push(next);
			}
		}
	}
	std::vector<int> from_leaf(n); std::iota(from_leaf.begin(), from_leaf.end(), 0);
	std::sort(from_leaf.rbegin(), from_leaf.rend(), [&depth](const int i, const int j) {return depth[i] < depth[j]; });
	long long int result{ 0 };
	for (auto d = 0; d < 30; ++d) {
		long long int one_path{ 0 };
		std::vector<int> end_path(n, 0);
		for (const auto node : from_leaf) {
			int count{ 0 };
			for (const auto [child, c] : graph[node]) {
				if (depth[child] <= depth[node] || (((c >> d) & 1) == 0)) continue;
				one_path += (count + 1LL) * (end_path[child] + 1LL);
				count += end_path[child] + 1;
			}
			end_path[node] = count;
		}
		result += ((one_path % MOD) << d) % MOD;
	}
	result %= MOD;
	std::cout << result << '\n';
}
0