您的位置:首页 > 其它

高斯消元

2013-01-17 18:36 106 查看
hdu 3949 XOR http://acm.hdu.edu.cn/showproblem.php?pid=3949    2013-1-18

给n个数,由这些数异或得到新的数,求第k小的数

把所有数看做一个向量空间,先求出向量空间的一个基

矩阵中mt(r,c)=a[r]>>(m-1-c) 化为约化阶梯矩阵

View Code

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

const int N=110;
int mt

,a
;
int gauss(int n,int m)
{
for(int r=0,c=0;r<n && c<m;r++,c++)
{
int p=r;
while(p<n && mt[p][c]==0) p++;
if(p==n) {r--; continue;}
if(p!=r) for(int i=c;i<=m;i++)
swap(mt[p][i],mt[r][i]);
for(int i=r+1;i<n;i++) if(mt[i][c]!=0)
{
for(int j=c;j<=m;j++) mt[i][j]^=mt[r][j];
}
}
for(int i=0;i<n;i++) if(mt[i][i]==0)
{
int p=i+1;
while(p<n && mt[i][p]==0) p++;
if(p==n)
{
for(int j=i;j<n;j++)
if(mt[j]
!=0) return n+1;
return i;
}
for(int j=0;j<n;j++) swap(mt[j][i],mt[j][p]);
}
return n;
}
int main()
{
//freopen("in.txt","r",stdin);
int T;
scanf("%d",&T);
while(T--)
{
int n,d;
scanf("%d%d",&n,&d);
memset(mt,0,sizeof(mt));
for(int i=0;i<n;i++) scanf("%d",&mt[i]
);
for(int i=0;i<n;i++)
for(int j=i-d>=0?i-d:0;j<=i+d && j<n;j++) mt[i][j]=1;
int r=gauss(n,n);
if(r>n) {printf("impossible\n"); continue;}
int ans=n;
for(int x=0;x<(1<<(n-r));x++)
{
for(int i=0;i<n-r;i++) a[r+i]=(x>>i)&1;
for(int i=r-1;i>=0;i--)
{
a[i]=mt[i]
;
for(int j=i+1;j<n;j++)
if(mt[i][j]) a[i]^=a[j];
}
int c=0;
for(int i=0;i<n;i++) c+=a[i];
ans=min(ans,c);
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: