UVA 140 带宽 Bandwidth (暴力枚举+剪枝)

解题思路:本题使用了STL中的next_permutation()函数(位于algorithm中)列举排列。先记录目前已经找到的最小带宽min_width,如果发现已经有某两个结点的距离大于或等于min_width,再怎么扩展也不可能比当前解更有,故应“剪”掉,即剪枝

#include<cstdio>
#include<algorithm>
#include<vector>
#include<map>
#include<cstring> 
using namespace std;
const int maxn=10;
int best[maxn]; //储存最优字符序列(不同数字对应不同字母) 
int p[maxn];    //保存排列 
int pos[maxn];  //字母在序列中的位置 
char letter[maxn]; //保存字母结点 
map<char,int>map1; //通过字母映射编号(以后编号就代表该字母) 
vector<int>v,u;    //分别储存起始结点,和起始结点的相邻结点 
int main(){
	char str[100];
	while(scanf("%s",str)==1 && str[0]!='#'){
		int len=strlen(str);
		int count=0;
	for(int i=0;i<len;i++){
		if(str[i]>='A'&&str[i]<='Z'){
			if(!map1.count(str[i]))
			{
			letter[count]=str[i];
			map1[str[i]]=count++;
			}
		}
	}
	sort(letter,letter+count); //由于题目要求当解有多个时,输出字典序最小,故需排序 
	for(int i=0;i<count;i++)
	map1[letter[i]]=i;  //排序后需重新对不同字母分配编号 
	for(int i=0;i<len;i++){
		int t=i;
		i+=2;
		 while(str[i]!=';' && i<len){
		 	v.push_back(map1[str[t]]);//加入起始结点(相邻结点有多少个就要加多少次) 
		 	u.push_back(map1[str[i]]);//加入起始结点的相邻结点 
		 	i++;
		 }
	}
	
	int min_width=maxn;   //最小带宽 
	for(int i=0;i<count;i++)p[i]=i;   
	do{
		int nodewidth=0;   //当前序列最大带宽 
		for(int i=0;i<count;i++)pos[p[i]]=i;  //各字母在序列中的位置 
		for(int i=0;i<v.size();i++)
		{
		nodewidth=max(nodewidth,abs(pos[v[i]]-pos[u[i]]));
	    if(nodewidth>=min_width)break; //剪枝 
	   }
	   if(min_width>nodewidth){
	   	memcpy(best,p,sizeof(p));  //memcpy更快 
	   	min_width=nodewidth;
	   }
	}while(next_permutation(p,p+count));	
	for(int i=0;i<count;i++)printf("%c ",letter[best[i]]);
	printf("-> %d\n",min_width);
	map1.clear();          //一定要清除容器(当时忘记了错了几次) 
	v.clear();
	u.clear();
	}
	return 0;
} 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柏油

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值