#53-【SPFA】B

版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/81282279

Description

Farmer John有B头奶牛(1<=B<=25000),有N(2*B<=N<=50000)个农场,编号1-N,有M(N-1<=M<=100000)条双向边,第i条边连接农场R_i和S_i(1<=R_i<=N;1<=S_i<=N),该边的长度是L_i(1<=L_i<=2000)。居住在农场P_i的奶牛A(1<=P_i<=N),它想送一份新年礼物给居住在农场Q_i(1<=Q_i<=N)的奶牛B,但是奶牛A必须先到FJ(居住在编号1的农场)那里取礼物,然后再送给奶牛B。

你的任务是:奶牛A至少需要走多远的路程?

Input

第1行:三个整数:N,M,B。

第2..M+1行:每行三个整数:R_i,S_i和L_i,描述一条边的信息。

第M+2..M+B+1行:共B行,每行两个整数P_i和Q_i,表示住在P_i农场的奶牛送礼物给住在Q_i农场的奶牛。

Output

共B行,每行一个整数,表示住在P_i农场的奶牛送礼给住在Q_i农场的奶牛至少需要走的路程

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

x到y要求的距离:dis[x][1] + dis[1][y]。又因为是无向图,dis[x][1] = dis[1][x]。所以,只要从1开始SPFA,后面的就很简单了。

#include <bits/stdc++.h>

#define SIZE 50001

using namespace std;

struct edge
{
	int to, dis;
};

queue<int> q;
vector<edge> graph[SIZE];
int dis[SIZE];
bool inqueue[SIZE];

void spfa(void) // SPFA
{
	int i, now, temp, d;
	
	inqueue[1] = true;
	q.push(1);
	dis[1] = 0;
	while (!q.empty())
	{
		now = q.front();
		inqueue[now] = false;
		q.pop();
		for (i = 0; i < graph[now].size(); ++i)
		{
			temp = graph[now][i].to;
			d = graph[now][i].dis;
			if (dis[now] + d < dis[temp])
			{
				dis[temp] = dis[now] + d;
				if (!inqueue[temp])
				{
					q.push(temp);
					inqueue[temp] = true;
				}
			}
		}
	}
	
	return;
}

int main(void)
{
	int n, m, b, x, y, w;
	
	scanf("%d%d%d", &n, &m, &b);
	while (m--)
	{
		scanf("%d%d%d", &x, &y, &w);
		graph[x].push_back({y, w});
		graph[y].push_back({x, w});
	}
	
	memset(dis, 63, sizeof (dis));
	spfa();
	
	while (b--)
	{
		scanf("%d%d", &x, &y);
		printf("%d\n", dis[x] + dis[y]); // 这样就简单多了,就是FFF(Faster Floyd Function)也救不了你
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/81282279
今日推荐