Maximum Control (medium) Codeforces - 958B2

https://codeforces.com/contest/958/problem/B2

题解:https://www.cnblogs.com/Cool-Angel/p/8862649.html

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<vector>
 5 #include<queue>
 6 using namespace std;
 7 #define fi first
 8 #define se second
 9 #define mp make_pair
10 #define pb push_back
11 typedef long long ll;
12 typedef unsigned long long ull;
13 typedef pair<int,int> pii;
14 struct E
15 {
16     int to,nxt;
17 }e[200100];
18 int f1[100100],ne;
19 int rt;
20 bool inq[101000];
21 int dep[101000],d[101000],mlen[100100],sz[101000],mson[101000];
22 void dfs1(int u,int fa)
23 {
24     dep[u]=dep[fa]+1;
25     for(int k=f1[u];k;k=e[k].nxt)
26         if(e[k].to!=fa)
27         {
28             dfs1(e[k].to,u);
29             mlen[u]=max(mlen[u],mlen[e[k].to]);
30             sz[u]+=sz[e[k].to];
31         }
32     mlen[u]++;
33     sz[u]++;
34 }
35 void dfs2(int u,int fa)
36 {
37     for(int k=f1[u];k;k=e[k].nxt)
38         if(e[k].to!=fa)
39             if(!mson[u]||mlen[e[k].to]>mlen[mson[u]])
40                 mson[u]=e[k].to;
41     d[u]=1;
42     if(u==mson[fa])    d[u]+=d[fa];
43     for(int k=f1[u];k;k=e[k].nxt)
44         if(e[k].to!=fa)
45             dfs2(e[k].to,u);
46 }
47 queue<int> q;
48 int n,nn;
49 int tt[100100];
50 int main()
51 {
52     int i,x,y,u;
53     scanf("%d",&n);nn=n;
54     for(i=1;i<n;i++)
55     {
56         scanf("%d%d",&x,&y);
57         e[++ne].to=y;e[ne].nxt=f1[x];f1[x]=ne;
58         e[++ne].to=x;e[ne].nxt=f1[y];f1[y]=ne;
59     }
60     q.push(1);
61     while(!q.empty())
62     {
63         u=q.front();q.pop();
64         rt=u;
65         for(int k=f1[u];k;k=e[k].nxt)
66             if(!inq[e[k].to])
67             {
68                 inq[e[k].to]=1;
69                 q.push(e[k].to);
70             }
71     }
72     dfs1(rt,0);
73     dfs2(rt,0);
74     printf("%d ",1);nn--;
75     /*
76     for(i=1;i<=n;i++)
77         printf("t%d %d %d\n",i,sz[i],d[i]);
78     */
79     for(i=1;i<=n;i++)
80         if(sz[i]==1)
81             tt[++tt[0]]=d[i];
82     sort(tt+1,tt+tt[0]+1);
83     int sum=0;
84     for(i=tt[0];i>=1&&nn;i--)
85     {
86         sum+=tt[i];
87         printf("%d ",sum);
88         nn--;
89     }
90     //puts("test");
91     for(;nn;nn--)    printf("%d ",sum);
92     return 0;
93 }
View Code

猜你喜欢

转载自www.cnblogs.com/hehe54321/p/9706401.html
今日推荐