// C# program to find minimum distance between
// source and destination node and visiting
// of intermediate node is compulsory
using System;
using System.Collections.Generic;
public class GFG
{
static int MAXN = 100005;
// to store mapped values of graph
static List<Pair<int, int>>[] v = new List<Pair<int, int>>[MAXN];
// to store distance of
// all nodes from the source node
static int[] dist = new int[MAXN];
// Dijkstra's algorithm to find
// shortest path from source to node
static void dijkstra(int source, int n)
{
// set all the vertices
// distances as infinity
Array.Fill(dist, int.MaxValue);
bool[] vis = new bool[n];
// make distance from source
// vertex to source vertex is zero
dist[source] = 0;
// // multiset do the job
// as a min-priority queue
SortedSet<Pair<int, int>> q = new SortedSet<Pair<int, int>>(Comparer<Pair<int, int>>.Create((a, b) => a.first.CompareTo(b.first)));
q.Add(new Pair<int, int>(0, source));
while (q.Count != 0)
{
Pair<int, int> p = q.Min;
q.Remove(p);
int x = p.second;
if (vis[x])
continue;
vis[x] = true;
foreach (Pair<int, int> e in v[x])
{
int to = e.first;
int w = e.second;
// check if the next vertex
// distance could be minimized
if (dist[x] != int.MaxValue && dist[x] + w < dist[to])
{
dist[to] = dist[x] + w;
q.Add(new Pair<int, int>(dist[to], to));
}
}
}
}
// function to add edges in graph
static void addEdge(int s, int t, int weight)
{
v[s].Add(new Pair<int, int>(t, weight));
v[t].Add(new Pair<int, int>(s, weight));
}
static int solve(int source, int destination, int intermediate, int n)
{
int ans = int.MaxValue;
dijkstra(source, n);
// store distance from source to
// all other vertices
int[] dsource = (int[])dist.Clone();
dijkstra(destination, n);
// store distance from destination
// to all other vertices
int[] ddestination = (int[])dist.Clone();
dijkstra(intermediate, n);
// store distance from intermediate
// to all other vertices
int[] dintermediate = (int[])dist.Clone();
//Find the ans
for (int i = 0; i < n; i++)
ans = Math.Min(ans, dsource[i] + ddestination[i] + dintermediate[i]);
return ans;
}
//Driver code
public static void Main(string[] args)
{
int n = 4;
int source = 0, destination = 2, intermediate = 3;
for (int i = 0; i < MAXN; i++)
v[i] = new List<Pair<int, int>>();
addEdge(0, 1, 1);
addEdge(1, 2, 2);
addEdge(1, 3, 3);
Console.WriteLine(solve(source, destination, intermediate, n));
}
class Pair<F, S>
{
public F first;
public S second;
public Pair(F first, S second)
{
this.first = first;
this.second = second;
}
}
}