L2-002. 链表去重
时间限制
300 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
给定一个带整数键值的单链表L,本题要求你编写程序,删除那些键值的绝对值有重复的结点。即对任意键值K,只有键值或其绝对值等于K的第一个结点可以被保留。同时,所有被删除的结点必须被保存在另外一个链表中。例如:另L为21→-15→-15→-7→15,则你必须输出去重后的链表21→-15→-7、以及被删除的链表-15→15。
输入格式:
输入第一行包含链表第一个结点的地址、以及结点个数N(<= 105 的正整数)。结点地址是一个非负的5位整数,NULL指针用-1表示。
随后N行,每行按下列格式给出一个结点的信息:
Address Key Next
其中Address是结点的地址,Key是绝对值不超过104的整数,Next是下一个结点的地址。
输出格式:
首先输出去重后的链表,然后输出被删除结点组成的链表。每个结点占一行,按输入的格式输出。
输入样例:00100 5 99999 -7 87654 23854 -15 00000 87654 15 -1 00000 -15 99999 00100 21 23854输出样例:
00100 21 23854 23854 -15 99999 99999 -7 -1 00000 -15 87654 87654 15 -1
#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=100010;
struct Node{
int add;
int key;
int next;
bool operator < (const Node &o)const{
return add<o.add||key<o.key||next<o.next;
}
};
Node node[maxn],temp,ttt,temp_t;
vector<Node>ans1,ans2;
map<int,int>q;
void fun(int n){
int cnt=0;
int t=n;
while(t){t/=10;cnt++;}
cnt=5-cnt;
if(n==0)cnt=4;
for(int i=0;i<cnt;i++)cout<<'0';
cout<<n;
}
int main(){
int st,n;
scanf("%d%d",&st,&n);
int a,b,c;
for(int i=0;i<n;i++){
scanf("%d%d%d",&a,&b,&c);
node[a].add=a;
node[a].key=b;
node[a].next=c;
}
int i=st,cnt=0,st2;
while(1){
temp=node[i];
i=node[i].next;
if(q[abs(temp.key)]==0){
q[abs(temp.key)]=1;
ans1.push_back(temp);
}
else{
if(cnt==0){cnt++;st2=temp.add;}
ans2.push_back(temp);
}
if(i==-1)break;
}
//cout<<"---------"<<endl;
//cout<<st<<' '<<st2<<" ------"<<endl;
for(int i=0;i<ans1.size();i++){
ttt=ans1[i];
if(i==0){
fun(st);
cout<<' '<<ttt.key<<' ';
if(i==ans1.size()-1)cout<<-1; else fun(ans1[i+1].add);
}
else {fun(ttt.add);cout<<' '<<ttt.key<<' '; if(i==ans1.size()-1)cout<<-1; else fun(ans1[i+1].add);}
cout<<endl;
}
for(int i=0;i<ans2.size();i++){
ttt=ans2[i];
if(i==0){
fun(st2);
cout<<' '<<ttt.key<<' ';
if(i==ans2.size()-1)cout<<-1; else fun(ans2[i+1].add);
}
else {fun(ttt.add);cout<<' '<<ttt.key<<' '; if(i==ans2.size()-1)cout<<-1; else fun(ans2[i+1].add);}
cout<<endl;
}
}
//00100 21 23854 -> 23854 -15 00000 -> 00000 -15 99999 -> 99999 -7 87654 -> 87654 15 -1
//00100 21 23854 -> 23854 -15 00000 -> 00000 -15 99999 -> 99999 -7 87654 -> 87654 15 -1
2310

被折叠的 条评论
为什么被折叠?



