luogu 2296 寻找道路

17 篇文章 0 订阅
7 篇文章 0 订阅

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;
    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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值