您的位置:首页 > 其它

UVa 140 (枚举排列) Bandwidth

2015-02-05 23:32 288 查看
题意较复杂,请参见原题=_=||

没什么好说的,直接枚举每个排列就好了,然后记录最小带宽,以及对应的最佳排列。

STL里的next_permutation函数真是好用。

比较蛋疼的就是题目的输入了。。

#include <bits/stdc++.h>
using namespace std;

const int maxn = 10;

int id[256], letter[maxn];
char in[1000];

int main()
{
//freopen("in.txt", "r", stdin);

while(scanf("%s", in) == 1 && in[0] != '#')
{
int n = 0;
for(char ch = 'A'; ch <= 'Z'; ++ch)
if(strchr(in, ch) != NULL)
{
id[ch] = n;
letter[n++] = ch;
}

int l = strlen(in), p = 0, q = 0;
vector<int> u, v;
for(;;)
{
while(p < l && in[p] != ':') p++;
if(p == l) break;
while(q < l && in[q] != ';') q++;
for(int i = p+1; i < q; ++i)
{
u.push_back(id[in[p-1]]);
v.push_back(id[in[i]]);
}
p++; q++;
}

int P[maxn], bestP[maxn], pos[maxn], ans = n;
for(int i = 0; i < n; ++i) P[i] = i;
do
{
for(int i = 0; i < n; ++i) pos[P[i]] = i;
int bandwidth = 0;
for(int i = 0; i < u.size(); ++i) bandwidth = max(bandwidth, abs(pos[u[i]] - pos[v[i]]));
if(bandwidth < ans)
{
ans = bandwidth;
memcpy(bestP, P, sizeof(P));
}
}while(next_permutation(P, P+n));

for(int i = 0; i < n; ++i) printf("%c ", letter[bestP[i]]);
printf("-> %d\n", ans);
}

return 0;
}

代码君


代码君
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: