zoukankan      html  css  js  c++  java
  • Zoj3332-Strange Country II(有向竞赛图)

    You want to visit a strange country. There are n cities in the country. Cities are numbered from 1 to n. The unique way to travel in the country is taking planes. Strangely, in this strange country, for every two cities A and B, there is a flight from A to B or from B to A, but not both. You can start at any city and you can finish your visit in any city you want. You want to visit each city exactly once. Is it possible?

    Input

    There are multiple test cases. The first line of input is an integer T (0 < T <= 100) indicating the number of test cases. Then T test cases follow. Each test case starts with a line containing an integer n (0 < n <= 100), which is the number of cities. Each of the next n * (n - 1) / 2 lines contains 2 numbers A, B (0 < A, B <= n, A != B), meaning that there is a flight from city A to city B.

    Output

    For each test case:

    • If you can visit each city exactly once, output the possible visiting order in a single line please. Separate the city numbers by spaces. If there are more than one orders, you can output any one.
    • Otherwise, output "Impossible" (without quotes) in a single line.

    Sample Input

    3
    1
    2
    1 2
    3
    1 2
    1 3
    2 3
    

    Sample Output

    1
    1 2
    1 2 3

    解析: 裸的有向竞赛图,有向竞赛图要满足的条件是有N*(N-1)/2条边,也就是每个点与其他点都有边相连,求哈密顿通路。

    代码

    #include<cstdio>
    #include<cstring>
    #include<string>
    #include<iostream>
    #include<sstream>
    #include<algorithm>
    #include<utility>
    #include<vector>
    #include<set>
    #include<map>
    #include<queue>
    #include<cmath>
    #include<iterator>
    #include<stack>
    using namespace std;
    const int maxn=105;
    int N,ans[maxn];
    bool link[maxn][maxn];
    int main()
    {
        int T;
        scanf("%d",&T);
        while(T--)
        {
            scanf("%d",&N);
            memset(link,false,sizeof(link));
            int tot=N*(N-1)/2;
            int u,v;
            for(int i=1;i<=tot;i++)
            {
                scanf("%d%d",&u,&v);
                link[u][v]=true;
            }
            ans[1]=1;
            int i,j,k;
            for(k=2;k<=N;k++)
            {
                for(j=1;j<k;j++) if(link[k][ans[j]]) break;
                for(i=k;i>j;i--) ans[i]=ans[i-1];
                ans[j]=k;
            }
            for(int i=1;i<=N;i++) printf("%d%c",ans[i],i==N?'
    ':' ');
        }
        return 0;
    }
    View Code
  • 相关阅读:
    mac下通过brew切换php版本
    大白话,讲编程之《ES6系列连载》汇总
    Mysql命令大全
    值得收藏的前端大牛博客
    web前端 —— 移动端知识的一些总结
    Linux 目录结构
    【WebSocket No.3】使用WebSocket协议来做服务器
    【WebSocket No.2】WebSocket和Socket实现聊天群发
    GroupBy分组的运用和linq左连接
    try、catch、finally详解,你不知道的异常处理
  • 原文地址:https://www.cnblogs.com/wust-ouyangli/p/5723040.html
Copyright © 2011-2022 走看看