-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy path711C. Coloring Trees.cpp
100 lines (78 loc) · 1.7 KB
/
711C. Coloring Trees.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
#include <bits/stdc++.h>
using namespace std;
int n, m, k, a[101], p[101][101];
long long dp[101][105][101];
long long rec(int idx, int lst, int cur) {
if(idx == n) {
if(cur == k)
return 0;
return 2e14;
}
long long &ret = dp[idx][lst + 1][cur];
if(ret != -1)
return ret;
ret = 2e14;
if(idx == 0) {
if(a[idx] != -1)
return ret = rec(idx + 1, a[idx], cur + 1);
for(int i = 0; i < m; ++i)
ret = min(ret, rec(idx + 1, i, cur + 1) + p[idx][i]);
return ret;
}
if(a[idx] != -1)
return ret = rec(idx + 1, a[idx], cur + (lst != a[idx]));
for(int i = 0; i < m; ++i)
ret = min(ret, rec(idx + 1, i, cur + (lst != i)) + p[idx][i]);
return ret;
}
void build_path(int idx, int lst, int cur) {
if(idx == n) {
return;
}
long long opt = rec(idx, lst, cur);
if(idx == 0) {
if(a[idx] != -1) {
build_path(idx + 1, a[idx], cur + 1);
return;
}
for(int i = 0; i < m; ++i) {
if(rec(idx + 1, i, cur + 1) + p[idx][i] == opt) {
cout << i +1 << ' ';
build_path(idx + 1, i, cur + 1);
return;
}
}
}
if(a[idx] != -1) {
cout << a[idx] + 1 << ' ';
build_path(idx + 1, a[idx], cur + (lst != a[idx]));
return;
}
for(int i = 0; i < m; ++i) {
if(opt == rec(idx + 1, i, cur + (lst != i)) + p[idx][i]) {
cout << i+ 1 << ' ';
build_path(idx + 1, i, cur + (lst != i));
return;
}
}
}
int main() {
cin >> n >> m >> k;
int zeros = 0;
for(int i = 0; i < n; ++i) {
cin >> a[i];
zeros += (a[i] == 0);
}
for(int i = 0; i < n; ++i)
for(int j = 0; j < m; ++j)
cin >> p[i][j];
for(int i = 0; i < n; ++i)
--a[i];
memset(dp, -1, sizeof dp);
long long ans = rec(0, a[0], 0);
if(ans >= 2e14)
cout << -1 << endl;
else
cout << ans << endl;
return 0;
}