bzoj千题计划187:bzoj1770: [Usaco2009 Nov]lights 燈 (高斯消元解异或方程组+枚举自由元)

http://www.lydsy.com/JudgeOnline/problem.php?id=1770

a[i][j] 表示i对j有影响

高斯消元解异或方程组

然后dfs枚举自由元确定最优解

#include<cstdio>
#include<algorithm>

using namespace std;

#define N 36

int n;

bool a[N][N];
bool x[N];

int ans=1e9;

void gauss()
{
    int j;
    for(int i=0;i<n;++i)
    {
        int j=i;
        while(j<n && !a[j][i]) ++j;
        if(j==n) continue;
        swap(a[j],a[i]);
        for(int k=i+1;k<n;++k)
            if(a[k][i]) 
                for(int l=i;l<=n;++l) a[k][l]^=a[i][l];
    }
}

void dfs(int now,int tot)
{
    if(tot>ans) return;
    if(now<0) { ans=min(tot,ans); return; }
    if(a[now][now])
    {
        x[now]=a[now][n];
        for(int j=n-1;j>now;--j) x[now]^=x[j]&a[now][j];
        if(x[now]) dfs(now-1,tot+1);
        else dfs(now-1,tot);
    }
    else
    {
        x[now]=false;
        dfs(now-1,tot);
        x[now]=true;
        dfs(now-1,tot+1);
    }
}

int main()
{
    int m;
    scanf("%d%d",&n,&m);
    int x,y;
    for(int i=1;i<=m;++i)
    {
        scanf("%d%d",&x,&y);
        x--; y--;
        a[x][y]=a[y][x]=true;
    }
    for(int i=0;i<n;++i) a[i][i]=a[i][n]=true;
    gauss();
    dfs(n-1,0);
    printf("%d",ans);
}
原文地址:https://www.cnblogs.com/TheRoadToTheGold/p/8184974.html