HDU 2544: shortest path

shortest path

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 81379    Accepted Submission(s): 35232


Problem Description
In the annual school competition, all the finalists will receive a beautiful t-shirt. But every time our staff transports hundreds of clothes from the store back to the arena, it's very tiring! So now they want to find the shortest route from the store to the arena, can you help them?

 

Input
The input includes multiple sets of data. The first line of each set of data is two integers N and M (N<=100, M<=10000). N represents how many intersections there are on the streets of Chengdu. The intersection marked with 1 is where the store is located, and the intersection marked with N It is the location of the stadium, and M means that there are several roads in Chengdu. N=M=0 means the end of input. Next M lines, each line includes 3 integers A, B, C (1<=A, B<=N, 1<=C<=1000), indicating that there is a road between intersection A and intersection B, we The staff takes C minutes to walk this way.
Enter a route that guarantees there is at least 1 store to the arena.
 

Output
For each set of inputs, output a line representing the minimum time for a worker to walk from the store to the arena
 

Sample Input
 
  
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0  

Sample Output
 
  
3 2  


#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#define INF 0x3f3f3f3f
const int maxn=1e3+10;
int way[maxn][maxn];
int flag[maxn],dis[maxn];
int n,m;
int a,b,c;
void Dijkstra()
{
	memset(flag,0,sizeof(flag));
	int ans,x;
	for(int i=1;i<=n;i++) dis[i]=way[1][i];
	dis[1]=0;
	flag[1]=1;
	for(int i=1;i<=n;i++)
	{
		ans=INF;
		for(int j=1;j<=n;j++)
		{
			if(ans>dis[j]&&!flag[j])
			{
				ans=dis[j];
				x=j;
			}
		}
		flag[x]=1;
		for(int j=1;j<=n;j++)
		if(!flag[j])
			dis[j]=std::min(dis[j],dis[x]+way[x][j]);
	}
}
intmain()
{
	while(~scanf("%d%d",&n,&m))
	{
		if(n==0&&m==0) break;
		for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
		way[i][j]=INF;
		while(m--)
		{
			scanf("%d%d%d",&a,&b,&c);
			way[a][b]=way[b][a]=c;
		}
		Dijkstra();
		printf("%d\n",dis[n]);
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324783486&siteId=291194637