HDOJ 5636 Shortest Path(dfs求最短路径)

Shortest Path

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


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
 

题意:有一个n个点的链,节点i与节点i+1之间有一条长度为1的边,现在有新加三条边,每条边的长度也为1,给出这些边的端点。有m条询问:x与y之间的最短路径是多长,结果是min_dis(x,y)*i累加。

题解:普通的建图跑最短路会超时,要按照新加入的点单独建图,复杂度减少。可是并不会(哭/(ㄒoㄒ)/~~
因为边长都为1,且加入的只有三条边,那么我们可以查询的x,y的结果只有这些情况:
①新加入的边一条都不走,直接abs(x-y);
②经过其中一条
③经过其中两条
④三条边全部经过
情况不多,用dfs暴力就行了,注意经过一条边的时候有两种情况,从x端进或者从y端进。

代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define mod 1000000007
#define LL long long 
LL ans,sum;
int mark[5];
int n,m,a[5][2],x,y;

void dfs(int k,int now,int dis)
{
	if(dis+abs(now-y)<ans)
		ans=dis+abs(now-y);
	if(k>3)//新加的边只有三条 
		return ;
	int i;
	for(i=0;i<3;++i)
	{
		if(!mark[i])
		{
			mark[i]=1;//标记走过了 
			dfs(k+1,a[i][0],dis+abs(now-a[i][1])+1);//从a[i][1]进入,从a[i][0]出来 
			dfs(k+1,a[i][1],dis+abs(now-a[i][0])+1);//同上 
			mark[i]=0;
		}
	}
}

int main()
{
	int i,t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d",&n,&m);
		for(i=0;i<3;++i)
			scanf("%d%d",&a[i][0],&a[i][1]);
		memset(mark,0,sizeof(mark));
		sum=0;
		for(i=1;i<=m;++i)
		{
			scanf("%d%d",&x,&y);
			ans=abs(x-y);
			dfs(1,x,0);
			sum=(sum+i*ans)%mod;
		}
		printf("%I64d\n",sum);
	}
	return 0;
}





你可能感兴趣的:(HDOJ 5636 Shortest Path(dfs求最短路径))