您的位置:首页 > 其它

UVA 140 Bandwidth

2016-04-21 11:32 369 查看
题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=19399

题意:给出一个n个节点的图和一个节点的排列,定义节点i的带宽b(i)为i和相邻节点在排列中的最远距离,而所有b(i)的最大值就是整个图的带宽。给定图G,求出让带宽最小的节点排列,如果有多个答案,输出字典序最小的那个。

思路:回溯搜索,每次找到一个没有用过的点,然后找到用当前这个点更新一下整个序列的带宽值,如果当前的值已经不小于当前答案了,就不继续向下搜索了,否则得到一个完整的序列然后再更新答案。


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

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod %100000007

bool net[26][26];

bool flag[30];
int ans[10];
int temp[10];
int val,n;

vector<int> P;

void dfs( int pos , int m )
{
if ( pos > n )
{
if ( m < val ) // 更新答案
{
rep(i,1,n) ans[i] = temp[i];
val = m;
}
return;
}

int nextm;
rep(i,0,int(P.size()-1) )
if ( flag[ i ] )  //如果这个位置上的节点没有被用过
{
nextm = m;
rep( j,1,pos-1 ) if ( net[ P[i] ][ P[temp[j]] ] ) nextm = max(nextm,pos-j);
if ( nextm>= val ) continue;
flag[i] = false;
temp[pos] = i;
dfs(pos+1,nextm);
flag[i] = true;
}
}

bool init()
{
Clean(flag,true);
Clean(net,false);
n = 0;
P.clear();//存放节点
char c;
c = getchar();
if ( c == '#' ) return false;
int ta;
while(  c != '\n' )
{
ta = c - 'A';
if ( flag[ta] )
{
P.push_back(ta);
n++;
flag[ta] = false;
}
getchar(); //  :
c = getchar();
while( c >='A' && c <= 'Z' )
{
if ( flag[c-'A'] )
{
n++;
P.push_back(c-'A');
flag[c-'A'] = false;
}
net[ta][c-'A'] = true;
net[c-'A'][ta] = true;
c = getchar();
}
if ( c == '\n' ) break;
c = getchar();
}
Clean(flag,true);
val = n;
sort(P.begin(),P.end());
return true;
}

int main()
{
while(init())
{
dfs( 1 , 0 );
rep(i,1,n) printf("%c ",P[ ans[i] ]+'A');
printf("-> %d\n",val);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: