我的PAT系列文章更新重心已移至Github,欢迎来看PAT题解的小伙伴请到Github Pages浏览最新内容。此处文章目前已更新至与Github Pages同步。欢迎star我的repo。
题目
集装箱运输货物时,我们必须特别小心,不能把不相容的货物装在一只箱子里。比如氧化剂绝对不能跟易燃液体同箱,否则很容易造成爆炸。
本题给定一张不相容物品的清单,需要你检查每一张集装箱货品清单,判断它们是否能装在同一只箱子里。
输入格式:
输入第一行给出两个正整数: (
) 是成对的不相容物品的对数;
(
) 是集装箱货品清单的单数。
随后数据分两大块给出。第一块有 行,每行给出一对不相容的物品。第二块有
行,每行给出一箱货物的清单,格式如下:
K G[1] G[2] ... G[K]
其中 K
( ) 是物品件数,
G[i]
是物品的编号。简单起见,每件物品用一个 5 位数的编号代表。两个数字之间用空格分隔。
输出格式:
对每箱货物清单,判断是否可以安全运输。如果没有不相容物品,则在一行中输出 Yes
,否则输出 No
。
输入样例:
6 3
20001 20002
20003 20004
20005 20006
20003 20001
20005 20004
20004 20006
4 00001 20004 00002 20003
5 98823 20002 20003 20006 10010
3 12345 67890 23333
输出样例:
No
Yes
Yes
思路
这道题费了我好长时间。。。其实不难-_-#
大致思路:
简单地说,就是在一个列表里查找一对值是否同时出现了,然后做M*N次
查找就使用二分查找,我觉得我的代码已经可以自己解释了,大家看代码
代码
最新代码@github,欢迎交流
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b)
{
return *(int*)a - *(int*)b;
}
int main()
{
int N, M, K, status;
int itemlist[1000], pairlist[10000][2] = {{0}};
/* Record incompatible list */
scanf("%d %d", &N, &M);
for(int i = 0; i < N; i ++)
scanf("%d %d", &pairlist[i][0], &pairlist[i][1]);
for(int i = 0; i < M; i++)
{
status = 1;
scanf("%d", &K);
for(int j = 0; j < K && status; j++)
scanf("%d", itemlist + j);
qsort(itemlist, K, sizeof(int), cmp);
for(int j = 0; j < N; j++)
{
if(bsearch(&pairlist[j][0], itemlist, K, sizeof(int), cmp)
&& bsearch(&pairlist[j][1], itemlist, K, sizeof(int), cmp))
{
puts("No");
status = 0;
break;
}
}
if(status)
puts("Yes");
}
return 0;
}