UVA - 140 Bandwidth

来源:互联网 发布:淘宝买家如何快速升钻 编辑:程序博客网 时间:2024/06/05 16:26

题目大意:给出字母间的连接关系,找到一个排列,使得字母间距离的最大值最小,如果有多个解输出字典序最小的。

解题思路:先排序一下保证答案相同时是字典序小的先,用 next_permutation 枚举所有排列。对于每个排列,我们找到两个有连接关系的字母距离最大的值,比较一下之前的最大值,储存较小的是答案。不难,主要是输入比较复杂,仔细一点就可以了。

#include<iostream> #include<cstdio>#include<cmath>#include<string.h>#include<stdlib.h>#include<algorithm>using namespace std;char s[50], str[50], as[50];bool link[50][50];int ans, tmp;int main() {    while (cin >> s) {        if (s[0] == '#') break;        memset(link, 0, sizeof(link));        int a, b;        int len = strlen(s);        for (int i = 0; i < len; i++)            if (s[i] == ':') {                a = s[i-1] - 'A';                for (int j = i+1; s[j] != ';' && j < len; j++) {                    b = s[j] - 'A';                    link[a][b] = 1;                    link[b][a] = 1;                }            }        int t = 0;        for (int i = 0; i < len; i++)            if (s[i] >= 'A' && s[i] <= 'Z') {                int tag = 1;                for (int j = 0; j < t; j++)                    if (s[i] == str[j]) tag = 0;                if (tag) str[t++] = s[i];            }        sort(str, str+t);        ans = 100000000;        do {            tmp = 0;            for (int i = 0; i < t; i++)                for (int j = i+1; j < t; j++)                    if (link[str[i]-'A'][str[j]-'A'] && j-i > tmp)                        tmp = j - i;            if (tmp < ans) {                ans = tmp;                for (int i = 0; i < t; i++)                    as[i] = str[i];            }        } while (next_permutation(str, str+t));        for (int i = 0; i < t; i++)            printf("%c ", as[i]);        printf("-> %d\n", ans);    }return 0; }
0 0