aozil_yang的博客

点滴记录,记录成长,帮助你我!

例题 7-6 UVA - 140 Bandwidth 带宽 (全排列暴力)

UVA 蹦了  不知道能不能过 先写上在说,不对在改吧!

思路很简单:

直接从输入中建立出一张图,然后全排列枚举图,在每一个全排列中遍历带宽

最后更新答案!

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<cmath>
#include<cstdlib>
#include<cctype>
using namespace std;
const int maxn = 200 + 10;
const int INF = 1e9;
vector<int>v[30];
char s[maxn];
int a[30];
int main(){
    while(scanf("%s",s+1) == 1 && s[1] != '#'){
        s[0] = ';';
        int len = strlen(s);
        s[len++] = ';';
        s[len] = 0;
        for (int i = 0; i < 26; ++i)v[i].clear();
        for (int i = 0; i < len; ++i){
            if (s[i] == ';'){
                int u = s[i+1]-'A',j;
                for (j = i + 3; j < len && s[j] != ';'; ++j){
                    int vv = s[j] - 'A';
                    v[u].push_back(vv);
                    v[vv].push_back(u);
                }
                i = j - 1;
            }
        }
        int cnt = 0;
        for (int i = 0; i < 26; ++i)if (!v[i].empty())a[cnt++] = i;
        sort(a,a+cnt);
        int aa[10];
        int ans = INF;
        do{
            int pos[10];
            int band = 0;
            for (int i = 0; i < cnt; ++i)pos[a[i]] = i;
            for (int i = 0; i < cnt; ++i){
                int u = a[i];
                for (int j = 0; j < v[u].size(); ++j){
                    band = max(band,abs(pos[v[u][j]]-pos[u]));
                }
            }
            if (band < ans){
                ans=band;
                memcpy(aa,a,sizeof(int)*10);
            }
        }while(next_permutation(a,a+cnt));
        for (int i = 0; i < cnt; ++i)printf("%c ",aa[i] + 'A');
        printf("-> %d\n",ans);
    }

    return 0;
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aozil_yang/article/details/51546431
文章标签: c语言 uva
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭