1. 程式人生 > >HDU 3491 Thieves(經典拆點建圖,割點)

HDU 3491 Thieves(經典拆點建圖,割點)

題目地址
題意:有一群小偷要從s點逃到t點,告訴你這個城市的道路圖,並且告訴你每個關鍵點要多少警察才不會讓小偷逃走,問你最少要多少警察才能阻止小偷逃走(小偷會知道警察的佈局)
思路:明顯的最小割點的題目,解決這類割點問題一般都是進行拆點建圖,把每個點拆成兩個點(i,i+n)和一條容量為代價的邊,然後道路的起點就是該起點的出點(x+n),終點就是該終點的入點(y),容量為inf無限大,這樣就不會去割邊了,最後以為最小割等於最大流,所以跑一邊最大流就好了。

#include <iostream>
#include <cstring>
#include <string>
#include <queue> #include <vector> #include <map> #include <set> #include <stack> #include <cmath> #include <cstdio> #include <algorithm> #include <iomanip> #define N 40010 #define M 100010 #define LL __int64 #define inf 0x3f3f3f3f #define lson l,mid,ans<<1
#define rson mid+1,r,ans<<1|1 #define getMid (l+r)>>1 #define movel ans<<1 #define mover ans<<1|1 using namespace std; const LL mod = 1000000007; int head[N], level[N]; int n, m, cnt; struct node { int to; int cap;//剩餘流量 int next; }edge[2 * M]; struct Dinic { void init() { memset
(head, -1, sizeof(head)); cnt = 0; } void add(int u, int v, int cap) {//有向圖 edge[cnt].to = v, edge[cnt].cap = cap, edge[cnt].next = head[u], head[u] = cnt++; edge[cnt].to = u, edge[cnt].cap = 0, edge[cnt].next = head[v], head[v] = cnt++;//反向邊 } bool bfs(int s, int t) {//建立分層圖 memset(level, -1, sizeof(level)); queue<int>q; level[s] = 0;//源點的層次最高 q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); for (int i = head[u]; i != -1; i = edge[i].next) { int v = edge[i].to; if (edge[i].cap > 0 && level[v] < 0) { level[v] = level[u] + 1; q.push(v); } } } return level[t] != -1; } int dfs(int u, int t, int num) {//找增廣路 if (u == t) {//找到了匯點返回當前的最小值,在這條路徑上分別減去最小值 return num; } for (int i = head[u]; i != -1; i = edge[i].next) { int v = edge[i].to; if (edge[i].cap > 0 && level[u] < level[v]) { int d = dfs(v, t, min(num, edge[i].cap)); if (d > 0) { edge[i].cap -= d; edge[i ^ 1].cap += d;//反向邊加值 return d; } } } level[u] = -1; return 0; } int minflow(int s, int t) {//源點和匯點 int sum = 0, num; while (bfs(s, t)) { while (num = dfs(s, t, inf), num > 0) {//當前層次圖不斷的找增廣路 sum += num; } } return sum; } }dc; int main() { cin.sync_with_stdio(false); int T; int a, b; int s, t; cin >> T; while (T--) { dc.init(); cin >> n >> m >> s >> t; dc.add(s, s + n, inf); dc.add(t, t + n, inf); for (int i = 1; i <= n; i++) { cin >> a; dc.add(i, i + n, a); } for (int i = 0; i < m; i++) { cin >> a >> b; dc.add(a + n, b, inf); dc.add(b + n, a, inf); } cout << dc.minflow(s, t + n) << endl; } return 0; }