結果
問題 | No.1843 Tree ANDistance |
ユーザー |
![]() |
提出日時 | 2023-03-31 09:40:54 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 951 ms / 2,000 ms |
コード長 | 2,870 bytes |
コンパイル時間 | 3,845 ms |
コンパイル使用メモリ | 264,704 KB |
最終ジャッジ日時 | 2025-02-11 19:29:50 |
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 38 |
ソースコード
#include <bits/stdc++.h> #include <atcoder/all> #pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") using namespace std; using namespace atcoder; #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define repll(i, n) for (long long i = 0; i < (long long)(n); i++) #define rep2(i, n, m) for (int i = n; i < (int)(m); i++) #define repll2(i, n, m) for (long long i = n; i < (long long)(m); i++) #define all(v) v.begin(),v.end() using ll=long long; using ld=long double; using vi=vector<int>; using vvi=vector<vi>; using vvvi=vector<vvi>; using vl=vector<ll>; using vvl=vector<vl>; using vvvl=vector<vvl>; using vld=vector<ld>; using vvld=vector<vld>; int dx[8]={1,0,-1,0,1,1,-1,-1}; int dy[8]={0,1,0,-1,1,-1,1,-1}; const double PI = acos(-1); //const ll MOD=1e9+7; //const ll MOD=998244353; const ll INF=(1LL<<60); const int INF2=(1<<30); using mint=modint1000000007; //using mint=modint998244353; /* UnionFind:素集合系管理の構造体(union by size) isSame(x, y): x と y が同じ集合にいるか。 計算量はならし O(α(n)) unite(x, y): x と y を同じ集合にする。計算量はならし O(α(n)) treeSize(x): x を含む集合の要素数。 */ struct UnionFind { vector<int> size, parents; UnionFind() {} UnionFind(int n) { // make n trees. size.resize(n, 0); parents.resize(n, 0); for (int i = 0; i < n; i++) { makeTree(i); } } void makeTree(int x) { parents[x] = x; // the parent of x is x size[x] = 1; } bool isSame(int x, int y) { return findRoot(x) == findRoot(y); } bool unite(int x, int y) { x = findRoot(x); y = findRoot(y); if (x == y) return false; if (size[x] > size[y]) { parents[y] = x; size[x] += size[y]; } else { parents[x] = y; size[y] += size[x]; } return true; } int findRoot(int x) { if (x != parents[x]) { parents[x] = findRoot(parents[x]); } return parents[x]; } int treeSize(int x) { return size[findRoot(x)]; } }; int main() { ios::sync_with_stdio(false); std::cin.tie(nullptr); ll n;cin>>n; vvvl g(n); rep(i,n-1){ ll a,b,c;cin>>a>>b>>c; g[a-1].push_back({b-1,c}); g[b-1].push_back({a-1,c}); } mint ans=0; repll(i,32){ UnionFind uf(n); rep(j,n){ for(auto e:g[j]){ if(e[1]&(1LL<<i))uf.unite(e[0],j); } } vi checked(n,0); rep(j,n){ int l=uf.findRoot(j); if(!checked[l]){ mint s=uf.treeSize(l); ans+=(1LL<<i)*s*(s-1)/2; checked[l]=1; } } } cout<<ans.val()<<endl; return 0; }