Shortest Path

时间:2022-09-25 16:47:35

Shortest Path

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1494    Accepted Submission(s): 476

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

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 T, indicating the number of test cases. For each test case:

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

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

The sum of values of m in all test cases doesn't exceed 106.

 
Output
For each test cases, output an integer S=(∑i=1mi⋅zi) mod (109+7), where zi is the answer for i-th query.
 
Sample Input
1
10 2
2 4 5 7 8 10
1 5
3 1
 
Sample Output
7
 
Source
 
Recommend
wange2014   |   We have carefully selected several similar problems for you:  5659 5658 5657 5655 5654 
 最近在学习最短路问题,floyd写法。
void floyd(){
    for(int k = 1; k<=6; k++)
        for(int i = 1; i<=6; i++)
            for(int j = 1; j<=6; j++)
                d[i][j] = min(d[i][j],d[i][k]+d[k][j]);
}
 #include <iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn = ;
const int INF = 0x3f3f3f3f;
const int mod = 1e9+;
int d[][];
int a[];
void floyd(){
for(int k = ; k<=; k++)
for(int i = ; i<=; i++)
for(int j = ; j<=; j++)
d[i][j] = min(d[i][j],d[i][k]+d[k][j]);
}
void solve(){
int t,n,m;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
for(int i = ; i<=; i++) scanf("%d",&a[i]);
for(int i = ; i<=; i++){
for(int j = ; j<=; j++){
d[i][j] = abs(a[i] - a[j]);
}
}
for(int i = ; i<=; i+=) d[i][i+] = d[i+][i] = ;
floyd();
long long sum = ; for(int k = ; k<=m; k++){
int x,y;
scanf("%d%d",&x,&y);
int ans = abs(x-y);
for(int i = ; i<=; i++)
for(int j = ; j<=; j++)
ans = min(ans,(abs(x-a[i])+d[i][j]+abs(y-a[j])));
sum = (sum + (long long)ans*k%mod)%mod;
}
printf("%I64d\n",sum);
}
}
int main()
{
solve();
return ;
}

卷珠帘