-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11408.cpp
128 lines (125 loc) · 2.13 KB
/
11408.cpp
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <iostream>
#include <set>
#include <vector>
#include <string>
#include <algorithm>
#include <queue>
#include <cstring>
#include <math.h>
#include <stack>
using namespace std;
#define inf 1e9
typedef pair<int, int> p;
int N, M;
int S = 0, T = 801;
vector<p> worker[802];
int flow[802][802]; // 현재 흐른 유량
queue<int> q;
int dist[802];
int prevnode[802];
bool inQ[802];
int cycle[802];
int cnt, ans;
void init()
{
while (!q.empty())
{
q.pop();
}
memset(prevnode, 0, sizeof(prevnode));
memset(inQ, 0, sizeof(inQ));
memset(cycle, 0, sizeof(cycle));
for (int i = 1; i <= 801; i++)
{
dist[i] = inf;
}
q.push(0);
inQ[0] = true;
cycle[0]++;
}
void spfa()
{
init();
while (!q.empty())
{
int now = q.front();
q.pop();
inQ[now] = false;
for (int i = 0; i < worker[now].size(); i++)
{
int nxt = worker[now][i].first;
int w = worker[now][i].second;
if (flow[now][nxt] == 0 && dist[nxt] > dist[now] + w)
{
dist[nxt] = dist[now] + w;
prevnode[nxt] = now;
if (inQ[nxt] == false)
{
inQ[nxt] = true;
cycle[nxt]++;
q.push(nxt);
if (cycle[nxt] >= N)
{
return;
}
}
}
}
}
return;
}
void mcnf()
{
while (1)
{
spfa();
if (prevnode[T] == 0)
{
break;
}
for (int i = T; i != S; i = prevnode[i])
{
int prev = prevnode[i];
flow[prev][i]++;
flow[i][prev]--;
}
cnt++;
ans += dist[T];
}
cout << cnt << '\n' << ans << '\n';
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> N >> M;
for (int i = 1; i <= N; i++)
{
int n;
cin >> n;
for (int j = 0; j < n; j++)
{
int v, w;
cin >> v >> w;
worker[i].push_back(p(400 + v, w));
worker[400 + v].push_back(p(i, -w));
flow[400 + v][i] = 1;
}
}
// Source와 연결
for (int i = 1; i <= N; i++)
{
worker[S].push_back(p(i, 0));
worker[i].push_back(p(S, 0));
flow[i][S] = 1;
}
// Sink와 연결
for (int i = 1; i <= M; i++)
{
worker[400 + i].push_back(p(T, 0));
worker[T].push_back(p(400 + i, 0));
flow[T][400 + i] = 1;
}
mcnf();
}