# BZOJ 3168 Heoi2013 钙铁锌硒维生素 矩阵求逆+匈牙利算法

Ci,j0表示Bi的线性表出须要Aj，因此CT就是这个二分图的邻接矩阵

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define M 330
#define MOD 999911657
using namespace std;
int n;
bool state[M];
int result[M];
long long Quick_Power(long long x,int y)
{
long long re=1;
while(y)
{
if(y&1) (re*=x)%=MOD;
(x*=x)%=MOD; y>>=1;
}
return re;
}
struct Matrix{
int a[M][M];
Matrix() {}
Matrix(bool flag)
{
int i;
memset(a,0,sizeof a);
for(i=1;i<=n;i++)
a[i][i]=flag;
}
int* operator [] (int x)
{
return a[x];
}
friend istream& operator >> (istream &_,Matrix &a)
{
int i,j;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
return _;
}
friend Matrix operator * (Matrix x,Matrix y)
{
Matrix z(false);
int i,j,k;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
for(k=1;k<=n;k++)
(z[i][j]+=(long long)x[i][k]*y[k][j]%MOD)%=MOD;
return z;
}
friend Matrix Get_Inv(Matrix a)
{
Matrix re(true);
int i,j,k;
for(i=1;i<=n;i++)
{
for(k=i;k<=n;k++)
if(a[k][i])
break;
for(j=1;j<=n;j++)
{
swap(a[i][j],a[k][j]);
swap(re[i][j],re[k][j]);
}
long long inv=Quick_Power(a[i][i],MOD-2);
for(j=1;j<=n;j++)
{
a[i][j]=a[i][j]*inv%MOD;
re[i][j]=re[i][j]*inv%MOD;
}
for(k=1;k<=n;k++)
if(k!=i)
{
long long temp=(MOD-a[k][i])%MOD;
for(j=1;j<=n;j++)
{
(a[k][j]+=a[i][j]*temp%MOD)%=MOD;
(re[k][j]+=re[i][j]*temp%MOD)%=MOD;
}
}
}
return re;
}
}A,B,C,f;
bool DFS1(int x)
{
int i;
for(i=1;i<=n;i++)
if(f[x][i]&&!state[i])
{
state[i]=true;
if( !result[i] || DFS1(result[i]) )
{
result[i]=x;
return true;
}
}
return false;
}
bool DFS2(int x,int from)
{
int i;
for(i=1;i<=n;i++)
if(f[x][i]&&!state[i])
{
state[i]=true;
if( result[i]==from || result[i]>from && DFS2(result[i],from) )
{
result[i]=x;
return true;
}
}
return false;
}
int main()
{
int i,j;
cin>>n>>A>>B;
C=B*Get_Inv(A);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
f[i][j]=(bool)C[j][i];
for(i=1;i<=n;i++)
{
memset(state,0,sizeof state);
if( !DFS1(i) )
return puts("NIE"),0;
}
puts("TAK");
for(i=1;i<=n;i++)
{
memset(state,0,sizeof state);
DFS2(i,i);
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(result[j]==i)
printf("%d\n",j);
return 0;
}
posted @ 2016-04-09 09:33  mengfanrong  阅读(371)  评论(0编辑  收藏  举报