标签:
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).
哈密顿通路:经过每个点有且仅有一次的一条通路。
由于图,只有n个边,那么最小度的那个边,最大只有2,先判定,是否连通,如果连通,每次,都找那个度最小的作为入点,因为,最小度的点,一定会成为某条路的端点,这样就可以用o(n )的复杂度,找到一条哈密顿回路。
给个测试数据,
5
1 5 1 2 2 3 2 4 1 3
#define N 1005 #define M 100005 #define maxn 205 #define MOD 1000000000000000007 int n,a,b,d[N],minx,mi; vector<int> p[N]; bool vis[N]; void DFS(int x){ vis[x] = true; FI(p[x].size()){ int goal = p[x][i]; if(!vis[goal]){ DFS(goal); } } } int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); while(S(n)!=EOF) { FI(n+1) p[i].clear(); fill(d,0); FI(n){ S2(a,b); if(a != b){ p[a].push_back(b); p[b].push_back(a); d[a]++;d[b]++; } } bool isConnect = true; fill(vis,false); DFS(1); For(i,1,n+1){ if(!vis[i]){ isConnect = false; break; } } if(!isConnect){ printf("NO\n"); continue; } minx = N;mi = 1; For(i,1,n+1){ if(d[i] < minx){ mi = i; minx = d[i]; } } fill(vis,false); vis[mi] = true; while(true){ bool isChange = false; minx = N; int mit = -1; FI(p[mi].size()){ int goal = p[mi][i]; if(!vis[goal]){ if(d[goal] < minx){ mit = goal; minx = d[goal]; } isChange = true; } } if(!isChange) break; mi = mit; vis[mi] = true; } isConnect = true; For(i,1,n+1){ if(!vis[i]){ isConnect = false; break; } } if(!isConnect) printf("NO\n"); else printf("YES\n"); } //fclose(stdin); //fclose(stdout); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
hdu 5424 Rikka with Graph II 哈密顿通路
标签:
原文地址:http://blog.csdn.net/mengzhengnan/article/details/48093985