UVa 140 - Bandwidth(回溯)

本文通过一个具体的回溯算法练习题,深入探讨了回溯算法的核心思想、实现细节及其实用场景。通过实例分析,读者可以更好地理解回溯算法在解决复杂问题时的高效性和灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一道回溯的练习题, 输入有点麻烦。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <map>
#include <set>

#define MAXN 110
using namespace std;

char s[MAXN], str[MAXN], A[MAXN];
int cnt, best_k, k;
int per[MAXN], best_sort[MAXN], G[MAXN][MAXN];

int best_sov() {
    k = 0;
    for(int i = 0; i < cnt; i++)
        for(int j = 0; j < cnt; j++)
            if(G[A[per[i]] - 'A'][A[per[j]] - 'A']) {
                k = max(k, abs(j - i));
                if(best_k&& k > best_k) return best_k;
            }
    return k;
}

void all_per(int cur) {
    if(cur == cnt) {
        if(!best_k) {
            best_k = best_sov();
            for(int i = 0; i < cnt; i++)
                best_sort[i] = per[i];
        } else if(best_sov() < best_k) {
            best_k = best_sov();
            for(int i = 0; i < cnt; i++)
                best_sort[i] = per[i];
        }
    } else for(int i = 0; i < cnt; i++) {
        bool ok = true;
        for(int j = 0; j < cur; j++) {
            if(per[j] == i) {ok = false; break;}
        }
        if(ok) {
            per[cur] = i;
            all_per(cur + 1);
        }
    }
}

int main() {
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    #endif // ONLINE_JUDGE
    while (cin >> str&& str[0] != '#') {
        int cur = -1, n = 0, j = 0;
        set<char> letter;
        for(int i = 0; i < strlen(str); i++) {
            if(isalpha(str[i]))
                s[n++] = str[i];
            if(str[i] == ':')
                cur = str[i - 1] - 'A';
            if(str[i] == ';')
                cur = -1;
            if(cur != -1&& isalpha(str[i]))
                G[cur][str[i] - 'A'] = 1;
        }
        sort(s, s + n);
        for(int i = 0; i < n; i++)
            if(!letter.count(s[i])) {
                A[j++] = s[i];
                letter.insert(s[i]);
            }
        cnt = j;
        best_k = 0;
        all_per(0);
        for(int i = 0; i < cnt; i++) {
            if(i) printf(" ");
            printf("%c", A[best_sort[i]]);
        }
        printf(" -> %d\n", best_k);
        memset(G, 0, sizeof(G));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值