hdoj--5636--Shortest Path(dfs)



Shortest Path

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


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)
 

Recommend
wange2014   |   We have carefully selected several similar problems for you:   5644  5643  5642  5641  5640 

崩溃了,刚开始一看还觉得挺简单,但是数据量太大了,1W*1W的数组开不出,试着用SPFA写了,但是果然超时了,一个一个遍历肯定要出事,,,,,
总共有三条添加的边,其他的边长度都可以表示为abs(a-b),重要的是看着三条边使用了多少,0,,1,2,3也就这样了,dfs看使用边的条数,同时记录走了多远,现在的位置,
如果现在的位置到走一条添加边需要的距离,这样一次一次列举加上回溯,找到最短路径,
真要命,因为一个中间数据开的太小,wa了无数次,以后数据尽量大一些吧,反正不要钱
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define Mod 1000000007
int p[10][2],n,m,x,y,vis[10];
long long ans;
void dfs(int k,int now,int dis)
{//记录用了多少添加边,现在的位置,以及走的距离 
	if(dis+abs(now-y)<ans)//如果现在直接到终点的距离小于当前的答案 
	ans=dis+abs(now-y);
	if(k>3)
	return ;
	for(int i=0;i<3;i++)
	{
		if(!vis[i])
		{
			vis[i]=1;//走到一条添加边起点或终点,并且走完 
			dfs(k+1,p[i][0],dis+abs(p[i][1]-now)+1);
			dfs(k+1,p[i][1],dis+abs(p[i][0]-now)+1);
			vis[i]=0;
		}
	}
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		memset(p,0,sizeof(p));
		scanf("%d%d",&n,&m);
		memset(vis,0,sizeof(vis));
		for(int i=0;i<3;i++)
		scanf("%d%d",&p[i][0],&p[i][1]);
		long long sum=0;
		for(int i=1;i<=m;i++)
		{
			scanf("%d%d",&x,&y);
			ans=abs(x-y);
			dfs(1,x,0);
			long long s=ans*i; 
			sum=(sum+s)%Mod;
		}
		printf("%I64d\n",sum);
	}
	return 0;
}

你可能感兴趣的:(hdoj--5636--Shortest Path(dfs))