結果
問題 | No.399 動的な領主 |
ユーザー | conf |
提出日時 | 2016-07-15 23:46:30 |
言語 | C++14 (gcc 12.3.0 + boost 1.83.0) |
結果 |
AC
|
実行時間 | 185 ms / 2,000 ms |
コード長 | 1,616 bytes |
コンパイル時間 | 744 ms |
コンパイル使用メモリ | 74,424 KB |
実行使用メモリ | 22,548 KB |
最終ジャッジ日時 | 2023-08-07 15:02:04 |
合計ジャッジ時間 | 3,715 ms |
ジャッジサーバーID (参考情報) |
judge11 / judge14 |
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 3 ms
11,852 KB |
testcase_01 | AC | 3 ms
11,924 KB |
testcase_02 | AC | 3 ms
11,844 KB |
testcase_03 | AC | 3 ms
11,852 KB |
testcase_04 | AC | 4 ms
11,896 KB |
testcase_05 | AC | 17 ms
12,464 KB |
testcase_06 | AC | 185 ms
17,280 KB |
testcase_07 | AC | 183 ms
17,064 KB |
testcase_08 | AC | 177 ms
17,000 KB |
testcase_09 | AC | 177 ms
17,000 KB |
testcase_10 | AC | 5 ms
12,148 KB |
testcase_11 | AC | 15 ms
12,408 KB |
testcase_12 | AC | 145 ms
17,152 KB |
testcase_13 | AC | 145 ms
17,136 KB |
testcase_14 | AC | 121 ms
22,548 KB |
testcase_15 | AC | 134 ms
22,464 KB |
testcase_16 | AC | 144 ms
19,336 KB |
testcase_17 | AC | 179 ms
17,124 KB |
testcase_18 | AC | 182 ms
17,072 KB |
ソースコード
#include <iostream> #include <vector> #include <algorithm> using namespace std; #define MAX_V 100000 #define MAX_LOG_V 17 vector<int> G[MAX_V]; int root=0; int parent[MAX_LOG_V][MAX_V]; int depth[MAX_V]; void dfs(int v, int p, int d){ parent[0][v]=p; depth[v]=d; for(auto &e:G[v]){ if(e!=p) dfs(e,v,d+1); } } void init(int V){ dfs(root,-1,0); for(int k=0;k+1<MAX_LOG_V;k++){ for(int v=0;v<V;v++){ if(parent[k][v]<0) parent[k+1][v]=-1; else parent[k+1][v]=parent[k][parent[k][v]]; } } } int lca(int u, int v){ if(depth[u]>depth[v])swap(u,v); for(int k=0;k<MAX_LOG_V;k++){ if((depth[v]-depth[u])>>k&1) v=parent[k][v]; } if(u==v) return u; for(int k=MAX_LOG_V-1;k>=0;k--){ if(parent[k][u]!=parent[k][v]){ u=parent[k][u]; v=parent[k][v]; } } return parent[0][u]; } int go[MAX_V]; int turn[MAX_V]; int path[MAX_V]; int dfs2(int v, int p){ int n=go[v]; for(auto &e:G[v]){ if(e!=p) n+=dfs2(e,v); } path[v]=n-turn[v]; return n-2*turn[v]; } int main(){ int N; cin>>N; for(int i=1;i<N;i++){ int u,v; cin>>u>>v; G[u-1].push_back(v-1); G[v-1].push_back(u-1); } init(N); int Q; cin>>Q; for(int i=0;i<Q;i++){ int A,B; cin>>A>>B; A--;B--; turn[lca(A,B)]++; go[A]++;go[B]++; } dfs2(0,-1); long long int ans=0; for(int i=0;i<N;i++){ ans+=(long long int)path[i]*(path[i]+1)/2; } cout<<ans<<endl; return 0; }