Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #ifdef NeverBeRed
- #include "debug.h"
- #else
- #define debug(...) 9715
- #endif
- typedef long long ll;
- typedef long double ld;
- typedef complex<ll> point;
- #define F first
- #define S second
- // max weight matching
- template<typename T>
- T hungarian(const vector<vector<T>> &a)
- {
- int n = a.size(), m = a[0].size(), p, q; // n <= m
- vector<T> fx(n, numeric_limits<T>::min()), fy(m, 0);
- vector<int> x(n, -1), y(m, -1);
- for (int i = 0; i < n; ++i)
- for (int j = 0; j < m; ++j)
- fx[i] = max(fx[i], a[i][j]);
- for (int i = 0; i < n;)
- {
- vector<int> t(m, -1), s(n + 1, i);
- for (p = q = 0; p <= q && x[i] < 0; ++p)
- for (int k = s[p], j = 0; j < m && x[i] < 0; ++j)
- if (fx[k] + fy[j] == a[k][j] && t[j] < 0) // be careful with comparison on doubles
- {
- s[++q] = y[j], t[j] = k;
- if (s[q] < 0)
- for (p = j; p >= 0; j = p)
- y[j] = k = t[j], p = x[k], x[k] = j;
- }
- if (x[i] < 0)
- {
- T d = numeric_limits<T>::max();
- for (int k = 0; k <= q; ++k)
- for (int j = 0; j < m; ++j)
- if (t[j] < 0)
- d = min(d, fx[s[k]] + fy[j] - a[s[k]][j]);
- for (int j = 0; j < m; ++j)
- fy[j] += (t[j] < 0 ? 0 : d);
- for (int k = 0; k <= q; ++k)
- fx[s[k]] -= d;
- }
- else
- ++i;
- }
- T ret = 0;
- for (int i = 0; i < n; ++i)
- ret += a[i][x[i]];
- return ret;
- }
- const int mov[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
- int main()
- {
- #ifdef TurnRed
- //freopen("a.in", "r", stdin);
- //freopen("a.out", "w", stdout);
- #endif
- ios_base::sync_with_stdio(0), cin.tie(0);
- int n, m, x, y;
- cin >> n >> m >> x >> y;
- vector<vector<int>> a(n, vector<int>(m));
- for (auto &i : a)
- for (auto &j : i)
- cin >> j;
- vector<int> s1(x), s2(y);
- for (auto &i : s1) cin >> i, --i;
- for (auto &i : s2) cin >> i, --i;
- vector<vector<ll>> c(x, vector<ll>(y));
- for (auto &p : s1)
- {
- vector<vector<ll>> d(n, vector<ll>(m, 1e14));
- queue<pair<int, int>> q;
- q.push({ 0, p });
- d[0][p] = 0;
- while (!q.empty())
- {
- int i, j;
- tie(i, j) = q.front();
- q.pop();
- for (int k = 0; k < 4; ++k)
- {
- int ni = i + mov[k][0];
- int nj = j + mov[k][1];
- if (ni >= 0 && ni < n && nj >= 0 && nj < m && d[ni][nj] > 1e5 && a[ni][nj] != 1)
- {
- d[ni][nj] = d[i][j] + 1;
- q.push({ ni, nj });
- }
- }
- }
- for (auto &j : s2)
- c[&p-&s1[0]][&j-&s2[0]] = -d[n-1][j];
- }
- ll ans = -hungarian(c);
- if (ans > 1e13) ans = -1;
- cout << ans << "\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement