题目链接:https://www.patest.cn/contests/gplt/L2-002
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <algorithm>
#include <cstring>
using namespace std;
const int inf = 1e6 + 10;
struct node{
char af[10];
char bf[10];
int val;
}th[inf];
int b[inf];
int s[inf];
int k1, k2;
bool fou[inf];
int main()
{
memset(fou, false, sizeof(fou));
char head[10];
int num;
scanf("%s %d", &head, &num);
getchar();
int k = 0;
for(int i = 0; i < num; i ++){
char u[10], v[10];
int val;
scanf("%s %d %s", &u, &val, &v);
strcpy(th[atoi(u)].af, u);
strcpy(th[atoi(u)].bf, v);
th[atoi(u)].val = val;
//cout << th[atoi(u)].af << " " << th[atoi(v)].bf << endl;
}
while(atoi(head) != -1){
if(!fou[abs(th[atoi(head)].val)]){
fou[abs(th[atoi(head)].val)] = true;
b[k1 ++] = atoi(head);
}else {
s[k2 ++] = atoi(head);
}
strcpy(head, th[atoi(head)].bf);
}
for(int i = 0; i < k1; i ++){
cout << th[b[i]].af << ' ' << th[b[i]].val << ' ';
if(i != k1 - 1) cout << th[b[i + 1]].af;
else cout << -1;
cout << endl;
//cout << b[i] << " ";
}
for(int i = 0; i < k2; i ++){
cout << th[s[i]].af << ' ' << th[s[i]].val << ' ';
if(i != k2 - 1) cout << th[s[i + 1]].af;
else cout << -1;
cout << endl;
//cout << s[i] << ' ';
}
return 0;
}
用for循环解复杂度太高了,所以用结构体来存每个节点,然后每个节点的存在结构体数组里的位置用本节点的地址来充当,因为不会重复,可以用atoi函数来将字符串化为整数,然后注意下输出就好了