Reading data to make adjacency list with two weights - c++

I'm making an adjacency list to represent a graph of roads, there are two kinds of weights (length and capacity) and for some reason this code never exits the for loop. it gets stuck on the cin for the last line. input is in the form:
4 5 4
0 1 1 5
0 2 1 4
1 2 2 2
1 3 1 4
2 3 1 5
I'm a student starting out. Help is very much appreciated thank you.
#include <iostream>
#include <vector>
using namespace std;
int N, M, T; //#cities N, #highways M, time available T
struct Road {
int Y, L, C; //destination Y, length L and capacity C
};
void readNetwork(vector<vector<Road>> &adjList) {
cin >> N >> M >> T;
adjList.resize(N);
for (int i = 0; i < M; i++){
int x, y, l, c;
cin >> x >> y >> l >> c;
adjList[x].push_back({y,l,c});
}
}
int main() {
vector<vector<Road>> adjList;
readNetwork(adjList);
cout << adjList.size();
return 0;
};

Related

Getting unknown values along with answer

Smaller Greater Equal Numbers
PrepBuddy has N baskets containing one fruit each with some quality factor(ith basket have Ai quality factor) and Tina has one single basket with one fruit having quality factor K. She wants to know how many PrepBuddy's baskets have quality factor less(L) than K, how many baskets have quality factor more(M) than K and how many baskets have quality factor equal(E) to K.
Input format
The first line contains an integer T, representing the number of test cases.T test cases follow,First linecontains two space-separated integers N and K.The second line contains N space-separated integers representing the quality factor of the basket.
Output format
For each test case on a new line, print three space-separated integers representing the values of L, M,and E.
Constraints
1<=T<=100
1<=N,K<=10^5
−10^6<=A[i]<=10^6
Sum of all N over any test case file doesn't exceed 5∗10^6
Time Limit
1 second
Example
Input
2
5 2
-1 0 -3 1 2
5 3
1 -1 -5 2 4
Output
4 0 1
4 1 0
Sample test case explanation
In the first test case,
K=2, the baskets with quality factor smaller than K are [1,2,3,4], there is no basket which has quality factor more than K and there is one basket [5] which have quality factor equal to K.
My solution
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
ll n, k;
cin >> n >> k;
ll arr[n];
for (ll i = 0; i < n; i++) {
cin >> arr[i];
}
int less = 0, more = 0, equal = 0;
for (ll i = 0; i < n; i++) {
if (arr[i] < k) {
less++;
} else if (arr[i] > k) {
more++;
} else {
equal++;
}
cout << less << " " << more << " " << equal << " ";
}
cout << endl;
}
return 0;
}
Input
2
5 2
-1 0 -3 1 2
5 3
1 -1 -5 2 4
Output
1 0 0 2 0 0 3 0 0 4 0 0 4 0 1
1 0 0 2 0 0 3 0 0 4 0 0 4 1 0
Why am I getting additional numbers like 1 0 0 2 0 0 3 0 0 4 0 0 along with my answer.How to correct this?? Please help
The error in your code was quiet simple, and easy to debug. You were printing the output every run through the array, thus, getting all these extra prints.
How does it become easy to debug? Reorganizing the code so it will be more readable, made it quiet possible. Actually, the fix was moving the line:
cout<<less<<" "<<more<<" "<<equal<<" ";
Two line lower than it was.
In order to demonstrate it, here is the code fixed and organized:
#include <iostream>
#include <vector>
#include <cstdint>
int main()
{
int t;
std::cin >> t;
while(t--)
{
std::int64_t n,k;
std::cin >> n >> k;
std::vector<int> vec{n};
for(std::size_t i = 0; i < n; ++i)
{
std::cin >> vec[i];
}
int less=0, more=0, equal=0;
for (std::size_t i = 0; i < n; i++)
{
if (vec[i] < k)
{
less++;
}
else if (vec[i] > k)
{
more++;
}
else
{
equal++;
}
// The next output line was here, under the for loop!!!
}
std::cout << less << " " << more<< " " << equal << " "; // this is its place!
std::cout << std::endl;
}
return 0;
}
I have made only 3 changes:
Removed the using namespace std; and #include <bit/stdc++.h>.
Realigned the code according to its logical order - each new scope has its own indentation level, showing which command runs in which scope, revealing the mistake.
Used proper types to each thing: In C++ there are no dynamic arrays in the format arr[n], thus, you need to use std::vector. Also, there are fixed size lengths in cstdint, and you should use those to ensure you are using the right type. Also, prefer using unsigned values when possible, for example, when indexing, use either std::size_t, std::uint32_t or std::uint64_t.
This code worked fine for me
#include <bits/stdc++.h>
using namespace std;
int main()
{
int T,N,K,arr[N];
cin>>T;
while(T--)
{
cin>>N;
cin>>K;
for(int i=0;i<N;i++)
{
cin>>arr[i];
}
int L=0,M=0,E=0;
for(int i=0;i<N;i++)
{
if(arr[i]<K){
L++;
}
else if(arr[i]>K)
{
M++;
}
else{
E++;
}
}
cout<<L<<" "<<M<<" "<<E<<endl;
}
return 0;
}

I get segmentation fault in my C++ code while using std::cin [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I was solving an algorithm problem (it's a problem about topology sort, and is in Korean http://boj.kr/1948) and while testing example input, I get segmentation fault in the middle of input
7
9
1 2 4
1 3 2
1 4 3
2 6 3
2 7 5
3 5 1
4 6 4
5 6 2 // here when I input 6, I get segmentation fault
6 7 5
1 7
I found out cin causes this error, but I have no idea why this makes an error and how to fix it.
This is my whole code:
#include <bits/stdc++.h>
#define FOR(i, n) for (int i = 0; i < (n); i++)
using ll = long long;
using pii = std::pair<int, int>;
using namespace std;
struct Edge {
int end, weight;
Edge(int e, int w): end(e), weight(w) {}
};
struct State {
int node, time, cnt;
bool operator<( State &rhs ) const {
return time < rhs.time;
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int n, m, start, end;
vector< State > last;
vector< Edge > edges[10001];
queue< State > q;
cin >> n >> m;
for (int i = 0; i < n; i++) {
int a, b, c;
cin >> a >> b >> c;
edges[a].push_back(Edge(b, c));
}
cin >> start >> end;
q.push({start, 0, 0});
while (!q.empty()) {
State cur = q.front(); q.pop();
for (Edge e: edges[cur.node])
q.push({e.end, cur.time + e.weight, cur.cnt + 1});
if (cur.node == end)
last.push_back(cur);
}
sort(last.begin(), last.end());
cout << last.back().time << endl << last.back().cnt;
return 0;
}
I think you should be used m instead of n.
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
edges[a].push_back(Edge(b, c));
}

Find how much xtreme distance two people walk together

Amir and Bond are walking on a street. Initially, both are at the position X=0 and they start walking in the direction of increasing X. After N seconds, they stop. Let's denote Amir's speed and Bond's speed during the i-th of these seconds by Ai and Bi respectively.
Sometimes, Aman and Bond walk together, i.e. with the same speed side by side. Let's define the xtreme distance as the total distance they walk this way. Find this xtreme distance.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers A1,A2,…,AN.
The third line contains N space-separated integers B1,B2,…,BN.
Output
For each test case, print a single line containing one integer ― the total weird distance. It can be proved that this distance is an integer.
Constraints
1≤T≤20
1≤N≤10e5
1≤Ai≤10e5 for each valid i
1≤Bi≤10e5 for each valid i
the sum of N over all test cases does not exceed 10e6
Code
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin >> T;
while(T--)
{
long long int N;
long long int i, w = 0;
cin >> N;
int * A = new int [N+1];
int * X = new int [N+1];
int * B = new int [N+1];
int * Y = new int [N+1];
Y[0] = 0;
X[0] = 0;
for(i=1;i<=N;i++)
{
cin >> A[i];
X[i] = X[i-1] + A[i];
}
for(i=1;i<=N;i++)
{
cin >> B[i];
Y[i] = Y[i-1] + B[i];
}
for(i=1;i<=N;i++)
{
if((X[i]-X[i-1]) == (Y[i]-Y[i-1]))
w += (Y[i] - Y[i-1]);
}
cout << w << endl;
delete [] A;
delete [] B;
delete [] X;
delete [] Y;
}
return 0;
}
Example Input
3
4
1 3 3 4
1 2 4 4
2
2 3
3 2
2
3 3
3 3
Example Output
5
0
6
Error
I am not able to figure out the error (may be there is error in constraints)

BFS traversal giving wrong output

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.

Dijkstra shortest path algorithm error

I wrote the following code to implement the Dijkstra's shortest path algorithm:
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
#include <functional>
#include <list>
#include <cstring>
int findPath(std::vector<std::list<std::pair<int, int>>> graph, int x, int y) {
int n = graph.size();
std::priority_queue < std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> pq;
pq.push(std::pair<int, int>(0, x));
int *visited = new int[n + 1]{};
int *distance = new int[n + 1];
memset(distance, -1, sizeof(*distance) * (n + 1));
distance[x] = 0;
int current;
while (!pq.empty()) {
current = pq.top().second;
pq.pop();
if (current == y) {
return distance[y];
}
if (!visited[current]) {
visited[current] = 1;
for (std::list<std::pair<int, int>>::iterator it = graph[current].begin(); it != graph[current].end(); it++) {
if (!visited[it->first]) {
if (distance[it->first] == -1 || distance[it->first] > distance[current] + it->second) {
distance[it->first] = distance[current] + it->second;
pq.push(std::pair<int, int>(distance[it->first], it->first));
}
}
}
}
}
return distance[y];
}
int main()
{
std::ios::sync_with_stdio(false);
int n;
int m;
int x;
int y;
std::cin >> n >> m >> x >> y;
int a;
int b;
int c;
std::vector<std::list<std::pair<int, int>>> graph(n + 1);
for (int i = 0; i < m; ++i) {
std::cin >> a >> b >> c;
graph[a].push_back(std::pair<int, int>(b, c));
}
std::cout << findPath(graph, x, y) << std::endl;
return 0;
}
The input is N - number of vertexes, M - number of edges, x, y - 2 vertexes.
Then you have M lines of a, b, c which implies that you have a path from a to b with distance c.
Also you can have multiple edges from one vertex to another.
The goal is to find the shortest path from x to y. (-1 if there is no path)
I am using a priority queue of pairs (first one is the current distance to the vertex, and the second is the vertex).
The code works for some tests and gives a wrong answer for the rest (its from a judge system, so I can't see what the tests are).
I looked at it for an hour and I can't seem to find why it is not working.
I would be grateful if you can find the mistake, and why is it not working.
A sample input:
5 5 1 5
1 2 1
1 3 2
2 4 4
3 4 4
4 5 5
Output:
10
EDIT: There seems to be no error in the code. The task was ambiguous in the way that if there is a path from a to b, there is one from b to a. That was the error.