dijistra优化终极版+upc6690

题目传送门
思路:
dis(s,k)+dis(k,t);
代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;
const ll INF=1e15+10;
const int MAX=100005;
typedef pair<ll,ll> p;
struct Edge
{
    ll to;
    ll cost;
    Edge(ll to,ll cost):to(to),cost(cost) {}
};
vector<Edge> edge[MAX*10];
ll dis[MAX];
ll u,v,w;
ll n,q,x;
void Dijkstra(int s)
{
    priority_queue<p,vector<p>,greater<p> > que;
    fill(dis+1,dis+n+1,INF);
    dis[s]=0;
    que.push(p(0,s));
    while(!que.empty())
    {
        p P=que.top();
        que.pop();
        v=P.second;
        if(dis[v]<P.first)
            continue;
        for(ll i=0; i<edge[v].size(); i++)
        {
            Edge e=edge[v][i];
            if(dis[e.to]>dis[v]+e.cost)
            {
                dis[e.to]=dis[v]+e.cost;
                que.push(p(dis[e.to],e.to));
            }
        }
    }
    return ;
}
int main()
{
    while(~scanf("%lld",&n))
    {
        for(ll i=1; i<=n-1; i++)
        {
            scanf("%lld%lld%lld",&u,&v,&w);
            edge[u].push_back(Edge(v,w));
            edge[v].push_back(Edge(u,w));
        }
        scanf("%lld%lld",&q,&x);
        Dijkstra(x);
        for(ll i=0; i<q; i++)
        {
            scanf("%lld%lld",&u,&v);
            printf("%lld\n",dis[u]+dis[v]);
        }
    }



}

猜你喜欢

转载自blog.csdn.net/wuxiaowu547/article/details/81192789