uva140Bandwidth带宽——字符串处理加全排列

/*带宽
题意:给出一串字符串,字符串中包括形如 A:FB;B:GC;D:GC;F:AGH;E:HD
A:FB;表示点A与F相连,A与B相连
如果将这个字符串的顶点排序为 A B C F G D H E
A与B之间边长为1;
A与C不相连;
A与F之间的边长为3;
A与剩下的不相连;
以此类推B也是如此;

在不同的顶点排列中,相连两点的边长随位置变化而变化
找出同一个顶点序列中最长的边长作为有效边长,
再找出所有顶点序列中有效边长最小的序列,并按题目所给格式输出

题解: 用邻接矩阵存储各个顶点是否相连;
再用字符串保存出现过的顶点;全排列字符串找出答案

*/

#include<stdio.h>
#include<string.h>
#include<algorithm>

using namespace std;

char str[500];
int book[100];
int mp[100][100];
int num[100];
int chr[100];

int main()
{

    while(scanf("%s",str))
    {
        if(strcmp(str,"#") == 0)
            break;

        memset(book,0,sizeof(book));
        memset(mp,0,sizeof(mp));
        memset(chr,0,sizeof(chr));


// 找出并存储邻接矩阵

       int flag  = 0;
        int ans;
        for(int i=0; i<strlen(str); i++)
        {
            if(flag == 0 && str[i] >= 'A' && str[i] <= 'Z')
                ans = str[i] - 'A' + 1;

            else if(flag == 1 && str[i] >= 'A' && str[i] <= 'Z')
                mp[ans][str[i]-'A'+1] = mp[str[i]-'A'+1][ans] = abs(ans-(str[i]-'A'+1));

            else if(str[i] == ':')
                flag = 1;

            else if(str[i] == ';')
                flag = 0;
        }

// 用字符串存储顶点

        int coun = 0;
        for(int i=0; i<strlen(str); i++)
            if(book[str[i] - 'A' +1] == 0 && str[i] >= 'A' && str[i] <= 'Z' )
            {
                book[str[i] - 'A' +1] = 1;
                chr[coun++] = str[i] -'A'+1;
            }

        sort(chr,chr+coun);

//  全排列
        int minn = 0x3f3f3f;
        int maxn;
        do
        {
            maxn = 0;
            for(int i=0; i<coun; i++)
            {
               for(int j=i+1; j<coun; j++)
               {
                   if(mp[chr[i]][chr[j]])
                   {
                       maxn = max(maxn,abs(i-j)); 
                   }
               }
            }
            if(minn > maxn)
            {
                minn = maxn;
                for(int i=0; i<coun; i++)
                    num[i] = chr[i];
            }
        }while(next_permutation(chr,chr+coun));

        for(int i=0; i<coun; i++)
            printf("%c ",num[i]-1+'A');
        printf("-> %d\n",minn);

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值