PAT 甲级 1149 Dangerous Goods Packaging(25 分)

题目地址:PAT Adv 1049

1149 Dangerous Goods Packaging(25 分)

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

题目说明:

对于每一个货物,我们存储它的所有的非兼容货物,在一个舱内的每一货物,如果我们发现其非兼容货物也在舱内,则不能运输,舱内任意货物的所有非兼容货物均不在舱内,则可以运输。

数组索引效率相对于二叉树来说应该是更高的。

代码:

#include
using namespace std;
const int maxn=1e5;
int isIn[maxn]={0};     //if a good is in the ship-list , isIn[i]=1, means good with id of i is in the list, 0 for not in
int read(){
    int input=0;
    char c=getchar();
    while(c<'0' || c>'9')
        c=getchar();
    while(c>='0' && c<='9'){
        input=input*10 + c - '0';
        c=getchar();
    }
    return input;
}
int main(){
    int n,k,g1,g2,cnt;
    //incompatible matrix , the vector in incomp[i] stores the good-ids that are incompatible with i
    vector< vector > incomp(maxn);
    cin >> n >> k;
    //read the incompatible pairs
    while(n--){
        g1=read(), g2=read();
        incomp[g1].push_back(g2);
        incomp[g2].push_back(g1);
    }
    vector list;   //ship-list
    while(k--){
        bool allCompatible=true;
        memset(isIn,0,sizeof(isIn));    //initialize
        list.clear();                   //initialize, clear the ship list
        cnt=read();                     //number of goods within the ship-list
        while(cnt--){
            g1=read();
            list.push_back(g1);         //read-in the list
            isIn[g1]=1;
        }
        for(int i=0;i

运行时间截图:

PAT 甲级 1149 Dangerous Goods Packaging(25 分)_第1张图片

你可能感兴趣的:(PAT,PAT)