Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define rep(i, a, b) for(int i = a; i < (b); ++i)
- #define all(x) begin(x), end(x)
- #define sz(x) (int)(x).size()
- typedef long long ll;
- typedef pair<int, int> pii;
- typedef vector<int> vi;
- const ll INF = numeric_limits<ll>::max() / 4;
- struct MCMF {
- struct edge {
- int from, to, rev;
- ll cap, cost, flow;
- };
- int N;
- vector<vector<edge>> ed;
- vector<ll> dist, pi;
- vector<edge*> par;
- MCMF(int N) : N(N), ed(N), dist(N), pi(N), par(N) {}
- void addEdge(int from, int to, ll cap, ll cost) {
- if (from == to) return;
- ed[from].push_back(edge{ from,to,sz(ed[to]),cap,cost,0 });
- ed[to].push_back(edge{ to,from,sz(ed[from])-1,0,-cost,0 });
- }
- void path(int s) {
- fill(all(dist), INF);
- dist[s] = 0;
- priority_queue<pair<ll, int>> q;
- q.push({ 0, s });
- while (!q.empty()) {
- auto [d,u] = q.top(); q.pop();
- if (-d > dist[u]) continue;
- for (edge& e : ed[u]) {
- ll val = pi[u] - d - pi[e.to] + e.cost;
- if (e.cap - e.flow > 0 && val < dist[e.to]) {
- dist[e.to] = val;
- par[e.to] = &e;
- q.push({ -dist[e.to], e.to });
- }
- }
- }
- rep(i,0,N) pi[i] = min(pi[i] + dist[i], INF);
- }
- pair<ll, ll> maxflow(int s, int t) {
- ll totflow = 0, totcost = 0;
- while (path(s), dist[t]!=INF) {
- ll fl = INF;
- for (edge* x = par[t]; x; x = par[x->from])
- fl = min(fl, x->cap - x->flow);
- totflow += fl;
- for (edge* x = par[t]; x; x = par[x->from]) {
- x->flow += fl;
- ed[x->to][x->rev].flow -= fl;
- }
- }
- rep(i,0,N) for(edge& e : ed[i]) totcost += e.cost * e.flow;
- return {totflow, totcost/2};
- }
- // If some costs can be negative, call this before maxflow:
- void setpi(int s) { // (otherwise, leave this out)
- fill(all(pi), INF); pi[s] = 0;
- int it = N, ch = 1; ll v;
- while (ch-- && it--)
- rep(i,0,N) if (pi[i] != INF)
- for (edge& e : ed[i]) if (e.cap)
- if ((v = pi[i] + e.cost) < pi[e.to])
- pi[e.to] = v, ch = 1;
- assert(it >= 0); // negative cost cycle
- }
- };
- int main() {
- cin.tie(0)->sync_with_stdio(0);
- ll t;
- cin >> t;
- while (t--)
- {
- ll m, n;
- cin >> m >> n;
- vector<string> grid(n);
- for (auto& s : grid) cin >> s;
- MCMF mc(n * m * 3);
- auto getout = [&](ll x) {return x + n * m; };
- auto getller = [&](ll x) {return x + (n * m) * 2; };
- rep(i, 0, n)
- {
- rep(j, 0, m)
- {
- ll ind = i * m + j;
- if (i + 1 < n) mc.addEdge(getout(ind), ind + m, 2, 0);
- if (j + 1 < m) mc.addEdge(getout(ind), ind + 1, 2, 0);
- if (grid[i][j] == '*')
- {
- mc.addEdge(ind, getout(ind), 1, 0);
- mc.addEdge(ind, getout(ind), 1, 1);
- }
- else if (grid[i][j] == '.')
- {
- mc.addEdge(ind, getout(ind), 2, 1);
- }
- }
- }
- pair<ll,ll> res = mc.maxflow(0, getout(n * m - 1));
- cout << ((n + m - 1) * 2 - res.second) << "\n";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment