Graph theory shortest topics B-

Graph theory topics

Shortest B-

Face questions
in the annual school competition, all students finalists will receive a very nice t-shirt. But whenever our staff to hundreds of pieces of clothing shipped back to the stadium from the store when they are very tired! So now they want to find the shortest route to the stadium from the store, you can help them?

Input
input includes a plurality of sets of data. The first line of each two integers N, M (N <= 100 , M <= 10000), N represents a few street intersections Chengdu, reference numeral 1 is to store the location of the intersection, the intersection designated N is the location of the stadium, M indicates a couple of choices in Chengdu. N = M = 0 indicates the end of input. Next M rows, each row comprising three integers A, B, C (1 < = A, B <= N, 1 <= C <= 1000), indicates there is a path between the intersection A and the intersection B, we staff need to C-minute time traveled this road.

Input line to ensure the presence of at least one track to store.

Output
For each input and output line, represents the track workers come from the store minimum time

Sample Input

2 1
1 2 3

3 3
1 2 5
2 3 5
3 1 2

0 0

Sample Output

3
2

Topic analysis
shortest path problem template title, withPriority queuing algorithm dijkstra +orFloyd algorithmTemplates can solve problems

Code

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#include<vector>
#define INF 1000000000

using namespace std;

struct edge{
	int to,cost;
};

typedef pair<int,int > P;//first是最短距离,second是顶点编号 

int N,M;
vector<edge> G[105];   //G[v]存与v点相连的边 

int d[105];            //d[v]记录到v点最短距离 

void dijkstra(int s)
{
    //通过指定greater<P>参数,堆按照first从小到大的顺序取出值
	priority_queue< P , vector<P> , greater<P> > que;
	fill(d+1,d+N+1,INF);
	d[s] = 0;
	que.push( P(0,s) );
	
	while(!que.empty()){
		P p=que.top();que.pop();
		int v=p.second;//v为从v点出发 
		if(d[v]<p.first) continue;
		
		for(int i=0;i< G[v].size();i++){
			edge e=G[v][i];
			if(d[e.to]>d[v]+e.cost){   			//遍历与v相接边找出与v下一点
				d[e.to]=d[v]+e.cost;			//最短距离放至vector中 
				que.push( P(d[e.to],e.to) );	//【vector 按first小到大取出值】 
			}
		}
	}
	
} 

int main()
{
	while(~scanf("%d%d",&N,&M))
	{
		if(N==0&&M==0)break;
		for(int i=1;i<=N;i++)G[i].clear();
		while(M--)
		{
			int A,B,C;
			scanf("%d%d%d",&A,&B,&C);
			edge E;
			E.to=B;E.cost=C;
			G[A].push_back(E);
			
			E.to=A;
			G[B].push_back(E);
		}
		dijkstra(1);
		printf("%d\n",d[N]);
	}
	
	return 0;
} 
Released two original articles · won praise 0 · Views 68

Guess you like

Origin blog.csdn.net/h_bby/article/details/104005201