第三部分 數據結構 --第四章 圖論算法-1381:城市路(Dijkstra)

1381:城市路(Dijkstra)

時間限制: 1000 ms 內存限制: 65536 KB
提交數: 8013 通過數: 2411
【題目描述】
羅老師被邀請參加一個舞會,是在城市n,而羅老師當前所處的城市爲1,附近還有很多城市2~n-1,有些城市之間沒有直接相連的路,有些城市之間有直接相連的路,這些路都是雙向的,當然也可能有多條。

現在給出直接相鄰城市的路長度,羅老師想知道從城市1到城市n,最短多少距離。

【輸入】
輸入n, m,表示n個城市和m條路;

接下來m行,每行a b c, 表示城市a與城市b有長度爲c的路。

【輸出】
輸出1到n的最短路。如果1到達不了n,就輸出-1。

【輸入樣例】
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
【輸出樣例】
90
【提示】
【數據規模和約定】

1≤n≤2000

1≤m≤10000

0≤c≤10000


思路:容易超時,這裏用Dijkstra,要用鄰接表而不是鄰接矩陣來做。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#define N 3001
#define INF 0x3f3f3f3f
using namespace std;
struct node{
	int pre;
	int next;
	int w;
}a[N*10];
int m,n;
int cnt;
int head[N],vis[N],f[N];
void add(int x, int y, int w){//鄰接表
	cnt++;
	a[cnt].pre = y;
	a[cnt].next = head[x];
	a[cnt].w = w;
	head[x] = cnt;
	cnt++;
	a[cnt].pre = x;
	a[cnt].next = head[y];
	a[cnt].w = w;
	head[y] = cnt;
	
}
int main(){
	cin >>n >> m;
	for(int i = 1; i <= m; i++)
	{
		int x,y,w;
		cin >> x >> y >> w;
		add(x,y,w);
	}
	memset(f,INF,sizeof(f));
	f[1] = 0;
	vis[1] = 1;
	int x = head[1];
	while( x!= 0){
		int y = a[x].pre;
		if(f[y] > a[x].w)
		f[y] = a[x].w;
		x = a[x].next;
	}
	int cnt = 0;
	while(cnt < n){
		cnt++;
		int k ;
		int minn = INF;
		for(int i = 1; i <= n; i++)
		if(!vis[i] && f[i] < minn)
		{
			minn = f[i];
			k = i;
		}
		vis[k] =1;
		int x = head[k];
		while( x!= 0){
		int y = a[x].pre;
		int w = a[x].w;
		if(!vis[y] && f[y] > f[k]+w)
		f[y] = f[k]+w;
		x = a[x].next;
	}
}
if(f[n] == INF)
cout << " -1" << endl;
else
cout << f[n] <<endl;
	return 0;
}```

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章