-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathC_Wonderful_City.cpp
More file actions
91 lines (75 loc) · 2.04 KB
/
C_Wonderful_City.cpp
File metadata and controls
91 lines (75 loc) · 2.04 KB
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
#include <bits/stdc++.h>
using namespace std;
// First you make it work, then you can always make it beautiful
#define int long long
const int inf = 1e18;
const int N = 1001;
int h[N][N], a[N], b[N];
int dp[N][2], dp2[N][2];
void solve() {
int n;
cin >> n;
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) cin >> h[i][j];
}
for(int i=0;i<n;i++) cin >> a[i];
for(int i=0;i<n;i++) cin >> b[i];
for(int i=0;i<n;i++) {
dp[i][0] = dp[i][1] = inf;
dp2[i][0] = dp2[i][1] = inf;
}
dp[0][0] = 0; dp2[0][0] = 0;
dp[0][1] = a[0]; dp2[0][1] = b[0];
for(int i=1;i<n;i++) {
bool f1 = 1, f2 = 1, f3 = 1;
for(int j=0;j<n;j++) {
f1 &= (h[i][j] != h[i-1][j]);
f2 &= (h[i][j] != h[i-1][j] + 1);
f3 &= (h[i][j] + 1 != h[i-1][j]);
}
if(f1) {
dp[i][0] = min(dp[i][0], dp[i-1][0]);
dp[i][1] = min(dp[i][1], dp[i-1][1] + a[i]);
}
if(f2) {
dp[i][0] = min(dp[i][0], dp[i-1][1]);
}
if(f3) {
dp[i][1] = min(dp[i][1], dp[i-1][0] + a[i]);
}
}
int row_cost = min(dp[n-1][0], dp[n-1][1]);
for(int j=1;j<n;j++) {
bool f1 = 1, f2 = 1, f3 = 1;
for(int i=0;i<n;i++) {
f1 &= (h[i][j] != h[i][j-1]);
f2 &= (h[i][j] != h[i][j-1] + 1);
f3 &= (h[i][j] + 1 != h[i][j-1]);
}
if(f1) {
dp2[j][0] = min(dp2[j][0], dp2[j-1][0]);
dp2[j][1] = min(dp2[j][1], dp2[j-1][1] + b[j]);
}
if(f2) {
dp2[j][0] = min(dp2[j][0], dp2[j-1][1]);
}
if(f3) {
dp2[j][1] = min(dp2[j][1], dp2[j-1][0] + b[j]);
}
}
int col_cost = min(dp2[n-1][0], dp2[n-1][1]);
int ans = row_cost + col_cost;
if(ans >= inf) cout << "-1\n";
else cout << ans << "\n";
}
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int _;
cin >> _;
while (_-->0) {
solve();
}
return 0;
}