码迷,mamicode.com
首页 > 其他好文 > 详细

【luogu P2984 [USACO10FEB]给巧克力Chocolate Giving】 题解

时间:2018-04-25 22:03:20      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:head   for   bsp   span   str   name   cstring   std   www.   

题目链接:https://www.luogu.org/problemnew/show/P2984

练习SPFA,把FJ当做起点,求出到所有牛的最短路,再把两个牛的相加。

 1 #include <cstdio>
 2 #include <queue>
 3 #include <iostream>
 4 #include <algorithm>
 5 #include <cstring>
 6 using namespace std;
 7 const int maxn = 1000000;
 8 const int inf = 0x7fffffff;
 9 int n, m, b, dis[maxn];
10 bool vis[maxn];
11 struct edge{
12     int len, to, next, from;
13 }e[maxn];
14 int head[maxn], cnt;
15 queue<int> q;
16 void add(int u, int v, int w)
17 {
18     e[++cnt].from = u;
19     e[cnt].to = v;
20     e[cnt].len = w;
21     e[cnt].next = head[u];
22     head[u] = cnt;
23 }
24 int SPFA()
25 {
26     while(!q.empty())
27     {
28         int now = q.front();
29         q.pop();
30         vis[now] = 0;
31         for(int i = head[now]; i ; i = e[i].next)
32         {
33             if(dis[e[i].to] > dis[now] + e[i].len)
34             {
35                 dis[e[i].to] = dis[now] + e[i].len;
36                 if(!vis[e[i].to])
37                 {
38                     vis[vis[e[i].to]] = 1;
39                     q.push(e[i].to);
40                 }
41             }
42         }
43     }
44 }
45 int main()
46 {
47     scanf("%d%d%d",&n,&m,&b);
48     for(int i = 1; i <= m; i++)
49     {
50         int u,v,w;
51         scanf("%d%d%d",&u,&v,&w);
52         add(u,v,w);
53         add(v,u,w);
54     }
55     for(int i = 1; i <= n; i++)
56     dis[i] = inf;
57     dis[1] = 0;
58     q.push(1);
59     vis[1] = 1;
60     SPFA();
61     for(int i = 1; i <= b; i++)
62     {
63         int p,q;
64         scanf("%d%d",&p,&q);
65         printf("%d\n",dis[p]+dis[q]);
66     }
67     return 0;
68 }

 

【luogu P2984 [USACO10FEB]给巧克力Chocolate Giving】 题解

标签:head   for   bsp   span   str   name   cstring   std   www.   

原文地址:https://www.cnblogs.com/MisakaAzusa/p/8947222.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!