UVa--140 BandWidth (DFS)

传送门

题意:

给出一个有n个顶点的图,结点编号 A ~ Z。给定顶点的一个排列,那么定义结点v的带宽B(v)为v和相邻结点在排列中的最远距离,而所有B(v)的最大值定义为图的带宽。本题所求为给定图G,求出让带宽最小的结点的排列。n <= 8.

题解:

考虑到n <= 8,枚举每个排列再分别计算带宽,然后选取带宽最小的一种排列。需要注意的是,结点编号在A~Z范围内取值,是跳跃性的,所以需要映射到一个连续的整数序列上,方便全排列。

此题建立图略微麻烦。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;

const int maxn = 30;
int  graph[maxn][maxn];
int  a[maxn], b[maxn];
int  n;
map<char, int> mp;

void solve()
{
    //结点映射到一个连续整数序列
    int i = 0;
    for(auto &it : mp){
        a[i++] = it.first - 'A';
    }

    int ans = 1 << 30;
    do{
        int cur = 0;
        //计算结点当前排列下的bandwidth
        for(int i = 0; i < n; ++i)
        {
            for(int j = 0; j < n; ++j)
            {
                if(graph[a[i]][a[j]]){
                    cur = max(cur, j - i);
                }
            }
        }
        //更新最小bandwidth
        if(cur < ans)
        {
            ans = cur;
            for(int i = 0; i < n; ++i)
                b[i] = a[i];
        }
    }while(next_permutation(a, a + n));

    for(int i = 0; i < n; ++i)
        printf("%c ", 'A' + b[i]);
    printf("-> %d\n", ans);
}

int main()
{
    string str;
    while(cin >> str && str != "#")
    {
        memset(graph, 0, sizeof(graph));
        mp.clear();
        //建图
        int s = 0, e = 0;
        for(int i = 0; i < (int)str.length(); ++i)
        {
            if(str[i] != ':' && str[i] != ';')
                mp[str[i]]++;

            e++;
            if(str[i] == ';')
            {
                for(int j = s + 2; j < s + e - 1; ++j)
                {
                    graph[str[s] - 'A'][str[j] - 'A'] = 1;
                    graph[str[j] - 'A'][str[s] - 'A'] = 1;
                }
                s += e;
                e = 0;
            }
        }
        for(int j = s + 2; j < s + e; ++j)
        {
            graph[str[s] - 'A'][str[j] - 'A'] = 1;
            graph[str[j] - 'A'][str[s] - 'A'] = 1;
        }
        //图的结点个数
        n = mp.size();
        solve();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值