fork download
  1. // ~~ icebear ~~
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<int, int> ii;
  7. typedef pair<int, ii> iii;
  8.  
  9. template<class T>
  10. bool minimize(T &a, const T &b) {
  11. if (a > b) return a = b, true;
  12. return false;
  13. }
  14.  
  15. template<class T>
  16. bool maximize(T &a, const T &b) {
  17. if (a < b) return a = b, true;
  18. return false;
  19. }
  20.  
  21. #define FOR(i,a,b) for(int i=(a); i<=(b); ++i)
  22. #define FORR(i,a,b) for(int i=(a); i>=(b); --i)
  23. #define REP(i, n) for(int i=0; i<(n); ++i)
  24. #define RED(i, n) for(int i=(n)-1; i>=0; --i)
  25. #define MASK(i) (1LL << (i))
  26. #define BIT(S, i) (((S) >> (i)) & 1)
  27. #define mp make_pair
  28. #define pb push_back
  29. #define fi first
  30. #define se second
  31. #define all(x) x.begin(), x.end()
  32. #define task "machine"
  33.  
  34. const int MOD = 1e9 + 7;
  35. const int inf = 1e9 + 27092008;
  36. const ll INF = 1e18 + 27092008;
  37. const int dx[] = {0, +1};
  38. const int dy[] = {+1, 0};
  39. const int N = 2000 + 5;
  40. int n, m, r[N], c[N];
  41. ll f[N][N][2][2]; // f(i, j, r, c): state of row and col
  42. int a[N][N];
  43.  
  44. bool reach(int x, int y, int R, int C) {
  45. return a[x][y] ^ R ^ C;
  46. }
  47.  
  48. bool inside(int x, int y) {
  49. return 1 <= x && x <= n && 1 <= y && y <= m;
  50. }
  51.  
  52. void init(void) {
  53. cin >> n >> m;
  54. FOR(i, 1, n) FOR(j, 1, m) {
  55. char x; cin >> x;
  56. a[i][j] = x - '0';
  57. }
  58. FOR(i, 1, n) cin >> r[i];
  59. FOR(j, 1, m) cin >> c[j];
  60. }
  61.  
  62. void process(void) {
  63. memset(f, 0x3f, sizeof f);
  64. ll tmp_inf = f[0][0][0][0];
  65. REP(R, 2) REP(C, 2) if (reach(1, 1, R, C))
  66. f[1][1][R][C] = R * r[1] + C * c[1];
  67.  
  68. FOR(i, 1, n) FOR(j, 1, m) REP(R, 2) REP(C, 2) if (f[i][j][R][C] != tmp_inf) {
  69. if (i + 1 <= n) {
  70. REP(_R, 2) if (reach(i + 1, j, _R, C))
  71. minimize(f[i + 1][j][_R][C], f[i][j][R][C] + _R * r[i + 1]);
  72. }
  73.  
  74. if (j + 1 <= m) {
  75. REP(_C, 2) if (reach(i, j + 1, R, _C))
  76. minimize(f[i][j + 1][R][_C], f[i][j][R][C] + _C * c[j + 1]);
  77. }
  78. }
  79.  
  80. ll ans = tmp_inf;
  81. REP(R, 2) REP(C, 2) minimize(ans, f[n][m][R][C]);
  82. cout << (ans == tmp_inf ? -1 : ans);
  83. }
  84.  
  85. int main() {
  86. ios_base::sync_with_stdio(0);
  87. cin.tie(0); cout.tie(0);
  88. if (fopen(task".inp", "r")) {
  89. freopen(task".inp", "r", stdin);
  90. freopen(task".out", "w", stdout);
  91. }
  92. int tc = 1;
  93. // cin >> tc;
  94. while(tc--) {
  95. init();
  96. process();
  97. }
  98. return 0;
  99. }
  100.  
  101.  
Success #stdin #stdout 0.02s 130348KB
stdin
Standard input is empty
stdout
-1