Shortest Path

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


 

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

​BestCoder Round #74 (div.2)​

 

 

Recommend

wange2014

 

题意:n个点,1——2——3........——n,两点之间路径为1,现在增加三条长度为1 的路径,用xi——yi表示,给出m个查询,询问连点间的距离。

分析:

我们可以知道x,y不加点之前的路径长度|x-y|,因为要求两点间最短路,所以增加的路径要有缩短路径的功能,否则就没有用,所以,我们可以直接枚举三条路径,看看是否能缩短路径,缩短就更新最小值,就行,然后就可以floyd,来更新最短路径。这六个点的最短路就用floy来求就可以。

#include<stdio.h>
#include<string>
#include<string.h>
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long ll;


const int mod=1e9+7;
ll dis[10][10];
ll a[10],b[10];
int pos[10];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,m;
scanf("%d%d",&n,&m);

for(int i=1;i<=6;i++)
{
scanf("%lld",&a[i]);
b[i]=a[i];
}
sort(a+1,a+6+1);
for(int i=1;i<=6;i++)
for(int j=1;j<=6;j++)
{
dis[i][j]= abs(a[i]-a[j]);
}


for(int i=1;i<=6;i++)
{
pos[i]=lower_bound(a+1,a+6+1,b[i])-a;
if(i%2==0)
dis[pos[i]][pos[i-1]]=dis[pos[i-1]][pos[i]]=min(dis[pos[i]][pos[i-1]],(ll)1);
}
for (int k = 1; k <= 6; k++)
{
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= 6; j++)
{
dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]);
}
}
}
ll sum=0;
for(int k=1;k<=m;k++)
{
ll x,y;
scanf("%lld%lld",&x,&y);
ll minn=abs(x-y);
for(int i=1;i<=6;i++)
for(int j=1;j<=6;j++)
{
minn=min(minn,(ll)abs(x-a[i])%mod+(ll)abs(y-a[j])%mod+dis[i][j]%mod)%mod;
}
//cout<<minn<<endl;
sum=(sum+(ll)(k*minn)%mod)%mod;
}
printf("%lld\n",sum);

}
return 0;
}