This is basically an ICPC Tokyo regional question - Slim Span(UVA -1395)
Link to the question-https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4141
The question states that the slimmest tree is one with minimum difference between its shortest and longest edge and the tree itself does not need to be a minimum spanning tree, it just needs to be a spanning tree.
#include <iostream>
#include <vector>
#include <stdio.h>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <utility>
#include <algorithm>
#include <set>
using namespace std;
const int MAX = 110;
struct ii{
int first,second,third;
ii(int x, int y, int z){
first=x;//destination node
second=y;//weight of the edge
third=z;//slimness
}
bool operator<(const ii& rhs) const
{
return third > rhs.third;//slimmest edge first
}
};
vector <ii> adj[MAX];//adjacency list
int prim(int source, int n){
int maximum=-1, minimum=987654321;//maximum and minimum edge lengths
set<int> notvisited;//nodes not yet visited by prim
priority_queue< ii, vector< ii > > pq;
for(int i=1;i<=n; ++i){
notvisited.insert(i);
}
pq.push(ii(source, 0,0));
set<int>::iterator iterator1;
while(!pq.empty() && !notvisited.empty()){
ii temp=pq.top();
pq.pop();
int s=temp.first;//target
int w=temp.second;//weight of edge
//if visited->continue
if((iterator1=notvisited.find(s))==notvisited.end())continue;
notvisited.erase(s);
if(w!=0){
maximum=max(maximum,w);
minimum=min(minimum,w);
}
for(int i=0; i<adj[source].size(); ++i){
int target=adj[source][i].first;
int targetw=adj[source][i].second;
int slimness=targetw-w;
if((iterator1=notvisited.find(target))!=notvisited.end()){
pq.push(ii(target,targetw,max(slimness, 0-slimness)));
}
}
}
return maximum-minimum;
}
My idea was to sort the edges using the slimness instead of the weights. It is not working because from the very start it always marks the shortest edge as visited.
How do I correct my program to solve this problem?
Sample Input-
4 6//number of nodes, number of edges
1 2 10//source destination weight
1 3 100
1 4 90
2 3 20
2 4 80
3 4 40
Output- 20