您的位置:首页 > 其它

HDU DFS

2015-08-31 21:23 211 查看


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(1≤n≤1000).

Then n lines
follow. Each line contains two numbers u,v(1≤u,v≤n) ,
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

4
1 1
1 2
2 3
2 4
3
1 2
2 3
3 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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: