国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

UVA 140 帶寬 Bandwidth (暴力枚舉+剪枝)

2019-11-10 17:26:24
字體:
來源:轉載
供稿:網友

解題思路:本題使用了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;} 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 吉林市| 磐石市| 保定市| 宜黄县| 黄石市| 吉首市| 正蓝旗| 盈江县| 东乌珠穆沁旗| 慈利县| 乌鲁木齐县| 木兰县| 探索| 山东| 台湾省| 兖州市| 深圳市| 淮北市| 邯郸市| 舞阳县| 健康| 逊克县| 瑞丽市| 白沙| 克东县| 宜丰县| 阿克| 乐亭县| 凤庆县| 娱乐| 湄潭县| 凤山县| 靖西县| 兴业县| 大同县| 无棣县| 隆林| 明光市| 兴仁县| 泾源县| 长春市|