Shortest Path

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


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+(1i<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 (1n,m105) -- the number of vertices and the number of queries. The next line contains 6 integers a1,b1,a2,b2,a3,b(1a1,a2,a3,b1,b2,b3n), 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 t(1si,tin), 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=1mizi) 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

 

 

如果想做出这道题, 重要的是思路和知识的熟练掌握, Floyd模板并不难, 但怎么将它巧妙的用到了题中是值得思考的问题,还是自己掌握的不熟练, 一看别人的就懂, 但让自己写却毫无头绪

 

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <cmath>
#include <iostream>

using namespace std;

#define MOD (1000000000+7)

int main()
{
    int T;
    scanf("%d", &T);
    
    while(T--)
    {
        int n, m, i, j, k, l, r, u, v, a[10];
        int dp[10][10];
        long long  res=0, len;
        
        scanf("%d%d", &n, &m);
        
        for(i=1; i<=6; i++)
           scanf("%d", &a[i]);
        
        for(i=1; i<=6; i++) ///相当于对dp初始化 
        for(j=1; j<=6; j++)
            dp[i][j] = abs(a[i]-a[j]);
        
        if(a[1]!=a[2]) dp[1][2] = dp[2][1] = 1; ///如果两点不相等的话就让两点的距离为1 
        if(a[3]!=a[4]) dp[3][4] = dp[4][3] = 1;
        if(a[5]!=a[6]) dp[5][6] = dp[6][5] = 1;
        
        for(k=1; k<=6; k++)
        for(i=1; i<=6; i++)
        for(j=1; j<=6; j++)
           dp[i][j] = min(dp[i][j], dp[i][k]+dp[k][j]);
        
        for(i=1; i<=m; i++)
        {
            scanf("%d%d", &l, &r);
            len = abs(l-r);
            
            for(u=1; u<=6; u++)
            for(v=1; v<=6; v++)
            len = min(len, (long long)(abs(a[u]-l)+dp[u][v]+abs(a[v]-r)));
            
            res = (res+len*i)%MOD;
        }
        
        printf("%I64d\n", res);
            
    }
    return 0;
} 

 

posted on 2016-03-06 16:14  栀蓝  阅读(258)  评论(0编辑  收藏  举报

levels of contents