哈密顿路径本来是NPC的问题,不过这题可以特判后直接暴力dfs
4 1 1 1 2 2 3 2 4 3 1 2 2 3 3 1
NO YES Hint For the second testcase, One of the path is 1->2->3 If you doesn't know what is Hamiltonian path, click here (https://en.wikipedia.org/wiki/Hamiltonian_path).
/* *********************************************** Author :CKboss Created Time :2015年09月03日 星期四 08时33分46秒 File Name :HDOJ5424.cpp ************************************************ */ #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <string> #include <cmath> #include <cstdlib> #include <vector> #include <queue> #include <set> #include <map> using namespace std; const int maxn=1100; int fa[maxn]; int Find(int x) { return (x==fa[x])?x:fa[x]=Find(fa[x]); } void Union(int u,int v) { u=Find(u); v=Find(v); if(u==v) return ; fa[u]=v; } int n,du[maxn]; bool vis[maxn]; vector<int> G[maxn]; bool flag; void dfs(int u,int c) { if(flag) return ; if(c==n) { flag=true; return ; } for(int i=0,sz=G[u].size();i<sz;i++) { int v=G[u][i]; if(vis[v]==true) continue; vis[v]=true; dfs(v,c+1); vis[v]=false; } } int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); while(scanf("%d",&n)!=EOF) { memset(du,0,sizeof(du)); memset(vis,0,sizeof(vis)); for(int i=1;i<=n;i++) { G[i].clear(); fa[i]=i; } for(int i=0;i<n;i++) { int u,v; scanf("%d%d",&u,&v); G[u].push_back(v); G[v].push_back(u); du[u]++; du[v]++; Union(u,v); } int st=1,g=Find(st); bool ok=true; for(int i=2;i<=n;i++) { if(du[i]<du[st]) st=i; if(Find(i)!=g) ok=false; } if(ok==false) { puts("NO"); continue; } flag=false; vis[st]=true; dfs(st,1); if(flag) puts("YES"); else puts("NO"); } return 0; }