P2984

[USACO10FEB]Chocolate Giving S

题意描述

Farmer John有B头奶牛(1<=B<=25000),有N(2*B<=N<=50000)个农场,编号1-N,有M(N-1<=M<=100000)条双向边,第i条边连接农场R_i和S_i(1<=R_i<=N;1<=S_i<=N),该边的长度是L_i(1<=L_i<=2000)。居住在农场P_i的奶牛A(1<=P_i<=N),它想送一份新年礼物给居住在农场Q_i(1<=Q_i<=N)的奶牛B,但是奶牛A必须先到FJ(居住在编号1的农场)那里取礼物,然后再送给奶牛B。你的任务是:奶牛A至少需要走多远的路程?

输入

6 7 3
1 2 3
5 4 3
3 1 1
6 1 9
3 4 2
1 4 4
3 2 2
2 4
5 1
3 6

输出

6
6
10

点拨

转化一下就是对原点求两个点的最短路

代码

#include<iostream>
#include<utility>
#include<queue>
using namespace std;
typedef long long ll;
#define fi(i,a,b) for(int i = a; i <= b; ++i)
#define fr(i,a,b) for(int i = a; i >= b; --i)
#define x first
#define y second
#define sz(x) ((int)(x).size())
#define pb push_back
using pii = pair<int,int>;
#define int long long 
//#define DEBUG
const int N = 1e5 + 5;
int cnt = 1;
int head[50005];
int dis[50005];
bool vis[50005];
struct edge{
    int e,w,ne;
}edge[N];
struct node{
    int e,w;
    bool operator < (const node p) const{
        return w > p.w;
    }
};

void add(int a,int b,int c){
    edge[cnt].e = b;
    edge[cnt].w = c;
    edge[cnt].ne = head[a];
    head[a] = cnt++;
}
int n,m,b;
void djstra(int s){
    priority_queue<node> pri;
    pri.push({s,0});
    while(!pri.empty()){
        node temp = pri.top();
        pri.pop();
        int e = temp.e;
        int w = temp.w;
        vis[e] = true;
        for(int j = head[e];j!=0;j=edge[j].ne){
            int p = edge[j].e;
            int q = edge[j].w;
            if(dis[p] >= dis[e] + q){
                dis[p] = dis[e] + q;
                if(!vis[p]) pri.push({p,dis[p]});
            }
        }
    }
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
#ifdef DEBUG
    //freopen(D:\in.txt,r,stdin);
#endif
    cin >> n >> m >> b;
    fi(i,1,n) dis[i] = 0x3f3f3f3f;
    dis[1] = 0;
    fi(i,1,m) {
        int a,b,c;
        cin >> a >> b >> c;
        add(a,b,c);
        add(b,a,c);
    }
    djstra(1);
    fi(i,1,b){
        int a,b;
        cin >> a >> b;
        cout << dis[a] + dis[b] << endl;
    }
    return 0;
}
posted @ 2022-03-18 20:42  Sun-Wind  阅读(32)  评论(0编辑  收藏  举报