Bandwidth UVA - 140(全排列剪纸)

本文介绍了一种通过枚举所有可能的排列来寻找最优解的方法。该算法利用C++实现,通过对给定字符集进行全排列,并针对每个排列计算特定的最大值,最终找到使该最大值最小化的排列方案。

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

枚举所有的排列如果当前的最大值大于最大值就continue

#include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#include <algorithm>
#include <cstring>

using namespace std;
#define INF 0x3f3f3f3f

char str[200];
vector<char> vt[200],ans;
set<char> st;

int main()
{
    while(scanf("%s",str)&&str[0]!='#')
    {
        for(int i=0;i<200;i++)
            vt[i].clear();
        st.clear();
        char a;
        char str1[200];
        
        for(int i=0;i<strlen(str);i++)
        {
            a=str[i];
            st.insert(a);
            int j;
            for(j=i+2;j<strlen(str);j++)
            {
                if(str[j]==';')
                    break;
                vt[a-'A'].push_back(str[j]);
                st.insert(str[j]);
                vt[str[j]-'A'].push_back(a);
            }
            i=j;
        }
        int cont=0;
        for(auto i=st.begin();i!=st.end();i++)
            str1[cont++]=*i;
        int max1=INF;
        do
        {
            int len[200];
            memset(len,0,sizeof(len));
            for(int i=0;i<cont;i++)
                len[str1[i]-'A']=i;
            int max2=-1;
            for(int i=0;i<cont;i++)
            {
                for(int j=0;j<vt[str1[i]-'A'].size();j++)
                {
                    int k=abs(len[vt[str1[i]-'A'][j]-'A']-len[str1[i]-'A']);
                    max2=max(max2,k);
                    if(max2>max1)
                        break;
                }
            }
            if(max2>=max1)
                continue;
            else
            {
                ans.clear();
                for(int i=0;i<cont;i++)
                    ans.push_back(str1[i]);
                max1=max2;
            }
            
        } while (next_permutation(str1,str1+cont));
        for(int i=0;i<ans.size();i++)
            printf("%c ",ans[i]);
        printf("-> ");
        printf("%d\n",max1);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值