欢迎来到PJCK的博客

(欧拉图 并查集 图论) nyoj 42-一笔画问题

题目描述:

zyc从小就比较喜欢玩一些小游戏,其中就包括画一笔画,他想请你帮他写一个程序,判断一个图是否能够用一笔画下来。

规定,所有的边都只能画一次,不能重复画。

 

输入描述:

第一行只有一个正整数N(N<=10)表示测试数据的组数。
每组测试数据的第一行有两个正整数P,Q(P<=1000,Q<=2000),分别表示这个画中有多少个顶点和多少条连线。(点的编号从1到P)
随后的Q行,每行有两个正整数A,B(0<A,B<P),表示编号为A和B的两点之间有连线。

输出描述:

如果存在符合条件的连线,则输出"Yes",
如果不存在符合条件的连线,输出"No"。

样例输入:

2
4 3
1 2
1 3
1 4
4 5
1 2
2 3
1 3
1 4
3 4

样例输出:

No
Yes


这是一个欧拉图的应用,思路如下:

1)首先判断是否都在一个集合中,因为这样才能一笔画,如果是在两个不同的集合中(即被分成两个图,而这两个图不连通),那就最少两笔画,不符合要求。

2)在一个前提下,判断奇点数是否为0或2(一个点的入度和出度的和为0或2),这样才能一笔画。

C++代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1002;
int father[maxn],node[maxn];
int Find(int x){
    while(x != father[x]){
        father[x] = father[father[x]];
        x = father[x];
    }
    return x;
}
void Union(int a,int b){
    int ax = Find(a);
    int bx = Find(b);
    if(ax != bx){
        father[ax] = bx;
    }
}
int main(){
    int N;
    scanf("%d",&N);
    int p,q;
    int a,b;
    while(N--){
        scanf("%d%d",&p,&q);
        for(int i = 1; i <= p; i++){
            father[i] = i;
        }
        memset(node,0,sizeof(node));
        for(int i = 0; i < q; i++){
            scanf("%d%d",&a,&b);
            Union(a,b);
            node[a]++;
            node[b]++;
        }     
        int cnt = 0,cnt1 = 0;
        bool flag1 = false,flag2 = false;
        for(int i = 1; i <= p; i++){
            if(father[i] == i){
                cnt++;
                if(cnt == 2){
                    flag1 = true;
                }
            }
            if(node[i] % 2) cnt1++;
        }
        if(cnt1 != 0 && cnt1 != 2) flag2 = true;
        if(!flag1 && !flag2) printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}

 

参考链接:https://www.cnblogs.com/GetcharZp/p/9091778.html

posted @ 2019-05-19 18:00  PJCK  阅读(187)  评论(0编辑  收藏  举报