原题链接:1149 Dangerous Goods Packaging (25分)
关键词:hash、枚举
When shipping goods with containers, we have to be careful not to pack some incompatible goods into the same container, or we might get ourselves in serious trouble. For example, oxidizing agent (氧化剂) must not be packed with flammable liquid (易燃液体), or it can cause explosion.
Now you are given a long list of incompatible goods, and several lists of goods to be shipped. You are supposed to tell if all the goods in a list can be packed into the same container.
Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers: N (≤104), the number of pairs of incompatible goods, and M (≤100), the number of lists of goods to be shipped.
Then two blocks follow. The first block contains N pairs of incompatible goods, each pair occupies a line; and the second one contains M lists of goods to be shipped, each list occupies a line in the following format:
K G[1] G[2] ... G[K]
where K (≤1,000) is the number of goods and G[i]'s are the IDs of the goods. To make it simple, each good is represented by a 5-digit ID number. All the numbers in a line are separated by spaces.
Output Specification:
For each shipping list, print in a line Yes if there are no incompatible goods in the list, or No if not.
Sample Input:
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
Sample Output:
No
Yes
Yes
题目大意: 给定两两互斥的物品列表,判断给定的物品清单是否满足不存在互斥物品。
思路: 首先是如何存互斥的物品。要知道同一个物品可能会有多个互斥的物品,这是个一对多的关系。因此使用map<int, vector<int>>
来记录。对于每一个物品清单,用两重循环判断是否存在互斥物品,用flag作为标记。
代码:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
const int N = 10000 + 10;
int n, m; //不相容物品的对数 货品清单的单数
map<int, vector<int>> mp; //物品a <-> 和a不相容的物品数组
int main(){
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i ++ ){
int a, b;
scanf("%d%d", &a, &b);
mp[a].push_back(b);
mp[b].push_back(a);
}
for(int i = 0; i < m; i ++ ){ //m组测试
int k, a[100000] = {0};
int flag = 1;
scanf("%d", &k);
vector<int> v(k);
for(int i = 0; i < k; i ++ ){
scanf("%d", &v[i]); //存入数组
a[v[i]] = 1;
}
for(int i = 0; i < v.size(); i ++ ){
for(int j = 0; j < mp[v[i]].size(); j ++ )
if(a[mp[v[i]][j]] == 1) flag = 0; //物品v[i]的不相容物品存在
}
if(flag == 1) puts("Yes");
else puts("No");
}
return 0;
}
注意:
- 判断条件
if(a[mp[v[i]][j]] == 1)
看起来复杂,但要理解a[]、mp[]、v[]的具体含义就容易写出来。 - 又双叒叕遇到
Segmentation Fault
,最讨厌的就是你了- =。解决办法:需要把数组开的大一点,否则在某些测试点数据较大时,会超过数组的范围报错。