This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define int long long
vector<int> adj[200001];
bool visited[200001];
int subsize[200001];
int ans,full;
int dfs(int x,int p,int depth){
ans+=depth;
subsize[x]=1;
visited[x]=true;
for(int&i:adj[x])if(i!=p)subsize[x]+=dfs(i,x,depth+1);
return subsize[x];
}
int reroot(int x,int p,int currans){
int tot = currans;
for(int&i:adj[x])if(i!=p)tot+=reroot(i,x,currans+full-2*subsize[i]);
return tot;
}
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n,m;
cin >> n >> m;
for(int i=1;i<=m;i++){
int a,b;cin>>a>>b;
adj[a].emplace_back(b);
adj[b].emplace_back(a);
}
int myans = 0;
for(int i=1;i<=n;i++)if(!visited[i]){
ans = 0;
full = dfs(i,0,-1);
myans+=reroot(i,0,ans);
}
cout << myans+n << '\n';
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |