PAT甲級1134 Vertex Cover (25分) 英語捉急。。。。 優化時間

1134 Vertex Cover (25分)
A vertex cover of a graph is a set of vertices such that each edge of the graph is incident to at least one vertex of the set. Now given a graph with several vertex sets, you are supposed to tell if each of them is a vertex cover or not.

Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers N and M (both no more than 10
​4
​​ ), being the total numbers of vertices and the edges, respectively. Then M lines follow, each describes an edge by giving the indices (from 0 to N−1) of the two ends of the edge.

After the graph, a positive integer K (≤ 100) is given, which is the number of queries. Then K lines of queries follow, each in the format:

N
​v
​​ v[1] v[2]⋯v[N
​v
​​ ]

where N
​v
​​ is the number of vertices in the set, and v[i]'s are the indices of the vertices.

Output Specification:
For each query, print in a line Yes if the set is a vertex cover, or No if not.

Sample Input:
10 11
8 7
6 8
4 5
8 4
8 1
1 2
1 4
9 8
9 1
1 0
2 4
5
4 0 3 8 4
6 6 1 7 5 4 9
3 1 8 4
2 2 8
7 9 8 7 6 5 4 2
Sample Output:
No
Yes
Yes
No
No

題目關鍵就這一句話:
A vertex cover of a graph is a set of vertices such that each edge of the graph is incident to at least one vertex of the set. Now given a graph with several vertex sets, you are supposed to tell if each of them is a vertex cover or not.

圖的頂點覆蓋是一個頂點的集合,要求圖每一個邊 至少與頂點覆蓋集合中的一個頂點有關

比如1 8 4 ,圖的所有邊都與1或者8 或者4有關,那麼就是YES

理解題意了就簡單了,我是把所有邊兩邊的端點id保存下來,然後需要判斷的頂點id構成一個set集合,所有的邊兩端的點到set集合裏面判斷 看是不是在裏面,時間上不太好,AC代碼


#include <iostream>
#include <unordered_set>
#include <vector>

using namespace std;


int main()
{
    int Nv,Ne;
    cin>>Nv>>Ne;
    int edge[Ne][2];
    for(int i=0; i<Ne; i++)
    {
        int a,b;
        cin>>a>>b;
        edge[i][0]=a;
        edge[i][1]=b;
    }
    int num;
    cin>>num;
    while(num>0)
    {
        num--;
        int inNum;
        cin>>inNum;
        int sn[inNum];
        unordered_set<int> sett;
        for(int i=0; i<inNum; i++){
            int n;
            cin>>n;
            sett.insert(n);
        }


        int sign=1;
        for(int i=0; i<Ne; i++)
        {
            //對除了sn[i]之外的所有頂點測試是否有邊


            if(sett.find(edge[i][0])==sett.end()&&sett.find(edge[i][1])==sett.end()){
                sign=0;
                break;
            }
        }
        if(sign==1)
        {
                cout<<"Yes"<<endl;
        }
        else{
           cout<<"No"<<endl;
        }

    }
    return 0;
}


效率更高的方法可以看看柳神的博客,主要是減少了我代碼裏面set集合查詢的時間了,雖然set查詢還行快,但還是不如hash方法 0(1)級別的快
https://blog.csdn.net/liuchuo/article/details/78037329

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章