To store English words, one method is to use linked lists and store a word letter by letter. To save some space, we may let the words share the same sublist if they share the same suffix. For example, Figure 1 You are supposed to find the starting position of the common suffix (e.g. the position of Input Specification:Each input file contains one test case. For each case, the first line contains two addresses of nodes and a positive N (≤105), where the two addresses are the addresses of the first nodes of the two words, and N is the total number of nodes. The address of a node is a 5-digit positive integer, and NULL is represented by −1. Then N lines follow, each describes a node in the format: where Output Specification:For each case, simply output the 5-digit starting position of the common suffix. If the two words have no common suffix, output
|
- 11111 22222 9
- 67890 i 00002
- 00010 a 12345
- 00003 g -1
- 12345 D 67890
- 00002 n 00003
- 22222 B 23456
- 11111 L 00001
- 23456 e 67890
- 00001 o 00010
67890
- 00001 00002 4
- 00001 a 10001
- 10001 s -1
- 00002 a 10002
- 10002 t -1
-1
题目大意
寻找俩个字符串中,第一个共用相同元素的地址,如果不存在输出-1
思路
将第一个字符串的所有地址全部标记true,然后从第二个字符串的头地址开始遍历,只要出现重复的就输出该地址并return
- #include
- using namespace std;
- int main()
- {
- char ch;
- int address[100001],st1,st2,M,num;
- cin >> st1 >> st2 >> M;
- while (M--){
- cin >> num;
- cin >> ch >> address[num];
- }
- bool apr[100001] = {false};
- while (st1!=-1){
- apr[st1] = true;
- st1 = address[st1];
- }
- while (st2!=-1){
- if(apr[st2]){
- printf("%05d",st2);
- return 0;
- }
- st2 = address[st2];
- }
- cout << -1 << endl;
- return 0;
- }