Travelling Sales Man (need to visit only subset of nodes): Bugged - algorithm

I need help with my travelling sales man problem code. Its bugged... I know because its a school assignment and there are test cases. So here it goes.
Given a connected graph where I need to visit a subset of nodes. How do I compute the shortest path?
As an example, refer to above image. I need to start from 0 and visit some/all nodes then go back to zero. In the process, I need to compute the shortest path.
Suppose I need to visit all nodes, I will go from 0 -> 1 -> 2 -> 3 -> 0 = 20 + 30 + 12 + 35 = 97. Suppose now I only need to visit node 2, I will go from 0 -> 3 -> 2 -> 3 -> 0 as that gives shortest path of 94 (I can visit nodes I don't have to visit if it can give a shortest path).
Basically, I did:
Compute shortest path between any 2 pairs of required nodes and the source (0). This gives me a shortest path 2D table like (I used dijkstra's):
| 0 1 2 3
--+--------------
0 |
1 |
2 |
3 |
Now, I modify the shopping sales man algorithm (aka. Floyd Warshall’s or APSP) to use this table. Current Java source (TSP and dijkstra's) looks like:
int TSP(int source, int visited) {
if (visited == (int)(Math.pow(2, K)-1)) { // all required visited
return sssp.get(source).get(0); // return to source (0)
} else if (memo.containsKey(source) && memo.get(source).containsKey(visited)) {
return memo.get(source).get(visited);
} else {
int item;
if (!memo.containsKey(source)) {
memo.put(source, new HashMap<Integer, Integer>());
}
memo.get(source).put(visited, 1000000);
for (int v = 0; v < K; v++) {
item = shoppingList[v];
if (!hasVisited(visited, item)) {
memo.get(source).put(visited, Math.min(
memo.get(source).get(visited),
sssp.get(source).get(item) + TSP(item, visit(visited, v))
));
}
}
return memo.get(source).get(visited);
}
}
int dijkstra(int src, int dest) {
PriorityQueue<IntegerPair> PQ = new PriorityQueue<IntegerPair>();
HashMap<Integer, Integer> dist = new HashMap<Integer, Integer>(); // shortest known dist from {src} to {node}
// init shortest known distance
for (int i = 0; i < N+1; i++) {
if (i != src) {
dist.put(i, Integer.MAX_VALUE); // dist to any {i} is big(unknown) by default
} else {
dist.put(src, 0); // dist to {src} is always 0
}
}
IntegerPair node;
int nodeDist;
int nodeIndex;
PQ.offer(new IntegerPair(0, src));
while (PQ.size() > 0) {
node = PQ.poll();
nodeDist = node.first();
nodeIndex = node.second();
if (nodeDist == dist.get(nodeIndex)) {
// process out going edges
for (int v = 0; v < N+1; v++) { // since its a complete graph, process all edges
if (v != nodeIndex) { // except curr node
if (dist.get(v) > dist.get(nodeIndex) + T[nodeIndex][v]) { // relax if possible
dist.put(v, dist.get(nodeIndex) + T[nodeIndex][v]);
PQ.offer(new IntegerPair(dist.get(v), v));
}
}
}
}
}
return dist.get(dest);
}
visited is used as a bitmask to indicate if a node has been visited
sssp is a HashMap<Integer, HashMap<Integer, Integer>> where the 1st hashmap's key is the source node and the key for 2nd hashmap is the destination. So it basically represent the 2D table u see in point 1.
memo is just what I used in dynamic programming as a "cache" of previously computed shortest path from a node, given a visited bitmap.
Full source: http://pastie.org/5171509
The test case that passes:
1
3 3
1 2 3
0 20 51 35
20 0 30 34
51 30 0 12
35 34 12 0
Where 1st line is the number of test cases. 3rd line (3 3). The 1st 3 is the number of nodes, 2nd 3 is the number of required nodes. 4th line is the list of required nodes. Then the rest is the table of edge weights.
The test case that fails is:
9 9
1 2 3 4 5 6 7 8 9
0 42 360 335 188 170 725 479 359 206
42 0 402 377 146 212 767 521 401 248
360 402 0 573 548 190 392 488 490 154
335 377 573 0 293 383 422 717 683 419
188 146 548 293 0 358 715 667 539 394
170 212 190 383 358 0 582 370 300 36
725 767 392 422 715 582 0 880 704 546
479 521 488 717 667 370 880 0 323 334
359 401 490 683 539 300 704 323 0 336
206 248 154 419 394 36 546 334 336 0
I got 3995 but the answer is 2537... sorry I know this is hard to debug ... I am having the same problem, the test case is too large ... at least for humans ... so I am creating smaller test case to test but they seem to pass ...

Perhaps not a full answer but I think it's at least pointing in the right direction: your code seems to give the results of following the paths 0->1->2->...->N->0. No real optimization seems to happen.
I reworked your code a bit to get a small failing test case:
int[][]mat=new int[N+1][N+1];
//original
//mat[0]=new int[]{0,20,51,35};
//mat[1]=new int[]{20,0,30,34};
//mat[2]=new int[]{51,30,0,12};
//mat[3]=new int[]{35,34,12,0};
//switched order of nodes, node 2 is now node 1
mat[0]=new int[]{0,51,20,35};
mat[1]=new int[]{51,0,30,12};
mat[2]=new int[]{20,30,0,34};
mat[3]=new int[]{35,12,34,0};
This produces 146 as a best path, showing that it follows the path 0->1->2->3->0 (47+30+34+35, 47 is the shortest path 0 to 1 using node 4) (all node numbers are with my order switch).
edit: I found the culprit after another quick look. You have the line if (!hasVisited(visited, item)) to check if you already visited node item. However, visited is built up by visit(visited, v), in which v is an index into the shoppinglist. item =shoppinglist[v] but you should use the same if you're shifting your visited vector.
You should use if (!hasVisited(visited, v)) instead of if (!hasVisited(visited, item))
On an unrelated note, I'm unsure if the first step of finding the shortest paths is necessary or could influence your results. If a direct link from A to B is longer than going through other nodes (say C), then it is replaced in the distance table. If you would then use that link in your final solution to go from A to B, then you would actually be going via C, which would already be in your path (since that path is a full TSP solution). If a node can only be visited once, then this might be a problem.

Related

Detect cycle in an undirected graph

In order to detect cycle in undirected graph,
following code anf algorithm are given; I am using normal Breadth First traversal along with slight modifications :
void bfsUtil(int s,vector<bool> &visited,vector<int> adj[],vector<int> &visits) {
queue<int> q;
q.push(s);
visits[s]++;
visited[s]=true;
while(!q.empty()) {
int vertex=q.front();
q.pop();
for(int i=0;i<adj[vertex].size();i++) {
if(!visited[adj[vertex][i]]) {
visited[adj[vertex][i]]=true;
q.push(adj[vertex][i]);
visits[adj[vertex][i]]++;
} else {
visits[adj[vertex][i]]++;
}
}
}
}
/* This function is used to detect a cycle in undirected graph
* adj[]: array of vectors to represent graph
* V: number of vertices
*/
bool isCyclic(vector<int> adj[], int V)
{
vector<int> visits(V,0);
vector<bool> visited(V,false);
for(int i=0;i<V;i++){
if(!visited[i]) {
bfsUtil(i,visited,adj,visits);
}
}
for(int i=0;i<visits.size();i++) {
if(visits[i]>2) {
return true;
}
}
return false;
}
Algorithm:
1. Normal Breadth first search and maintaining a count aray for the no of visits of each vertex.
2. If no of visits>2
print cycle is present
else
print no cycle
But i am getting wrong anwer for below test case:
Input:
46 45
0 44 1 23 1 35 1 37 1 38 2 20 2 35 3 13 4 44 5 21 5 36 6 41 7 8 8 18 9 17 9 41 9 45 10 13 10 21 10 33 10 34 10 39 10 42 11 17 12 24 13 44 14 19 15 25 16 34 18 24 19 25 21 24 21 26 22 37 23 28 25 31 25 35 25 40 25 41 25 44 27 43 27 44 29 40 30 34 32 33
Its Correct output is:
0
And Your Code's output is:
1
Where is my algorithm going wrong ?
Your algorithm is wrong. consider a graph of the following edges:
0 - 1
0 - 2
When the current node is 1, it also checks 0 as there is an edge from 1 to 0 too. so it will increment the visits count of 0. Similarly, 2 will also increment the count. So your code will always detect cycles wrongly.
To resolve this, you should keep a parent node for each node, from where the node is visited. When you are checking, you should never consider the edge to the parent.
And finally, you don't need the visits array. If you find an adjacent node that is not parent of current node, but is still visited before, then you can conclude that there is a cycle.
Modifying your code:
bool bfsUtil(int s,vector<bool> &visited,vector<int> adj[],vector<int> &parent) {
queue<int> q;
q.push(s);
visited[s]=true;
while(!q.empty()) {
int vertex=q.front();
q.pop();
for(int i=0;i<adj[vertex].size();i++) {
if(adj[vertex][i] == parent[vertex])
continue;
if(!visited[adj[vertex][i]]) {
visited[adj[vertex][i]]=true;
q.push(adj[vertex][i]);
parent[adj[vertex][i]] = vertex;
} else {
//cycle detected;
return true;
}
}
}
return false;
}
/* This function is used to detect a cycle in undirected graph
* adj[]: array of vectors to represent graph
* V: number of vertices
*/
bool isCyclic(vector<int> adj[], int V)
{
vector<bool> visited(V,false);
vector<int> parent(V, -1); // -1 means no parent assigned
for(int i=0;i<V;i++){
if(!visited[i]) {
if(bfsUtil(i,visited,adj,parent)) return true;
}
}
return false;
}

Algorithm for visiting all grid cells in pseudo-random order that has a guaranteed uniformity at any stage

Context:
I have a hydraulic erosion algorithm that needs to receive an array of droplet starting positions. I also already have a pattern replicating algorithm, so I only need a good pattern to replicate.
The Requirements:
I need an algorism that produces a set of n^2 entries in a set of format (x,y) or [index] that describe cells in an nxn grid (where n = 2^i where i is any positive integer).
(as a set it means that every cell is mentioned in exactly one entry)
The pattern [created by the algorism ] should contain zero to none clustering of "visited" cells at any stage.
The cell (0,0) is as close to (n-1,n-1) as to (1,1), this relates to the definition of clustering
Note
I was/am trying to find solutions through fractal-like patterns built through recursion, but at the time of writing this, my solution is a lookup table of a checkerboard pattern(list of black cells + list of white cells) (which is bad, but yields fewer artifacts than an ordered list)
C, C++, C#, Java implementations (if any) are preferred
You can use a linear congruential generator to create an even distribution across your n×n space. For example, if you have a 64×64 grid, using a stride of 47 will create the pattern on the left below. (Run on jsbin) The cells are visited from light to dark.
That pattern does not cluster, but it is rather uniform. It uses a simple row-wide transformation where
k = (k + 47) mod (n * n)
x = k mod n
y = k div n
You can add a bit of randomness by making k the index of a space-filling curve such as the Hilbert curve. This will yield the pattern on the right. (Run on jsbin)
     
     
You can see the code in the jsbin links.
I have solved the problem myself and just sharing my solution:
here are my outputs for the i between 0 and 3:
power: 0
ordering:
0
matrix visit order:
0
power: 1
ordering:
0 3 2 1
matrix visit order:
0 3
2 1
power: 2
ordering:
0 10 8 2 5 15 13 7 4 14 12 6 1 11 9 3
matrix visit order:
0 12 3 15
8 4 11 7
2 14 1 13
10 6 9 5
power: 3
ordering:
0 36 32 4 18 54 50 22 16 52 48 20 2 38 34 6
9 45 41 13 27 63 59 31 25 61 57 29 11 47 43 15
8 44 40 12 26 62 58 30 24 60 56 28 10 46 42 14
1 37 33 5 19 55 51 23 17 53 49 21 3 39 35 7
matrix visit order:
0 48 12 60 3 51 15 63
32 16 44 28 35 19 47 31
8 56 4 52 11 59 7 55
40 24 36 20 43 27 39 23
2 50 14 62 1 49 13 61
34 18 46 30 33 17 45 29
10 58 6 54 9 57 5 53
42 26 38 22 41 25 37 21
the code:
public static int[] GetPattern(int power, int maxReturnSize = int.MaxValue)
{
int sideLength = 1 << power;
int cellsNumber = sideLength * sideLength;
int[] ret = new int[cellsNumber];
for ( int i = 0 ; i < cellsNumber && i < maxReturnSize ; i++ ) {
// this loop's body can be used for per-request computation
int x = 0;
int y = 0;
for ( int p = power - 1 ; p >= 0 ; p-- ) {
int temp = (i >> (p * 2)) % 4; //2 bits of the index starting from the begining
int a = temp % 2; // the first bit
int b = temp >> 1; // the second bit
x += a << power - 1 - p;
y += (a ^ b) << power - 1 - p;// ^ is XOR
// 00=>(0,0), 01 =>(1,1) 10 =>(0,1) 11 =>(1,0) scaled to 2^p where 0<=p
}
//to index
int index = y * sideLength + x;
ret[i] = index;
}
return ret;
}
I do admit that somewhere along the way the values got transposed, but it does not matter because of how it works.
After doing some optimization I came up with this loop body:
int x = 0;
int y = 0;
for ( int p = 0 ; p < power ; p++ ) {
int temp = ( i >> ( p * 2 ) ) & 3;
int a = temp & 1;
int b = temp >> 1;
x = ( x << 1 ) | a;
y = ( y << 1 ) | ( a ^ b );
}
int index = y * sideLength + x;
(the code assumes that c# optimizer, IL2CPP, and CPP compiler will optimize variables temp, a, b out)

Algorithm to produce number series

I am not sure how to attack this problem... I tried many things, and it seems to be that it shouldn't be so difficult, but not getting there...
Is it possible to create a function "series ( _x )", that produces this :
The function for example should be myfunction( 11 ) => 211
The terms become suffix for the next terms. See below picture for more clarity. The boxes with same color gets repeated. So, we could just keep prepending 1 and 2 for previous results.
Code(In java):
public class Solution {
public static void main(String[] args) {
List<String> ans = solve(10);
for(int i=0;i<ans.size();++i) System.out.println(ans.get(i));
}
private static List<String> solve(int terms){
List<String> ans = new ArrayList<>();
String[] digits = new String[]{"1","2"};
ans.add("1");
if(terms == 1) return ans;
ans.add("2");
if(terms == 2) return ans;
List<String> final_result = new ArrayList<>();
final_result.addAll(ans);
terms -= 2;//since 2 numbers are already added
while(terms > 0){
List<String> temp = new ArrayList<>();
for(String s : digits){
for(int j=0;j<ans.size() && terms > 0;++j){
temp.add(s + ans.get(j));
terms--;
}
}
ans = temp;
final_result.addAll(ans);
}
return final_result;
}
}
This hint should help you... It isn't quite binary, but it is close. Let me know if you need any further help
0 -> - -> -
1 -> - -> -
10 -> 0 -> 1
11 -> 1 -> 2
100 -> 00 -> 11
101 -> 01 -> 12
110 -> 10 -> 21
111 -> 11 -> 22
1000 -> 000 -> 111
1001 -> 001 -> 112
1010 -> 010 -> 121
1011 -> 011 -> 122
1100 -> 100 -> 211
1101 -> 101 -> 212
1110 -> 110 -> 221
1111 -> 111 -> 222
Edit: I didn't like the way I ordered the columns, so I swapped 2 and 3
Python approach
First thing that we need to do is produce binary strings
in Python this can be done with bin(number)
However this will return a number in the form 0b101
We can easily strip away the 0b from the beginning though by telling python that we dont want the first two characters, but we want all the rest of them. The code for that is: bin(number)[2:] left side of the : says start two spaces in, and since the right side is blank go to the end
Now we have the binary numbers, but we need to strip away the first number. Luckily we already know how to strip away leading characters so change that line to bin(number)[3:].
All that is left to do now is add one to every position in the number. To do that lets make a new string and add each character from our other string to it after incrementing it by one.
# we already had this
binary = bin(user_in + 1)[3:]
new = ""
for char in binary:
# add to the string the character + 1
new += str(int(char) + 1)
And we are done. That snippet will convert from decimal to whatever this system is. One thing you might notice is that this solution will be offset by one (2 will be 1, 3 will be 2) we can fix this by simply adding one to user input before we begin.
final code with some convenience (a while loop and print statement)
while True:
user_in = int(input("enter number: "))
binary = bin(user_in + 1)[3:]
new = ""
for char in binary:
new += str(int(char) + 1)
print(user_in, "\t->\t", binary, "\t->\t", new)
According to A000055
We should perform 3 steps:
Convert value + 1 to base 2
Remove 1st 1
Add 1 to the rest digits
For instance, for 11 we have
Converting 11 + 1 == 12 to binary: 1100
Removing 1st 1: 100
Adding 1 to the rest digits: 211
So 11 has 211 representation.
C# code:
private static String MyCode(int value) =>
string.Concat(Convert
.ToString(value + 1, 2) // To Binary
.Skip(1) // Skip (Remove) 1st 1
.Select(c => (char)(c + 1))); // Add 1 to the rest digits
Demo:
var result = Enumerable
.Range(1, 22)
.Select(value => $"{MyCode(value),4} : {value,2}");
Console.Write(string.Join(Emvironment.NewLine, result));
Outcome:
1 : 1
2 : 2
11 : 3
12 : 4
21 : 5
22 : 6
111 : 7
112 : 8
121 : 9
122 : 10
211 : 11
212 : 12
221 : 13
222 : 14
1111 : 15
1112 : 16
1121 : 17
1122 : 18
1211 : 19
1212 : 20
1221 : 21
1222 : 22
In VB.NET, showing both the counting in base-3 and OEIS formula ways, with no attempts at optimisation:
Module Module1
Function OEIS_A007931(n As Integer) As Integer
' From https://oeis.org/A007931
Dim m = Math.Floor(Math.Log(n + 1) / Math.Log(2))
Dim x = 0
For j = 0 To m - 1
Dim b = Math.Floor((n + 1 - 2 ^ m) / (2 ^ j))
x += CInt((1 + b Mod 2) * 10 ^ j)
Next
Return x
End Function
Function ToBase3(n As Integer) As String
Dim s = ""
While n > 0
s = (n Mod 3).ToString() & s
n \= 3
End While
Return s
End Function
Function SkipZeros(n As Integer) As String
Dim i = 0
Dim num = 1
Dim s = ""
While i < n
s = ToBase3(num)
If s.IndexOf("0"c) = -1 Then
i += 1
End If
num += 1
End While
Return s
End Function
Sub Main()
Console.WriteLine("A007931 Base3 ITERATION")
For i = 1 To 22
Console.WriteLine(OEIS_A007931(i).ToString().PadLeft(7) & SkipZeros(i).PadLeft(7) & i.ToString().PadLeft(11))
Next
Console.ReadLine()
End Sub
End Module
Outputs:
A007931 Base3 ITERATION
1 1 1
2 2 2
11 11 3
12 12 4
21 21 5
22 22 6
111 111 7
112 112 8
121 121 9
122 122 10
211 211 11
212 212 12
221 221 13
222 222 14
1111 1111 15
1112 1112 16
1121 1121 17
1122 1122 18
1211 1211 19
1212 1212 20
1221 1221 21
1222 1222 22

How do I make this program work for input >10 for the USACO Training Pages Square Palindromes?

Problem Statement -
Given a number base B (2 <= B <= 20 base 10), print all the integers N (1 <= N <= 300 base 10) such that the square of N is palindromic when expressed in base B; also print the value of that palindromic square. Use the letters 'A', 'B', and so on to represent the digits 10, 11, and so on.
Print both the number and its square in base B.
INPUT FORMAT
A single line with B, the base (specified in base 10).
SAMPLE INPUT
10
OUTPUT FORMAT
Lines with two integers represented in base B. The first integer is the number whose square is palindromic; the second integer is the square itself. NOTE WELL THAT BOTH INTEGERS ARE IN BASE B!
SAMPLE OUTPUT
1 1
2 4
3 9
11 121
22 484
26 676
101 10201
111 12321
121 14641
202 40804
212 44944
264 69696
My code works for all inputs <=10, however, gives me some weird output for inputs >10.
My Code-
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int baseToBase(int num, int base) //accepts a number in base 10 and the base to be converted into as arguments
{
int result=0, temp=0, i=1;
while(num>0)
{
result = result + (num%base)*pow(10, i);
i++;
num = num/base;
}
result/=10;
return result;
}
long long int isPalin(int n, int base) //checks the palindrome
{
long long int result=0, temp, num=n*n, x=n*n;
num = baseToBase(num, base);
x = baseToBase(x, base);
while(num)
{
temp=num%10;
result = result*10 + temp;
num/=10;
}
if(x==result)
return x;
else
return 0;
}
int main()
{
int base, i, temp;
long long int sq;
cin >> base;
for(i=1; i<=300; i++)
{
temp=baseToBase(i, base);
sq=isPalin(i, base);
if(sq!=0)
cout << temp << " " << sq << endl;
}
return 0;
}
For input = 11, the answer should be
1 1
2 4
3 9
6 33
11 121
22 484
24 565
66 3993
77 5335
101 10201
111 12321
121 14641
202 40804
212 44944
234 53535
While my answer is
1 1
2 4
3 9
6 33
11 121
22 484
24 565
66 3993
77 5335
110 10901
101 10201
111 12321
121 14641
209 40304
202 40804
212 44944
227 50205
234 53535
There is a difference in my output and the required one as 202 shows under 209 and 110 shows up before 101.
Help appreciated, thanks!
a simple example for B = 11 to show error in your base conversion is for i = 10 temp should be A but your code calculates temp = 10. Cause in we have only 10 symbols 0-9 to perfectly show every number in base 10 or lower but for bases greater than that you have to use other symbols to represent a different digit like 'A', 'B' and so on. problem description clearly states that. Hope You will be able to fix your code now by modifying your int baseToBase(int num, int base)function.

Dijkstra boost distance map gives random values

I am trying to solve the problem where I am given:
a graph with v vertices and e edges and the edge weights.
Output:
the weight of the minimum spanning tree
the distance between the first node(0) and the farthest node(which can be any node except 0)
Problem:
My distance map just stores a random unknown number.
My input is:
5
5 6
0 1 1
0 2 2
1 2 5
1 3 1
3 2 2
2 4 3
4 5
1 0 91
2 0 50
2 1 849
3 0 451
3 1 724
8 25
1 0 91
2 0 176
2 1 658
3 0 61
3 1 740
4 0 21
4 1 817
4 2 407
4 3 469
5 0 468
5 1 493
5 2 400
5 3 814
5 4 86
6 0 611
6 1 457
6 2 776
6 4 452
6 5 4
7 0 601
7 2 722
7 3 11
7 4 249
7 5 530
7 6 632
9 9
1 0 64
3 1 914
4 1 331
4 2 824
5 3 509
7 5 520
7 6 460
8 1 415
8 7 263
3 2
1 0 533
2 1 920
The first number is the number of testcases,then for each testcase I have the number of vertices and edges,followed by the vertice number(2 of the denoting an edge) and the respective weights.
Example:
testcases
no_vert no_edges
node_1 node_2 weight_1
node_2 node_3 weight_2
ect....
Output: is the weight of spanning tree and the distance between first and farthest node:
7 5
592 451
450 176
3386 1262
1453 1453
So instead of this correct output I get:
7 5
592 2147483647
450 2147483647
3386 2147483647
Which means there is a problem with my dijkstras approach. I am not where there is a mistake,I assume it is with the distance vector,but where?
Here is my code
//============================================================================
// Name : boost_ex_1.cpp
// Author : priya
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include<vector>
#include<algorithm>
#include<boost/graph/adjacency_list.hpp>
#include<boost/graph/prim_minimum_spanning_tree.hpp>
#include<boost/graph/dijkstra_shortest_paths.hpp>
#include<boost/graph/kruskal_min_spanning_tree.hpp>
using namespace std;
using namespace boost;
typedef adjacency_list<vecS, vecS, directedS, no_property,property<edge_weight_t, int> > Graph;
//vertex and edge descriptor
typedef graph_traits<Graph>::vertex_descriptor Vertex;
typedef graph_traits<Graph>::edge_descriptor Edge;
int testcases();
int main() {
ios_base::sync_with_stdio(false);
int n=0;
cin>>n;
while(n--)
{
testcases();
}
return 0;
}
int testcases()
{
//creation of graphs
//get number of edges and vertices
int NEDGES,NVERT;
cin>>NVERT>>NEDGES;
//graph g
Graph g(NVERT);
Vertex SOURCE=0;
int a,b,c;
//property map for edge weights
property_map<Graph,edge_weight_t>::type weightMap = get(edge_weight,g);
//fill graph details in g
for(int i=0;i<NEDGES;++i)
{
cin >> a >> b >> c;
bool success;
Edge e;
tie(e,success) = add_edge(a,b,g);
weightMap[e]=c;
}
//filled graph with edges and vertices and weight in weightMap
vector<Edge> spanning_tree;
kruskal_minimum_spanning_tree(g,back_inserter(spanning_tree));
a=0;
for(vector<Edge>::iterator ei=spanning_tree.begin();ei!=spanning_tree.end();++ei)
{
a+=weightMap[*ei];
}
vector<int>distancep(NVERT); //distance ebtween nodes
dijkstra_shortest_paths(g,SOURCE,distance_map(&distancep[0]));
b=0;
for(int i=0;i<num_vertices(g);++i)
{
b=max(b,distancep[i]);
}
cout << a <<" "<< b << endl;
return 0;
}
I would be very grateful if anyone could help me.
Thank you.
EDIT:: In addition as you can see in my output,the last output is missing,Im also not able to figure out why.Thank you
I wanted to post the answer,In case someone has the same problem.
So, the first problem was the while loop it should be
while(n--)
NOT
while(--n)
It misses a testcase of the input.
Secondly, I had declared the grah as directedS, which is wrong,it should be undirectedS,and gave random distance values,since the values for distance was empty the otherway around.

Resources