输入样例:
6 10
6 2
3 4
1 5
2 5
3 1
4 1
1 6
6 3
1 2
4 5
6
7 5 1 4 3 6 2 5
6 5 1 4 3 6 2
9 6 2 1 6 3 4 5 2 6
4 1 2 5 1
7 6 1 3 4 5 2 6
7 6 1 2 5 4 3 1
输出样例:
YES
NO
NO
NO
YES
NO
解题思路:
满足哈密顿回路的条件是:相邻两点都有边相连,每个点只能遍历一次,图中所有的点都遍历过。
Java代码:
import java.io.*;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] split = br.readLine().split(" ");
int n = Integer.parseInt(split[0]);
int m = Integer.parseInt(split[1]);
boolean [][]g = new boolean[n + 1][n + 1];
boolean []vis = new boolean[n + 1];
while(m-- > 0) {
split = br.readLine().split(" ");
int a = Integer.parseInt(split[0]);
int b = Integer.parseInt(split[1]);
g[a][b] = g[b][a] = true;
}
m = Integer.parseInt(br.readLine());
StringBuilder ans = new StringBuilder();
while(m-- > 0) {
Arrays.fill(vis, false);
split = br.readLine().split(" ");
int []arr = new int[split.length];
for(int i = 1; i < arr.length; i++)
arr[i] = Integer.parseInt(split[i]);
int i = 0, cnt = n; // 判断是否遍历到了正好n个点
for(i = 1; i < arr.length - 1; i++) {
if(g[arr[i]][arr[i + 1]] && !vis[arr[i + 1]]) { // 图中有路径并且没有被访问过
vis[arr[i + 1]] = true;
cnt--;
}else break;
}
if(i == arr.length - 1 && cnt == 0) ans.append("YES\n");
else ans.append("NO\n");
}
System.out.print(ans);
}
}