标签:stack printf nbsp contains size style int dem created
1 - 2 - 5 | | 3 4 |
input | output |
---|---|
5 1 1 2 2 |
1 2 |
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #include <cmath> #include <string> #include <stack> #include <queue> #include <vector> #define inf 0x3f3f3f3f #define met(a,b) memset(a,b,sizeof a) typedef long long ll; using namespace std; const int N = 10005; const int M = 24005; int vis[N],dis[N],pre[N],head[N]; int n,m,tot=0,son,maxn; struct EDG{int to,next;}edg[N*N]; void add(int u,int v){ edg[tot].to=v;edg[tot].next=head[u];head[u]=tot++; } void bfs(int s) { met(vis,0);met(dis,inf);met(pre,0); dis[s] = 0; vis[s] = 1;maxn=0; queue<int>q;q.push(s); while(!q.empty()){ int u=q.front();q.pop();vis[u]=0; for(int i=head[u];i!=-1;i=edg[i].next){ int v=edg[i].to; if(dis[v]>dis[u]+1){ dis[v]=dis[u]+1;maxn=max(maxn,dis[v]);pre[v]=u; if(!vis[v]){ q.push(v);vis[v]=1; } } } son=u; } } int main() { met(head,-1); int a[N],cnt=0; scanf("%d",&n); for(int i=2;i<=n;i++){ scanf("%d",&m);add(i,m);add(m,i); } bfs(1);int s=son; bfs(son);int t=son;//printf("!!%d %d\n",s,t); if(maxn&1){ int x=maxn/2; while(t){ if(dis[t]==x||dis[t]==x+1)a[cnt++]=t; t=pre[t]; } } else { int x=maxn/2; while(t){ if(dis[t]==x)a[cnt++]=t; t=pre[t]; } } sort(a,a+cnt); for(int i=0;i<cnt;i++)printf("%d ",a[i]); printf("\n"); return 0; }
标签:stack printf nbsp contains size style int dem created
原文地址:http://www.cnblogs.com/jianrenfang/p/6010240.html