zoukankan      html  css  js  c++  java
  • PAT (Advanced Level) Practice 1122 Hamiltonian Cycle (25分)

    1.题目

    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 (2<N≤200), the number of vertices, and M, the number of edges in an undirected graph. Then M lines follow, each describes an edge in the format Vertex1 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 V​1​​ V​2​​ ... V​n​​

    where n is the number of vertices in the list, and V​i​​'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:

    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

    2.代码

    #include<iostream>
    #include<vector>
    using namespace std;
    int edges[201][201];
    int main()
    {
    	int n, m,a,b,k,amount;
    	scanf("%d %d", &n, &m);
    	for (int i = 1; i <=m; i++)
    	{
    		scanf("%d %d", &a, &b);
    		edges[a][b] = edges[b][a] = 1;
    	}
    	scanf("%d", &k);
    	
    	for (int i = 1; i <=k; i++)
    	{
    		bool ok = true;
    		scanf("%d", &amount);
    		vector<int>in(amount);
    		vector<int>mark(n+1);
    		for (int i = 0; i < amount; i++)
    			scanf("%d", &in[i]);
    		if (amount < n) { printf("NO
    ");  continue; }
    		if ((amount == 0 || amount == 1) && amount == n) { printf("YES
    "); continue; }
    		int j;
    		for ( j = 0; j < amount - 1; j++)
    		{
    			if (mark[in[j]] == 1) { ok = false; break; }
    			if (edges[in[j]][in[j + 1]] == 0) { ok = false; break; }
    			mark[in[j]] = 1;
    		}
    		if (in[j]!=in[0])ok = false;
    		if (ok)printf("YES
    ");
    		else printf("NO
    ");
    	}
    }
  • 相关阅读:
    laravel5.2 开发中打印sql语句
    centos 安装 vsftpd
    linux 安装 DenyHosts 防止密码被暴力破解
    linux nginx 安装防火墙ngx_lua_waf
    mysql 下载资源地址
    微信公众号 access_token 没有过期 却失效
    centos 安装 composer
    五十个小技巧提高PHP执行效率
    yii 使用DB实现rbac 权限控制
    git 的使用
  • 原文地址:https://www.cnblogs.com/Jason66661010/p/12788863.html
Copyright © 2011-2022 走看看