1. 程式人生 > >[poj 3436]最大流+輸出結果每條邊流量

[poj 3436]最大流+輸出結果每條邊流量

flag log ret ++ .org += space max set

題目鏈接:http://poj.org/problem?id=3436

大力套kuangbin板過了orz

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

const int MAXN = 210;
const int MAXM = 40010;
const int INF = 0x3f3f3f3f;
struct Edge
{
    int to,next,cap,flow;
} edge[MAXM];
int tol;
int head[MAXN];
int gap[MAXN],dep[MAXN],pre[MAXN],cur[MAXN];
void init() { tol = 0; memset(head,-1,sizeof(head)); } void addedge(int u,int v,int w,int rw=0) { edge[tol].to = v; edge[tol].cap = w; edge[tol].next = head[u]; edge[tol].flow = 0; head[u] = tol++; edge[tol].to = u; edge[tol].cap = rw; edge[tol].next = head[v]; edge[tol].flow
= 0; head[v]=tol++; } int sap(int start,int end,int N) { memset(gap,0,sizeof(gap)); memset(dep,0,sizeof(dep)); memcpy(cur,head,sizeof(head)); int u = start; pre[u] = -1; gap[0] = N; int ans = 0; while(dep[start] < N) { if(u == end) {
int Min = INF; for(int i = pre[u]; i != -1; i = pre[edge[i^1].to]) if(Min > edge[i].cap - edge[i].flow) Min = edge[i].cap - edge[i].flow; for(int i = pre[u]; i != -1; i = pre[edge[i^1].to]) { edge[i].flow += Min; edge[i^1].flow -= Min; } u = start; ans += Min; continue; } bool flag = false; int v; for(int i = cur[u]; i != -1; i = edge[i].next) { v = edge[i].to; if(edge[i].cap - edge[i].flow && dep[v]+1 == dep[u]) { flag = true; cur[u] = pre[v] = i; break; } } if(flag) { u = v; continue; } int Min = N; for(int i = head[u]; i != -1; i = edge[i].next) if(edge[i].cap - edge[i].flow && dep[edge[i].to] < Min) { Min = dep[edge[i].to]; cur[u] = i; } gap[dep[u]]--; if(!gap[dep[u]])return ans; dep[u] = Min+1; gap[dep[u]]++; if(u != start) u = edge[pre[u]^1].to; } return ans; } int P; bool jr(int out,int in) { for (int i=0; i<P; i++) { int tout=out%3; int tin=in%3; if (tout==0 && tin==1 || tout==1 && tin==0) return false; out/=3; in/=3; } return true; } int input[MAXN],output[MAXN]; int ef[MAXN]; int main() { init(); int n; scanf("%d%d",&P,&n); for (int i=0; i<n; i++) { scanf("%d",&ef[i]); int tout=0,tin=0; for (int j=0; j<P; j++) { int x; scanf("%d",&x); tin=tin*3+x; } for (int j=0; j<P; j++) { int x; scanf("%d",&x); tout=tout*3+x; } input[i]=tin; output[i]=tout; } output[n]=0; input[n+1]=0; for (int j=0; j<P; j++) input[n+1]=input[n+1]*3+1; for (int i=0;i<n;i++) addedge(i,i+n,ef[i]); for (int i=0; i<n; i++) for (int j=0; j<n; j++) { if (jr(output[i],input[j])) { addedge(i+n,j,ef[i]); } } for (int i=0; i<n; i++) if (jr(output[n],input[i])) addedge(n+n,i,INF); for (int i=0; i<n; i++) if (jr(output[i],input[n+1])) addedge(i+n,n+n+1,ef[i]); printf("%d ",sap(n+n,n+n+1,n+n+2)); int cnt=0; for (int i=0;i<n;i++) { for (int j=head[i+n];j!=-1;j=edge[j].next) { if (edge[j].flow>0 && edge[j].to>=0 && edge[j].to<n) cnt++; } } printf("%d\n",cnt); for (int i=0;i<n;i++) { for (int j=head[i+n];j!=-1;j=edge[j].next) { if (edge[j].flow>0 && edge[j].to>=0 && edge[j].to<n) printf("%d %d %d\n",i+1,edge[j].to+1,edge[j].flow); } } return 0; }

[poj 3436]最大流+輸出結果每條邊流量