NYOJ 一笔画

# include<iostream>
# include<string>
# include<string.h>
# include<queue>
# include<stdio.h>
# include<math.h>
#include <algorithm>
using namespace std;
#define MAX 4005 
int first[MAX],next[MAX],u[MAX],v[MAX],used[MAX],h=1,in[MAX];
//int out[MAX];
void AddEdge(int a,int b)
{
    u[h] = a;
    v[h] = b;
    if(h%2==1)
    {
        in[a]++;
        //out[a]++;
        in[b]++;
        //out[b]++;
    }
    next[h] = first[u[h]];
    first[u[h]] = h;
    h++;
}
int judge(int p)
{
    int count = 0;
    int vertex[2];
    for(int i=1;i<=p;i++)
    {
        if(in[i] % 2 == 1)
        {
            if(count>=2)
                return -1;
            vertex[count] = i;
            count ++;
        }
    }
    if(count==0)
    {
        return 1;
    }
    else if(count == 1)
    {
        return -1;
    }
    else if(count == 2)
    {
        return vertex[0];
    }
    else
        return -1;
}
void dfs(int k)        //k是出发顶点  
{
    //printf("%d\n------------------\n",first[k]);
    if(first[k]==-1)    //不存在以k为顶点的边 
        return;
    else
    {
        k = first[k];
        while(k != -1)
        {
            if(used[k]!=0)
            {
                used[k] = 0;
                if(k%2==1)
                    used[k+1] = 0;
                else
                {
                    used[k-1] = 0;
                }
                dfs(v[k]);
            }
            k = next[k];
        }
    }
    
}
int main()
{
    int m,n,i,j;
    cin>>n;
    while(n--)
    {
        int p,q;
        cin>>p>>q;
        h = 1;
        for(i=0;i<MAX;i++)
        {
            first[i] = -1;
            next[i] = -1;
            used[i] = 1;
            in[i] = 0;
            //out[i] = 0;
        }
        for(i=1;i<=q;i++)
        {
            int a,b;
            scanf("%d %d",&a,&b);
            AddEdge(a,b);
            AddEdge(b,a);
        }
        
        int k,flag = 1;
        k = judge(p);    //k为起点 
        if(k==-1)
        {
            printf("No\n");
            continue;
        }
        //printf("%d\n------------------\n",k);
        dfs(k);    //从起点开始寻找是否存在欧拉路 
        
        /******
        for(i=1;i<=h;i++)
        {
            k = first[i];
            while(k!=-1) 
            {
                printf("%d %d %d %d %d\n",u[k],v[k],used[k],first[k],next[k]);
                k = next[k];
            } 
        }
        *******/
        
        for(i=1;i<h;i++)
        {
            if(used[i]!=0)        //有边尚未访问 故不能一笔画 
            {
                //printf("kk");
                flag = 0;
                break;
            } 
        }
        if(flag==1)    printf("Yes\n"); 
        else        printf("No\n");
    } 
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/fzuhyj/p/9493378.html