【23.03.11】上海理工天梯选拔赛

该代码实现了一个解决图论问题的程序,通过BFS预处理出每个节点到源点1的最少城市路径,然后用Dijkstra算法在保证最少城市数的条件下找到从1到n的最短距离。主要涉及图的邻接表存储、优先队列和路径优化策略。
摘要由CSDN通过智能技术生成

https://ac.nowcoder.com/acm/contest/52244

F 坐火车

大意:在经过最少城市的条件下1到n的最短路

思路:bfs预处理出经过最少城市的路线(权值为1),按途经城市最少的路线跑dijkstra(d[j] != d[num] + 1,即不是最少城市路线,continue)

//坐火车
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <sstream>
#include <cstring>
#include <numeric>
#include <istream>
#include <iomanip>
#include <vector>
#include <iterator>
#include <queue>
#include <map>
#include <stack>
#include <set>
using namespace std;
const int inf = 0x3f3f3f3f, mod = 1e9 + 7;
const int N = 1e5 + 10, M = 4 * N; //题目中N是1e5,M是2e5,双向边
#define LL long long
#define PII pair<int, int>
int n, m, d[N], ne[M], e[M], h[N], idx, w[M], vis[N], dis[N], st[N];

void add(int a, int b, int c){
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx ++;
}

void bfs(){
    queue<int> q;
    q.push(1);
    vis[1] = 1;
    d[1] = 1;
    while(q.size()){
        int t = q.front();
        q.pop();
        for(int i = h[t]; i != -1; i = ne[i]){
            int j = e[i];
            if(!vis[j]){
                d[j] = d[t] + 1;
                vis[j] = 1;
                q.push(j);
            }
        }
    }
}

int dijkstra(){
    memset(dis, inf, sizeof dis);
    dis[1] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.push({0, 1});
    while(heap.size()){
        auto t = heap.top();
        heap.pop();
        int num = t.second, dist = t.first;
        if(st[num]) continue;
        st[num] = 1;
        for(int i = h[num]; i != -1; i = ne[i]){
            int j = e[i];
            if(d[j] != d[num] + 1) continue;
            if(dis[j] > dis[num] + w[i]){
                dis[j] = dis[num] + w[i];
                heap.push({dis[j], j});
            }
        }
    }
    return dis[n];
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(), cout.tie();

    memset(h, -1, sizeof h);
    cin >> n >> m;
    while(m --){
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c), add(b, a, c);
    }
    bfs();
    int ans = dijkstra();
    cout << d[n] << ' ' << ans;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值