浙江大学PAT_甲级_1032. Sharing (25)

来源:互联网 发布:抽奖软件 破解版 编辑:程序博客网 时间:2024/06/06 02:09

题目地址:点击打开链接

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, "loading" and "being" are stored as showed in Figure 1.


Figure 1

You are supposed to find the starting position of the common suffix (e.g. the position of "i" in Figure 1).

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:

Address Data Next

where Address is the position of the 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 of the next node.

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 "-1" instead.

Sample Input 1:
11111 22222 967890 i 0000200010 a 1234500003 g -112345 D 6789000002 n 0000322222 B 2345611111 L 0000123456 e 6789000001 o 00010
Sample Output 1:
67890
Sample Input 2:
00001 00002 400001 a 1000110001 s -100002 a 1000210002 t -1
Sample Output 2:
-1
题意:输入两个单词的各位字符和地址和下一位字符地址,输出公共的字符部分的第一个字符的地址。

解法:把第一个单词的每一个字符放进集合set ,把第二个单词里的字符在set里进行查找,找到了就输出这个字符的地址。

我的C++代码:

#include <iostream>  #include<set>using namespace std;int main(){int n, pointer1, pointer2 ;//n结点总个数, pointer1第一个单词首结点地址int nodeaddress[100000]; //数组保存各结点地址set<int>word1charset; //单词1字符组成的集合int addr, next; //addr地址,next下一个结点地址char ch; //结点字符信息cin >> pointer1 >> pointer2 >> n;for (int i = 0; i<n; i++){cin >> addr >> ch >> next;nodeaddress[addr] = next;//保存下一个结点的地址}while (pointer1 != -1)//当单词1字符没被遍历完{word1charset.insert(pointer1);//把单词1的字符添加进setpointer1 = nodeaddress[pointer1];//地址向后移}while (pointer2 != -1)//当单词2字符没被遍历完{if (word1charset.count(pointer2) != 0)//找到了相同的元素{printf("%05d", pointer2);//输出相同的字符的地址return 0;//结束退出程序}pointer2 = nodeaddress[pointer2];//地址向后移}printf("-1");return 0;}


1 0