Shortest Path
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1466 Accepted Submission(s): 466
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
题意:
有一条长度为n的链,节点i和i+1之间有长度为1的边. 现在又新加了3条边, 每条边长度都是1. 给出m个询问, 每次询问两点之间的最短
路。
思路:
不加这三条边时,从x到y只有一条路径,加了之后我们发现我们可以选择仍然从以前的路走或者通过新加的几条路径来走,这种通过其他边来中转之前的距离的思路让我们想到了floyd,只需要在这新加的6个点终跑一边floyd,我们就可以发现这6个点之间最优的路径,然后再类似于floyd的处理数据即可。记得求余。
AC-code:
#include<cstdio>
#include<cstring>
#include<cmath>
#define min(a,b) a>b?b:a
int mod=1e9+7;
using namespace std;
int dis[6][6];
int main()
{
int T,n,m,k,i,j,a,p,b,s[6];
long long ans;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
scanf("%d%d%d%d%d%d",&s[0],&s[1],&s[2],&s[3],&s[4],&s[5]);
for(i=0;i<6;i++)
for(j=0;j<6;j++)
dis[i][j]=abs(s[i]-s[j]);
dis[0][1]=dis[1][0]=dis[2][3]=dis[3][2]=dis[4][5]=dis[5][4]=1;
for(i=0;i<6;i++)//中间跳板的顺序不可改变
for(j=0;j<6;j++)
for(k=0;k<6;k++)
dis[k][j]=min(dis[k][j],dis[i][k]+dis[j][i]);
ans=0;
for(i=1;i<=m;i++)
{
scanf("%d%d",&a,&b);
j=abs(a-b);
for(k=0;k<6;k++)
for(p=0;p<6;p++)
j=min(j,abs(a-s[p])+abs(b-s[k])+dis[k][p]);
j%=mod;
ans=(ans+(long long)i*j)%mod;
}
printf("%lld\n",ans);
}
return 0;
}