当前位置: 代码迷 >> 综合 >> POJ 3686 The Windy's(拆点、最小权匹配)
  详细解决方案

POJ 3686 The Windy's(拆点、最小权匹配)

热度:19   发布时间:2023-12-08 10:49:53.0

题目链接:
POJ 3686 The Windy’s
题意:
有m个作坊和n件物品,给出每件商品在每个作坊加工完成的时间,求出加工完n件商品的最少平均时间。每件商品只能在一个作坊完成,每个作坊同一时间只能加工一件商品,每件商品的完成时间需要加上它的等待时间。
分析:
假设一个作坊最终加工k件商品,加工顺序依次是从1到k,则在该作坊加工的商品的总耗时是:

cost[1] + (cost[1] + cost[2]) + (cost[1] + cost[2] + cost[3]) + .. +
(cost[1] + … + cost)

则第i个商品对总耗时的贡献是:

cost[i] * ( k - i + 1)

那么倒数第i个商品对总耗时的贡献是:

cost[i] * i

需要将m个作坊拆成n * m个作坊,用w[i][j * n + p]表示第i个商品在第j个作坊倒数第p个加工完成的权值(对总耗时的贡献)。剩下的就是常规的将最小权匹配转换成最大权匹配做法。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <climits>
#include <cmath>
#include <string>
#include <iomanip>
using namespace std;
const int MAX_N = 55;
const int MAX_M = 2600;
int T, n, m;
int lx[MAX_N], ly[MAX_M], match[MAX_M], visx[MAX_N], visy[MAX_M];
int w[MAX_N][MAX_M], slack[MAX_M]; inline bool dfs(int x)
{visx[x] = 1;for(int y = 0; y < m; y++){if(visy[y]) continue;int tmp = lx[x] + ly[y] - w[x][y];if(tmp == 0){visy[y] = 1;if(match[y] == -1 || dfs(match[y])){match[y] = x;return true;}}else {slack[y] = min(slack[y], tmp);}}return false;
}inline int KM()
{memset(match, -1, sizeof(match));memset(ly, 0, sizeof(ly));for(int i = 0; i < n; i++){lx[i] = INT_MIN;for(int j = 0; j < m; j++){lx[i] = max(lx[i], w[i][j]);} }for(int i = 0; i < n; i++){for(int j = 0; j < m; j++) { slack[j] = INT_MAX; }while(1){memset(visx, 0, sizeof(visx));memset(visy, 0, sizeof(visy));if(dfs(i)) break;int d = INT_MAX;for(int j = 0; j < m; j++){if(!visy[j]) d = min(d, slack[j]);}for(int j = 0; j < n; j++) { if(visx[j]) lx[j] -= d; }for(int j = 0; j < m; j++) {if(visy[j]) ly[j] += d;else slack[j] -= d;}}}int res = 0;for(int i = 0; i < m; i++){if(match[i] != -1) {res += w[match[i]][i];//cout << "(" << match[i] << "," << i << ")" << ":" << w[match[i]][i] << endl;}}return res;
}int main()
{ios_base::sync_with_stdio(0);cin.tie(0);cin >> T;while(T-- > 0 ){cin >> n >> m;for(int i = 0; i < n; i++){for(int j = 0; j < m; j++){int tmp;cin >> tmp;for(int k = 0; k < n; k++){w[i][j * n + k] = - (k + 1) * tmp;}}}m = n * m;double res = -1.0 * KM() / n;cout << fixed << setprecision(6) << res << endl;}return 0;
}