luogu 2296 寻找道路
2017-10-25 21:08
218 查看
luogu 2296 寻找道路
从终点开始bfs(一开始先建反向边), 记录下每个节点能否从终点到达(有一个标记数组标记), 之后初始化所有的边重新建边, 再bfs找到最短距离。一直被T和WA了好久
(太懒了, 没有建反向边又加了一个数组)
#include <cstdio> #include <cstring> #include <queue> #define MAXN 10010 #define MAXM 200010 using namespace std; int now[MAXN], now1[MAXN];//和边相对应的 int cnt, n, x, y, s, t, m; int vis[MAXN], dis[MAXN]; bool v[MAXN]; queue <int> q; struct E { int from, to, nxt; } es[MAXM], es1[MAXM]; //一个是正向边一个是反向边 int read() { int f = 1, k = 0 a011 ; char c = getchar(); while(c < '0' || c > '9') { if(c == '-') { f = -1; } c = getchar(); } while(c >= '0' && c <= '9') { k = k * 10 + c - '0'; c = getchar(); } return f * k; } void addedge(int a, int b) { es1[++ cnt].from = a; es1[cnt].to = b; es1[cnt].nxt = now1[a]; now1[a] = cnt; } void bfs(int a) { vis[a] = 1; q.push(a); while(!q.empty()) { int top = q.front(); q.pop(); for(int i = now1[top]; i != 0; i = es1[i].nxt) { if(!vis[es1[i].to]) { vis[es1[i].to] = 1; q.push(es1[i].to); } } } } bool cheak(int a) { for(int i = now[a]; i != 0; i = es[i].nxt) { if(!vis[es[i].to]) { return false; } } return true; } void bfs1(int a) { v[a] = false; q.push(a); while(!q.empty()) { int top = q.front(); q.pop(); if(top == t) return ; if(!cheak(top)) continue; for(int i = now[top]; i != 0; i = es[i].nxt) { if(v[es[i].to]) { v[es[i].to] = false; dis[es[i].to] = dis[top] + 1; q.push(es[i].to); } } } } int main() { memset(v, true, sizeof(v)); memset(vis, 0, sizeof(vis)); n = read(), m = read(); for(int i = 1; i <= n; i ++) { dis[i] = MAXN; } for(int i = 1; i <= m; i ++) { x = read(), y = read(); es[i].from = x; es[i].to = y; es[i].nxt = now[x]; now[x] = i; addedge(y, x); } s = read(), t = read(); bfs(t); dis[s] = 0; bfs1(s); if(dis[t] == MAXN) { printf("-1"); return 0; } printf("%d", dis[t]); return 0; }
相关文章推荐
- codevs3731 luogu2296 寻找道路
- codevs3731 luogu2296 寻找道路
- 洛谷oj 2296寻找道路 【sb错误*1】
- luogu P2296 寻找道路
- 洛谷2296 寻找道路
- 洛谷 2296_寻找道路_spfa+dfs
- 寻找道路(洛谷 2296)
- 【洛谷 2296】寻找道路
- (洛谷 2296)寻找道路
- 洛谷2296 寻找道路
- 洛谷2296 寻找道路
- 寻找道路 【gzoi】
- NOIP2014 day2 T2 洛谷P2296 寻找道路
- #NOIP 2014# day.2 T2 寻找道路
- 【NOIP2014】D2T2 寻找道路
- noip2014寻找道路
- P2296 寻找道路
- Noip 2014 提高组 寻找道路
- 【30.00%】【vijos 1909】寻找道路
- 【遍历】UOJ#19 【NOIP2014】寻找道路