2019-2020 ACM-ICPC Brazil Subregional Programming Contest G Getting Confidence
Getting Confidence
费用流
经典费用流模型,先建立 \(n * n\) 个点,来模拟一行,一行中的连接边流量为 \(1\),费用为 \(0\),源点连接每一行的第一个点
对上述生成的点中,同一列连接到一个新的点,流量为 \(1\),费用为 \(-a[i][j]\),然后该点连接一个流量为 \(1\),费用为 \(0\) 的点到汇点
这样构造之后,相当于跑一个最大费用最大流,可以保证如果选取了一行中的一个点,列也就只能选一个
因为是乘法,数字特别大,因此可以考虑变成 \(log\) 之后换成加法来跑
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <vector>
using namespace std;
typedef long long ll;
const int maxn = 2e5 + 10;
const int maxm = 2e5 + 10;
const double inf = 1e17;
const double eps = 1e-8;
int n, m, s, t, tp = 1;
int head[maxn], nex[maxm], to[maxm], cur[maxn], vis[maxn];
double dis[maxn], cost[maxm];
ll val[maxm];
inline int dcmp(double x)
{
return (x > eps) - (x < -eps);
}
void add(int u, int v, ll f, double c)
{
tp++;
nex[tp] = head[u];
head[u] = tp;
to[tp] = v;
cost[tp] = c;
val[tp] = f;
}
bool spfa()
{
for(int i=0; i<=t; i++) cur[i] = head[i];
for(int i=0; i<=t; i++) dis[i] = inf;
dis[s] = 0;
queue<int>q;
q.push(s);
while(q.size())
{
int u = q.front();
q.pop();
vis[u] = 0;
for(int i=head[u]; i; i=nex[i])
{
int v = to[i];
if(val[i] > 0 && dis[u] + cost[i] < dis[v])
{
dis[v] = dis[u] + cost[i];
if(vis[v] == 0)
{
vis[v] = 1;
q.push(v);
}
}
}
}
return dcmp(inf - dis[t]);
}
double c_ans = 0;
ll dfs(int now, ll flow)
{
if(now == t) return flow;
vis[now] = 1;
ll ans = 0;
for(int i=cur[now]; i && ans < flow; i=nex[i])
{
cur[now] = i;
int v = to[i];
if(vis[v] == 0 && val[i] > 0 && dis[v] == dis[now] + cost[i])
{
ll x = dfs(v, min(val[i], flow - ans));
c_ans += x * cost[i];
val[i] -= x;
val[i ^ 1] += x;
ans += x;
}
}
vis[now] = 0;
return ans;
}
ll mcmf()
{
ll ans = 0;
while(spfa())
{
ll x = dfs(s, inf);
ans += x;
}
return ans;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
s = n * n + n + 1;
t = s + 1;
int tx = 0;
for(int i=0; i<n; i++)
{
int now = ++tx;
add(s, now, 1, 0);
add(now, s, 0, 0);
for(int j=1; j<n; j++)
{
++tx;
add(now, tx, 1, 0);
add(tx, now, 0, 0);
now = tx;
}
}
for(int i=1; i<=n*n; i++)
{
int g = (i - 1) % n + 1 + n * n;
double x;
cin >> x;
x = log10(x);
add(i, g, 1, -x);
add(g, i, 0, x);
}
for(int i=1; i<=n; i++)
{
int g = i + n * n;
add(g, t, 1, 0);
add(t, g, 0, 0);
}
ll ax = mcmf();
vector<int>ans(n);
for(int i=1; i<=n*n; i++)
{
for(int j=head[i]; j; j=nex[j])
{
int nex = to[j];
if(nex > n * n && nex != s && val[j] == 0)
ans[(i - 1) % n] = (i - 1) / n + 1;
}
}
for(int i=0; i<ans.size(); i++)
{
if(i) cout << " ";
cout << ans[i];
}
cout << endl;
return 0;
}