Блог пользователя hoshyarchand

Автор hoshyarchand, история, 6 лет назад, По-английски

Why my code give below is giving TLE ? For the problem Dijkstra?

#include <bits/stdc++.h>
#define int long long
using namespace std;

const int INF = 1e18 ;

int parent[100001];

void f(int n) {
	if(n != 1) {
		f(parent[n]);
	}
	cout << n << ' ' ;
}


int32_t main() {
	
	#ifndef ONLINE_JUDGE
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
	#endif

	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int n, m, a, b, w;
	cin >> n >> m ; 
	vector<pair<int, int>> arr[n+1];
	int dist[n+1];
	
	for(int i = 0 ; i < m ; i++) {
		cin >> a >> b >> w ;
		arr[a].push_back({b, w});
		arr[b].push_back({a, w});
	}
	

	priority_queue< pair<int, int> > q;

	for(int i = 0 ; i <= n ; i++) {
		dist[i] = INF ;
	}

	dist[1] = 0;
	
	q.push({1, 0});

	while(!q.empty()) {
		int curr = q.top().first ;
		int curr_d = q.top().second ;
		q.pop();
		for(auto p : arr[curr]) {
			if(dist[p.first] > curr_d + p.second) {
				parent[p.first] = curr;
				dist[p.first] = curr_d + p.second ;
				q.push({p.first, dist[p.first]});
			}
		}
	}

	if(dist[n] == INF) {
		cout << -1 << '\n';
	} else {
		f(n);
	}

}

Thanks, in advance :)

  • Проголосовать: нравится
  • -24
  • Проголосовать: не нравится