UVA 140 Bandwidth

题目链接: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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值