Reputation: 3
I was just trying to implement an adjacency list based graph, I'm not able to sort out, why second value appears twice in output print:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
int k = 0;
int n = 0;
cin>>k;
while(k>0){
cin>>n;
//Declare Adjacency List
vector<vector<pair<int, int>>> G;
G.resize(n);
//Add an edge u,v of weight w
while(n>0){
int u=0,v=0,w=0;
cin>>u>>v>>w;
G[u].push_back({v,w});
n--;
}
int i=0;
vector<vector<pair<int,int>>>::iterator it;
vector<pair<int,int>>::iterator it1;
for(it=G.begin() ; it < G.end(); it++,i++ ) {
for (it1=G[i].begin();it1<G[i].end();it1++){
for(pair<int,int> p: G[i]){
cout <<" "<<i<<"-> (w = "<<p.second<<") -> "<<p.first;
}
cout<<endl;
}
}
k--;
}
return 0;
}
Input:
1
5
1 2 2
2 3 1
2 4 4
4 5 3
Output:
0-> (w = 0) -> 0
1-> (w = 2) -> 2
2-> (w = 1) -> 3 2-> (w = 4) -> 4
2-> (w = 1) -> 3 2-> (w = 4) -> 4
4-> (w = 3) -> 5
I want to learn implementation.
Any new implementation will also be welcomed, I want to implement an undirected, weighted graph.
Upvotes: 0
Views: 271
Reputation: 248
Because of your second for-loop
for (it1=G[i].begin();it1<G[i].end();it1++)
you get a duplicate output.
I assume you use C++11. Here's a slightly improved version of your program. First of all, I have added the option to read in the number of vertices and edges.
#include <iostream>
#include <utility>
#include <vector>
int main() {
int k = 0;
std::cin >> k;
while (k > 0) {
// read in number of nodes and edges
auto n = 0;
auto m = 0;
std::cin >> n >> m;
// Adjacency list
std::vector<std::vector<std::pair<int, int>>> G;
G.resize(n);
// Add an edge (u,v) with weight w
while (m > 0) {
int u=0, v=0, w=0;
std::cin >> u >> v >> w;
G[u].emplace_back(v,w);
--m;
}
// Print out adjacency list
for (auto i = 0; i < G.size(); ++i) {
for (const auto pair: G[i]) {
std::cout << " " << i << "-- (w = " << pair.second << ") --> " << pair.first;
}
std::cout << '\n';
}
--k;
}
return 0;
}
With your example-input
1
5
4
1 2 2
2 3 1
2 4 4
4 5 3
which denotes a graph with 5 vertices and 4 edges we get the following output:
1-- (w = 2) --> 2
2-- (w = 1) --> 3 2-- (w = 4) --> 4
4-- (w = 3) --> 5
Upvotes: 1