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
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?
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 .
4 1 1 1 2 2 3 2 4 3 1 2 2 3 3 1
NOYES
注意统计度数 大于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; } } }