题目:
jxtxzzw和好朋友去探险,在山洞里jxtxzzw发现了许多古诗,他很兴奋地呼唤同伴过来,用相机把这些古诗拍下来。每个人都选了一部分进行拍照。
回到学校以后,所有人把相机中的照片导出,保存在电脑。
这时jxtxzzw发现,竟然当时没有让伙伴们按照顺序拍照。
现在这些照片根本就不是有序的,所以这些古代诗歌的碎片完全连不成一个整体。
好在现在有一个线索,在相邻的两张照片中,一定有一句是重复的。分别出现在两张碎片的头和尾。
样例:
input
2 3
This is the 3rd line.
This is the 4th line.
This is the 5th line.
This is the 1st line.
This is the 2nd line.
This is the 3rd line.
output
This is the 1st line.
This is the 2nd line.
This is the 3rd line.
This is the 4th line.
This is the 5th line.
思路:
将每一段的第一句和最后一句建立索引,最后一句和第一句相同的可以找到对应的句子。
代码:
#include <cstring>
#include <iostream>
#include <map>
#include <string>
using namespace std;
string s[1111][111];
map<string, int> parahead, paratail;
int p, l;
int main() {
cin >> p >> l;
cin.ignore();
for (int i = 0; i < p; i++)
for (int j = 0; j < l; j++) {
getline(cin, s[i][j]);
if (!j)
parahead[s[i][j]] = i;
if (j == l - 1)
paratail[s[i][j]] = i;
}
int first = 0;
for (int i = 0; i < p; i++) {
if (!paratail.count(s[i][0])) {
first = i;
break;
}
}
int point = first;
for (int i = 0; i < p; i++) {
if (point == first)
cout << s[point][0] << endl;
for (int j = 1; j < l; j++) {
cout << s[point][j] << endl;
}
point = parahead[s[point][l - 1]];
}
return 0;
}