codeforces 1204 C Anna, Svyatoslav and Maps (bfs多源最短路径)

4 篇文章 0 订阅

题目:https://codeforces.com/problemset/problem/1204/C

题意:给出有向图,给出路径,把路径压缩到最短的表示方式,使得路长和之前表示的不变。

思路:先求出多源最短路径。对于一个路径a->b->c,若dist[a][c] < dist[a][b] + dist[b][c]说明b是不可压缩的,反之若相等则表示从a->c的最短路径唯一,是可压缩的。

代码:

#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> P;
const int maxn = 105;

int Map[maxn][maxn], n, m, dist[maxn][maxn], vis[maxn], q[1000005], vis1[1000005];
void bfs(int start){
    memset(vis, 0, sizeof vis); vis[start] = 1;
    queue<P>que; que.push(P(start, 0)), dist[start][start] = 0;
    while(que.size()){
        P now = que.front(); que.pop();
        for(int i=1; i<=n; i++){
            if(Map[now.first][i] && !vis[i]){
                vis[i] = 1; que.push(P(i, now.second+1));
                dist[start][i] = now.second+1;
            }
        }
    }
}
int main(){
    memset(dist, 0x3f, sizeof dist);
    cin >> n;
    for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) scanf("%1d", &Map[i][j]);
    for(int i=1; i<=n; i++) bfs(i);

    cin >> m; int cnt = m;
    for(int i=1; i<=m; i++) scanf("%d", &q[i]);
    int a = q[1], b = q[2], c;
    for(int i=3; i<=m; i++){
        c = q[i];
        if(dist[a][c] < dist[a][b] + dist[b][c]) a = b, b = c;
        else vis1[i-1] = 1, cnt --, b = c;
    }
    cout << cnt << endl;
    for(int i=1; i<=m; i++) if(!vis1[i]) printf("%d%c", q[i], " \n"[i==m]);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值