1032. Sharing (25)
时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
To store English words, one method is to use linked lists and store aword letter by letter. To save some space, we may let thewords share the same sublist if they share the same suffix. For example, "loading"and"being" are stored as showed in Figure 1.
Figure 1
You are supposed to find the starting position ofthe common suffix (e.g. the position of"i"in Figure 1).
Input Specification:
Each input filecontainsone test case. For eachcase, thefirstlinecontainstwo addresses of nodes anda positive N (<= 105), where thetwo addresses are the addresses ofthefirst nodes ofthetwowords, and N is the total numberof nodes. The address ofa node is a5-digit positive integer, andNULL is represented by -1.
Then N lines follow, each describes a node intheformat:
Address Data Next
where Address is the position ofthe node, Data is the letter contained by this node which is an English letter chosen from {a-z, A-Z}, and Next is the position ofthe next node.
Output Specification:
For eachcase, simply output the5-digit starting position ofthe common suffix. If thetwowords have no common suffix, output "-1" instead.
Sample Input 1:
1111122222967890 i 0000200010a1234500003 g -112345 D 6789000002 n 0000322222 B 2345611111 L 0000123456 e 6789000001 o 00010
Sample Output 1:
67890
Sample Input 2:
0000100002400001a1000110001 s -100002a1000210002 t -1
Sample Output 2:
-1
解题思路
1.长的那个减掉长的个数,然后在比较,找到地址相同了的即可。
代码
#include<iostream>#include<cstdio>usingnamespacestd;
char value[99999];
int next1[99999];
int main(){
int f,s,n;
scanf("%d %d %d",&f,&s,&n);
int where,to;char a;
for (int i= 0; i < n; ++i) {
scanf("%d %c %d",&where,&a,&to);
value[where] = a;
next1[where] = to;
}
int la = 0,lb = 0;
int now = f;
while (now != -1) {
la++;
now = next1[now];
}
now = s;
while (now != -1) {
lb++;
now =next1[now];
}
// cout << la << lb;int nowa = f;
int nowb =s;
if (la>lb) {
int d = la - lb;
while (d--) {
nowa = next1[nowa];
}
}else {
int d = lb - la;
while (d--) {
nowb =next1[nowb];
}
}
while (nowa !=nowb) {
nowa = next1[nowa];
nowb = next1[nowb];
}
if (nowa == -1) {
printf("%d\n",-1);
}else {
printf("%05d\n",nowa);
}
}