Showing posts with label Dijkstra. Show all posts
Showing posts with label Dijkstra. Show all posts

Thursday, September 3, 2020

UVa :: 10986 :: Sending email

Problem : Please find the problem here.

Explanation : Given an undirected weighted graph, find the minimum distance between two given nodes. The problem is naive and clearly suggested to use the algorithm suited to calculate the SSSP.

Code : Used Dijkstra's Algorithm.

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

const int mxN = 2e5;
int n, m, s, t, d[mxN];
vector<array<int, 2>> adj[mxN];
bool vis[mxN];


void init(){
    memset(vis, false, sizeof(vis));
    for(int i = 0; i < n; i++){
        adj[i].clear();
        d[i] = INT_MAX;
    }
}

void solve(){
    cin >> n >> m >> s >> t;
    init();
    for(int i = 0, u, v, w; i < m; i++){
        cin >> u >> v >> w;
        adj[u].push_back({v, w});
        adj[v].push_back({u, w});
    }
    priority_queue<array<int,2>, vector<array<int, 2>>, greater<array<int, 2>>> pq;
    d[s] = 0;
    pq.push({0, s}); 
    while(pq.size()){
        array<int, 2> uu = pq.top();
        pq.pop();
        int u = uu[1];
        if(vis[u]) continue;
        vis[u] = 1;
        for(array<int, 2> vv : adj[u]){
            int v = vv[0], w = vv[1];
            if(d[v] > d[u]+w){
                d[v] = d[u]+w;
                pq.push({d[v], v});
            }
        }
    }
    if(d[t] == INT_MAX) cout << "unreachable\n";
    else cout << d[t] << '\n';
    
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int test_case;
    cin >> test_case;
    for(int i = 1; i <= test_case; i++){
        cout << "Case #" << i << ": ";
        solve();
    }
    return 0;
}

Friday, July 31, 2020

SPOJ : Highways Solution

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

#define ll long long

const int mxN = 1e5+5;
ll n, m, d[mxN], s, e;
vector<array<ll, 2>> adj[mxN];
bool vis[mxN];

int main()
{
	int t;
	cin >> t;
	while(t--){
		cin >> n >> m >> s >> e;
		s--, e--;
		for(int i = 0; i < n; i++){
			adj[i].clear();
			d[i] = mxN;
			vis[i] = 0;
		}
		for(int i = 0, a, b, c; i < m; i++){
			cin >> a >> b >> c;
			a--, b--;
			adj[a].push_back({c, b});
			adj[b].push_back({c, a});
		}
		d[s] = 0;
		priority_queue<array<ll, 2>> pq;
		pq.push({0, s});
		while(!pq.empty()){
			array<ll, 2> u = pq.top();
			pq.pop();
			if(vis[u[1]])continue;
			vis[u[1]] = 1;
			for(array<ll, 2> v : adj[u[1]]){
				if(d[v[1]] > d[u[1]]+v[0]){
					d[v[1]] = d[u[1]]+v[0];
					pq.push({-d[v[1]], v[1]});
				}
			}
		}
		if(d[e] == mxN){
			cout << "NONE\n";
		}else{
			cout << d[e] << '\n';
		}
	}
	return 0;
}