1122.Hamiltonian Cycle

题目描述

The "Hamilton cycle problem" is to find a simple cycle that contains every vertex in a graph. Such a cycle is called a "Hamiltonian cycle".
In this problem, you are supposed to tell if a given cycle is a Hamiltonian cycle.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive integers N (2Vertex1 Vertex2, where the vertices are numbered from 1 to N. The next line gives a positive integer K which is the number of queries, followed by K lines of queries, each in the format:

n V1​ V2 ... Vn

​​ where n is the number of vertices in the list, and Vi​'s are the vertices on a path.

Output Specification:

For each query, print in a line YES if the path does form a Hamiltonian cycle, or NO if not.

Sample Input 1:

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

Sample Output :

YES
NO
NO
NO
YES
NO

题意理解

判断是否为哈密顿回路
由指定的起点前往指定的终点,途中经过所有其他节点且只经过一次。

代码

#include 
#include 
using namespace std;
int main() {
    int n, m, k, a, b;
    cin >> n >> m;
    vector> e(n+1);
    for (int i = 0; i < m; i++) {
        cin >> a >> b;
        e[a].push_back(b);
        e[b].push_back(a);
    }
    cin >> k;
    for (int i = 0; i < k; i++) {
        int num, count = 0, pre, cur, first, flag=1;
        cin >> num;
        vector visit(n+1, 0);
        for (int j = 0; j < num; j++) {
            cin >> cur;
            visit[cur] = 1;
            if (j > 0) {
                for (int it : e[pre])
                    if (it == cur) count++;
            }
            else first = cur;
            pre = cur;
        }
        for (int t = 1; t <= n; t++) if (visit[t] == 0) flag = 0;
        if (num == n + 1 && count == n && first == cur && flag) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
    return 0;
}

优化

1.在判断是否每个点都访问过时,使用了set,最后只需判断set的大小是否等于图中的顶点数即可。
2.在比较简单的题目中,直接使用int类型的二维数组,在判断两个点之间是否有边时更方便。

  • 代码
    柳神的代码
#include 
#include 
#include 
using namespace std;
int main() {
    int n, m, cnt, k, a[210][210] = {0};
    cin >> n >> m;
    for(int i = 0; i < m; i++) {
        int t1, t2;
        scanf("%d%d", &t1, &t2);
        a[t1][t2] = a[t2][t1] = 1;
    }
    cin >> cnt;
    while(cnt--) {
        cin >> k;
        vector v(k);
        set s;
        int flag1 = 1, flag2 = 1;
        for(int i = 0; i < k; i++) {
            scanf("%d", &v[i]);
            s.insert(v[i]);
        }
        if(s.size() != n || k - 1 != n || v[0] != v[k-1]) flag1 = 0;
        for(int i = 0; i < k - 1; i++)
            if(a[v[i]][v[i+1]] == 0) flag2 = 0;
        printf("%s",flag1 && flag2 ? "YES\n" : "NO\n");
    }
    return 0;
}

你可能感兴趣的:(1122.Hamiltonian Cycle)