SPOJ 962 Intergalactic Map (从A到B再到C的路线)
生活随笔
收集整理的這篇文章主要介紹了
SPOJ 962 Intergalactic Map (从A到B再到C的路线)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【題意】在一個無向圖中,一個人要從A點趕往B點,之后再趕往C點,且要求中途不能多次經過同一個點。問是否存在這樣的路線。(3 <= N <= 30011, 1 <= M <= 50011) 【思路】很巧的一道題,一般我們都是把源點連接起點,但那樣的話就不好控制從A先到B再到C了,所以我們換個思路,以B為源點,A、C為匯點,看最大流是否為2即可~不經過同一個點就直接拆點連一條(i, i', 1)即可,無向圖……就連兩條反向邊吧~~本來想改一下反向流就好的,可是想想那樣也把源點匯點連出來的邊也變成雙向了……沒試行不行…… ?
#include
#include
#include
#include
#include
#include
#define MID(x,y) ((x+y)/2)
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int MAXV = 60055;
const int MAXE = 200055;
const int oo = 0x3fffffff;
struct node{int u, v, flow;int opp;int next;
};
struct Dinic{node arc[2*MAXE];int vn, en, head[MAXV]; //vn點個數(包括源點匯點),en邊個數int cur[MAXV]; //當前弧int q[MAXV]; //bfs建層次圖時的隊列int path[2*MAXE], top; //存dfs當前最短路徑的棧int dep[MAXV]; //各節點層次void init(int n){vn = n;en = 0;mem(head, -1);}void insert_flow(int u, int v, int flow){arc[en].u = u;arc[en].v = v;arc[en].flow = flow;arc[en].opp = en + 1;arc[en].next = head[u];head[u] = en ++;arc[en].u = v;arc[en].v = u;arc[en].flow = 0; //反向弧arc[en].opp = en - 1;arc[en].next = head[v];head[v] = en ++;}bool bfs(int s, int t){mem(dep, -1);int lq = 0, rq = 1;dep[s] = 0;q[lq] = s;while(lq < rq){int u = q[lq ++];if (u == t){return true;}for (int i = head[u]; i != -1; i = arc[i].next){int v = arc[i].v;if (dep[v] == -1 && arc[i].flow > 0){dep[v] = dep[u] + 1;q[rq ++] = v;}}}return false;}int solve(int s, int t){int maxflow = 0;while(bfs(s, t)){int i, j;for (i = 1; i <= vn; i ++) cur[i] = head[i];for (i = s, top = 0;;){if (i == t){int mink;int minflow = 0x3fffffff;for (int k = 0; k < top; k ++)if (minflow > arc[path[k]].flow){minflow = arc[path[k]].flow;mink = k;}for (int k = 0; k < top; k ++)arc[path[k]].flow -= minflow, arc[arc[path[k]].opp].flow += minflow;maxflow += minflow;top = mink; //arc[mink]這條邊流量變為0, 則直接回溯到該邊的起點即可(這條邊將不再包含在增廣路內).i = arc[path[top]].u;}for (j = cur[i]; j != -1; cur[i] = j = arc[j].next){int v = arc[j].v;if (arc[j].flow && dep[v] == dep[i] + 1)break;}if (j != -1){path[top ++] = j;i = arc[j].v;}else{if (top == 0) break;dep[i] = -1;i = arc[path[-- top]].u;}}}return maxflow;}
}dinic;
int main(){int t;scanf("%d",&t);while(t --){int n, m;scanf("%d %d", &n, &m);if (n < 3){puts("NO");continue;}dinic.init(2*n+2);for (int i = 1; i <= n; i ++){dinic.insert_flow(2*i-1, 2*i, 1);}for (int i = 1; i <= m; i ++){int u, v;scanf("%d %d", &u, &v);if(u > n || v > n) continue;dinic.insert_flow(2*u, 2*v-1, 1);dinic.insert_flow(2*v, 2*u-1, 1);}dinic.insert_flow(2*n+1, 2*2, 2);dinic.insert_flow(2*1, 2*n+2, 1);dinic.insert_flow(2*3, 2*n+2, 1);if (dinic.solve(2*n+1, 2*n+2) == 2){puts("YES");}else{puts("NO");}}return 0;
}
轉載于:https://www.cnblogs.com/AbandonZHANG/p/4114048.html
總結
以上是生活随笔為你收集整理的SPOJ 962 Intergalactic Map (从A到B再到C的路线)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ldap无法启动 system libr
- 下一篇: 【UGUI源码分析】Unity遮罩之Ma