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;
const int MAXN = 5010;
vector<int> adj[MAXN];
vector<int> graph[MAXN],st;
int N,ans;
int bfs(int start){
queue<int> q; q.push(start);
vector<int> dist(N+1,-1); dist[start] = 0;
int maxd = -1;
while(!q.empty()){
int u = q.front(); q.pop();
for(auto v : adj[u]){
if(dist[v] == -1){
dist[v] = dist[u]+1;
q.push(v);
maxd = max(maxd,dist[v]);
}
}
}
return maxd;
}
void dfs(int u, int p){
for(auto v : graph[u]){
if(v != p){
dfs(v,u);
st[u] += st[v];
}
}
++st[u];
ans += st[u];
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> N;
for(int i = 1;i<=N;++i){
int k; cin >> k;
for(int j = 0;j<k;++j){
int v; cin >> v;
adj[v].push_back(i);
}
}
int res = -1, root = -1;
for(int i = 1;i<=N;++i){
int ret = bfs(i);
if(ret == -1) continue;
if(ret < res || res == -1){
res = ret;
root = i;
}
}
queue<int> q; q.push(root);
//cout << root << "\n";
vector<int> dist(N+1,-1),par(N+1,-1); dist[root] = 0;
while(!q.empty()){
int u = q.front(); q.pop();
for(auto v : adj[u]){
if(dist[v] == -1){
dist[v] = dist[u]+1;
par[v] = u;
q.push(v);
}
}
}
st = vector<int>(N+1,0);
for(int i = 1;i<=N;++i){
if(par[i] == -1) continue;
graph[par[i]].push_back(i);
graph[i].push_back(par[i]);
}
ans = 0;
dfs(root,0);
cout << ans << "\n";
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |