笔者所用的是动态链表的方式存储数据
其中注意一点有一个空节点的问题
建了两个map
分别是从头开始
一个是从尾开始
其中一点 需要注意 由于是“-1”为起始点 故 第二个表的数据地址应在next处
#include<iostream>
#include<map>
#include<string>
#include<algorithm>
#include<cstdio>
using namespace std;
struct SKT
{
long long int num;
string next;
};
int m;
map<string, SKT>mp;
map<string, int>vis;
map<string, SKT>lp;
string head, lhead;
int len = 0;
int main()
{
cin >> head >> m;
len = m;
for (int i = 1; i <= m; i++)
{
string r, l;
int num;
cin >> r >> num >> l;
SKT t;
t.num = num;
t.next = l;
mp[r] = t;
t.next = r;
lp[l] = t;
}
//string fin = lf(head);
string begin = head;
string fin = "-1";
bool p = 1;
//int r = 1, l = m;
//if (len == 1)
//{
// string fin = lf(begin);
// cout << fin << " " << mp[fin].num << " " << "-1";
//}
while (len > 0)
{
if (p)
{
//if(fin=="-1")
cout << lp[fin].next << " " << lp[fin].num << " ";
//cout << fin << " " << lp[fin].num << " ";
vis[lp[fin].next] = 1;
fin = lp[fin].next;
if (vis[begin])
{
cout << "-1";
return 0;
}
else
{
cout << begin;
cout << endl;
}
p = 0;
}
else
{
cout << begin << " " << mp[begin].num << " ";
vis[begin] = 1;
begin = mp[begin].next;
//if (last = fin)
// cout << "-1";
//else
if (vis[lp[fin].next])
{
cout << "-1";
return 0;
}
else
{
cout << lp[fin].next;
cout << endl;
}
p = 1;
}
len--;
}
return 0;
}