Shortest Path
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1494 Accepted Submission(s): 476
You are given the graph and several queries about the shortest path between some pairs of vertices.
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.
10 2
2 4 5 7 8 10
1 5
3 1
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 ;
}
卷珠帘