HDU 5636 Shortest Path【弗洛伊德 floyd】

参看资料:

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值