uva 140 Bandwidth

本文介绍了一种利用next_permutation函数解决Bandwidth问题的方法。通过构建节点缓存和图结构,实现对字符串中字符进行排序并计算带宽的最大值。程序详细解释了如何读取输入字符串、构建图、计算最大带宽以及使用next_permutation进行全排列搜索。

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

此题就是使用next_permutation

//
//  main.cpp
//  uva 140 - Bandwidth
//
//  Created by XD on 15/7/27.
//  Copyright (c) 2015年 XD. All rights reserved.
//

#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include<vector>
#include <string.h>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <cstdio>
using namespace std ;


set<char> nodecache ;
set<char> graph[30] ;

int getMaxBi(char node[],int len)
{
    int pos[27] ;
    for (int i = 0; i < len ; i++) {
        pos[node[i] - 'A'] = i  ;
    }
    int maxb = -1 ;
    for (set<char>::iterator it = nodecache.begin(); it!= nodecache.end(); it++) {
        len = (int ) graph[*it - 'A'].size() ;
        int tm = -1 ;
        for (set<char>::iterator mit = graph[*it-'A'].begin(); mit!= graph[*it-'A'].end(); mit++) {
            int b=abs(pos[*mit-'A'] - pos[*it-'A']);
            tm = tm > b?tm :b ;
        }
        maxb = tm  > maxb ? tm  : maxb ;
    }
    return maxb ;
}



int main(int argc, const char * argv[]) {
    char node[10] ;
    char g[100] ;
    int pos ;
    int minb = 0 ;
    while (scanf(" %s" , g )==1 && g[0]!='#') {
        nodecache.clear() ;
        for (int i = 0; i < 30; i++) {
            graph[i].clear() ;
        }
        int len = (int )strlen(g) ;
        for (int i = 0; i < len; i++) {
            if (g[i]  >= 'A' && g[i]<='Z') {
                pos = g[i] - 'A' ;
                nodecache.insert(g[i]) ;
                i+=2 ;
                while (i < len && g[i]!=';') {
                    nodecache.insert(g[i]) ;
                    graph[pos].insert(g[i]) ;
                    graph[g[i]-'A'].insert(pos + 'A') ;
                    i++ ;
                }
            }
        }
        int  j = 0 ;
        minb = 10 ;
        char result[10] ;
        
        for (set<char>::iterator it = nodecache.begin() ; it!=nodecache.end(); it++) {
            node[j++] = *it ;
        }
        do{
            int  bandwidth = getMaxBi(node , j ) ;
            if (minb > bandwidth) {
                minb = bandwidth ;
                for (int i = 0 ; i < j ; i++) {
                    result[i] = node[i] ;
                }
            }
        }while (next_permutation(node, node+j)) ;
        
        for (int i = 0; i < j ; i++) {
            printf("%c " , result[i]) ;
        }
        printf("-> %d\n",minb) ;
        
    }
    
    
    
    
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值