poj 1149 最大流

时间:2024-05-14 22:06:32

题目链接:http://poj.org/problem?id=1149

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <queue>
#include <vector> #define maxn 1050
#define maxe 200000
using namespace std; const int INF = 0x3f3f3f; struct Edge{
int u,v,flow,cap;
int next;
Edge(int u=,int v=,int flow=,int cap=,int next=):
u(u),v(v),flow(flow),cap(cap),next(next) { }
}; struct Dinic{
int s,t;
int d[maxn];
int cur[maxn];
bool vis[maxn];
Edge edges[maxe];
int head[maxn],cnt; void init(){
memset(head,-,sizeof(head));
cnt = ;
} void addedge(int u,int v,int cap){
edges[cnt] = Edge(u,v,,cap,head[u]);
head[u] = cnt++;
edges[cnt] = Edge(v,u,,,head[v]);
head[v] = cnt++;
} bool bfs(){
memset(vis,,sizeof(vis));
queue<int> Q;
Q.push(s);
vis[s] = true;
d[s] = ;
while(!Q.empty()){
int u = Q.front(); Q.pop();
for(int i=head[u];i!=-;i=edges[i].next){
Edge& e = edges[i];
if(!vis[e.v] && e.cap > e.flow){
vis[e.v] = true;
d[e.v] = d[e.u] + ;
Q.push(e.v);
}
}
}
return vis[t];
} int dfs(int u,int res){
if(u == t || res == ) return res; //res 残流大小;
int flow = ,f;
for(int& i=cur[u];i!=-;i=edges[i].next){
Edge& e = edges[i];
if(d[e.v] == d[e.u] + && (f = dfs(e.v,min(res,e.cap-e.flow))) > ){
e.flow += f;
edges[i^].flow -= f;
flow += f;
res -= f;
if(res == ) break;
}
}
return flow;
} int MaxFlow(int s_,int t_){
s = s_; t = t_;
int flow = ;
while(bfs()){
for(int i=s;i<=t;i++) cur[i] = head[i];
flow += dfs(s,INF);
}
return flow;
}
}solver; int main()
{
//freopen("E:\\acm\\input.txt","r",stdin);
solver.init();
int N,M;
cin>>M>>N;
int s = , t = N+M+;
for(int i=;i<=M;i++){
int a;
scanf("%d",&a);
solver.addedge(s,i,a);
}
vector<int> G[];
for(int i=;i<=N;i++){
int a;
scanf("%d",&a);
for(int j=;j<=a;j++){
int temp;
scanf("%d",&temp);
solver.addedge(temp,M+i,INF);
for(int k=;k<i;k++){
bool flag = false;
for(int m=;m<G[k].size();m++)
if(G[k][m] == temp){
flag = true;
break;
}
if(flag) solver.addedge(M+k,M+i,INF);
}
G[i].push_back(temp);
}
int b;
scanf("%d",&b);
solver.addedge(M+i,t,b);
}
printf("%d\n",solver.MaxFlow(s,t));
}