思路:随便想想就能想出来啦把。。。 卡了我一个vector。。。
#include<bits/stdc++.h> #define LL long long #define fi first #define se second #define mk make_pair #define pii pair<int,int> #define piii pair<int, pair<int,int> > using namespace std; const int N = 1e6 + 10; const int M = 10 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-6; int n, tot, head[N]; LL cnt[N], sum[N], dp[N]; struct Edge { int to, nx; } edge[N << 1]; void add(int u, int v) { edge[tot].to = v; edge[tot].nx = head[u]; head[u] = tot++; } void dfs1(int u, int p) { cnt[u] = 1; for(int i = head[u]; ~i; i = edge[i].nx) { int v = edge[i].to; if(v == p) continue; dfs1(v, u); cnt[u] += cnt[v]; sum[u] += sum[v] + cnt[v]; } } void dfs2(int u, int p) { if(p) { dp[u] = sum[u] + (dp[p] - (sum[u] + cnt[u]) + n - cnt[u]); } for(int i = head[u]; ~i; i = edge[i].nx) { int v = edge[i].to; if(v == p) continue; dfs2(v, u); } } int main() { memset(head, -1, sizeof(head)); scanf("%d", &n); for(int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); add(u, v); add(v, u); } dfs1(1, 0); dp[1] = sum[1]; dfs2(1, 0); int ans = 1; for(int i = 1; i <= n; i++) { if(dp[ans] < dp[i]) { ans = i; } } printf("%d\n", ans); return 0; } /* */
原文地址:https://www.cnblogs.com/CJLHY/p/9183525.html
时间: 2024-10-13 00:59:03