其他分享
首页 > 其他分享> > 洛谷 P2984 [USACO10FEB]给巧克力Chocolate Giving

洛谷 P2984 [USACO10FEB]给巧克力Chocolate Giving

作者:互联网

洛谷 P2984 [USACO10FEB]给巧克力Chocolate Giving

Description

Input

Output

Sample Input

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 

Sample Output

6 
6 
10 

题解:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define N 50005
#define M 200005
using namespace std;

struct Node
{
    int val, pos;
    friend bool operator < (Node x, Node y) {
        return x.val > y.val;
    }
};
struct E {int next, to, dis;} e[M];
int n, m, q, num;
int h[N], dis[N];
bool vis[N];

int read()
{
    int x = 0; char c = getchar();
    while(c < '0' || c > '9') c = getchar();
    while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
    return x;
}

void add(int u, int v, int w)
{
    e[++num].next = h[u];
    e[num].to = v;
    e[num].dis = w;
    h[u] = num;
}

void dijkstra()
{
    priority_queue<Node> que;
    memset(dis, 0x3f, sizeof(dis));
    dis[1] = 0, que.push((Node){0, 1});
    while(que.size())
    {
        int now = que.top().pos;
        que.pop();
        if(vis[now]) continue;
        vis[now] = 1;
        for(int i = h[now]; i != 0; i = e[i].next)
            if(dis[now] + e[i].dis < dis[e[i].to])
            {
                dis[e[i].to] = dis[now] + e[i].dis;
                if(!vis[e[i].to]) que.push((Node){dis[e[i].to], e[i].to});
            }
    }
}

int main()
{
    cin >> n >> m >> q;
    for(int i = 1; i <= m; i++)
    {
        int u = read(), v = read(), w = read();
        add(u, v, w), add(v, u, w);
    }
    dijkstra();
    for(int i = 1; i <= q; i++)
    {
        int u = read(), v = read();
        printf("%d\n", dis[u] + dis[v]);
    }
    return 0;
}

标签:Node,include,洛谷,Giving,USACO10FEB,int,que,now,dis
来源: https://www.cnblogs.com/BigYellowDog/p/11252182.html