一笔画问题
- 描述
-
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
-
#include<iostream>
#include<cstdio>
#include<queue>
#include<malloc.h>
#include<cstring>using namespace std;
typedef struct node
{
int id;
struct node *link;
}word;int d[1002];
void add_edge(int a,int b);
word c[1002];
int result[1002];//存放结果
queue<word *> que;//BFS一般都要用到队列的
void dfs(int x);int main()
{
int t,i,p,q,a,b,count;
scanf("%d",&t);
while(t--)
{
count=0;
int ok=1;
memset(result,0,sizeof(result));
memset(d,0,sizeof(d));scanf("%d%d",&p,&q);
for(i = 0 ; i <= p ; ++i)//初始化
{
c[i].id = i;
c[i].link = NULL;
}
for(i=1;i<=q;i++)
{
scanf("%d%d",&a,&b);
add_edge(a,b);
d[a+1]++;
d[b+1]++;
}dfs(1);
for(i=1;i<=p;i++)
if(result[i]!=1)
{
printf("No\n");
ok=0;
break;
}
for(i=1;i<=p;i++)
if(d[i]%2!=0)
count++;
if(ok)
{
if(count==0||count==2)
printf("Yes\n");
else printf("No\n");
}
}
return 0;
}
void add_edge(int a,int b)//无向图,加两次
{
word * p = (word *)malloc(sizeof(word));
p->id = a;
p->link = c[b].link;
c[b].link=p;
//free(p); //这个一定不能free
word *q = (word *)malloc(sizeof(word));
q->id = b;
q->link =c[a].link;
c[a].link=q;
}void dfs(int x)
{
word *temp;
result[x] = 1;
temp = c[x].link;
while(temp != NULL)
{
if(!result[temp -> id])
{
dfs(temp -> id);
}
temp = temp -> link;
}
}