I'm having a trouble solving a question which asks me to generate an edge graph using 4 random numbers a,b,c,d , so the formula is as follows , to generate the nodges of the graph we'll use variable d , if we divide d with 3 and we get a remainder of 0 then 10 nodges are generated , if d/3 = 1 then 11 nodges if d/3 = 2 then 12 nodges are generated , as for the edges we have the following formula (i,j) ∈ U <-> ((ai+bj)/c) / d ≤ 1 , basically the edge will connect the nodge of i with the nodge of j if the formula after dividing by d gives a remainder smaller or equal to 1. Can someone tell me what's the problem with the code below ?
Here is the code :
#include <iostream>
#include <vector>
using namespace std;
struct Edge {
int src, dest;
};
class Graph
{
public:
vector<vector<int>> adjList;
Graph(vector<Edge> const& edges, int N)
{
adjList.resize(N);
for (auto& edge : edges)
{
adjList[edge.src].push_back(edge.dest);
}
}
};
void printGraph(Graph const& graph, int N)
{
for (int i = 0; i < N; i++)
{
cout << i << " ——> ";
for (int v : graph.adjList[i])
{
cout << v << " ";
}
cout << endl;
}
}
int main()
{
vector<Edge> edges;
int a, b, c, d,remainder,Nodges,result;
cout << "Enter 4 values : \n";
cin >> a >> b >> c >> d;
remainder = d % 3;
if (remainder == 0)
{
Nodges = 10;
}
else if (remainder == 1)
{
Nodges = 11;
}
else if (remainder == 2)
{
Nodges = 12;
}
for (int i = 0; i < Nodges; i++)
{
for (int j = 0; j < Nodges; j++)
{
result = ((a * i + b * j) / c) % d;
if (result <= 1)
{
edges =
{
{i,j}
};
}
}
}
Graph graph(edges, Nodges);
printGraph(graph, Nodges);
return 0;
}
At first you do not handle the case of d being outside of desired range. If d is e. g. 37, then you leave Nodges uninitialised, invoking undefined behaviour afterwards by reading it. You might add a final else to catch that case, printing some representation for an empty graph or a message and then return, so that you do not meet the for loops at all.
Simpler, though:
if(remainder < 3)
{
nodes = 10 + remainder;
// your for loops here
}
If you want to create an empty graph anyway, then don't forget to initialise nodes to 0; otherwise you should include the graph code in the if block above, too.
The main point your code fails is the following, though:
edges =
{
{i,j}
};
That way, you create a new vector again and again, always containing a single element, and the old one is replaced by that.
You actually need:
edges.emplace_back(i, j);
Finally: Get used to always check the stream's state after input operation. Users tend to provide invalid input, if you do not catch that you might get inexpected and actually undefined behaviour (such as dividing by 0).
if(std::cin >> a >> b >> c >> d)
{
/* your code */
}
else
{
// handle invalid input, e. g. by printing some message
// if you want to go on reading the stream:
// clears the error flags:
std::cin.clear();
// clears the stream's buffer yet containing the invalid input:
std::cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
So, I was trying to solve the below problem using the most basic method i.e. storing the paths and finding LCA.
My code is working fine on VSCode and giving the right output. But when submitting on SPOJ, it gives runtime error (SIGSEGV).
Problem Link: https://www.spoj.com/problems/LCA/
Problem Description:
A tree is an undirected graph in which any two vertices are connected by exactly one simple path. In other words, any connected graph without cycles is a tree. - Wikipedia
The lowest common ancestor (LCA) is a concept in graph theory and computer science. Let T be a rooted tree with N nodes. The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself). - Wikipedia
Your task in this problem is to find the LCA of any two given nodes v and w in a given tree T.
Sample Input:
1
7
3 2 3 4
0
3 5 6 7
0
0
0
0
2
5 7
2 7
Sample Output:
Case 1:
3
1
My Code:
#include <iostream>
#include <vector>
#include <cmath>
#include <cstring>
using namespace std;
vector<vector<int>> edges;
bool storepath(int s, int d, vector<int>& path, vector<bool>& visited) {
if(s == d)
{
path.push_back(d);
return true;
}
else if(edges[s].size() == 1) {
if(s != d)
{
for(int i = 0; i < path.size(); i++)
if(path[i] == s) {
path.erase(path.begin() + i);
}
}
return false;
}
visited[s] = true;
path.push_back(s);
for(auto e: edges[s])
{
if(visited[e] == false)
{
bool ans = storepath(e, d, path, visited);
if(ans)
break;
}
}
}
int LCA(int a, int b)
{
if(a == b)
return a;
vector<int> path1, path2;
vector<bool> visited(edges.size(), false);
storepath(1, a, path1, visited);
visited.assign(edges.size(), false);
storepath(1, b, path2, visited);
int n = path1.size();
int m = path2.size();
int i = 0,j = 0;
while(i < n && j < m && path1[i] == path2[j]) {
i++;
j++;
}
return path1[i-1];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int t;
cin >> t;
int Case = 1;
while(t--)
{
int n;
cin >> n;
edges.resize(n+1);
for(int i = 1; i <= n; i++)
{
int size, val;
cin >> size;
while(size--)
{
cin >> val;
edges[i].push_back(val);
edges[val].push_back(i);
}
}
int q;
cin >> q;
cout << "Case "<< Case << ":" << endl;
while(q--)
{
int a, b;
cin >> a >> b;
cout << LCA(a, b) << endl;
}
Case++;
edges.clear(); //added after igor's comment (forgot to add before but used while submitting)
}
return 0;
}
I think I'm not accessing any out of scope element so SIGSEGV should not occur.
Please tell me how can I fix and improve my code.
Some bugs are easy to find, when you know how to find them. The tools every programmer should know about are valgrind and -fsanitize. Remember to always compile with warnings enabled and fix them. Compiling your code with:
g++ -Wall -Wextra -fsanitize=undefined 1.cpp && ./a.out </tmp/2
results in a helpful warning:
1.cpp:38:1: warning: control reaches end of non-void function [-Wreturn-type]
38 | }
| ^
and a runtime error:
1.cpp:9:6: runtime error: execution reached the end of a value-returning function without returning a value
Your storepath doesn't return value.
I am trying to solve the problem using the adjacency list now. But the problem I am facing here is when I am trying to insert the element in an adjacency list, it stores the value in the sequence I have entered.
For example for the test case:
5 8 0 1 0 4 1 2 2 0 2 4 3 0 3 2 4 3
My output is:
0 1 4 2 3
Expected output is:
0 1 2 3 4.
It is because my adjacency list stores the value in the fashion it was not entered in a sorted manner. How would I store it in a sorted manner? If I sort it, it just increases the complexity of the code. Please help.
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
void addEdge(vector<ll> edges[], ll u, ll v)
{
edges[u].push_back(v);
edges[v].push_back(u);
}
void BFS(vector<ll> edges[], ll v, bool * visited, queue<ll> q)
{
while(!q.empty())
{
ll s = q.front();
cout << s << " ";
q.pop();
for(ll i = 0; i < edges[s].size(); i++)
{
if(!visited[edges[s][i]])
{
visited[edges[s][i]] = true;
q.push(edges[s][i]);
}
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll v, e;
cin >> v >> e;
vector<ll> edges[v];
for(ll i = 0 ; i < e; i++)
{
int x, y;
cin >> x >> y;
addEdge(edges, x, y);
}
bool * visited = new bool[v];
memset(visited, false, sizeof(visited));
queue<ll> q;
q.push(0);
visited[0] = true;
BFS(edges, v, visited, q);
return 0;
}
Yes, you were right, the behaviour is due to the order in the input.
You could try using a priority queue instead of a simple vector for your adjacency list, to keep your vertices in a specific order, but this does add complexity to your algorithm.
I am trying to solve a problem on infoarena.ro (site similar to codeforces.com, but it's in Romanian) and for some reason, some elements from a set just change to random values. Relevant code:
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ofstream out("test.out");
ifstream in("test.in");
struct Edge
{
int from, to, color, index;
bool erased = false, visited = false;
};
struct Event;
int point(const Event* event);
struct Event
{
int time;
bool add;
Edge *edge;
bool operator < (const Event other) const
{
return (this->time < other.time) ||
(this->time == other.time && this->add < other.add) ||
(this->time == other.time && this->add < other.add &&
point(this)>point(&other));
}
};
int point(const Event* event)
{
if(event->edge->from == event->time)
return event->edge->to;
else
return event->edge->from;
}
vector<Edge> edges;
vector<Event> events;
int main()
{
int N, M;
in >> N >> M;
for(int i = 0; i < M; i++)
{
int x, y;
in >> x >> y;
if(x > y)
swap(x, y);
Edge e = {x, y, i, i};
edges.push_back(e);
events.push_back(Event{x, true, &edges.back()});
Edge debug = *events.back().edge;
events.push_back(Event{y, false, &edges.back()});
debug = *events.back().edge;
}
sort(events.begin(), events.end());
for(Event event : events)
out << event.edge->from << " " << event.edge->to << "\n";
return 0;
}
I excluded code I wrote that is not relevant to the question.
Input:
5 6
1 2
2 5
1 4
3 1
4 3
5 3
First line is N (number of vertices) and M (number of edges). Next lines are all the edges.
Output:
44935712 44896968
1 4
1 3
44935712 44896968
3 1941924608
1 3
3 4
3 5
1 4
3 4
3 1941924608
3 5
I am trying to make a "journal" like my teacher called it. For each edge (x,y) I want to add it in a stack at stage x, and erase it at stage y (along with all other elements in the stack until I reach (x, y)). I want to sort by the "time" when I make those operations (hence "time" value in the Event struct). "Add" indicates if this is an event of adding an edge or removing it from the stack.
I am outputting the edges in the "events" vector for debugging purposes and I noticed that the values change to random stuff. Can someone explain why is this happening?
The problem is here
events.push_back(Event{x, true, &edges.back()});
and here
events.push_back(Event{y, false, &edges.back()});
As you push structures into the edges vector, the vector will reallocate the memory needed to store the contained structures. If such a relocation happens then all iterators and pointers to elements in the vector become invalid.
A simple solution is to store pointers in the edges vector instead, and copy the pointers for the Event structures. Another possible solution is to do two passes. One to create the edges vector, and then a separate pass (loop) to create the events vector.
I tried to write a program that receive from the user 5 integers and print the second minimum number.
Here is a sample of what I've tried:
#include <iostream>
using namespace std;
int main () {
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
if (a>b && a<c && a<d && a<e)
cout<<a<<endl;
if (b>a && b<c && b<d && b<e)
cout<<b<<endl;
if (c>a && c<b && c<d && c<e)
cout<<c<<endl;
if (d>a && d<b && d<c && d<e)
cout <<d<<endl;
if (e>a && e<b && e<c && e<d)
cout <<e<<endl;
return 0;
}
When I enter 1 2 3 4 5 it prints the second minimum, but when I enter
5 4 3 2 1 Nothing will print on the screen. What am I doing wrong with this? Is there any other way to write my program?
The problem you have with your logic is that you do not enforce yourself to print only 1 item, and at least one item.
By using the 'else' part of the if/else syntax, you will ensure that only one branch can ever be hit. You can then follow this up with just an else at the end, as you know all other conditions are false.
Once you've done this, you'll see that you print the last value, (1) rather than the expected (4). This is because your logic regarding how to find the 2nd lowest is wrong. b>a is false for the case 5,4...
Note:
Every employed engineer, ever, would make this a loop in a std::vector / std::array, and I would suggest you point your teacher to this post because encouraging loops is a good thing rather than bad.
Something like
vector<int> data;
for (int i=0; i<5; ++i) {
int t;
cin >> t;
data.push_back(t);
}
std::nth_element(data.begin(), data.begin()+1, data.end(), std::greater<int>());
cout << data[1];
There are 120 possible permutations on 5 elements. Your code should output the correct number for all of them. So a fool-proof code would use 120 repetitions of a check, like the following:
if (a > b && b > c && c > d && d > e) // the order is a>b>c>d>e
cout << d;
else if (a > b && b > c && c > e && e > d) // the order is a>b>c>e>d
cout << e;
...
else if (e > d && d > c && c > a && e > b) // the order is e>d>c>a>b
cout << a;
else // the order is e>d>c>b>a
cout << b;
This is very long, inefficient and tricky code. If you do a typo in just one variable, it will output a wrong answer in some rare cases. Also, it doesn't handle the possibility of some inputs being equal.
If the number of inputs to a sorting algorithm is a known small constant, you can use an approach called sorting networks. This is a well-defined computer science problem, which has well-known optimal solutions for small numbers of inputs, and 5 certainly is small. An optimal sorting network for 5 inputs contains 9 comparators, and is described e.g. here.
Since you don't need to sort the numbers, but only to know the second smallest input, you can reduce the size of the network further, to 7 comparators.
The full sorting network (without the reduction from 9 to 7) translated to C++:
if (b < c)
swap(b, c);
if (d < e)
swap(d, e);
if (b < d)
swap(b, d);
if (a < c)
swap(a, c);
if (c < e)
swap(c, e);
if (a < d)
swap(a, d);
if (a < b)
swap(a, b);
if (c < d)
swap(c, d);
if (b < c)
swap(b, c);
// now the order is a ≥ b ≥ c ≥ d ≥ e
cout << d;
This code is also obscure - not obvious at all how and why it works - but at least it is small and in a sense optimal. Also, it's clear that it always prints something (so it fixes the original problem) and supports the case of partially equal inputs.
If you ever use such code in a larger project, you should document where you took it from, and test it. Fortunately, there are exactly 120 different possibilities (or 32, if you use the
zero-one principle), so there is a way to prove that this code has no bugs.
This should work for you. (Note that it might not be the best approach and you can minimize it with a function to calculate min and secondMin instead of the ugly copy paste of the logic but it will get you started:
#include <iostream>
using namespace std;
int main () {
int a,b,c,d,e;
int min, secondMin;
cin>>a>>b;
min = a < b ? a : b;
secondMin = a < b ? b : a;
cin>>c;
if (c < min)
{
secondMin = min;
min = c;
}
else if (c < secondMin)
{
secondMin = c;
}
cin>>d;
if (d < min)
{
secondMin = min;
min = d;
}
else if (c < secondMin)
{
secondMin = d;
}
cin>>e;
if (e < min)
{
secondMin = min;
min = e;
}
else if (e < secondMin)
{
secondMin = e;
}
cout << "min = " << min << ", secondMin = " << secondMin << endl;
return 0;
}
if you have any questions feel free to ask in the comment
#include <set>
std::set<int> values = { a, b, c, d, e }; // not an array.
int second_min = *std::next(values.begin(), 1); // not a loop
What about a recursive and more generic approach?
No arrays, no loops and not limited to just 5 integers.
The following function get_2nd_min() keeps track of the two lowest integers read from std::cin a total of count times:
#include <climits>
#include <cstddef>
#include <iostream>
int get_2nd_min(size_t count, int min = INT_MAX, int second_min = INT_MAX)
{
if (!count)
return second_min; // end of recursion
// read next value from cin
int value;
std::cin >> value;
// Does second_min need to be updated?
if (value < second_min) {
// Does min also need to be updated?
if (value < min) {
// new min found
second_min = min; // move the so far min to second_min
min = value; // update the new min
} else {
// value is lower than second_min but higher than min
second_min = value; // new second_min found, update it
}
}
// perform recursion
return get_2nd_min(count - 1, min, second_min);
}
In order to read 5 integers and obtain the 2nd lowest:
int second_min = get_2nd_min(5);
One approach is to first find the minimum number, min and then find the smallest value that isn't min. To do this first find the minimum value:
int min = std::min(a, std::min(b, std::min(c, std::min(d, e))));
Now we need to do the same again, but ignoring min. We can do this using a function called triMin which takes 3 values and discards any value that is the minimum:
int triMin(int currentMin, int left, int right)
{
if(currentMin == left) return right;
if(currentMin == right) return left;
return std::min(left, right);
}
You can now combine them to get the answer:
int a = 5, b = 4, c = 3, d = 2, e = 1;
int min = std::min(a, std::min(b, std::min(c, std::min(d, e))));
int min2 = triMin(min, a, triMin(min, b, triMin(min, c, triMin(min, d, e))));
std::cout << "Second min = " << min2 << std::endl;
This prints 2
This task can be fulfilled using one-pass algorithm. There is no need to use any collections (arrays, sets or anything).
This one-pass algorithm is memory efficient - it does not require storing all elements in collection (and wasting memory) and will work even with large number of elements when other solutions fail with out of memory.
General idea of this algorithm is like this:
take each number in order
you need two variables to store minimum and second minimum numbers from all already seen numbers.
when you get number you need to test it with current minumum to find if it is new minimum number.
if it is store it as minimum, store old minimum in second minimumnumber
otherwise check if it is less than second minimum number.
if it is store it as second minimum number.
now second minimum number contains answer for all already seen numbers.
repeat while there numbers that was not seen.
After investigating all numbers second minimum contain the answer.
Here is implementation with c++17 (link to wandbox):
#include <iostream>
#include <optional>
int main()
{
int a, b, c, d, e;
std::cin >> a >> b >> c >> d >> e;
// you can find second minimal number while going through each number once
auto find_current_answer = [minimum = std::optional<int>{}, next_to_minimum = std::optional<int>{}](int next) mutable {
// when receiving next number
// 1. check if it is new minimum
if (!minimum || minimum > next) {
// move values like this: next_to_minimum <- minimum <- next
next_to_minimum = std::exchange(minimum, next);
}
// 2. else check if it is new next_to_minimum
else if (!next_to_minimum || next_to_minimum > next) {
next_to_minimum = next;
}
// 3. return current answer
return next_to_minimum;
};
// repeat as much as you like
find_current_answer(a);
find_current_answer(b);
find_current_answer(c);
find_current_answer(d);
// store answer that is interesting to you
auto result = find_current_answer(e);
// if it has value - it is the answer
if (result) {
std::cout << "Answer: " << *result << '\n';
}
else {
std::cout << "Not enough numbers!\n";
}
}
Update
In this solution I'm using the min function:
#include <iostream>
using namespace std;
int minDifferentFromFirstMin(int x, int y, int firstMin) {
if(x < y) {
if(x != firstMin) {
return x;
}
else {
return y;
}
}
if(y < x) {
if(y != firstMin) {
return y;
}
else {
return x;
}
}
//if x & y are equals, return one of them
return x;
}
int main () {
int a,b,c,d,e;
int iter11, iter12, iter13;
int iter21, iter22, iter23;
int firstMinimum, secondMinimum;
cin>>a>>b>>c>>d>>e;
//iteration 1: find the first minimum
iter11 = min(a, b);
iter12 = min(c, d);
iter13 = min(iter11, iter12);
firstMinimum = min(iter13, e);
//iteration 2: find the second minimum
iter21 = minDifferentFromFirstMin(a, b, firstMinimum);
iter22 = minDifferentFromFirstMin(c, d, firstMinimum);
iter23 = minDifferentFromFirstMin(iter21, iter22, firstMinimum);
secondMinimum = minDifferentFromFirstMin(iter23, e, firstMinimum);
cout<<secondMinimum<<endl;
}