Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
Dinic求解释···TL了一个晚上。麻烦大神们指点下#include <algorithm> #include <iostream> using namespace std; #define MAX 20000 #define INF 9999999999999999 #define min(a,b) (a<b?a:b) struct Edge { int st, ed; __int64 flow; int next; } edge[MAX*3]; int head[MAX], out[MAX]; int stk[MAX], que[MAX]; int leve[MAX]; bool vis[MAX]; int E, src, sink; inline void add_edge ( int u, int v, __int64 flw ) { edge[E].st = u; edge[E].ed = v; edge[E].flow = flw; edge[E].next = head[u]; head[u] = E++; edge[E].ed = v; edge[E].st = u; edge[E].flow = 0; edge[E].next = head[v]; head[v] = E++; } __int64 Dinic() { __int64 maxFlow = 0; int front, rear, top; int cur, u, i; while ( 1 ) { memset(leve,-1,sizeof(leve)); front = rear = leve[src] = 0; que[rear++] = src; while ( front != ( rear + 1 ) % MAX ) { u = que[front]; front = ( front + 1 ) % MAX; for ( i = head[u]; i != -1; i = edge[i].next) { if ( edge[i].flow && leve[edge[i].ed] == -1 ) { leve[edge[i].ed] = leve[u] + 1; que[rear]= edge[i].ed; rear = ( rear + 1 ) % MAX; } } } if ( leve[sink] == -1 ) break; for ( i = src; i <= sink; i++ ) out[i] = head[i]; top = 0; while ( 1 ) { if ( top == 0 ) { for ( cur = out[src]; cur != -1; cur = edge[cur].next ) if ( edge[cur].flow && out[edge[cur].ed] != -1 && leve[edge[cur].ed] == 1 ) break; if ( cur < 0 ) break; stk[top++] = cur; out[src] = edge[cur].next; } u = edge[stk[top-1]].ed; if ( u == sink ) { __int64 dd = INF; int index = -1; for ( i = top - 1; i >= 0; i-- ) { if ( dd >= edge[stk[i]].flow ) { dd = edge[stk[i]].flow; index = i; } } maxFlow += dd; for ( i = 0; i < top; i++ ) { edge[stk[i]].flow -= dd; edge[stk[i]^1].flow += dd; } top = index; } else { for( cur = out[u]; cur != -1; cur = edge[cur].next ) if ( edge[cur].flow && out[edge[cur].ed] != -1 && leve[u] + 1 == leve[edge[cur].ed] ) break; if ( cur != -1 ) { stk[top++] = cur; out[u] = edge[cur].next; } else { out[u] = -1; top--; } } } } return maxFlow; } int dfs ( int u ) { vis[u] = true; int v, i, cnt = 1; for ( i = head[u]; i != -1; i = edge[i].next ) { v = edge[i].ed; if ( ! vis[v] && edge[i].flow > 0 ) cnt += dfs(v); } return cnt; } int main() { __int64 sum = 0; int n, m, u, v, b; scanf("%d%d",&n,&m); E = src = 0; sink = n + 1; memset(head,-1,sizeof(head)); for ( int i = 1; i <= n; i++ ) { scanf("%d",&b); if ( b > 0 ) { sum += b; add_edge ( src, i, b ); } else add_edge ( i, sink, -b ); } while ( m-- ) { scanf("%d%d",&u,&v); add_edge ( u, v, INF ); } memset(vis,0,sizeof(vis)); __int64 maxFlow = Dinic(); int cnt = dfs ( src ) - 1; printf("%d %I64d\n", cnt, sum - maxFlow); return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator