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 101 102 103
| #include<bits/stdc++.h> using namespace std; const int N = 504, M = 100005; struct Edge{ int to, nxt, w, cost; }edge[M]; int h[N], cnt=1; void add(int u, int v, int w, int x){ edge[++cnt] = {v, h[u], w, x}; h[u] = cnt; } void addedge(int u, int v, int w, int x){ add(u, v, w, x), add(v, u, 0, -x); }
int dis[N], vis[N]; int n, m, s, t;
bool spfa(){ memset(dis, 0x3f, sizeof dis); dis[s] = 0, vis[s] = 1; queue<int>q; q.push(s); while(q.size()){ int u = q.front(); q.pop(); vis[u] = 0; for(int i=h[u];i;i=edge[i].nxt){ int v = edge[i].to; if(edge[i].w&&dis[v]>dis[u]+edge[i].cost){ dis[v] = dis[u] + edge[i].cost; if(!vis[v]) vis[v] = 1, q.push(v); } } } return dis[t] != 0x3f3f3f3f; }
int ret = 0;
int cur[N];
int dfs(int u, int flow){ if(u==t) return flow; int ans = 0; vis[u] = 1; for(int i=cur[u];i&&ans<flow;i=edge[i].nxt){ int v = edge[i].to; cur[u] = i; if(edge[i].w&&!vis[v]&&dis[v]==dis[u]+edge[i].cost){ int fl = dfs(v, min(edge[i].w, flow-ans)); if(fl){ ret += fl * edge[i].cost; edge[i].w -= fl; edge[i^1].w += fl; ans += fl; } } } vis[u] = 0; return ans; }
int dinic(){ int ans = 0; while(spfa()){ memcpy(cur, h, sizeof h); int x = 0; while(x=dfs(s, 0x3f3f3f3f)) ans += x; } return ans; }
int id(int linerow, int row){ return linerow + row*n; } char str[N]; int main(){ ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); cin>>n>>m; s = 0, t = n+m+1; for(int i=1;i<=n;i++){ cin>>(str+1); for(int j=1;j<=m;j++){ if(str[j]=='S'){ addedge(s, id(i, 0), 0x3f3f3f3f, 0); addedge(s, id(j, 1), 0x3f3f3f3f, 0); }else if(str[j]=='T'){ addedge(id(i, 0), t, 0x3f3f3f3f, 0); addedge(id(j, 1), t, 0x3f3f3f3f, 0); }else if(str[j]=='o'){ addedge(id(i, 0), id(j, 1), 1, 0); addedge(id(j, 1), id(i, 0), 1, 0); } } } int ans = dinic(); if(ans >=0x3f3f3f3f/2) cout<<"-1"; else cout<<ans; return 0; }
|