I have just started coding in C++ and I am using codeblocks. My build log is giving me 0 errors and 0 warning but I do not know why when I run it, it is giving me no result in the terminal.
Terminal Window Result:
Process returned -1073741571 (0xC00000FD) execution time : 1.252 s
Press any key to continue.
my code:
#include <iostream>
#include<math.h>
using namespace std;
int main() {
int n;
cin>>n;
int a[n];
for(int i = 0; i <n ; i++){
cin>>a[i];
}
const int N = pow(10, 6);
int idx[N];
for(int i = 0; i< N; i++){
idx[i] = -1;
}
int minidx = INT_MAX;
for(int i = 0; i<n; i++){
if(idx[a[i]] != -1){
minidx = min(minidx, idx[a[i]]);
}
else{
idx[a[i]] = i;
}
}
if (minidx == INT_MAX){
cout<<"-1"<<endl;
}
else{
cout<<minidx+1<<endl;
}
return 0;
}
Please help me in finding my mistake in the code.
This:
int n;
std::cin >> n;
int a [n];
for (int i = 0; i < n ; i++) {
std::cin >> a [i];
}
is bad practice. Don't use VLAs whose size you don't know at compile time. Instead, if I guess correctly that this is some Competitive Programming problem, you'll probably know what the max size will be as stated in the problem. So, do it this way instead:
int n;
std::cin >> n;
constexpr int max_size = 1000000;
int a [max_size];
for (int i = 0; i < n; i++) {
std::cin >> a [i];
}
However, even doing it this way will crash your program anyway. This is simply because of stack overflow when you declare an array that size inside a function. For slightly smaller sizes however, that would be okay. Just don't use VLAs the way you're using them.
One solution is to use a standard container like std::vector as the allocation takes place on the heap. Note that using std::array will crash too as the allocation is not on the heap.
Another solution is to make your array a global. This way you can increase to sizes well over 1e6. Not really recommended though.
In your code above, irrespective of what the size n for array a is (even if it's a fairly small size to fit on the stack), your code will definitely crash when you declare the array idx [1000000]. Reason is the same, stack overflow.
Also, please post indented code and use good indentation practices.
Related
Given an input array, the output must be the length of the longest arithmetic subarray of the given array.
I am getting a different output other than the desired one. I don't understand where I went wrong, I'm still a beginner so please ignore the rookie mistakes and kindly help me out wherever I'm wrong. Thanks in advance.
Here's the code:
#include <iostream>
using namespace std;
int main () {
int n;
cin>>n;
int array[n];
for (int i=0;i<n;i++)
{
cin>>array[i];
}
int length = 2;
int cd = array[1] - array[0];
for(int i=2; i<n; i++){
if(array[i] - array[i-1] == cd){
length++;
}
else {
cd = array[i] - array[i-1];
length=2;
}
cout<<length<<" ";
}
return 0;
}
If you are looking for a subsequence then what you did would not accomplish that.
For example:
Input: nums = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
You would require a nested loop structure (a for loop within the for loop you currently have) to accomplish that as you want to check a certain cd with the entire array and not just the next element.
If you require to find a subsequence/subarray given that the elements must be adjacent to one another then your program would work correctly.
Also a big error in your code is that you are printing the length inside the for loop. Unsure of whether that was for debugging purposes.
The problem here is you're resetting length after every update. You need a variable to store the maximum of every length.
#include <iostream>
using namespace std;
const int maxn = 1e6;
int arr[maxn];
int main ()
{
int n; cin>>n;
for (int i=0;i<n;i++) { cin >> arr[i]; }
int length = 2;
int maxLength = 2; //max variable
int cd = arr[1] - arr[0];
for(int i=2; i<n; i++){
if(arr[i] - arr[i-1] == cd) {length++;}
else {
cd = arr[i] - arr[i-1];
length=2;
}
//cout<<length<<" "; //remove this
maxLength = max(maxLength, length); //update maxLength
}
cout << maxLength;
}
A few more aesthetic notes:
array is a keyword in C++ used to declare std::array. Although the program may still run, it could create unnecessary confusion.
int array[n] is a VLAs (variable length array). It's not a C++ standard. It may or may not work depends on the compiler.
Why is "using namespace std;" considered bad practice?
I don't understand why this is happening.
The Code is working fine, but it won't show output in my system when I take a large array size and on the other side it gives the correct output in the online compiler.
It works fine and shows output in my system if I take a small array size.
#define N 805
Here is a code in C++ language.
#include<bits/stdc++.h>
using namespace std;
#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL);
#define M 1000000007
#define N 805
#define ll long long int
void init_start(){
fast_io;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int main()
{
init_start();
int n, k, limi;
cin>>n>>k;
int n_arr[N][N];
int k_arr[N][N];
for (int i = 0; i < N; i++)
{
k_arr[i][0]=0;
k_arr[0][i]=0;
}
int mini = -1, maxi = 1000000000, mid;
bool check;
limi = ((k*k) / 2) + 1;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
cin >> n_arr[i][j];
}
}
while((mini + 1) < maxi)
{
mid = (mini + maxi) / 2;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
k_arr[i+1][j+1] = k_arr[i+1][j] + k_arr[i][j+1] - k_arr[i][j];
if(n_arr[i][j] > mid)
{
k_arr[i+1][j+1]++;
}
}
}
check = false;
for (int i = 0; i < n-k+1; ++i)
{
for (int j = 0; j < n-k+1; ++j)
{
if ((k_arr[i+k][j+k] + k_arr[i][j] - k_arr[i][j+k] - k_arr[i+k][j])<limi)
{
check = true;
}
}
}
if (check)
{
maxi = mid;
}
else
{
mini = mid;
}
}
cout << maxi << endl;
return 0;
}
int n_arr[N][N];
int k_arr[N][N];
I suspect your local environment is configured with a smaller stack size that the online one. With N set to 805, and with 32-bit integers, that's going to consume about 5M of stack, quite a lot.
You may want to think about using the heap, which is usually less restrictive (new and delete). An easy solution is to keep the first dimension on the stack (805 pointers is not too bad) but use the heap for the second dimension, something like:
int *n_arr[N], *k_arr[N];
for (int i = 0; i < N; ++i) {
n_arr[i] = new int[N];
k_arr[i] = new int[N];
}
// Use them here as you currently do, e.g., n_arr[42][99].
for (int i = 0; i < N; ++i) {
delete [] n_arr[i];
delete [] k_arr[i];
}
A better solution for C++ would probably be to use std::vector, or find/create a heap-based matrix class of some description.
#include<bits/stdc++.h>
Avoid abusing implementation defined headers. The purpose of this header is to use in pre-compiled headers.
using namespace std;
Avoid using this in the namespace scope. Prefer using the scope resolution operator instead.
#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL);
Avoid obfuscating the program like this. Prefer using a function instead.
#define M 1000000007
#define N 805
Avoid using macros for constants. Prefer (constant) variables instead.
#define ll long long int
Avoid using macros for type aliases. Prefer typedef/using instead.
Just avoid using macros altogether unless there are no better alternatives (and there usually is).
Also, prefer to avoid using type aliases altogether except for template purposes. long long isn't that much to type, and it is immediately obvious to a reader what type it is.
The size available for automatic variables is typically very limited on most systems. You should avoid large automatic objects since those will likely result in a... stack overflow.
int n_arr[N][N];
This is an automatic variable. And it is huge. It is very likely to overflow the stack on some systems. Avoid doing this.
For this program, the simplest solution is to use static storage instead of automatic.
I wrote this knapsack problem solution in c++ however when I run it, it gives me segmentation fault
I have tried everything and my compiler will always give me the segmentation fault error.
#include<iostream>
#include<algorithm>
int knapsack(int v[],int w[],int n,int W)
{
int V[n][W];
for(int i = 0; i<=W;i++)
{
V[0][i] = 0;
}
for(int i = 0; i <= n; i++){
for(int j = 1; j<=W; j++)
{
if(w[i]<=W)
{
V[i][j] = std::max(V[i-1][j], v[i]+V[i-1][j-w[i]]);
}
else
{
V[i][j] = V[i-1][j];
}
}
}
return V[n][W];
}
int main()
{
int v[4] = {10,40,30,50};
int w[4] = {5,4,6,3};
int n = 3;
int W = 10;
std::cout<<"item value:"<<knapsack(v,w,n,W);
}
Don't use VLAs. The size of an array must be known at compile time, else it's not standard C++. Those are compiler extensions that are not portable and introduce some hidden costs.
Array indices go from 0 to length-1. in you loop
for(int i = 0; i<=W;i++)
i can reach W, then V[0][W] is out of bounds which causes the seg fault. You have to use < instead of <=:
for(int i = 0; i < W; i++)
n should probably be 4, if it's meant to represent the size of the array, a std::vector would make your life easier here, because a vector knows it's size
In general don't use C-style arrays or raw pointers at all in this day and age, use std::vector instead.
int V[n][W];
for(int i = 0; i<=W;i++)
{
V[0][i] = 0;
}
Note that V's indexes go from V[0][0] to V[0][W-1]. Your for loop will try to read V[0][W].
The same error is repeated in other places. Your end condition in your for loops should be < (strictly less) instead of <= (less or equal than).
i used to code in javascript, but my new school force me to learn c++.
Im kind new in this language, and here's the problem:
In javascript i can write such a code:
for(let i = 0; i < 10; i++){
var variable[i] = i+3;
}
for(let j = 0; j < 10; j++){
console.log(variable[j]);
}
You may say 'Why don't you just write the code into 1 for loop', but that's only example.
And now i'm trying to rewrite above code to cpp:
int n,k,w;
cin>>n>>k;
for(int i = 0; i < n; i++){
int w[i];
cin>>w[i];
}
//some code here
for(int i = 0; i < n; i++){
cout<<w[i];
}
And here's the question. How can i cout all variables w with index i, cause im getting an error [Error] invalid types 'int[int]' for array subscript.
What you probably want is:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec;
int size = 0;
std::cin >> size;
for(int i = 0; i < size; i++){
int number = 0;
std::cin >> number;
vec.push_back(number);
}
for(int i : vec){
std::cout << i << " ";
}
}
std::vector<int> is a class designed to provide an interface to resizable array. The push_back() function appends the vector with given argument.
The last loop, which is called a ranged-based for(), is used to print all elements of the vector. You can replace it with plain old for() loop with indexing, since std::vector supports operator [], but if ranged-based approach is sufficient, it should be preferred.
EDIT: I don't know JavaScript, but I assume (from your example) that variables declared inside loops are visible everywhere. This is not the case in C++. Variables' visibility is dependent on the scope they are declared in. If you want your list/array/vector/any other container to be visible to those two for() loops, you have to declare it outside them - like in my example above.
EDIT2: While you should almost always use std::vector for such tasks, one could argue that they want to disable resizing the container. In this case, we are left with simple dynamic allocation. We reach for <memory> library, since we shouldn't manage it ourselves:
#include <iostream>
#include <memory>
int main() {
int size = 0;
std::cin >> size;
auto arr = std::make_unique<int[]>(size);
for(int i = 0; i < size; i++){
int number = 0;
std::cin >> number;
arr[i] = number;
}
for(int i = 0; i < size; i++){
std::cout << arr[i] << " ";
}
}
For auto, either read here or imagine that it's just a magic type that is (almost always) correct. It's like var in Python or JavaScript (but later on its type cannot be changed).
For std::unique_ptr<T[]>, either read here or imagine that it's just a dynamically allocated array that automatically delete[]s itself. If you did not learn about dynamic allocation yet, simply ignore what that means and wait until it's introduced.
Notice that we also got rid of the ranged-based for() loop. Unfortunately, it does not work with plain, dynamically allocated arrays.
Not all compilers support VLA so stick to the Standards; always specify a constant size for arrays. If you need some dynamically changed size then consider using another type of containers like: std::vector.
Also why you re-declared int w inside the for loop? It is local to for loop and changes to it won't affect the outer one.
You get a compile time error in the second loop that complains that w is not an array. To solve it make int w[] outer and on top of the two loops.
int n, k;
cin >> n >> k;
int w[n];
for(int i = 0; i < n; i++)
cin >> w[i];
//some code here
for(int i = 0; i < n; i++)
cout << w[i];
The alternative to VAL use std::vector:
std::vector<int> w;
int n, k;
std::cin >> n;
for(int i(0); i!= n; ++i){
std::cin >> k;
w.push_back(k);
}
for(auto i(0); i != w.length(); ++i)
std::cout << w[i] << ", ";
I wrote this program using Sieve of Eratosthenes. It is supposed to output prime numbers up to 2'500'000, but it crashes when trying to create array bigger than ~2'100'000. Any ideas what might be broken?
Compiling with gcc in Code::Blocks (Windows 8.1, shame on me).
PS It works flawless for N <= 2'000'000
#include <stdio.h>
int main() {
// Input
long n;
scanf("%ld", &n);
// Initialize vars
bool number[n+1];
for(long i = 0; i < n; i++)
number[i] = false;
// Main loop
for(long i = 2; i*i <= n; i++) {
if(number[i]) // If number is already removed
continue; // Do next number
// Remove x * i
for(long j = i*2; j <= n; j += i)
number[j] = true;
}
// Print
for(long i = 2; i <= n; i++)
if(!number[i]) printf("%ld ", i);
}
This is not valid C++, if n is not a constant integral expression (yours isn't):
bool number[n+1];
It is a g++ extension, and puts the array on the call stack, which has limited size. You're overflowing it, causing an immediate program crash (no exception to recover from) so this is a bad idea even in g++.
Try
std::vector<bool> number(n+1);
(Note you'll need #include <vector> to make that work)
Also note that vector<bool> is a weird beast. Should work just fine for your usage, but to get something closer to bool[], you can also try
std::vector<char> number(n+1);
This looks wrong:
bool number[n+1];
Try either std::vector<bool> number(n+1) or bool* number = new bool[n+1]
You are trying to allocate array of n bools on stack, which might be simply to small. Try allocating on heap with std::vector or new operator.