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 .
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<iostream>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
typedef long long LL;
const int INF = 0x7FFFFFFF;
const int mod = 1e9 + 7;
const int maxn = 1e5 + 10;
int T, n, m, s, t, ans, res;
int a[6], f[6];
void dfs(int s, int dis)
{
ans = min(ans, dis + abs(s - t));
for (int i = 0; i < 6; i++)
if (f[i])
{
f[i] = f[i ^ 1] = 0;
dfs(a[i ^ 1], dis + abs(s - a[i]) + 1);
f[i] = f[i ^ 1] = 1;
}
}
int main()
{
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &n, &m);
for (int i = 0; i < 6; i++) scanf("%d", &a[i]), f[i] = 1;
res = 0;
for (int i = 1; i <= m; i++)
{
scanf("%d%d", &s, &t);
ans = INF;
dfs(s, 0);
(res += (LL)ans*i%mod) %= mod;
}
printf("%d\n", res);
}
return 0;
}
现在补上floyd的,这题数据不多,用读入优化的意义不大
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=1e5+10;
const int mod=1e9+7;
int T,n,m,a[6],dis[6][6],x,y;
int main()
{
scanf("%d",&T);
while (T--)
{
scanf("%d%d",&n,&m);
for (int i=0;i<6;i++) scanf("%d",&a[i]);
for (int i=0;i<6;i++)
for (int j=0;j<6;j++) dis[i][j]=abs(a[i]-a[j]);
for (int i=0;i<6;i+=2) dis[i][i^1]=dis[i^1][i]=1;
for (int i=0;i<6;i++)
for (int j=0;j<6;j++)
for (int k=0;k<6;k++)
dis[j][k]=min(dis[j][k],dis[j][i]+dis[i][k]);
int res=0;
for (int k=1;k<=m;k++)
{
scanf("%d%d",&x,&y);
int ans=abs(x-y);
for (int i=0;i<6;i++)
for (int j=0;j<6;j++)
{
ans=min(ans,abs(x-a[i])+dis[i][j]+abs(y-a[j]));
}
(res+=(LL)k*ans%mod)%=mod;
}
printf("%d\n",res);
}
return 0;
}