NC24723. [USACO 2010 Feb S]Chocolate Giving
描述
As an example, consider a farm with 6 pastures, 6 paths, and 3 bulls (in pastures 2, 3, and 5) who wish to bestow chocolates on their love-objects: *1 <-- Bull wants chocolates for pasture 1 cow [4]--3--[5] <-- [5] is the pasture ID / | / | 4 2 <-- 2 is the cowpath length / | between [3] and [4] [1]--1--[3]*6 / \ / 9 3 2 / \/ [6] [2]*4 * The Bull in pasture 2 can travel distance 3 (two different ways) to get to the barn then travel distance 2+1 to pastures [3] and [4] to gift his chocolate. That's 6 altogether. * The Bull in pasture 5 can travel to pasture 4 (distance 3), then pastures 3 and 1 (total: 3 + 2 + 1 = 6) to bestow his chocolate offer. * The Bull in pasture 3 can travel distance 1 to pasture 1 and then take his chocolate 9 more to pasture 6, a total distance of 10.
输入描述
* Line 1: Three space separated integers: N, M, and B
* Lines 2..M+1: Line i+1 describes cowpath i with three space-separated integers: , , and
* Lines M+2..M+B+1: Line M+i+1 contains two space separated integers: and
输出描述
* Lines 1..B: Line i should contain a single integer, the smallest distance that the bull in pasture must travel to get chocolates from the barn and then award them to the cow of his dreams in pasture
示例1
输入:
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
Pascal(fpc 3.0.2) 解法, 执行用时: 63ms, 内存消耗: 3168K, 提交时间: 2019-11-09 20:04:32
var n,m,q,i,t,w,cnt,x,y,z:longint; a,b,c,d:array[0..400001]of longint; f:array[0..100001]of longint; e:array[0..1000001]of longint; begin readln(n,m,q); for i:=1 to m do begin readln(x,y,z); inc(cnt);a[cnt]:=y;b[cnt]:=c[x];c[x]:=cnt;d[cnt]:=z; inc(cnt);a[cnt]:=x;b[cnt]:=c[y];c[y]:=cnt;d[cnt]:=z; end; fillchar(f,sizeof(f),63); t:=1;w:=1;e[1]:=1; f[1]:=0; while t<=w do begin i:=c[e[t]]; while i<>0 do begin if f[a[i]]>f[e[t]]+d[i] then begin inc(w); f[a[i]]:=f[e[t]]+d[i]; e[w]:=a[i]; end; i:=b[i]; end; inc(t); end; for q:=1 to q do begin readln(x,y); writeln(f[x]+f[y]); end; end.
C++ 解法, 执行用时: 45ms, 内存消耗: 4728K, 提交时间: 2022-05-18 20:01:21
#include <bits/stdc++.h> using namespace std; const int N = 50010; const int INF = 0x3f3f3f3f; int n, m, k; vector <pair<int, int>>e[N]; int dis[N], vis[N]; void spfa() { memset(dis, INF, sizeof dis); dis[1] = 0; queue<int>q; q.push(1); while (!q.empty()) { int u = q.front(); q.pop(); vis[u] = 0; for (auto& op : e[u]) { int v = op.first, w = op.second; if (dis[v] > dis[u] + w) { dis[v] = dis[u] + w; if (!vis[v]) { vis[v] = 1; q.push(v); } } } } } int main() { scanf("%d%d%d", &n, &m, &k); while (m--) { int a, b, c; scanf("%d%d%d", &a, &b, &c); e[a].push_back({ b,c }); e[b].push_back({ a,c }); } spfa(); while (k--) { int a, b; scanf("%d%d", &a, &b); printf("%d\n", dis[a] + dis[b]); } return 0; }