UVA 140 BandWidth

本文介绍了一种基于枚举法的算法实现,并通过优化减少不必要的计算,提高效率。通过具体的代码实例展示了如何使用枚举法求解特定问题,特别关注了在遍历过程中提前终止以节省计算资源的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

采用的是枚举法,同时在判断的时候注意优化:如果当前计算出来的距离值已经比之前记录的最小距离值大,那么后续的计算就不需要进行了,具体实现见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
using namespace std;

int main(){
	string s;
	while (getline(cin, s)){
		if (s == "#") break;
		string s2 = "";
		for (int i = 0; i < s.size(); i++){
			if (s[i] != ' ') s2 += s[i];
		}
		s = s2;
		map<char, int> ch2int;
		map<int, char> int2ch;
		int amount = 0;
		for (char start = 'A'; start <= 'Z'; start++){
			if (s.find(start) != string::npos){
				ch2int[start] = amount;
				int2ch[amount] = start;
				amount++;
			}
		}
		int* result = new int[amount];
		int* temp = new int[amount];
		for (int i = 0; i < amount; i++) temp[i] = i;
		vector<int> head;
		vector<int> tail;
		for (int i = 0; i < s.size(); i++){
			int first = ch2int[s[i]];
			i += 2;
			while (i < s.size() && s[i] != ';'){
				int second = ch2int[s[i]];
				head.push_back(first);
				tail.push_back(second);
				i++;
			}
		}
		
		int *pos = new int[amount];
		int ans = 10000000;
		
		do{
			int ans_t = 0;
			for (int i = 0; i < amount; i++) pos[temp[i]] = i;
			for (int i = 0; i < head.size(); i++){
				ans_t = max(ans_t, abs(pos[head[i]] - pos[tail[i]]));
				if (ans_t >= ans) break;
			}
			if (ans_t < ans){
				ans = ans_t;
				for (int i = 0; i < amount; i++) result[i] = temp[i];
			}
		} while (next_permutation(temp,temp+amount));
		
		for (int i = 0; i < amount; i++){
			cout << int2ch[result[i]] << ' ';
		}
		cout << "-> " << ans << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值