题目:http://pat.zju.edu.cn/contests/pat-a-practise/1032
题解:
给两个字符串的链表存储,如果两个字符有相同的后缀,其后缀会存放在相同内存块,问这两个字符串是否有相同的后缀,如果有相同的后缀求出最开始相同的字母的内存地址。
先遍历一个字符串,标记出现过哪些地址,再遍历另一个字符串,出现相同地址的即所求解。
注:竟然卡STL
C中格式字符串的一般形式为: %[标志][输出最小宽度][.精度][长度]类型, 其中方括号[]中的项为可选项。
代码:
#include<cstdio> #include<cstring> #include<cmath> #include<string> #include<vector> #include<map> #include<set> #include<algorithm> using namespace std; int mapx[100005]; bool flag[100005]; int main() { int sta,stb,a,c,outx; char b[5]; int n; memset(flag,false,sizeof(flag)); scanf("%d%d%d",&sta,&stb,&n); for(int i=0;i<n;++i) { scanf("%d%s%d",&a,b,&c); mapx[a]=c; } flag[sta]=true; outx=sta; for(;outx!=-1;) { outx=mapx[outx]; flag[outx]=true; } outx=stb; for(;outx!=-1;) { if(flag[outx]) { printf("%.5d\n",outx); return 0; } outx=mapx[outx]; } printf("-1\n"); return 0; }