Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P3967 [TJOI2014]匹配

P3967 [TJOI2014]匹配

先做带权匹配,对于每一条匹配的边,如果删除了后答案减小,则一定是匹配边。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
#include <cstdio>
#include <queue>
#include <climits>
#define inf INT_MAX
using namespace std;
const int N = 210, M = 2e4 + 10;
bool vis[N], intersection[M];
int n, st, ed, ans, d[N], pre[N], incf[N];
int idx = -1, hd[N], nxt[M], edg[M], wt[M], f[M];
bool spfa ()
{
for (int i = st; i <= ed; i++)
incf[i] = 0;
for (int i = st; i <= ed; i++)
d[i] = -inf;
incf[st] = inf;
d[st] = 0;
queue <int> q;
q.push(st);
while (!q.empty())
{
int t = q.front();
q.pop();
vis[t] = false;
for (int i = hd[t]; ~i; i = nxt[i])
if (d[t] + f[i] > d[edg[i]] && wt[i])
{
d[edg[i]] = d[t] + f[i];
pre[edg[i]] = i;
incf[edg[i]] = min(wt[i], incf[t]);
if (!vis[edg[i]])
{
vis[edg[i]] = true;
q.push(edg[i]);
}
}
}
return incf[ed] > 0;
}
int ek ()
{
int cost = 0;
while (spfa())
{
int t = incf[ed];
cost += t * d[ed];
for (int i = ed; i != st; i = edg[pre[i] ^ 1])
{
wt[pre[i]] -= t;
wt[pre[i] ^ 1] += t;
}
}
return cost;
}
void add (int a, int b, int c, int d)
{
nxt[++idx] = hd[a];
hd[a] = idx;
edg[idx] = b;
wt[idx] = c;
f[idx] = d;
}
int main ()
{
cin >> n;
st = 0;
ed = n << 1 | 1;
for (int i = st; i <= ed; i++)
hd[i] = -1;
for (int i = 1; i <= n; i++)
{
add(st, i, 1, 0);
add(i, st, 0, 0);
}
for (int i = 1, a; i <= n; i++)
for (int j = n + 1; j < ed; j++)
{
cin >> a;
add(i, j, 1, a);
add(j, i, 0, -a);
}
for (int i = n + 1; i < ed; i++)
{
add(i, ed, 1, 0);
add(ed, i, 0, 0);
}
cout << (ans = ek()) << endl;
for (int i = n << 1; i < n * 2 + n * n * 2; i += 2)
intersection[i] = wt[i];
for (int i = n << 1; i < n * 2 + n * n * 2; i += 2)
if (!intersection[i])
{
for (int j = 0; j <= idx; j += 2)
{
wt[j] += wt[j ^ 1];
wt[j ^ 1] = 0;
}
int t = wt[i];
wt[i] = 0;
if (ek() < ans)
cout << edg[i ^ 1] << ' ' << edg[i] - n << endl;
wt[i] = t;
}
return 0;
}