PAT (Advanced Level) 1032. Sharing (25)
Posted Fighting Heart
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT (Advanced Level) 1032. Sharing (25)相关的知识,希望对你有一定的参考价值。
简单题,不过数据中好像存在有环的链表......
#include<iostream> #include<cstring> #include<cmath> #include<algorithm> #include<cstdio> #include<map> #include<queue> #include<vector> using namespace std; const int maxn=100000+10; struct Node { int id; char c; int nx; } node[maxn]; int add1,add2,n; int s1[maxn],s2[maxn]; int len1=0,len2=0; int m[maxn]; int main() { memset(m,-1,sizeof m); scanf("%d%d%d",&add1,&add2,&n); for(int i=1; i<=n; i++) { scanf("%d",&node[i].id); m[node[i].id]=i; cin>>node[i].c; scanf("%d",&node[i].nx); } for(int i=1; i<=n; i++) { if(node[i].nx==-1) continue; node[i].nx=m[node[i].nx]; } memset(s1,-1,sizeof s1); memset(s2,-1,sizeof s2); int now=m[add1]; while(1) { if(now==-1) break; s1[len1++]=now; now=node[now].nx; } now=m[add2]; bool flag[maxn]; memset(flag,0,sizeof flag); int fail=0; while(1) { if(now==-1) break; if(flag[now]==1) { fail=1; break; } flag[now]=1; s2[len2++]=now; now=node[now].nx; } if(fail==1) { printf("-1\n"); } else { len1--; len2--; while(len1>=0&&len2>=0) { if(s1[len1]==s2[len2]) { len1--; len2--; } else break; } len1++; len2++; if(s1[len1]==-1) printf("-1\n"); else printf("%05d\n",node[s1[len1]].id); } return 0; }
以上是关于PAT (Advanced Level) 1032. Sharing (25)的主要内容,如果未能解决你的问题,请参考以下文章
PAT (Advanced Level) 1025. PAT Ranking (25)