【hdu 5636】Shortest Path 中文题意&题解&代码(C++)

Shortest Path

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)

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 . 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的处理数据即可。

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<math.h>
using namespace std;
int T,n,m,dis[6][6],a[6],x,y;
long long ans;
int main()
{
    scanf("%d",&T);
    int mmod=1e9+7;
    while(T--)
    {
        ans=0;
        scanf("%d%d",&n,&m);
        scanf("%d%d%d%d%d%d",&a[0],&a[1],&a[2],&a[3],&a[4],&a[5]);
        for (int i=0;i<6;i++)
        for (int j=0;j<6;j++)
        dis[i][j]=abs(a[i]-a[j]);

        dis[0][1]=1;dis[1][0]=1;
        dis[2][3]=1;dis[3][2]=1;
        dis[4][5]=1;dis[5][4]=1;

        for (int k=0;k<6;k++)
        for (int i=0;i<6;i++)
        for (int j=0;j<6;j++)
        dis[i][j]=min(dis[i][j],dis[i][k]+dis[k][j]);

        for (int k=1;k<=m;k++)
        {
            scanf("%d%d",&x,&y);
            int mm=abs(x-y);
            for (int i=0;i<6;i++)
            for (int j=0;j<6;j++)
            mm=min(mm,abs(a[i]-x)+abs(a[j]-y)+dis[i][j]);
            mm%=mmod;
            ans=(ans+(long long )mm*(long long )k)%mmod;
        }
        printf("%I64d\n",ans);
    // cout<<ans<<endl;
    }
}

你可能感兴趣的:(bc,bc,HDU)