There is a kind of special fish in the East Lake where is closed to campus of Wuhan University. It’s hard to say which gender of those fish are, because every fish believes itself as a male, and it may attack one of some other fish who is believed to be female by it.
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.
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
最大费用流模板,但是可以不是最大流,只要求费用最大的可能,所以if(d[t]==inf||(d[t]>=0) return res;
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 1e6+10;
const int M = 1000;
int head[M], cnt;
struct node
{
int from, to, cap, cost, next;
}p[N];
void add(int u,int v,int w,int z)
{
p[cnt].from=u, p[cnt].to=v, p[cnt].cap=w, p[cnt].cost=z, p[cnt].next=head[u], head[u]=cnt++;
p[cnt].from=v, p[cnt].to=u, p[cnt].cap=0, p[cnt].cost=-z, p[cnt].next=head[v], head[v]=cnt++;
return ;
}
int d[M], pre[M], vis[M];
const int inf = 1<<30;
int min_cost_flow(int s,int t,int f)
{
int res=0;
while(f>0)
{
queue<int>q;
q.push(s);
for(int i=0;i<=t;i++) d[i]=inf;
memset(pre,-1,sizeof(pre));
memset(vis,0,sizeof(vis));
vis[s]=1, d[s]=0;
while(!q.empty())
{
int u=q.front();q.pop();
for(int i=head[u];i!=-1;i=p[i].next)
{
int v=p[i].to;
if(d[v]>d[u]+p[i].cost&&p[i].cap>0)
{
d[v]=d[u]+p[i].cost;
pre[v]=i;
if(!vis[v])
{
q.push(v);
vis[v]=1;
}
}
}
vis[u]=0;
}
if(d[t]==inf) return res;
if(d[t]>=0) return res;
int flow=f;
for(int i=pre[t];i!=-1;i=pre[p[i].from])
{
flow=min(flow,p[i].cap);
}
res+=flow*d[t];
for(int i=pre[t];i!=-1;i=pre[p[i].from])
{
p[i].cap-=flow, p[1^i].cap+=flow;
}
f-=flow;
}
return res;
}
int v[N];
int main()
{
int n;
while(scanf("%d", &n)!=EOF&&n!=0)
{
memset(head,-1,sizeof(head));
cnt=0;
int s=0, t=2*n+10;
for(int i=1;i<=n;i++)
{
scanf("%d", &v[i]);
add(s,i,1,0);
add(n+i,t,1,0);
}
int x;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%1d",&x);
if(i==j) continue;
if(x==1)
add(i,n+j,1,-(v[i]^v[j]));
}
}
printf("%d\n",-min_cost_flow(s,t,n));
}
return 0;
}