hdu5636 BestCoder Round #74 (div.2) 1002 Shortest Path

Shortest Path

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


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   (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  m   (1n,m105)  -- the number of vertices and the number of queries. The next line contains 6 integers  a1,b1,a2,b2,a3,b3   (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  ti   (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
BestCoder Round #74 (div.2)


官方题解:

Shortest Path

你可以选择分类讨论, 但是估计可能会写漏一些地方. 只要抽出新增边的端点作为关键点, 建立一个新图, 然后跑一遍floyd就好了. 复杂度大概O(62⋅m)O(6^2 \cdot m)O(62m)



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

using namespace std;

const int mod = 1000000007;

int n, m;
int dp[10][10], a[10];

int main()
{
	int T;
	while (~scanf("%d", &T)) {
		while (T--) {
			scanf("%d%d", &n, &m);
			for (int i = 1; i <= 6; i++) {
				scanf("%d", &a[i]);
			}
			
			//初始化新输入的6个点的距离
			for (int i = 1; i <= 6; i++) {
				for (int j = 1; j <= 6; j++) {
					dp[i][j] = abs(a[i] - a[j]);
				}
			}
			//因为新加入的边,使得六个点两两有一条最短边1 
			dp[1][2] = dp[2][1] = 1;
			dp[3][4] = dp[4][3] = 1;
			dp[5][6] = dp[6][5] = 1;
			
			//Floyd求6个点中任意两点的最短距离 
			for (int k = 1; k <= 6; k++) {
				for (int i = 1; i <= 6; i++) {
					for (int j = 1; j <= 6; j++) {
						dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]);
					}
				}
			}
			long long res = 0, ans;  //不用long long会溢出 
			for (int i = 1; i <= m; i++) {
				int s, t;
				scanf("%d%d", &s, &t);
				ans = abs(s - t);
				for (int j = 1; j <= 6; j++) {
					for (int k = 1; k <= 6; k++) {
						//最小值取值有两种情况,一种是原始距离,一种是通过那6个点其中两个,
						//已知dp[i][j]都是最小距离了,然后再加上s到达j和k到达t的距离,取小值 
						ans = min(ans, (long long)abs(s - a[j]) + dp[j][k] + abs(a[k] - t));
					}
				}
				res = (res + ans * i) % mod;
			}
			printf("%I64d\n", res);
		}
	}
	return 0;
}


你可能感兴趣的:(dp,ACM,图论,BestCoder,hduoj)