【PAT】A1134 Vertex Cover【图论】

天大地大妈咪最大 提交于 2019-11-28 11:04:34

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:

Nv​​ 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

题意

在无向图中,如果一组顶点覆盖了图中所有边的至少一个顶点,就称为点覆盖。现给出一个无向图和K个查询,判断每组查询中的点集是否是点覆盖。

思路

将M条边编号为0~M-1,使用向量数组VToE存储每个顶点相关的边的编号。对于一个查询,首先初始化所有的边都未被覆盖,将给出的点集中的每个顶点相关的边标记为已覆盖,然后遍历一遍是否全部边都被覆盖,即得到答案。

代码

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX_N 10000
vector<int> VToE[MAX_N];
bool cover[MAX_N];
int N, M;
bool check(){
    for(int i = 0; i < M; i++){
        if(!cover[i]) return false;
    }
    return true;
}
int main() {
    // 读取输入,记录每个顶点相关的边的编号
    scanf("%d %d", &N, &M);
    for(int i = 0, u, v; i < M; i++){
        scanf("%d %d", &u, &v);
        VToE[u].push_back(i);
        VToE[v].push_back(i);
    }
    
    int K;
    scanf("%d", &K);
    for(int i = 0, n, u; i < K; i++){
        
        fill(cover, cover + M, false);// 初始化
        scanf("%d", &n);
        for(int j = 0; j < n; j++){// 将点集中每个顶点相关的边标记为已覆盖
            scanf("%d", &u);
            for(int v : VToE[u]){
                cover[v] = true;
            }
        }
        
        printf(check() ? "Yes\n" : "No\n");// 检查,输出结果
    }
    return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!