题目链接
题目分析
注:结点的输入是乱序的
解题思路
1、由于结点并非按链表输入,故需先用静态链表整体保存;
2、遍历一遍链表,筛选,
思路一:分别装入两个vector<node>
模拟的队列
思路二:node
中增加序号属性,对结点原址排序
3、分别输出即可(注意vector<node>
有可能为空)
AC程序(C++)思路一:
/**************************
*@Author: 3stone
*@ACM: PAT-A1097.Deduplication
*@Time: 18/3/ 16
*@IDE: VSCode 2018
***************************/
#include<cstdio>
#include <iostream>
#include<cstring>
#include <vector>
using namespace std;
struct Node {//结点类型
int st, value, ed;
};
vector<Node> L1, L2;
bool flag[10100];
Node node[100010];
int main() {
int head, n;
int st, ed, val;
while(scanf("%d %d", &head, &n) != EOF){
memset(flag, false, sizeof(flag));
L1.clear();
L2.clear();
//输入,筛选
for (int i = 0; i < n; i++) {
scanf("%d%d%d", &st, &val, &ed);
node[st].st = st;
node[st].ed = ed;
node[st].value = val;
}
while(head != -1){
val = abs(node[head].value);
if(flag[val])
L2.push_back(node[head]);
else
L1.push_back(node[head]);
flag[val] = true;
head = node[head].ed;
}
int sz = L1.size();
for(int i = 0; i < sz - 1; i++){
printf("%05d %d %05d\n", L1[i].st, L1[i].value, L1[i + 1].st);
}
if(sz > 0)
printf("%05d %d -1\n", L1[sz - 1].st, L1[sz -1].value);
sz = L2.size();
for(int i = 0; i < sz - 1; i++){
printf("%05d %d %05d\n", L2[i].st, L2[i].value, L2[i + 1].st);
}
if(sz > 0)
printf("%05d %d -1\n", L2[sz - 1].st, L2[sz -1].value);
}//while
return 0;
}
AC程序(C++)思路二:
#include<cstdio>
#include <iostream>
#include<cstring>
#include <algorithm>
using namespace std;
#define maxn 100010
struct Node {//结点类型
int st, value, ed;
int order;
};
bool flag[10100];
Node node[maxn];
bool cmp(Node a, Node b){
return a.order < b.order;
}
int main() {
int head, n, p;
int st, ed, val;
int count, countValued, countRemoved;
while(scanf("%d %d", &head, &n) != EOF){
memset(flag, false, sizeof(flag));
for(int i = 0; i < maxn; i++) {
node[i].order = 2 * maxn;
//无效结点的序号全初始化为maxn*2,保留结点从0开始编号,删除结点从maxn开始编号
}
//输入,筛选
for (int i = 0; i < n; i++) {
scanf("%d%d%d", &st, &val, &ed);
node[st].st = st;
node[st].ed = ed;
node[st].value = val;
}
countValued = 0; countRemoved = 0; p = head;
while(p != -1){
val = abs(node[p].value);
if(flag[val]) //删除结点从maxn开始编号
node[p].order = maxn + countRemoved++;
else
node[p].order = countValued++;
flag[val] = true;
p = node[p].ed;
}
sort(node, node + maxn, cmp);
count = countValued + countRemoved;
for(int i = 0; i < count; i++){
if(i != count - 1 && i != countValued - 1)
printf("%05d %d %05d\n", node[i].st, node[i].value, node[i + 1].st);
else
printf("%05d %d -1\n", node[i].st, node[i].value);
}
}//while
return 0;
}