1121 Damn Single (25point(s))
“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 (≤ 50,000), 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 (≤ 10,000) 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 23333
Sample Output:
5
10000 23333 44444 55555 88888
題目大意:
設計思路:
- 用 -1 當初始值,均爲單身狗(因爲有 0 號客人,所以最好不用 0 當初始值)
- 用數組映射一對伴侶
- 用 -2 表示客人到場。讀取客人入場,用映射尋找自己的伴侶,當自己單身或伴侶還未到場,自己用 -2 表示到場
- 若映射的伴侶狀態爲 -2 到場,則兩人配對成功,兩人用 -3 表示脫離單身狗標籤,單身狗數目減二
編譯器:C (gcc)
#include <stdio.h>
#define BLANK -1
#define ATTEND -2
#define PAIR -3
int main()
{
int n, m, couple[100000];
int id1, id2, count = 0;
int i;
for (i = 0; i < 100000; i++)
couple[i] = BLANK;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d %d", &id1, &id2);
couple[id1] = id2;
couple[id2] = id1;
}
scanf("%d", &m);
for (i = 0; i < m; i++) {
scanf("%d", &id1);
if (couple[id1] >= 0 && couple[couple[id1]] == ATTEND) {
couple[couple[id1]] = PAIR;
couple[id1] = PAIR;
count += 2;
} else {
couple[id1] = ATTEND;
}
}
printf("%d\n", m - count);
count = m - count;
for (i = 0; i < 100000; i++)
if (couple[i] == ATTEND)
printf("%05d%s", i, --count? " " : "");
return 0;
}
此方案二(同樣 AC)整體思路是,用正數記錄伴侶,伴侶到場後更新映射值爲相應的負數,這樣最後彼此的映射值還在。但有 0 號客人,他正負都是 0,要對此特別處理,故採取了較好處理的方案一(用 -1、-2、-3 表示不同的狀態)
#include <stdio.h>
int comp(const void *a, const void *b)
{
return *(int*)a - *(int*)b;
}
int main()
{
int n, m, couple[100001] = {0};
int id1, id2, count = 0, id[100001];
int i;
scanf("%d", &n);
for (i = 0; i < n; i++){
scanf("%d %d", &id1, &id2);
id1++;
id2++;
couple[id1] = id2;
couple[id2] = id1;
}
scanf("%d", &m);
for (i = 0; i < m; i++){
scanf("%d", &id[i]);
id[i]++;
id2 = abs(couple[id[i]]);
couple[id2] *= -1;
}
qsort(id, m, sizeof(id[0]), comp);
for (i = 0; i < m; i++)
if (couple[id[i]] >= 0)
count++;
printf("%d\n", count);
for (i = 0; i < m; i++)
if (couple[id[i]] >= 0)
printf("%05d%s", id[i] - 1, --count ? " " : "");
return 0;
}