两者都是求最小权匹配。
通过这次练习发现一个问题,就是求最小权匹配时,最好把W的赋值为-INF。在做第二题时,出现两者之间没有连边的匹配到了一块,所以最好赋值为-INF。输出时,只加上已经匹配边的长度。即:for(int i = 1; i <= m; i++) if(Left[i] && W[Left[i]][i] != -INF) ans += W[Left[i]][i];
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
#include <map>
using namespace std;
const int maxn = 510;
const int INF = 0x3f3f3f3f;
int n, m;
int W[maxn][maxn];
int Lx[maxn], Ly[maxn];
int Left[maxn];
bool S[maxn], T[maxn];
bool match(int i)
{
S[i] = 1;
for(int j = 1; j <= m; j++) if(Lx[i]+Ly[j] == W[i][j] && !T[j])
{
T[j] = 1;
if(!Left[j] || match(Left[j]))
{
Left[j] = i;
return 1;
}
}
return 0;
}
void update()
{
int a = INF;
for(int i = 1; i <= n; i++) if(S[i])
for(int j = 1; j <= m; j++) if(!T[j])
a = min(a, Lx[i]+Ly[j]-W[i][j]);
for(int i = 1; i <= n; i++)
{
if(S[i]) Lx[i] -= a;
}
for(int j = 1; j <= m; j++)
{
if(T[j]) Ly[j] += a;
}
}
void KM()
{
memset(Left, 0, sizeof(Left));
memset(Lx, 0, sizeof(Lx));
memset(Ly, 0, sizeof(Ly));
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
Lx[i] = max(Lx[i], W[i][j]);
}
for(int i = 1; i <= n; i++)
{
for(;;)
{
for(int j = 1; j <= m; j++) S[j] = T[j] = 0;
if(match(i)) break; else update();
}
}
}
inline void readint(int &x)
{
char c;
c = getchar();
while(!isdigit(c)) c = getchar();
x = 0;
while(isdigit(c)) x = x*10+c-'0', c = getchar();
}
inline void writeint(int x)
{
if(x > 9) writeint(x/10);
putchar(x%10+'0');
}
int num[maxn];
int N;
int X[maxn], Y[maxn];
void read_case()
{
for(int i = 1; i <= N; i++) readint(num[i]);
}
void build()
{
n = m = 1;
for(int i = 1; i <= N; i++)
{
if(!num[i]) Y[m++] = i;
else
{
while(num[i] > 1) X[n++] = i, num[i] -= 1;
}
}
n--, m--;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++) W[i][j] = -INF;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
{
W[i][j] = -min(abs(X[i]-Y[j]), N-(abs(X[i]-Y[j])));
}
}
void solve()
{
read_case();
build();
KM();
int ans = 0;
for(int i = 1; i <= m; i++) if(Left[i] && W[Left[i]][i] != -INF) ans += W[Left[i]][i];
writeint(-ans), puts("");
}
int main()
{
while(~scanf("%d", &N))
{
solve();
}
return 0;
}