can´t print anything after declaring vector in c++ - c++

I was making an algorithm to solve Problem 1310 from the URI Online Judge and at some point i needed to delete an item from an array in an easy way, so i declared a vector, but, besides having no issues running whatsoever, my code doesn´t print anything using , cout doesn´t work at all.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int Lucro(int c, int n, vector<int> r){
if (n == 0){
return 0;
}else if (n == 1){
return max(r[0] - c, 0);
}
int q;
q = 0;
for (int k = 0; k < n; k++){
r.erase(r.begin() + k);
q = max(q, r[k] - c + Lucro(c, n-1, r));
}
return q;
}
int main()
{
int C, N, items;
cin >> N >> C;
vector<int> R;
for (int i = 0; i < N; i++){
cin >> items;
R.push_back (items);
}
cout << Lucro(C, N, R) << endl;
cout << 'test' << endl;
}
As i´m quite new to using vectors in c++, could someone please explain to me what´s going on and how to fix it?

Most likely your program crashes because you are getting out-of-range of your vector by erasing elements and not decrementing the size n:
for (int k = 0; k < n; k++){
r.erase(r.begin() + k); //decrement n after this
q = max(q, r[k] - c + Lucro(c, n-1, r));
}
In any case you shouldn't really have n variable at all, you should use r.size() to always get the current size of the vector.

Related

What's wrong in this code , it's doing nothing other than taking inputs of n and m

Here in this question the function call is not executing also tell me abut can't I use array instead of vectors here.
if Possible to use array please provide me with code that how to pass arrays to a function in c++
Here in this question the function call is not executing also tell me abut can't I use array instead of vectors here.
if Possible to use array please provide me with code that how to pass arrays to a function in c++
#include <iostream>
#include <vector>
using namespace std;
int recursion(vector<vector<int>> &v, int n, int m)
{
if (n == 0 && m == 0)
{
return v[n][m];
}
int left = v[n][m] + recursion(v, n - 1, m);
int right = v[n][m] + recursion(v, n, m - 1);
return min(left, right);
}
int main()
{
int n, m;
cout << "enter the value of n and m" << endl;
cin >> n >> m;
cout << n << m;
//it's doing nothing after this point.
vector<vector<int>> vec(n, vector<int>(m));
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= m; j++)
{
vec[i][j] = (i)*m + (j + 1);
}
}
int result = recursion(vec, n, m);
cout << result;
return 0;
}
vec[i][j] = (i)*m + (j + 1);
is out-of-bounds for i = n and j = m. Same problem with calling recursion(vec, n, m);

C++ program test case acceptance

I've attempted to solve a coding contest out of curiosity. Out there, there's one of the problems which couldn't pass all the test cases for my solution. Could there be any improvement in my solution that you would suggest that might help? TIA. The problem along with my solution is stated down below.
The Constraints:
1 ≤ M,N ≤ 10^7,
1 ≤ a[i],b[i] ≤ 10^7
The Output:
Print a single int that the maximum cool value that he
can obtain after buying two items with the given
amount of money
And my solution is:
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long N, M, C, count;
cin>>N>>M>>C;
long long a[N], b[M];
for(long long i=0; i<N; i++){
cin>>a[i];
}
for(long long i=0; i<M; i++){
cin>>b[i];
}
sort(a, a+N);
sort(b, b+M);
if(a[N-1] + b[M-1] <= C){
count = (N-1) + (M-1);
cout<<count<<endl;
}
else{
cout<<"Not even closer"<<endl;
}
return 0;
}
Can anyone suggest what I could improve here to pass all the test?
After sorting, the price a[i] has a coolness equal to i.
Therefore, a solution consists in sorting a and b, and then maximize i+j such that a[i]+a[j] <= C
This last optimisation is performed by a simple for loop, with two indices, one for a and one for b
Complexity is dominated by sorting: O(NlogN + MlogM)
Note: the code currently posted in the question was edited after some comments, and do not correspond to the original code
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
int N, M, C;
std::cin >> N >> M >> C;
std::vector<int> a(N), b(M);
for (int i = 0; i < N; i++){
std::cin >> a[i];
}
for (int i = 0; i < M; i++){
std::cin >> b[i];
}
sort(a.begin(), a.end());
sort(b.begin(), b.end());
if(a[0] + b[0] > C) {
std::cout <<"E kemon aynabaji!!!" << std::endl;
return 0;
}
int max_cool = 0;
int iB = M-1;
for (int iA = 0; iA < N; ++iA) {
while (iB >= 0 && (a[iA] + b[iB] > C)) {
iB--;
}
if (iB < 0) break;
int cool = iA + iB;
if (cool > max_cool) max_cool = cool;
}
std::cout << max_cool << std::endl;
return 0;
}

Memory Leaks in C++ using Vectors

I'm currently working on a program that is pretty well explained in the comment section at the top. I know that when n = 10, E(4) = 8 and E(6) = 9. However, I'm showing E(4) = 7 and E(6) now tells me k is too large. I'm fairly new to coding, and I could really use some pointers on finding my mistakes (no pun intended).
Edit: I do realize that this program is pretty inefficient. If anyone has some tips on optimization they would be much appreciated as well.
Edit: Solved! I ended up making a 2D vector and made a function to sort it in ascending order. My issue with the primes vector not filling was due to me accidentally passing rads to the findPrimes function.
/* This program takes in integers n and k. It fills a vector with prime numbers up to n.
It then finds all prime numbers that can divide integers 1 to n with no remainder and
fills a vector with the results and the associated n (i in loop) value. The vector is
then sorted and the (k-1)th element (k for user) of the resulting vector is displayed. */
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void findPrimes(vector<int>&, int);
bool sortRads(const vector<int>& a, const vector<int>& b);
int main(int argc, const char * argv[]) {
vector<int> primes;
vector< vector<int> > kVec;
vector<int> rads (2, 0);
int n;
int k;
int radN;
cout << "Enter n: ";
cin >> n;
cout << "Enter k: ";
cin >> k;
findPrimes(primes, n);
//Fills rads vector with rad(n)
for (int i = 1; i <= n; i++) {
radN = 1;
for (int j = 0; ((j < primes.size()) && (j < i)); j++) {
if (i % primes[j] == 0) {
radN = radN * primes[j];
}
}
rads[0] = i;
rads[1] = radN;
kVec.push_back(rads);
}
sort(kVec.begin(), kVec.end(), sortRads);
//Ensures k is within the bounds of rads vector
while (k > n) {
cout << "k value too large. new k: ";
cin >> k;
}
cout << "E(" << k << "): " << kVec[k-1][0] << endl;
return 0;
}
void findPrimes(vector<int>& primes, int n) {
bool isPrime;
primes.push_back(1);
primes.push_back(2);
for (int i = 3; i <= n; i++) {
isPrime = true;
for (int j = 2; j <= (i/2); j++) {
if (i % j == 0) {
isPrime = false;
}
}
if (isPrime == true) {
primes.push_back(i);
}
}
}
bool sortRads(const vector<int>& a, const vector<int>& b) {
if (a[1] == b[1]) {
return a[0] < b[0];
}
else {
return a[1] < b[1];
}
}
The only thing that can possibly be causing errors is when you use the k value. It's read in, but you never check if k is bigger than the size of the vector. If it is, then there will be problems because you're trying to access something outside the vector. If you change the program to handle that error where k is bigger than the size of the array, then you shouldn't get any memory errors or invalid reads.
-Ash
The incorrect results may be because at the end of main you're sorting primes and printing the kth prime rather than sorting rads and printing rad[k].

How to run this code in less than 1 second?

How can I solve this problem without getting time limit exceeded
http://codeforces.com/problemset/problem/474/B
I tried putting all ranges in a 2D vector then looking for the desired index using binary search but it seems that the loop in the fn BS() takes a lot to execute as the size of the vector can be 10^6.
here is my code:
#include <iostream>
#include <vector>
using namespace std;
int Search(vector <vector<int> > a,int key){
int start = 0;
int end = a.size() - 1;
while (start <= end){
int mid = start + (end - start) / 2;
if (a[mid][0] > key && a[mid][1] > key){
end = mid - 1;
}
else if (a[mid][0] < key && a[mid][1] < key){
start = mid + 1;
}
else {
return mid;
}
}
return -1;
}
vector <int> BS(vector <vector <int> > v, vector<int> keys){
int j = 0;
vector <int> piles;
for (int i = 0; i < keys.size(); i++){
piles.push_back(Search(v, keys[i])+1);
}
return piles;
}
vector < vector<int> > Range(vector<int> v){
vector < vector<int> > ranges(v.size());
int sum1 = 1;
int sum2 = v[0];
for (int i = 0; i < v.size(); i++){
if (i == 0){
ranges[i].push_back(sum1);
ranges[i].push_back(v[i]);
sum1 += v[i];
}
else{
ranges[i].push_back(sum1);
sum2 += v[i];
ranges[i].push_back(sum2);
sum1 += v[i];
}
}
return ranges;
}
int main(){
int n, m;
cin >> n;
vector <int> a, q;
vector < vector <int> > v;
for (int i = 0; i < n; i++){
int k;
cin >> k;
a.push_back(k);
}
cin >> m;
for (int i = 0; i < m; i++){
int l;
cin >> l;
q.push_back(l);
}
v = Range(a);
vector <int> jucy = BS(v, q);
for (int i = 0; i < jucy.size(); i++){
cout << jucy[i] << endl;
}
}
In fact i don`t think you need 2D vector at all, you need just 1D. Which for example would look like this [2,9,12,16,25], the upper bound of each pile, you can construct this really easy. Then for every juicy worm you do binary search in that manner that it returns index with value greater or equal to the value you are looking for. The index you got from the search is the pile you are looking for.
Some pseudo-code:
A[n] - vector of upper bounds
A[0] = a0
For each 0<i<=n A[i]=A[i-1]+ai
For each q do std lower_bound on A looking for q,
the index you get is with first value equal or greater than q, so the pile where is q.
and C++ code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int n, m;
cin >> n;
vector<int>A;
A.resize(n);
int ai;
cin >> ai;
A[0]=ai;
for (int i = 1; i < n; i++){
cin >> ai;
A[i]=A[i-1]+ai;
}
cin >> m;
int q;
for (int i = 0; i < m; i++){
cin >> q;
cout << std::distance(A.begin(),std::lower_bound(A.begin(),A.end(),q))+1<<endl;
}
return 0;
}
You have to add +1 to distance because the piles are numbered from 1. Work for the example, and looks pretty fast.
The most obvious optimization opportunity is, instead of using a vector<vector<int>> use a vector<int> and manually adjust the 2D indices to 1D. You can write a simple wrapper class that does this for you.
The reason that that will be much faster is that then all the memory will be allocated as a single contiguous unit. If you have a vector of vectors, then each row will be somewhere else and you'll have lots of cache misses.
Here's a code example:
struct 2D_Vector {
std::vector<int> me_;
int ncols_;
2D_Vector(int nrows, int ncols) : me(nrows * ncols), ncols_(ncols) {}
int & get(int y, int x) { return me_[y * ncols_ + x]; }
const int & get(int y, int x) const { return me_[y * ncols_ + x]; }
...
};
If you preallocate this with all the space that it will need, then it should use memory very efficiently.
Also, passing large function parameters by value instead of by reference is very wasteful, because it results in needless copies being made and destroyed. (Like WhozCraig pointed out.)

To count the comparisons in QuickSort, small size data is OK, but large size(like over 50 ints)would take a long time, why?

Following code runs correctly when the size of array below 40, but larger size makes it run very long time.
please tell me why it work like this. Thank you very much.
why the website always tells me to add some more details.
here is my code
#include<iostream>
using namespace std;
int Quicksort(int arr[], int l, int r) {
int p = arr[l];
int i = l+1;
for (int j = l+1; j <=r; j++){
if (arr[j] < p){
int tem = arr[i];
arr[i] = arr[j];
arr[j] = tem;
i +=1;
}
}
arr[l] = arr[i-1];
arr[i-1] = p;
int count = r-l;//each subarray has (r-l) comparisons
if (r-l ==0){
return 0;
}else{
int j =i-1;
if (j>l){
Quicksort(arr, l,j-1);
count +=Quicksort(arr,l,j-1);
}
if (j <r){
Quicksort(arr, j+1,r);
count += Quicksort(arr, j+1,r);
}
}
return count;
}
int main(){
int n;
cin >>n;
int arr[n];
for (int i = 0; i<n; i++){
cin >>arr[i];
}
cout<<Quicksort(arr, 0, n-1)<<endl;
for (int i = 0; i<n; i++){
cout << arr[i] <<' ';
}
cout <<endl;
return 0;
}
You are using the leftmost element of the partition as your pivot. This has a worst case scenario when the array is already sorted.
"But my array isn't already sorted!" you say. Well, look at these lines of code:
if (j <r){
Quicksort(arr, j+1,r);
count += Quicksort(arr, j+1,r);
}
You are calling QuickSort twice, the second time you call it, the partition is already sorted. Leading to a worst case scenario for the second call.
Your two consecutive calls to Quicksort with the same arguments and poor choice of pivot will result in exponential runtime. It can be tricky to write a good Quicksort algorithm, but there are excellent algorithm texts, such as by Robert Sedgewick, which have good implementations of Quicksort.
On the other hand, you can use the generic sort algorithm provided by the C++ STL.
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int n;
cin >> n;
vector<int> arr;
for (int i = 0; i < n; i++) {
int val;
cin >> val;
arr.push_back(val);
}
sort(arr.begin(), arr.end());
for (int x : arr)
cout << x << ' ';
cout << endl;
return 0;
}