标签:
2 10 3 5 10 3 10 3 3 2 5 3 6 7 10 5 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9
28 46 80
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int INF = 0x3f3f3f3f; 4 const int maxn = 601*602*2; 5 struct arc { 6 int to,flow,cost,next; 7 arc(int x = 0,int y = 0,int z = 0,int nxt = -1) { 8 to = x; 9 flow = y; 10 cost = z; 11 next = nxt; 12 } 13 } e[3000010]; 14 int head[maxn],d[maxn],p[maxn],tot,S,T; 15 bool in[maxn]; 16 void add(int u,int v,int flow,int cost) { 17 e[tot] = arc(v,flow,cost,head[u]); 18 head[u] = tot++; 19 e[tot] = arc(u,0,-cost,head[v]); 20 head[v] = tot++; 21 } 22 bool spfa() { 23 memset(in,false,sizeof in); 24 memset(d,-1,sizeof d); 25 memset(p,-1,sizeof p); 26 queue<int>q; 27 d[S] = 0; 28 q.push(S); 29 while(!q.empty()) { 30 int u = q.front(); 31 q.pop(); 32 in[u] = false; 33 for(int i = head[u]; ~i; i = e[i].next) { 34 if(e[i].flow && d[e[i].to] < d[u] + e[i].cost) { 35 d[e[i].to] = d[u] + e[i].cost; 36 p[e[i].to] = i; 37 if(!in[e[i].to]) { 38 in[e[i].to] = true; 39 q.push(e[i].to); 40 } 41 } 42 } 43 } 44 return p[T] > -1; 45 } 46 int solve(int ret = 0) { 47 while(spfa()) { 48 int mh = 1; 49 //for(int i = p[T]; ~i; i = p[e[i^1].to]) 50 //mh = min(mh,e[i].flow); 51 for(int i = p[T]; ~i; i = p[e[i^1].to]) { 52 e[i].flow -= mh; 53 e[i^1].flow += mh; 54 } 55 ret += mh*d[T]; 56 } 57 return ret; 58 } 59 int main() { 60 int n; 61 while(~scanf("%d",&n)) { 62 memset(head,-1,sizeof head); 63 int ret = tot = 0; 64 for(int i = 1; i <= n; ++i) 65 for(int j = 1,val; j <= n; ++j) { 66 scanf("%d",&val); 67 int u = (i-1)*n + j,v = u + n*n; 68 if(u == 1 || u == n*n) { 69 add(u,v,2,val); 70 ret -= val; 71 } else add(u,v,1,val); 72 if(i < n) add(v,u + n,1,0); 73 if(j < n) add(v,u + 1,1,0); 74 } 75 S = 1; 76 T = 2*n*n; 77 printf("%d\n",solve() + ret); 78 } 79 return 0; 80 }
标签:
原文地址:http://www.cnblogs.com/crackpotisback/p/4945129.html