例题7-6(uva-140)

#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>


#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
const int maxn = 10;
char id[256], letter[maxn];

int main()
{
	string input;
	while (cin >> input && !input.empty() && input.front() != '#') {
		int n = 0,i;
		//给字母编号 离散化
		for (i = 'A'; i <= 'Z'; i++) {
			if (input.find(i) != string::npos) {
				letter[n] = i;
				id[i] = n++;
			}
		}

		vector<pair<int, int> > edges;
		
		int base = 0, ans = n,temp = 0;
		i = 0;

		while (true)
		{
			while (i < input.size() && input[i] != ':')i++;
			if(i >= input.size()) break;
			base = input[i-1];
			i++;
			while (i < input.size() && input[i] != ';') {
				edges.emplace_back(make_pair(id[base], id[input[i]]));
				i++;
			}
			i++;
		}

		vector<int> q(n,0),pos(n,0),res(n,0);

		for (i = 0; i < n; i++)q[i] = i;

		do 
		{
			//当前位置是哪个字母 记录字母位置
			for (i = 0; i < n; i++) {
				pos[q[i]] = i;
			}
			temp = 0;
			for (i = 0; i < edges.size(); i++) {
				temp = max(abs(pos[edges[i].first] - pos[edges[i].second]), temp);
			}
			if (temp < ans) {
				res = q;
				ans = temp;
			}
		} while (next_permutation(q.begin(),q.end()));

		for (int i = 0; i < n; i++) cout << letter[res[i]] << " ";
		cout << "-> " << ans << endl;
	}
	return 0;
}
上一篇:UVA 10294 Arif in Dhaka


下一篇:UVA 1073 Glenbow Museum