PAT甲级——A1149DangerousGoodsPackaging25
Posted zzw1024
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT甲级——A1149DangerousGoodsPackaging25相关的知识,希望对你有一定的参考价值。
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 (≤), the number of pairs of incompatible goods, and M (≤), 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
(≤) 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
Soulution:
直接总结一下寻找配对的题目的一致解法:
先告诉你谁两是一对,然后给个数列,然后判断里面有没有配对的!!
若数量级小,则直接上矩阵,v[a][b]是一对,然后遍历数列,看看存不存在一对
一般都是数量级比较大的
使用unordered_map<int, vector<int>>map 来存储每个数的配偶
然后先标记一遍数列中哪些数字存在 bool int[10000] = { false }; v[xxx] = true;
然后再遍历一遍数列,对于每个数,判断他的所有配偶在不在数列中,即v[x] == true ?
1 #include <iostream> 2 #include <vector> 3 #include <unordered_map> 4 using namespace std; 5 int main() 6 { 7 int n, m, k, a, b; 8 cin >> n >> m; 9 unordered_map<int, vector<int>>thePair; 10 for (int i = 0; i < n; ++i) 11 { 12 cin >> a >> b; 13 thePair[a].push_back(b); 14 thePair[b].push_back(a); 15 } 16 while (m--) 17 { 18 cin >> k; 19 vector<int>temp(k); 20 unordered_map<int, bool>nums; 21 bool flag = true; 22 for (int i = 0; i < k; ++i) 23 { 24 cin >>temp[i]; 25 nums[temp[i]] = true; 26 } 27 for (int i = 0; i < k && flag; ++i) 28 for (auto a : thePair[temp[i]]) 29 if (nums[a] == true) 30 flag = false; 31 cout << (flag ? "Yes" : "No") << endl; 32 } 33 return 0; 34 }
以上是关于PAT甲级——A1149DangerousGoodsPackaging25的主要内容,如果未能解决你的问题,请参考以下文章