题目链接:https://www.luogu.org/problemnew/show/P2984
练习SPFA,把FJ当做起点,求出到所有牛的最短路,再把两个牛的相加。
#include <cstdio>
#include <queue>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = ;
const int inf = 0x7fffffff;
int n, m, b, dis[maxn];
bool vis[maxn];
struct edge{
int len, to, next, from;
}e[maxn];
int head[maxn], cnt;
queue<int> q;
void add(int u, int v, int w)
{
e[++cnt].from = u;
e[cnt].to = v;
e[cnt].len = w;
e[cnt].next = head[u];
head[u] = cnt;
}
int SPFA()
{
while(!q.empty())
{
int now = q.front();
q.pop();
vis[now] = ;
for(int i = head[now]; i ; i = e[i].next)
{
if(dis[e[i].to] > dis[now] + e[i].len)
{
dis[e[i].to] = dis[now] + e[i].len;
if(!vis[e[i].to])
{
vis[e[i].to] = ;
q.push(e[i].to);
}
}
}
}
}
int main()
{
scanf("%d%d%d",&n,&m,&b);
for(int i = ; i <= m; i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
for(int i = ; i <= n; i++)
dis[i] = inf;
dis[] = ;
q.push();
vis[] = ;
SPFA();
for(int i = ; i <= b; i++)
{
int p,q;
scanf("%d%d",&p,&q);
printf("%d\n",dis[p]+dis[q]);
}
return ;
}