您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: