1121. Damn Single (25)
"Damn Single (单身狗)" is the Chinese nickname for someone who is being single. You are supposed to find those who are alone in a big party, so they can be taken care of.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=50000), the total number of couples. Then N lines of the couples follow, each gives a couple of ID's which are 5-digit numbers (i.e. from 00000 to 99999). After the list of couples, there is a positive integer M (<=10000) followed by M ID's of the party guests. The numbers are separated by spaces. It is guaranteed that nobody is having bigamous marriage (重婚) or dangling with more than one companion.
Output Specification:
First print in a line the total number of lonely guests. Then in the next line, print their ID's in increasing order. The numbers must be separated by exactly 1 space, and there must be no extra space at the end of the line.
Sample Input:3 11111 22222 33333 44444 55555 66666 7 55555 44444 10000 88888 22222 11111 23333Sample Output:
5 10000 23333 44444 55555 88888
首先给每队夫妻从1开始编号,其余人为0表示单身。
接下来将待判断序列per按夫妻编号大小排列,使得夫妻相邻,如果per[i]与per[i+1]的编号相同且不为0说明是夫妻,跳过,如果不是说明是不是单身,插入ans中。
最后将ans按ID从小到大排序,输出即可,注意输出为5位整数
注: 本题使用了利用排序方法凑对的思想,建立结构体并将同组数据给予相同编号,然后根据编号大小排序则可将同组成员挨住,然后根据相邻成员之间的编号是否相同确定 组与组的分界位置,如果需要进一步处理,则将要处理的组插入到另一个序列中去处理即可(与电话通话记录匹配,停车场记录匹配等类似)
题解:
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int MAX = 100000;
const int MAXN = 10000;
struct Person{
int id, order;
}per[MAXN];
int order[MAX] = {0};
int n, m, num = 1;
vector<int> ans;
bool cmp(Person a, Person b){
if(a.order != b.order) return a.order < b.order;
else return a.id < b.id;
}
bool cmp2(int a, int b){
return a < b;
}
int main(){
scanf("%d", &n);
while(n--){
int id1, id2;
scanf("%d %d", &id1, &id2);
order[id1] = order[id2] = num++;
}
scanf("%d", &m);
num = 0;
while(num < m){
scanf("%d", &per[num].id);
per[num].order = order[per[num].id];
num++;
}
sort(per, per+m, cmp);
for(int i = 0; i < m; i++){
if(i < m-1 && per[i].order == per[i+1].order && per[i].order != 0){
i++;
}else ans.push_back(per[i].id);
}
printf("%d\n", ans.size());
sort(ans.begin(), ans.end(), cmp2);
for(int i = 0; i < ans.size(); i++){
printf("%05d", ans[i]);
if(i != ans.size()-1) printf(" ");
}
return 0;
}