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;
}
}
}
相关文章推荐
- 枚举类型的使用
- where、having、group by、order by的顺序
- Hibernate自学详细笔记
- 百度面试题 最长公共子串-动态规划法
- Linux学习一:安装/配置vi,熟悉gcc/vi
- 我排第几个
- android传递数据方式2--通过剪切板传数据
- 间隔300ms第一次一个管亮流动一次,第二次两个管亮流动。依次到8个管亮,然后重复此过程
- poj 2226 Muddy Fields(最小点覆盖+巧妙构图)
- 今天又看到了一篇关于程序运行时内存方面的文章,特地来分享一下。
- asp.net如何解决传递中文参数乱码问题
- LeetCode之Best Time to Buy and Sell Stock
- HTML发展历史
- Spring学习笔记之三----基于Annotation的Spring IOC配置
- Hadoop系列之单机版安装
- Hive函数row_number实现
- 快速创建九宫格
- Building a RESTful Web Service
- win7双系统安装ubuntu并配置常用软件
- Java 调用cmd.exe命令