目录
题目
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
思路
难度评级:⭐️⭐️⭐️
难度三颗星是因为思路不优的话,测试点2会运行超时。
传统思路:遍历每次的goods list,从list中选择两个不同的goods,判断他们是否兼容;这种办法无论记录商品兼容与否的变量类型是什么都是运行超时,使用unordered类型的set/map都是如此,所以思路一定要变。
优秀思路:遍历每次goods list中的good时,再去遍历与该good不兼容的goods,判断这些不兼容的goods是否出现在了这次的goods list中,如果出现了,那么本次输出肯定是No。
代码
#include <iostream>
#include <unordered_map>
#include <vector>
#include <unordered_set>
using namespace std;
unordered_map<int,unordered_set<int>> incompatibleData;
int main(int argc, char** argv) {
int n,m;
cin>>n>>m;
for(int i=0;i<n;i++) {
int id1,id2;
cin>>id1>>id2;
incompatibleData[id1].insert(id2);
incompatibleData[id2].insert(id1);
}
for(int i=0;i<m;i++) {
int num,flag=true;
cin>>num;
unordered_set<int> list(num);
for(int j=0;j<num;j++) {
int id;
cin>>id;
list.insert(id);
}
for(int id:list) {
for(int good:incompatibleData[id]) {
if(list.count(good)==1) {
cout<<"No"<<endl;
flag=false;
break;
}
}
if(!flag) break;
}
if(flag) cout<<"Yes"<<endl;
}
return 0;
}