标签:
题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1927
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstring> 5 #include <queue> 6 #define rep(i,l,r) for(int i=l; i<=r; i++) 7 #define clr(x,y) memset(x,y,sizeof(x)) 8 #define travel(x) for(Edge *p=last[x]; p; p=p->pre) 9 using namespace std; 10 const int INF = 0x3f3f3f3f; 11 const int maxn = 1610; 12 inline int read(){ 13 int ans = 0, f = 1; 14 char c = getchar(); 15 for(; !isdigit(c); c = getchar()) 16 if (c == ‘-‘) f = -1; 17 for(; isdigit(c); c = getchar()) 18 ans = ans * 10 + c - ‘0‘; 19 return ans * f; 20 } 21 struct Edge{ 22 Edge *pre,*rev; int to,cap,cost; 23 }edge[100010],*last[maxn],*cur[maxn],*pt; 24 int n,m,x,y,z,S,T,cost,d[maxn]; 25 bool isin[maxn],vis[maxn]; 26 queue <int> q; 27 inline void add(int x,int y,int z,int w){ 28 pt->pre = last[x]; pt->to = y; pt->cap = z; pt->cost = w; last[x] = pt++; 29 pt->pre = last[y]; pt->to = x; pt->cap = 0; pt->cost = -w; last[y] = pt++; 30 last[x]->rev = last[y]; last[y]->rev = last[x]; 31 } 32 bool spfa(){ 33 clr(d,INF); d[S] = 0; 34 clr(isin,0); isin[S] = 1; q.push(S); 35 while (!q.empty()){ 36 int now = q.front(); q.pop(); isin[now] = 0; 37 travel(now){ 38 if (p->cap > 0 && d[p->to] > d[now] + p->cost){ 39 d[p->to] = d[now] + p->cost; 40 if (!isin[p->to]) isin[p->to] = 1, q.push(p->to); 41 } 42 } 43 } 44 return d[T] != INF; 45 } 46 int dfs(int x,int flow){ 47 if (x == T || !flow) return flow; vis[x] = 1; int w = 0; 48 for(Edge *p = cur[x]; p && w < flow; p = p->pre){ 49 if (p->cap > 0 && d[p->to] == d[x] + p->cost && (!vis[p->to])){ 50 int delta = dfs(p->to,min(p->cap,flow-w)); 51 p->cap -= delta; p->rev->cap += delta; w += delta; 52 cost += delta * p->cost; 53 if (p->cap) cur[x] = p; 54 } 55 } 56 return w; 57 } 58 void mincost(){ 59 while(spfa()){ 60 rep(i,S,T) vis[i] = 0, cur[i] = last[i]; 61 dfs(S,INF); 62 } 63 } 64 int main(){ 65 n = read(); m = read(); 66 clr(last,0); pt = edge; S = 0; T = n << 1 | 1; 67 rep(i,1,n){ 68 x = read(); 69 add(S,i+n,1,x); add(i+n,T,1,0); add(S,i,1,0); 70 } 71 rep(i,1,m){ 72 x = read(); y = read(); z = read(); 73 if (x > y) swap(x,y); 74 add(x,y+n,1,z); 75 } 76 mincost(); 77 printf("%d\n",cost); 78 return 0; 79 }
标签:
原文地址:http://www.cnblogs.com/jimzeng/p/bzoj1927.html