HDU DFS

来源:互联网 发布:行程路线图制作软件 编辑:程序博客网 时间:2024/05/17 01:27

Rikka with Graph II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 887    Accepted Submission(s): 222


Problem Description
As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them:

Yuta has a non-direct graph with n vertices and n edges. Now he wants you to tell him if there exist a Hamiltonian path.

It is too difficult for Rikka. Can you help her?
 

Input
There are no more than 100 testcases. 

For each testcase, the first line contains a number n(1n1000).

Then n lines follow. Each line contains two numbers u,v(1u,vn) , which means there is an edge between u and v.
 

Output
For each testcase, if there exist a Hamiltonian path print "YES" , otherwise print "NO".
 

Sample Input
41 11 22 32 431 22 33 1
 

Sample Output
NO

YES

注意统计度数 大于2直接错 还有初始化

#include<cstdio>#include<iostream>using namespace std;int map[1005][1005]={0};int sum=1;bool used[1005]={0};int du[1005]={0};int n=0;bool mark=0;void dfs(int x);int main(){while(scanf("%d",&n)!=EOF){mark=0;sum=1;memset(used,0,sizeof(used));memset(du,0,sizeof(du));memset(map,0,sizeof(map));for(int i=1;i<=n;i++){int a=0,b=0;scanf("%d%d",&a,&b);if(a!=b&&!map[a][b]){map[a][b]=map[b][a]=1;du[a]++;du[b]++;}}int top=0;int s=1;for(int i=1;i<=n;i++){if(du[i]==1){  s=i;  top++;    }}    if(top>2)    {    printf("NO\n");    continue;    }    used[s]=1;    dfs(s);    if(mark)    {      printf("YES\n");    }    else    {    printf("NO\n");    }   }return 0;}void dfs(int x){if(sum==n){mark=1;return;}for(int i=1;i<=n&&!mark;i++){if(!used[i]&&map[x][i]){used[i]=1;sum++;dfs(i);sum--;used[i]=0;}}}

0 0
原创粉丝点击