题意:给你n对不能同时存在的货物,现在有m对包裹,让你验证里面是否存在不能同时存在的物品。(n<=1e4,m<=1e2)
思路:定义一个map<string, set<string> > 用于记录每个物品与之不能同时存在的物品集合。判断每个包裹时,逐个读入,判断下该物品是否存在于pre(pre是用于保存之前物品所有不能同时存在的物品集合)中,如果有,则说明与之前物品有不能同时存在的,如果没有,则把他对应的不同同时存在的物品集合加入到pre中,继续读如下一个。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<string>
using namespace std;
const int maxn = 1e4+5;
int main(void)
{
int n, m, k;
while(cin >> n >> m)
{
map<string, set<string> > M;
set<string> S;
M.clear();
S.clear();
for(int i = 0; i < n; i++)
{
string x, y;
cin >> x >> y;
M[x].insert(y);
M[y].insert(x);
}
for(int i = 0; i < m; i++)
{
scanf("%d", &k);
bool ok = 1;
set<string> pre;
pre.clear();
for(int j = 0; j < k; j++)
{
string tmp;
cin >> tmp;
if(pre.find(tmp) != pre.end()) ok = 0;
set<string> t = M[tmp];
for(set<string>::iterator it = t.begin(); it != t.end(); it++)
pre.insert(*it);
}
puts(ok ? "Yes" : "No");
}
}
return 0;
}