AcWing 4273. 链表合并
原题链接
简单
作者:
YAX_AC
,
2024-12-10 14:49:32
,
所有人可见
,
阅读 3
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 100010;
int e[N],ne[N];
int n,st[N];
int h1,h2;
int main()
{
cin>>h1>>h2>>n;
for(int i = 1; i<=n; i++)
{
int address,data,next;
cin>>address>>data>>next;
e[address] = data,ne[address] = next;
}
vector<int> a,b;
for(int i = h1; i !=-1; i = ne[i]) a.push_back(i);
for(int i = h2; i !=-1; i = ne[i]) b.push_back(i);
if(a.size() < b.size()) swap(a,b);
reverse(b.begin(),b.end());
vector<int> ans;
for(int i = 0,j = 0; i<a.size(); )
{
ans.push_back(a[i++]);
if(i % 2 == 0 && j<b.size())
ans.push_back(b[j++]);
}
for(int i = 0; i<ans.size(); i++)
{
printf("%05d %d ",ans[i],e[ans[i]]);
if(i == ans.size()-1) cout<<-1<<endl;
else printf("%05d\n",ans[i+1]);
}
return 0;
}