题目
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 (≤10^4), 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
题意
给出不能共存的物品id和装运名单,判断名单能不能执行。
放在第二题这个位置,其实也不是多难吧。就是用的方法比较巧妙:hash思想。
容易超时的思路
查询的时候,如果k个元素是两两举例的,然后去其中一个的违禁品名单里找,最坏情况要查10的2+3+3+4=12次方,超时了。
比较好的做法还是以k个元素为数组a的下标,标记是否出现,然后对k个元素的违禁品进行遍历,看看是不是在数组a里。
错误加超时代码 15/25分
int n,m,k,a,b;
map<int, vector<int>> mp;
int main(){
cin>>n>>m;
for(int i=0;i<n;i++){
cin>>a>>b;
mp[a].push_back(b);
mp[b].push_back(a);
}
for(int i=0;i<m;i++){
vector<int> v;
bool f=true;
cin>>k;
for(int j=0;j<k;j++){
cin>>a;
if(!v.empty()){
for(auto q:v){
for(auto it:mp[q]){
if(a==it){
cout<<"No"<<endl;
f=false;
break;
}
}
}
}
v.push_back(a);
}
if(f)cout<<"Yes"<<endl;
}
return 0;
}
满分代码
#include<iostream>
#include<vector>
using namespace std;
int n,m,k,u,w;
map<int, vector<int>> mp;//mp[id]是存放id克物的名单
int main(){
cin>>n>>m;
for(int i=0;i<n;i++){
scanf("%d %d",&u,&w);
mp[u].push_back(w);
mp[w].push_back(u);
}
while(m--){
vector<int> v,a(100000);
cin>>k;
for(int i=0;i<k;i++){
scanf("%d",&u);
v.push_back(u);//v存放某批的物品名单
a[u]=1;//给物品u签到
}
bool f=true;
for(auto i:v){
for(auto j:mp[i]){
if(a[j]==1){//如果u的相克也签了到,直接输出否
f=false;
break;
}
}
}
printf("%s\n",f?"Yes":"No");
}
return 0;
}
如果喜欢我的文章请给我点赞哦,谢谢!