Special Fish
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2174 Accepted Submission(s): 822
A fish will spawn after it has been attacked. Each fish can attack one other fish and can only be attacked once. No matter a fish is attacked or not, it can still try to attack another fish which is believed to be female by it.
There is a value we assigned to each fish and the spawns that two fish spawned also have a value which can be calculated by XOR operator through the value of its parents.
We want to know the maximum possibility of the sum of the spawns.
The last test case is followed by a zero, which means the end of the input.
3 1 2 3 011 101 110 0
6
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 201;
int lx[N], ly[N], visx[N], visy[N], match[N], wight[N][N], slack[N], val[N];
int dfs(int x);
int n;
const int inf = 0x3f3f3f3f;
void km();
int main()
{
while(scanf("%d", &n)!=EOF&&n!=0)
{
for(int i=1;i<=n;i++)
{
scanf("%d",&val[i]);
}
memset(wight,0,sizeof(wight));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
int v;
scanf("%1d", &v);
if(v==1)
{
wight[i][j]=val[i]^val[j];
}
}
}
memset(match,-1,sizeof(match));
km();
}
return 0;
}
void km()
{
memset(ly,0,sizeof(ly));
for(int i=1;i<=n;i++)
{
lx[i]= -inf;
for(int j=1;j<=n;j++)
{
lx[i]=max(wight[i][j],lx[i]);
}
}
for(int i=1;i<=n;i++)
{
memset(slack,0x3f3f,sizeof(slack));
while(1)
{
memset(visx,0,sizeof(visx));
memset(visy,0,sizeof(visy));
if(dfs(i))
{
break;
}
else
{
int tmp=inf;
for(int j=1;j<=n;j++)
{
if(!visy[j])
{
tmp=min(tmp,slack[j]);
}
}
for(int j=1;j<=n;j++)
{
if(visx[j])
{
lx[j]-=tmp;
}
if(visy[j])
{
ly[j]+=tmp;
}
else
{
slack[j]-=tmp;
}
}
}
}
}
int sum=0;
for(int i=1;i<=n;i++)
{
if(match[i]==-1||wight[match[i]][i]==0)
{
continue;
}
sum+=wight[match[i]][i];
}
printf("%d\n",sum);
}
int dfs(int x)
{
visx[x]=1;
for(int i=1;i<=n;i++)
{
if(visy[i])
{
continue;
}
if(lx[x]+ly[i]==wight[x][i])
{
visy[i]=1;
if(match[i]==-1||dfs(match[i]))
{
match[i]=x;
return 1;
}
}
else
{
slack[i]=min(slack[i],lx[x]+ly[i]-wight[x][i]);
}
}
return 0;
}