Duplicate data when printing the adjacency list of a graph - c++

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.

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

Related

Getting WA, created own test cases too but not getting approved answers

Link of Question : https://www.codechef.com/JULY20B/problems/PTMSSNG
Question Statement
Chef has N axis-parallel rectangles in a 2D Cartesian coordinate system. These rectangles may intersect, but it is guaranteed that all their 4N vertices are pairwise distinct.
Unfortunately, Chef lost one vertex, and up until now, none of his fixes have worked (although putting an image of a point on a milk carton might not have been the greatest idea after all…). Therefore, he gave you the task of finding it! You are given the remaining 4N−1 points and you should find the missing one.
Can anyone suggest where I'm going wrong or update my code or share a few test cases.
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#define ll long long
using namespace std;
int main()
{
int t;
cin >> t;
for (int i = 0; i < t; i++)
{
vector<pair<ll, ll>> v;
ll n, m, a;
bool checkx = false;
cin >> n;
m = 4 * n - 1;
ll x[m], y[m];
ll c, d;
a = (m - 1) / 2;
for (ll i = 0; i < m; i++)
{
cin >> x[i] >> y[i];
v.push_back(make_pair(x[i], y[i]));
}
sort(v.begin(), v.end());
for (ll i = a; i >= 1; --i)
{
if (v[2 * i].first != v[2 * i - 1].first)
{
c = v[2 * i].first;
checkx = true;
if ((2 * i) % 4 == 0 && i >= 2)
{
if (v[2 * i].second == v[2 * i + 1].second)
{
d = v[2 * i + 2].second;
}
else
{
d = v[2 * i + 1].second;
}
}
else
{
if (v[2 * i].second != v[2 * i - 1].second)
{
d = v[2 * i - 1].second;
}
else
{
d = v[2 * i - 2].second;
}
}
break;
}
}
if (checkx)
{
cout << c << " " << d;
}
else
{
if (v[0].second == v[1].second)
{
d = v[2].second;
}
else
{
d = v[1].second;
}
cout << v[0].first << " " << d;
}
cout << endl;
}
return 0;
}
You don't need to do such complex things. Just input your x and y vectors and xor every element of each vector. The final value will be the required answer.
LOGIC :
(a,b)------------------(c,b)
| |
| |
| |
| |
(a,d)------------------(c,d)
See by this figure, each variable (a, b, c, d) occurs even number of times. This "even thing" will also be true for the N rectangles. Hence, you have to find the values of x and y which are occurring odd number of times.
To find the odd one out in such cases, the best trick is to xor every element of the vector. This works because of these properties of xor : k xor k = 0 and k xor 0 = k.
CODE:
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
signed main() {
std::size_t t, n;
std::cin >> t;
while (t--) {
std::cin >> n;
n = 4 * n - 1;
std::vector<int> x(n), y(n);
for (std::size_t i = 0; i < n; ++i)
std::cin >> x.at(i) >> y.at(i);
std::cout << std::accumulate(x.begin(), x.end(), 0L, std::bit_xor<int>()) << ' '
<< std::accumulate(y.begin(), y.end(), 0L, std::bit_xor<int>()) << '\n';
}
return 0;
}
here is a test case that your code doesn't work:
1
2
1 1
1 4
4 6
6 1
9 6
9 3
4 3
the output of your code is (6,3),but it should be (6,4).
I guess you can check more cases where the rectangles intersects.
from functools import reduce
for _ in range(int(input())):
n=int(input())
li=[]
li1=[]
for i in range(4*n-1):
m,n=map(int,input().split())
li.append(m)
li1.append(n)
r =reduce(lambda x, y: x ^ y,li)
print(r,end=' ')
r =reduce(lambda x, y: x ^ y,li1)
print(r,end=' ')
print()

How to generate a permutation without two adjacent consecutive numbers?

In this problem, we will say that a permutation is cool is it does not have two adjacent consecutive numbers. Given n, print all the cool permutations of {0, …, n − 1}.
Input
input consists of several cases, each with an n between 1 and 9.
Output
For every case, print in lexicographical order all the cool permutations of {0, …, n − 1}.
I know how to solve the problem that prints all the permutations of { 1, …, n-1 } in lexicographical order. But I do not know how to generate the permutations without two adjacent consecutive numbers.
#include <iostream>
#include <vector>
using namespace std;
void write(const vector<int>& v) {
int s = v.size()-1;
for (int i = 0; i < s; ++i) cout << v[i] << ' ';
cout << v[s] << endl;
}
void generate(vector<int>& v, vector<bool>& u, int i, int n) {
if (i == n) write(v);
else {
for (int s = 1; s <= n; ++s) {
if (not u[s]) {
v[i] = s;
u[s] = true;
generate(v, u, i+1, n);
u[s] = false;
}
}
}
}
int main() {
int n;
while (cin >> n) {
vector<int> v(n);
vector<bool> u(n, false);
generate(v, u, 0, n-1);
cout << endl;
}
}
With this input:
1
2
3
4
5
I expect this output:
0
1 3 0 2
2 0 3 1
0 2 4 1 3
0 3 1 4 2
1 3 0 2 4
1 3 0 4 2
1 4 2 0 3
2 0 3 1 4
2 0 4 1 3
2 4 0 3 1
2 4 1 3 0
3 0 2 4 1
3 1 4 0 2
3 1 4 2 0
4 1 3 0 2
4 2 0 3 1
Thanks in advance!
An inefficient way of generating cool permutations, would be to first generate all permutations, and then to create a method that takes the vector v (who stores a candidate permutation), and evaluate whether this permutation is cool or not. If yes, print, if no, skip it, as #YSC suggested.
Example:
bool isCool(const vector<int>& v)
{
// special case, v.size==2
if(v.size() == 2) {
if(v[0] == v[1] + 1 || v[0] == v[1] - 1) {
return false;
} else {
return true;
}
}
// start from second element to pre-last
// and check if prev and next are adjacent to it
for(size_t i = 1; i < v.size() - 1; ++i) {
if(v[i] == v[i - 1] + 1 || v[i] == v[i - 1] - 1 ||
v[i] == v[i + 1] + 1 || v[i] == v[i + 1] - 1)
return false;
}
return true;
}
and then you would use it like in your generate method:
if (i == n && isCool(v)) write(v);
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
bool ConsecValues(int x, int y)
{
return abs(x - y) == 1;
}
bool HasConsecAdjValues(const vector<int>& v)
{
vector<int>::const_iterator cIter = adjacent_find(v.cbegin(), v.cend(),
ConsecValues);
return cIter != v.end();
}
vector<vector<int>> GetCoolPerms(int n)
{
vector<vector<int>> result;
vector<int> v(n);
iota(v.begin(), v.end(), 0);
do {
if (!HasConsecAdjValues(v))
result.push_back(v);
} while (std::next_permutation(v.begin(), v.end()));
return result;
}
void PrintPerm(const vector<int>& v)
{
for (const auto& num : v)
cout << num;
cout << endl;
}
int main()
{
vector<vector<int>> coolPerms = GetCoolPerms(5);
for (const auto& perm : coolPerms)
PrintPerm(perm);
getchar();
}

C++ - DFS code error

I tried to implement this algorithm but there's some logical error. The algorithm is given below.
DFS(G)
1. for each vertex u ∈ G.V
2. u.color = WHITE
3. u.pi = NIL
4. time = 0
5. for each vertex u ∈ G.V
6. if u.color == WHITE
7. DFS-VISIT(G,u)
DFS-VISIT(G,u)
1. time = time + 1
2. u.d = time
3. u.color = GRAY
4. for each v ∈ G.Adj[u]
5. if v.color == WHITE
6. v.pi = u
7. DFS-VISIT(G,v)
8. u.color = BLACK
9. time = time + 1
10. u.f = time
Code:
#include <bits/stdc++.h>
using namespace std;
#define WHITE 0
#define GRAY 1
#define BLACK 2
#define SIZE 100
int Time;
int adj[SIZE][SIZE];
int color[SIZE];
int parent[SIZE];
int d[SIZE];
void dfs_Visit(int G, int u)
{
Time++;
d[u] = Time;
color[u] = GRAY;
for(int i = 0; i < G; i++)
{
if(color[i] == WHITE)
{
parent[i] = u;
dfs_Visit(G, i);
}
}
color[u] = BLACK;
Time++;
cout << u << " ";
}
void dfs(int G)
{
for(int i = 0; i < G; i++)
{
color[i] = WHITE;
parent[i]=NULL;
}
Time=0;
cout << "DFS is ";
for(int i = 0; i < G; i++)
{
if(color[i] == WHITE)
{
dfs_Visit(G, i);
}
}
}
int main()
{
int vertex;
int edge;
cout << "VERTEX & Edge : ";
cin >> vertex >> edge;
cout << "Vertex is : " << vertex <<endl;
cout << "Edge is : " << edge <<endl;
int node1, node2;
for(int i = 0; i < edge; i++)
{
cout << "EDGE " << i << ": ";
cin >> node1 >> node2;
adj[node1][node2] = 1;
adj[node2][node1] = 1;
}
dfs(vertex);
}
Output picture
Inputs:
VERTEX & Edge : 4 5
Vertex is : 4
Edge is : 5
EDGE 0: 0 1
EDGE 1: 1 2
EDGE 2: 2 0
EDGE 3: 0 3
EDGE 4: 2 4
Output:
DFS is 3 2 1 0
And the accepted result is 2 1 3 0
The problem is that you haven't coded DFS-VISIT step 4 correctly
Step 4 says for each v ∈ G.Adj[u] but your code says for(int i=0; i<G; i++). Those aren't the same thing at all. You should only visit the adjacent vertexes.
In fact if you look at your code you never use adj at all. That can't be right.

I can't figure out a sum and numbers solution

I am not that skilled or advanced in C++ and I have trouble solving a problem.
I know how to do it mathematically but I can't write the source code, my algorithm is wrong and messy.
So, the problem is that I have to write a code that reads a number ( n ) from the keyboard and then it has to find a sum that is equal to n squared ( n ^ 2 ) and the number of sum's elements has to be equal to n.
For example 3^2 = 9, 3^2 = 2 + 3 + 4, 3 elements and 3^2 is 9 = 2 + 3 + 4.
I had several attempts but none of them were successful.
I know I'm borderline stupid but at least I tried.
If anyone has the time to look over this problem and is willing to help me I'd be very thankful.
1
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
//1,3,5,7,9,11,13,15,17,19,21,23,25,27..
int n;
list<int> l;
cin >> n;
if ( n % 2 == 0 ){
cout << "Wrong." << endl;
}
for ( int i = 1; i <= 99;i+=2){
l.push_back(i);
}
//List is full with 1,3,5,7,9,11,13,15,17,19,21,23,25,27..
list<int>::iterator it = find(begin(l),end(l), n);
}
2
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
// 3^2 = 2 + 3 + 4
// 7^2 = 4 + 5 + 6 + 7 + 8 + 9 + 10
int n;
int numbers[100];
for (int i = 0; i <= 100; i++){
numbers[i] = i;
}
cin >> n;
int requiredSum;
requiredSum = n * n;
//while(sum < requiredSum){
// for(int i = 1; i < requiredSum; i++){
// sum += i;
// sumnums.push_back(sum);
// }
//}
int sum = 0;
std::vector<int> sumnums;
while(sum < requiredSum){
for(int i = 1; i < requiredSum; i++){
sum += i;
sumnums.push_back(sum);
}
}
for(int i=0; i<sumnums.size(); ++i)
std::cout << sumnums[i] << ' ';
}
Update:
The numbers of the sum have to be consecutive numbers.Like 3 * 3 has to be equal to 2 + 3 + 4 not 3 + 3 + 3.
So, my first try was that I found a rule for each sum.
Like 3 * 3 = 2 + 3 + 4, 5 * 5 = 3 + 4 + 5 + 6 + 7, 7 * 7 = 4 + 5 + 6 + 7 + 8 + 9 + 10.
Every sum starts with the second element of the previous sum and continues for a number of elements equal to n - 1, like 3 * 3 = 2 + 3 + 4, 5 * 5 , the sum for 5 * 5 starts with 3 + another 4 elements.
And another algorithm would be #molbdnilo 's, like 3 * 3 = 3 + 3 + 3 = 3 + 3 + 3 - 1 + 1, 3 * 3 = ( 3 - 1 ) + 3 + ( 3 + 1 ), but then 5 * 5 = (5 - 2) + ( 5 - 1 ) + 5 + 5 + 1 + 5 + 2
Let's do a few special cases by hand.
(The division here is integer division.)
3^2: 9
2 + 3 + 4 = 9
x-1 x x+1
1 is 3/2
5: 25
3 + 4 + 5 + 6 + 7 = 25
x-2 x-1 x x+1 x+2
2 is 5/2
7: 49
4 + 5 + 6 + 7 + 8 + 9 + 10
x-3 x-2 x-1 x x+1 x+2 x+3
3 is 7/2
It appears that we're looking for the sequence from n - n / 2 to n + n / 2.
(Or, equivalently, n / 2 + 1 to n / 2 + n, but I like symmetry.)
Assuming that this is correct (the proof left as an exercise ;-):
int main()
{
int n = 0;
std::cin >> n;
if (n % 2 == 0)
{
std::cout << "Must be odd\n";
return -1;
}
int delta = n / 2;
for (int i = n - delta; i <= n + delta; i++)
{
std::cout << i << " ";
}
std::cout << std::endl;
}
If there is not constraints on what are the elements forming the sum, the simplest solution is just to sum up the number n, n times, which is always n^2.
int main()
{
int n;
cout<<"Enter n: ";
cin >> n;
for(int i=0; i<n-1; i++){
cout<<n<<"+";
}
cout<<n<<"="<<(n*n);
return 0;
}
Firstly, better use std::vector<> than std::list<>, at least while you have less than ~million elements (it will be faster, because of inside structure of the containers).
Secondly, prefer ++i usage, instead of, i++. Specially in situation like that
...for(int i = 1; i < requiredSum; i++)...
Take a look over here
Finally,
the only error you had that you were simply pushing new numbers inside container (std::list, std::vector, etc.) instead of summing them, so
while(sum < requiredSum){
for(int i = 1; i < requiredSum; i++){
sum += i;
sumnums.push_back(sum);
}
change to
// will count our numbers
amountOfNumbers = 1;
while(sum < requiredSum && amountOfNumber < n)
{
sum += amountOfNumbers;
++amountOfNumbers;
}
// we should make -1 to our amount
--amountOfNumber;
// now let's check our requirements...
if(sum == requiredSum && amountOfNumbers == n)
{
cout << "Got it!";
// you can easily cout them, if you wish, because you have amountOfNumbers.
// implementation of that I am leaving for you, because it is not hard ;)
}
else
{
cout << "Damn it!;
}
I assumed that you need sequential sum of numbers that starts from 1 and equals to n*n and their amount equils to n.
If something wrong or need explanation, please, do not hesitate to contact me.
Upd. amountOfNumber < n intead <=
Also, regarding "not starting from 1". You said that you know how do it on paper, than could you provide your algorithm, then we can better understand your problem.
Upd.#2: Correct and simple answer.
Sorry for such a long answer. I came up with a great and simple solution.
Your condition requires this equation x+(x+1)+(x+2)+... = n*n to be true then we can easily find a solution.
nx+ArPrg = nn, where is
ArPrg - Arithmetic progression (ArPrg = ((n-1)*(1+n-1))/2)
After some manipulation with only unknown variable x, our final equation will be
#include <iostream>
int main()
{
int n;
std::cout << "Enter x: ";
std::cin >> n;
auto squareOfN = n * n;
if (n % 2 == 0)
{
std::cout << "Can't count this.\n";
}
auto x = n - (n - 1) / 2;
std::cout << "Our numbers: ";
for (int i = 0; i < n; ++i)
std::cout << x + i << " ";
return 0;
}
Math is cool :)

Dijkstra's Algorithm , C++, Priority Queue, Adjacency List

#include <iostream>
#include <fstream>
#include <functional>
#include <climits>
#include <vector>
#include <queue>
#include <list>
using namespace std;
struct Vertices {
int vertex;
int weight;
Vertices(int v, int w) : vertex(v), weight(w) { };
Vertices() { }
};
class CompareGreater {
public:
bool const operator()(Vertices &nodeX, Vertices &nodeY) {
return (nodeX.weight > nodeY.weight) ;
}
};
vector< list<Vertices> > adj;
vector<int> weights;
priority_queue<Vertices, vector<Vertices>, CompareGreater> Q;
int nrVertices, nrEdges;
void Dijkstra(Vertices);
void makeGraph() {
ifstream myFile;
myFile.open("graph.txt");
myFile >> nrVertices >> nrEdges;
adj.resize(nrVertices+1);
int nodeX, nodeY, weight;
for (int i = 1; i <= nrVertices; ++i) {
weights.push_back(INT_MAX);
}
for (int i = 1; i <= nrEdges; ++i) {
myFile >> nodeX >> nodeY >> weight;
adj[nodeX].push_back(Vertices(nodeY, weight));
}
}
void printPath()
{
for (vector<int>::iterator itr = weights.begin()+1; itr != weights.end(); ++itr) {
cout << (*itr) << " "<<endl;
}
}
void Dijkstra(Vertices startNode) {
Vertices currVertex;
weights[startNode.vertex] = 0;
Q.push(startNode);
while (!Q.empty()) {
currVertex = Q.top();
Q.pop();
cout<<"Removed "<<&currVertex<<"from heap"<<endl;
if (currVertex.weight <= weights[currVertex.vertex]) {
for (list<Vertices>::iterator it = adj[currVertex.vertex].begin(); it != adj[currVertex.vertex].end(); ++it)
{
if (weights[it->vertex] > weights[currVertex.vertex] + it->weight) {
weights[it->vertex] = weights[currVertex.vertex] + it->weight;
Q.push(Vertices((it->vertex), weights[it->vertex]));
}
}
}
}
}
int main() {
makeGraph();
Dijkstra(Vertices(1, 0));
printPath();
return 0;
}
So this is my code to implement Dijkstra's algorithm with an adjacency list. With input:
7
2
2 2
4 1
2
4 3
5 10
2
1 4
6 5
4
3 2
5 2
6 8
7 4
1
7 6
0
1
6 1
This means that there exists 7 vertices in order from vertex 1 to 7. Vertex 1 has 2 edges, one to vertex 2 with weight 2, the second to vertex 4 with weight 1. Vertex 2 has 2 edges, the first to vertex 4 with weight 3, the second to vertex 5 with weight 10. Vertex 3 has 2 edges, the first to vertex 1 with weight 4, the second to vertex 6 with weight 5. And so forth.
However, it print out this:
Removed 0xbfb9d7a8from heap
Removed 0xbfb9d7a8from heap
0
4
2147483647
2147483647
2147483647
2147483647
When I need it to print out this:
V1: V2, 2; V4, 1
V2: v4, 3; V5, 10
V3: V1, 4; V6, 5
V4: V3, 2; V5, 2; V6, 8; V7, 4
V5: V7, 6
V6:
V7: V6, 1
Removed minimum 1 from heap
Print heap: V2, d=inf V4., d=inf v3, d= inf v7, d=inf v5......
Please help!!!!!