HDU:5636 Shortest Path(floyd+最短路径)

来源:互联网 发布:mysql读写分离中间件 编辑:程序博客网 时间:2024/05/07 23:21

Shortest Path

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


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
110 22 4 5 7 8 101 53 1
 

Sample Output
7
 

Source
BestCoder Round #74 (div.2)
 

Recommend

wange2014   |   We have carefully selected several similar problems for you:  5867 5866 5865 5864 5863 


题目大意:n个节点,汽车和火车都从1出发,问各自沿着最短路,谁后到达n点,输出后到的那个所用的时间,如果有一个不能到达n点,输出-1.。这里每两个点之间时间为1,保证该图是完全图。两种交通工具不能在途中任何点相遇。

解题思路:既然说不能在途中任何点相遇,那么比如火车能从a到达b,那么汽车就不能从a到达b了,然后比较下他俩最短路的大小。题中数据较小,考虑用floyd算法。

代码如下:

#include <cstdio>#include <cstring>#include <algorithm>#define INF 0x3f3f3f3fusing namespace std;int maphuo[410][410];//火车 int mapqi[410][410];//汽车 int main(){int n,m;scanf("%d%d",&n,&m);for(int i=1;i<=n;i++)//初始化火车的map {for(int j=1;j<=n;j++){if(i==j){maphuo[i][j]=0;}else{maphuo[i][j]=INF;}}}for(int i=0;i<m;i++)//输入火车所连接的点 {int x,y;scanf("%d%d",&x,&y);maphuo[x][y]=1;maphuo[y][x]=1;}for(int i=1;i<=n;i++)//初始化汽车的map ,火车能走的,汽车不能走 {for(int j=1;j<=n;j++){if(i==j){mapqi[i][j]=0;continue;}if(maphuo[i][j]==INF)//火车不能走的,汽车能走 {mapqi[i][j]=1;}else//火车能走的,汽车不能走 {mapqi[i][j]=INF;}}}for(int k=1;k<=n;k++)//打表火车的最短路径和汽车的最短路径 {for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){if(mapqi[i][k]+mapqi[k][j]<mapqi[i][j]){mapqi[i][j]=mapqi[i][k]+mapqi[k][j];}if(maphuo[i][k]+maphuo[k][j]<maphuo[i][j]){maphuo[i][j]=maphuo[i][k]+maphuo[k][j];}}}}if(mapqi[1][n]!=INF&&maphuo[1][n]!=INF)//两个都能到达n点,则比较谁后到达 {printf("%d\n",max(mapqi[1][n],maphuo[1][n]));}else//其中任意一个到不了n点的,则输出-1 {printf("-1\n");}return 0;}


0 0
原创粉丝点击