题意
给出已知的不能放在一起的物品,然后输入几组物品,判断是否合理。
思路
题目没什么难的,难在时间复杂度和空间复杂度之间的权衡,任何一方面把握不好就ac不了。我觉得我的思路挺好,所以分享一下。大致思路是准备一个充分大的数组,对于每一组,物品一个一个的放进去,同时也将其不兼容的物品全部放进这个数组,一旦放入新的物品时发现这个位置已经是 1,说明这个物品不能放进去。
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
#include "bits/stdc++.h"
using namespace std;
const int maxn = 100000;
int a[maxn];
int main(){
// freopen("input.txt","r",stdin);
int n,m; cin >> n >> m;
unordered_map<int,vector<int>> map1;
for (int i = 0; i < n; ++i) {
int t1,t2; scanf("%d%d",&t1,&t2);
map1[t1].push_back(t2); map1[t2].push_back(t1);
}
for (int i = 0; i < m; ++i) {
int k; scanf("%d",&k);
fill(a,a+maxn,0);
bool no = false;
for (int j = 0; j < k; ++j) {
int id; scanf("%d",&id);
if (a[id]) {
no = true;
} else if (map1.count(id)){
for(int t:map1[id]) a[t] = 1;
}
}
if (no) printf("No\n");
else printf("Yes\n");
}
}