静态链表。。STL要超时。。
View Code
1 #include <iostream> 2 #include <cstdio> 3 #include <vector> 4 #include <cstring> 5 using namespace std; 6 7 vector<int> G[50001]; 8 int dp[50001],visit[50001],head[50001]; 9 int n,k; 10 struct Edge 11 { 12 int v; 13 int next; 14 }edge[50001 * 2]; 15 int max(int a,int b) 16 { 17 return a > b ? a : b; 18 } 19 20 int min(int a,int b) 21 { 22 return a < b ? a : b; 23 } 24 25 void addedge(int a,int b) 26 { 27 edge[k].v = b; 28 edge[k].next = head[a]; 29 head[a] = k; 30 k++; 31 } 32 int dfs(int u) 33 { 34 visit[u] = true; 35 int sum = 1,temp; 36 for(int i = head[u];i;i = edge[i].next) 37 { 38 int v = edge[i].v; 39 if(visit[v]) 40 continue; 41 temp = dfs(v); 42 sum += temp; 43 dp[u] = max(dp[u],temp); 44 } 45 dp[u] = max(dp[u],n - sum); 46 return sum; 47 } 48 49 int main() 50 { 51 scanf("%d",&n); 52 int a,b; 53 memset(visit,false,sizeof(visit)); 54 memset(dp,0,sizeof(dp)); 55 memset(head,0,sizeof(head)); 56 k = 1; 57 for(int i = 1;i <= n - 1;i++) 58 { 59 scanf("%d%d",&a,&b); 60 addedge(a,b); 61 addedge(b,a); 62 } 63 dfs(1); 64 int ans = 0xffffff; 65 for(int i = 1;i <= n;i++) 66 { 67 ans = min(ans,dp[i]); 68 } 69 bool flag = true; 70 for(int i = 1;i <= n;i++) 71 { 72 if(dp[i] == ans) 73 { 74 if(flag) 75 { 76 printf("%d",i); 77 flag = false; 78 } 79 else 80 { 81 printf(" %d",i); 82 } 83 } 84 } 85 printf("\n"); 86 return 0; 87 }