【luogu P2296 尋找道路】 題解
阿新 • • 發佈:2018-09-13
mes can 所有 pty main else ron cstring str
題目鏈接:https://www.luogu.org/problemnew/show/P2296
題意:給定起點終點,找一條從起點到終點的最短路徑使路上的每個點都能有路徑到達終點。
我們先反著建一遍圖,然後從終點開始bfs一遍圖,標記所有終點可以到達的點。然後再枚舉一遍點,如果這個點是終點沒法到達的點,那麽再枚舉這個點所能連接的所有點,如果這些點是終點可以到達的,那麽這些點就是不符合條件的。最後在符合條件的點上做一遍最短路。
#include <queue> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int maxn = 200010; int start, end, n, m, u[maxn], v[maxn], dis[maxn]; bool vis1[maxn], vis2[maxn], vis[maxn]; struct edge{ int from, to, next, len; }e1[maxn<<2], e[maxn<<2]; int cnt1, cnt, head1[maxn], head[maxn]; void add1(int u, int v, int w) { e1[++cnt1].from = u; e1[cnt1].len = w; e1[cnt1].to = v; e1[cnt1].next = head1[u]; head1[u] = cnt1; } void add(int u, int v, int w) { e[++cnt].from = u; e[cnt].len = w; e[cnt].to = v; e[cnt].next = head[u]; head[u] = cnt; } queue<int> q1, q; void bfs() { q1.push(end), vis1[end] = 1; while(!q1.empty()) { int now = q1.front(); q1.pop(); for(int i = head1[now]; i != -1; i = e1[i].next) { if(!vis1[e1[i].to]) { vis1[e1[i].to] = 1; q1.push(e1[i].to); } } } memcpy(vis2, vis1, sizeof(vis1)); for(int i = 1; i <= n; i++) { if(vis1[i] == 0) for(int j = head1[i]; j != -1; j = e1[j].next) { if(vis2[e1[j].to] == 1) vis2[e1[j].to] = 0; } } } void SPFA() { q.push(start); vis[start] = 1, dis[start] = 0; while(!q.empty()) { int now = q.front(); q.pop(); for(int i = head[now]; i != -1; i = e[i].next) { if(dis[e[i].to] > dis[now] + e[i].len) { dis[e[i].to] = dis[now] + e[i].len; if(!vis[e[i].to]) { q.push(e[i].to); } } } } } int main() { memset(head1, -1, sizeof(head1)); memset(head, -1, sizeof(head)); scanf("%d%d",&n,&m); for(int i = 1; i <= n; i++) dis[i] = 233333333; for(int i = 1; i <= m; i++) { scanf("%d%d",&u[i],&v[i]); if(u[i] != v[i]) add1(v[i], u[i], 1); } scanf("%d%d",&start,&end); bfs(); for(int i = 1; i <= m; i++) { if(u[i] != v[i] && vis2[u[i]] != 0 && vis2[v[i]] != 0) add(u[i], v[i], 1); } SPFA(); if(dis[end] == 233333333) { printf("-1\n"); return 0; } else printf("%d\n",dis[end]); return 0; }
【luogu P2296 尋找道路】 題解