HDU 5636 Shortest Path【弗洛伊德 floyd】

版权声明:转载什么的好说,附上友链就ojek了,同为咸鱼,一起学习。 https://blog.csdn.net/sodacoco/article/details/86510206

参看资料:

https://blog.csdn.net/hexianhao/article/details/52143812


题目:

There is a path graph G=(V,E)G=(V,E) with nn vertices. Vertices are numbered from 11 to nnand there is an edge with unit length between ii and i+1i+1 (1≤i<n)(1≤i<n). To make the graph more interesting, someone adds three more edges to the graph. The length of each new edge is 11. 

You are given the graph and several queries about the shortest path between some pairs of vertices.

Input

There are multiple test cases. The first line of input contains an integer TT, indicating the number of test cases. For each test case: 

The first line contains two integer nn and mm (1≤n,m≤105)(1≤n,m≤105) -- the number of vertices and the number of queries. The next line contains 6 integers a1,b1,a2,b2,a3,b3a1,b1,a2,b2,a3,b3 (1≤a1,a2,a3,b1,b2,b3≤n)(1≤a1,a2,a3,b1,b2,b3≤n), separated by a space, denoting the new added three edges are (a1,b1)(a1,b1), (a2,b2)(a2,b2), (a3,b3)(a3,b3). 

In the next mm lines, each contains two integers sisi and titi (1≤si,ti≤n)(1≤si,ti≤n), denoting a query. 

The sum of values of mm in all test cases doesn't exceed 106106.

Output

For each test cases, output an integer S=(∑i=1mi⋅zi) mod (109+7)S=(∑i=1mi⋅zi) mod (109+7), where zizi is the answer for ii-th query.

Sample Input

1
10 2
2 4 5 7 8 10
1 5
3 1

Sample Output

7

题目大意:

       给定n个点,1--n-1每个点 i 与点 i+1 形成一条通路,通路长为1;另外加三条边,每边权值为1;求任意两点之间的最短路径的值;

解题思路:

       一开始没注意数据量,直接暴力开了100000^2的数组,直接爆了;

       后来看了题解发现只求那六个点之间的最短路径就好了。在求任意两点最短路时,将经过这六个点之间的最短路遍历,选择最小的那个,即为最后的最短路。

代码实现:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
 
const int maxn = 100005;
const int mod = 1e9+7;
int n,m,x[6],dis[6][6];
 
void floyd(){
	for(int k = 0; k < 6; k++)
    for(int i = 0; i < 6; i++)
    for(int j = 0; j < 6; j++)
        dis[i][j] = min(dis[i][j],dis[i][k] + dis[k][j]);
}
 
int main(){
	int t,u,v;
	scanf("%d",&t);
	while(t--){
		scanf("%d%d",&n,&m);
		for(int i = 0; i < 6; i++) //六个点
			scanf("%d",&x[i]);
		for(int i = 0; i < 6; i++)
        for(int j = 0; j < 6; j++)
            dis[i][j] = abs(x[i] - x[j]);
		
		for(int i = 0; i < 6; i += 2) //新加入的边
			dis[i][i+1] = dis[i+1][i] = 1;
		
		floyd();
		
		long long ans = 0;
		
		for(int i = 1; i <= m; i++){
			scanf("%d%d",&u,&v);
			int len = abs(u - v);
			for(int j = 0; j < 6; j++)
            for(int k = 0; k < 6; k++){
                int tmp = abs(u - x[j]) + abs(v - x[k]) + dis[j][k];
                len = min(len,tmp);
            }
			ans = (ans + (long long) i * len % mod) % mod;
		}
		printf("%lld\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/sodacoco/article/details/86510206