POJ-1222EXTENDED LIGHTS OUT-位运算枚举模板

传送门:http://poj.org/problem?id=1222

题意:开关灯问题,一幅开关的灯中,给出一种操作,使得灯全关掉,(操作一个开关,相邻的灯也会改变)

思路:利用位运算枚举第一行;

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;

char orilights[10],lights[10],ans[10];

int GetBit(char c, int i)
{
    return (c>>i) & 1;
}
void SetBit(char &c,int i,int v)
{
    if(v)
    {
        c |= (1<<i);
    }
    else 
    {
        c &= ~(1<<i);
    }
}
void FlipBit(char &c, int i)
{
    c ^= (1 << i);
}
void Output(int t)
{
    cout<<"PUZZLE #"<<t<<endl;
    for(int i=0; i<5; ++i)
    {
        for(int j=0; j<6; ++j)
        {
            cout<< GetBit(ans[i],j);
            if(j<5)cout<<" ";
        }
        cout<<endl;

    }
}
int main(){
    int T;
    cin>>T;
    for(int t = 1; t<=T; t++)
    {
        for(int i=0; i < 5; ++i)
        {
            for(int j = 0; j < 6; ++j)
            {
                int s;
                cin>>s;
                SetBit(orilights[i], j, s);
            }
        }
        //cout<<1<<endl;
        for(int n=0; n<64; ++n)
        {
            int switchs = n;
            memcpy(lights,orilights,sizeof(orilights));
            for(int i=0; i < 5; ++i)
            {
                ans[i] = switchs;
                for(int j = 0;j < 6; ++j)
                {
                    if(GetBit(switchs,j))
                    {
                        if(j>0)FlipBit(lights[i],j-1);
                        FlipBit(lights[i],j);
                        if(j<5)FlipBit(lights[i],j+1);
                    }
                }
                if(i<4)lights[i+1] ^= switchs;
                switchs = lights[i];
            }
            if(lights[4]==0)
            {
                Output(t);
                break;
            }

        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/ckxkexing/p/8933023.html