【HDOJ】2853 Assignment

时间:2021-04-23 14:46:58

最小费用最大流可解最优解。至于dif如何解,可以把w扩大100倍,如果mission编号和排列P相等则对w+1,然后建立网络流。
对结果取模100可以得到没有改变mission的company数目,用company数目减之可以得到dif.

 /* 2853 */
#include <iostream>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <deque>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <climits>
#include <cctype>
#include <cassert>
#include <functional>
#include <iterator>
#include <iomanip>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,1024000") #define sti set<int>
#define stpii set<pair<int, int> >
#define mpii map<int,int>
#define vi vector<int>
#define pii pair<int,int>
#define vpii vector<pair<int,int> >
#define rep(i, a, n) for (int i=a;i<n;++i)
#define per(i, a, n) for (int i=n-1;i>=a;--i)
#define clr clear
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define lson l, mid, rt<<1
#define rson mid+1, r, rt<<1|1 const int INF = 0x1f1f1f1f;
const int maxn = ;
const int maxv = maxn * ;
const int maxe = maxv * maxv * ;
int V[maxe], F[maxe], W[maxe], nxt[maxe];
int head[maxv], dis[maxv], pre[maxv], ID[maxv];
bool visit[maxv];
int M[maxn][maxn], P[maxn];
int s, t, m; void addEdge(int u, int v, int f, int w) {
V[m] = v;
F[m] = f;
W[m] = w;
nxt[m] = head[u];
head[u] = m++; V[m] = u;
F[m] = ;
W[m] = -w;
nxt[m] = head[v];
head[v] = m++;
} bool bfs() {
queue<int> Q;
int u, v, k; memset(dis, INF, sizeof(dis));
memset(visit, false, sizeof(visit));
Q.push(s);
dis[s] = ; while (!Q.empty()) {
u = Q.front();
Q.pop();
visit[u] = false;
for (k=head[u]; k!=-; k=nxt[k]) {
v = V[k];
if (F[k] && dis[v]>dis[u]+W[k]) {
dis[v] = dis[u] + W[k];
ID[v] = k;
pre[v] = u;
if (!visit[v]) {
visit[v] = true;
Q.push(v);
}
}
}
} return dis[t]==INF;
} int MCMF() {
int ret = , tmp;
int u, v, k; while () {
if (bfs())
break; tmp = INF;
for (v=t, u=pre[v]; v!=s; v=u, u=pre[v]) {
k = ID[v];
tmp = min(F[k], tmp);
} for (v=t, u=pre[v]; v!=s; v=u, u=pre[v]) {
k = ID[v];
F[k] -= tmp;
F[k^] += tmp;
} ret += dis[t] * tmp;
} return ret;
} int main() {
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif int r, c;
int ans, tot, tmp, dif; while (scanf("%d %d", &r, &c) != EOF) { s = m = ;
t = r + c + ;
memset(head, -, sizeof(head)); rep(i, , r+)
rep(j, , c+)
scanf("%d", &M[i][j]);
rep(i, , r+)
scanf("%d", &P[i]); rep(i, , r+)
addEdge(s, i, , ); rep(j, , c+)
addEdge(j+r, t, , ); tot = ;
rep(i, , r+) {
rep(j, , c+) {
if (j == P[i]) {
tmp = M[i][j] * + ;
} else {
tmp = M[i][j] * ;
}
addEdge(i, j+r, , -tmp);
}
tot += M[i][P[i]];
} tmp = -MCMF();
ans = tmp/ - tot;
#ifndef ONLINE_JUDGE
printf("tot = %d, MCMF = %d\n", tot, tmp);
#endif
dif = r - tmp%;
printf("%d %d\n", dif, ans);
} #ifndef ONLINE_JUDGE
printf("time = %d.\n", (int)clock());
#endif return ;
}