【PAT甲级】1074 Reversing Linked List (25 分)

题意:

输入链表头结点的地址(五位的字符串)和两个正整数N和K(N<=100000,K<=N),接着输入N行数据,每行包括结点的地址,结点的数据和下一个结点的地址。输出每K个结点局部反转的链表。

trick:

测试点6包含一些不在起点这条链表上的结点。

代码:

#define HAVE_STRUCT_TIMESPEC
#include<bits/stdc++.h>
using namespace std;
map<string,pair<int,string> >mp;
pair<string,int>ans[100007];
pair<string,int>ans2[100007];
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
string s;
int n,k;
cin>>s>>n>>k;
for(int i=1;i<=n;++i){
string s1,t1;
int x;
cin>>s1>>x>>t1;
mp[s1]={x,t1};
}
int cnt=0;
while(1){
string now=s;
ans[++cnt]={now,mp[now].first};
s=mp[now].second;
if(s=="-1")
break;
}
int pos=0;
for(int i=1;i*k<=cnt;++i){
pos=i*k;
for(int j=i*k-k+1;j<=i*k;++j){
ans2[j]=ans[(2*i-1)*k+1-j];
}
}
for(int i=pos+1;i<=cnt;++i){
ans2[i]=ans[i];
}
for(int i=1;i<=cnt;++i){
cout<<ans2[i].first<<" "<<ans2[i].second<<" ";
if(i<cnt)
cout<<ans2[i+1].first;
else
cout<<-1;
cout<<"\n";
}
return 0;
}

猜你喜欢

转载自www.cnblogs.com/ldudxy/p/11809806.html