UVa140 Bandwidth 【最优性剪枝】

题目链接:https://vjudge.net/contest/210334#problem/F

 转载于:https://www.cnblogs.com/luruiyuan/p/5847706.html

 

题目大意:
给出一个n个节点的图,求该图中相邻的节点在哪一个由这些节点组成的排列中,带宽最小,输出该排列和最小带宽。(各个节点到相邻节点的最远距离,这些最远距离的最大值即为带宽。)

 

紫书上介绍了两种剪枝方法,但是以下只给出了一种比较好实现的剪枝。

#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm> 
using namespace std;

const int maxn = 10, inf = 0x7fffffff;
char letter[maxn], s[100];//字母,输入序列 
int id[256]; //字母的编号 
int p[maxn]; //全排列的遍历数组 ,存储的是每个字母的编号 
int pos[maxn];//记录每个字母的位置,避免频繁使用strchr 

int main() {
    while (scanf("%s", &s), s[0] != '#') {
        int len = strlen(s), n = 0;
        for (char ch = 'A'; ch <= 'Z'; ch++)if (strchr(s, ch) != NULL) {
            letter[n] = ch;
            id[ch] = n++;
        }
        vector<int> u, v;
        for (int i = 0; i<len; i++) {
            int t = i;//记录起始节点 
            i += 2;
            while (i<len && s[i] != ';') {
                u.push_back(id[s[t]]);//加入起始节点 
                v.push_back(id[s[i]]);//加入起始节点的相邻节点 
                i++;
            }
        }
        //遍历+剪枝                     //以下只用了一种剪枝方式,即若发现当前已经排列有某两节点带宽超过了已经遍历过的排列的最小带宽,则当前排列直接跳过
        int bandwidth = 0, res = inf;
        int bestP[maxn];//存储最终结果 
        for (int i = 0; i<n; i++)p[i] = i;
        do {
            bandwidth = 0;//初始化别忘了 
            for (int i = 0; i<n; i++)pos[p[i]] = i;//记录编号为pi的节点的位置 
            for (int i = 0; i<u.size(); i++) {
                bandwidth = max(bandwidth, abs(pos[u[i]] - pos[v[i]]));
                if (bandwidth >= res)break;//剪枝
            }
            if (bandwidth<res) {
                memcpy(bestP, p, sizeof(p));//memcpy比较快 
                res = bandwidth;
            }
        } while (next_permutation(p, p + n));          //进行下一个排列的比较
        for (int i = 0; i<n; i++)printf("%c ", letter[bestP[i]]);
        printf("-> %d\n", res);
    }
}

 

2018-04-15

转载于:https://www.cnblogs.com/00isok/p/8848175.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值