PAT甲级1149 Dangerous Goods Packaging (25分)|C++实现

一、题目描述

原题链接
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:

在这里插入图片描述

​​Output Specification:

在这里插入图片描述

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

二、解题思路

一道比较简单的题目,可以用哈希的方式解决,数组下标表示物品的标号,对应值为true表示在序列中,对应值为false则表示不在。用一个二维vector存放每一个物品的冲突物品,对于输入的每一个物品,我们查询与它冲突的物品在不在序列中即可。代码还是比较易读的。

三、AC代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 100010;
vector<int> pairs[maxn];
int main()
{
    
    
  int N, K, tmp1, tmp2;
  scanf("%d%d", &N, &K);
  for(int i=0; i<N; i++)
  {
    
    
    scanf("%d%d", &tmp1, &tmp2);
    pairs[tmp1].push_back(tmp2);    //存放与tmp1冲突的物品
  }
  int num;
  for(int i=0; i<K; i++)
  {
    
    
    scanf("%d", &num);
    vector<int> all;
    bool isHere[maxn] = {
    
    false};
    bool flag = false;
    for(int j=0; j<num; j++)
    {
    
    
      scanf("%d", &tmp1);
      isHere[tmp1] = true;  //标记 在队列中
      all.push_back(tmp1);
    }
    for(int j=0; j<all.size(); j++)
    {
    
    
      for(int k=0; k<pairs[all[j]].size(); k++)
      {
    
    
        if(isHere[pairs[all[j]][k]])	flag = true;    //有冲突的物品也在队列中
      }
      if(flag)	break;
    }
    flag ? printf("No\n") : printf("Yes\n");
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/109092749