POJ 3686 The Windy's 最小费用最大流
每个工厂拆成N个工厂,费用分别为1~N倍原费用。
//#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<iostream> #include<sstream> #include<cmath> #include<climits> #include<string> #include<map> #include<queue> #include<vector> #include<stack> #include<set> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; #define pb(a) push(a) #define INF 0x1f1f1f1f #define lson idx<<1,l,mid #define rson idx<<1|1,mid+1,r #define PI 3.1415926535898 template<class T> T min(const T& a,const T& b,const T& c) { return min(min(a,b),min(a,c)); } template<class T> T max(const T& a,const T& b,const T& c) { return max(max(a,b),max(a,c)); } void debug() { #ifdef ONLINE_JUDGE #else freopen("in.txt","r",stdin); // freopen("d:\\out1.txt","w",stdout); #endif } int getch() { int ch; while((ch=getchar())!=EOF) { if(ch!=' '&&ch!='\n')return ch; } return EOF; } const int maxn = 55; int N, M; int cost[maxn][maxn]; void Input() { scanf("%d%d", &N, &M); for(int i = 1; i <= N; i++) for(int j = 1; j <= M; j++) scanf("%d", &cost[i][j]); } struct Edge { int from, to, cost, cap; }; const int maxv = maxn * maxn + maxn; vector<int> g[maxv]; vector<Edge> edge; int n,s,t; void add(int from, int to, int cost, int cap) { edge.push_back((Edge){from, to, cost, cap}); g[from].push_back(edge.size() - 1); edge.push_back((Edge){to, from, -cost, 0}); g[to].push_back(edge.size() - 1); } void init() { for(int i = 1; i <= n; i++) g[i].clear(); edge.clear(); } void construct() { n = N + N * M + 2; s = n - 1; t = n; init(); for(int i = 1; i <= N; i++) add(s, i, 0, 1); for(int k = 1; k <= N; k++) { for(int j = 1; j <= M; j++) { int id = N + (k - 1) * M + j; add(id, t, 0, 1); for(int i = 1; i <= N; i++) add(i, id, k * cost[i][j], 1); } } } int d[maxv]; int inq[maxv]; int road[maxv]; int SPFA() { memset(d, INF, sizeof(d)); memset(inq, 0, sizeof(inq)); queue<int> q; q.push(s); d[s] = 0; road[s] = -1; while(!q.empty()) { int u = q.front(); q.pop(); inq[u] = false; for(int i = 0; i < g[u].size(); i++) { Edge &e = edge[g[u][i]]; if(e.cap > 0 && d[u] + e.cost < d[e.to]) { d[e.to] = d[u] + e.cost; road[e.to] = g[u][i]; if(!inq[e.to]) { inq[e.to] = true; q.push(e.to); } } } } return d[t] != INF; } int MCMF() { int cost = 0; while(SPFA()) { cost += d[t]; for(int e = road[t]; e != -1; e = road[edge[e].from]) { edge[e].cap -= 1; edge[e^1].cap += 1; } } return cost; } int main() { debug(); int t; scanf("%d", &t); for(int ca = 1; ca <= t; ca++) { Input(); construct(); printf("%.6f\n", MCMF() * 1.0 / N); } return 0; }