HDU 3414 Tour Route(竞赛图的哈密顿回路)

135 篇文章 0 订阅
109 篇文章 0 订阅

题目地址
题意:给出一个n阶的竞赛图,找出一个哈密顿回路,如果有输出路径,否则输出-1。
思路:按照竞赛图的性质竞赛图一定是存在哈密顿路径的,所以我们遍历每个点为起点的哈密顿路径,再判断是不是首尾相连,如果是直接输出路径就好了。
补充:

  • 1、竞赛图:就是一个把所有的边从有向边转化为无向边,之后这个图是完全图。
  • 2、哈密顿路径:通过图中的每一个节点一次并且仅一次的路径。
  • 3、哈密顿回路:通过图中的每一个节点一次并且仅一次,最后回到起点的路径。
#include <iostream>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <cstdio>
#include <algorithm>
#define LL long long 
#define N 1010
#define M 200010
#define inf 0x3f3f3f3f
using namespace std;
const LL mod = 998244353;
const double eps = 1e-9;
int mapp[N][N], nex[N], n;
bool check(int s) {
    memset(nex, -1, sizeof(nex));
    int head = s, tail = s;
    for (int i = 1; i <= n; i++) {
        if (i == s) continue;
        if (mapp[i][head]) {
            nex[i] = head;
            head = i;
        }
        else {
            int x = head, y = nex[head];
            while (y != -1 && mapp[y][i]) {
                x = y;
                y = nex[y];
            }
            nex[x] = i;
            nex[i] = y;
            if(y == -1)  
                tail = i;  
        }
    }
    if (mapp[tail][head]) {
        nex[tail] = head;
        return true;
    }
    return false;
}
bool solve() {
    for (int i = 1; i <= n; i++) {//每个点找哈密尔顿回路
        if (check(i)) return true;
    }
    return false;
}
int main(){
    cin.sync_with_stdio(false);
    while (cin >> n) {
        if (n == 0) break;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                cin >> mapp[i][j];
            }
        }
        if (n == 1) {
            cout << "1" << endl;
        }
        else if (n == 2 || !solve()) {
            cout << -1 << endl;
        }
        else {
            cout << 1;
            for (int i = 1, j = nex[1]; i < n; i++, j = nex[j]) {
                cout << " " << j;
            }
            cout << endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值