Rikka with Graph II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 717 Accepted Submission(s): 174
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
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).
问你一个图是否存在哈密顿通路。
哈密顿通路:经过图中每个点一次的一条通路。
直接套板子必然会TLE,加用dfs优化。先判断图是否连通,连通则每次找度最小的点开始。
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 1005;
int n, cnt, deg[MAXN];
bool flag, vis[MAXN], map[MAXN][MAXN];
void dfs(int x)
{
if(cnt == n) {
flag = true;
return ;
}
for(int i = 1; i <= n && !flag; ++i)
if(!vis[i] && map[x][i]) {
vis[i] = true;
++cnt;
dfs(i);
--cnt;
vis[i] = false;
}
}
int main(int argc, char const *argv[])
{
while(scanf("%d", &n) != EOF) {
memset(deg, 0, sizeof(deg));
memset(vis, false, sizeof(vis));
memset(map, false, sizeof(map));
flag = false;
cnt = 1;
for(int i = 0; i < n; ++i) {
int x, y;
scanf("%d%d", &x, &y);
if(x != y && !map[x][y]) {
map[x][y] = map[y][x] = true;
++deg[x], ++deg[y];
}
}
int tmp = 1, sum = 0;
for(int i = 1; i <= n; ++i)
if(deg[i] == 1) {
tmp = i;
++sum;
}
if(sum > 2) {
printf("NO\n");
continue;
}
vis[tmp] = true;
dfs(tmp);
if(flag) printf("YES\n");
else printf("NO\n");
}
return 0;
}
3647



被折叠的 条评论
为什么被折叠?



