UVA 11205

来源:互联网 发布:网络监控布线 编辑:程序博客网 时间:2024/05/29 07:38

第一次做到这么暴力的题,我看题的时候被吓到了。。。除了枚举想不出别的算法了,但是枚举好像效率很低,但是算一算就知道15个灯泡有2^15种组合方式,枚举量也就3W左右,每次需要判断100+99+……+1次,数量级是10^3,总的算下来一次数据是10^7,这样的效率应该也够了,看了下别人的写法也是直接暴力。。。。代码附上

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
string LEDS[101];
string temp[101];
bool cut[20];
int N,P,n;
bool check()///判断是否有重复
{
    for(int i=0; i<n; i++)
        for(int k=i+1; k<n; k++)
        {
            if(temp[i]==temp[k])
                return false;
        }
    return true;
}
int get(int cc)///获得子集的01序列
{
    int cont=0;
    for(int i=0; i<P; i++)
    {
        if(cc&(1<<i))
        {
            cut[i]=1;cont++;
        }
        else
            cut[i]=0;
    }
    return cont;
}
void cuts()///根据序列制造子集
{
    for(int i=0; i<n; i++)
        for(int k=0; k<P; k++)
        {
            if(cut[k])
            {
                temp[i].push_back(LEDS[i][k*2]);
            }
        }
}
void clr()
{
    for(int i=0; i<100; i++)
        temp[i].clear();
}
int main()
{
    cin>>N;
    while(N>0)
    {
        N--;
        cin>>P>>n;
        getline(cin,LEDS[0]);
        for(int i=0; i<n; i++)
            getline(cin,LEDS[i]);
        int mm=P,C=0,nums=pow(2,P)-1;
        while(C<nums)
        {
            clr();
            C++;
            int t=get(C);
            cuts();
            if(check()&&t<mm)///搞好多函数可以把main变得很短,而且易于分功能测试,看着比较清晰,虽然代码长度会增加(毕竟多好多括号占行数),但是我越来越倾向这种写法了,这次的程序也是一次过,基本没怎么调试
                mm=t;
        }
        cout<<mm<<endl;
    }
    return 0;
}

0 0