I was trying to do a problem on HackerEarth, and I am getting Segmentation Faults for this for loop:
for (int index = 0; index < 18; index++){
cout << arr_list[arr_index][index];
}
Even though I assigned values to arr_list[arr_index][index] in the loop right before (so I'm guessing the values are somehow not being saved, but I don't know how the values aren't being saved).
When I remove this for loop, I don't get any segfaults, and the cout information prints what's expected (the numbers I've inputted, with each digit twice for each cout inside the loop).
#include <iostream>
#include <string>
using namespace std;
void step(int arr_list[1000000][18], int cs, int N){
/**
int freq[100000] = {0};
for (int i = 0; i < N; i++){
int cur_arr[18];
for (int index = 0; index < 18; index++){
cur_arr[index] = arr_list[i][index];
}
if (cs == 4){
freq[cur_arr[0]*100 + cur_arr[1] * 10 + cur_arr[2]] += 1;
} else{
freq[cur_arr[18 - cs*5] * 10000 + cur_arr[18 - cs*5 + 1] * 1000 + cur_arr[18 - cs*5 + 2]*100 + cur_arr[18 - cs*5 + 3] * 10 + cur_arr[18 - cs*5 + 4]] += 1;
}
}
for (int i = 1; i < 100000; i++){
freq[i] += freq[i-1];
}
int new_arr_list[1000000][18];
for (int i = N-1; i >= 0; i--){
int pos;
int cur_arr[18];
for (int index = 0; index < 18; index++){
cur_arr[index] = arr_list[i][index];
}
if (cs == 4){
pos = cur_arr[0]*100 + cur_arr[1] * 10 + cur_arr[2];
} else{
pos = cur_arr[18 - cs*5] * 10000 + cur_arr[18 - cs*5 + 1] * 1000 + cur_arr[18 - cs*5 + 2]*100 + cur_arr[18 - cs*5 + 3] * 10 + cur_arr[18 - cs*5 + 4];
}
for (int index = 0; index < 18; index++){
new_arr_list[freq[pos] - 1][index] = arr_list[i][index];
}
freq[pos] --;
}
for (int i = 0; i < N; i++){
for (int index = 0; index < 18; index++){
arr_list[i][index] = new_arr_list[i][index];
}
}
**/
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T;
int arr_index = 0;
cin >> T;
int arr_list[1000000][18];
int max_len = 0;
for (int testcase = 0; testcase < T; testcase ++){
string a;
cin >> a;
int a_len = a.length();
if (a_len > max_len){
max_len = a_len;
}
int arr_entry[18];
for (int i = 0; i < a_len ; i++){
arr_entry[18 - a_len + i] = a[i] - 48;
}
for (int i = 0; i < 18 - a_len; i++){
arr_entry[i] = 0;
}
for (int index = 0; index < 18; index++){
arr_list[arr_index][index] = arr_entry[index];
cout << arr_entry[index];
cout << arr_list[arr_index][index];
}
for (int index = 0; index < 18; index++){
cout << arr_list[arr_index][index];
}
arr_index ++;
}
/**
for (int c = 1; c < 5; c++){
if (max_len > (c-1)*5){
step(arr_list, c, T);
for (int i = 0; i < T; i++){
int is_leading_zero = 1;
for (int j = 0; j < 18; j++){
if (is_leading_zero == 0){
cout << arr_list[i][j];
}else{
if (arr_list[i][j] != 0){
is_leading_zero = 0;
cout << arr_list[i][j];
}
}
}
cout << " ";
}
cout << "\n";
}
}
**/
}
I'm assuming this is a common error, and that I'm missing something simple that gives me segfaults for values I already assigned data to.
Does anyone know why this is happening?
You are allocating 72 MB on the stack:
int main()
{
[...]
int arr_list[1000000][18];
[...]
}
This is probably causing a stack overflow.
On the Microsoft Windows platform, the maximum stack size is, by default, 1 MB. On Linux, it is typically 8 MB.
When allocating such large amounts of memory, I recommend that you instead either use
dynamic memory allocation, or
a global variable, or
a static local variable.
This ensures that the array is not stored on the stack.
I have written this counting sort algorithm, but am not sure why it isn't working... Could anyone check and give me a few pointers on what to fix? Thanks!
#include <iostream>
using namespace std;
int main(){
int arr[10] = {1434, 1415, 1217, 4218, 3618, 176, 1021, 3785, 1891, 1522};
int C[4219];
for (int i = 0; i < 4219; ++i) {
C[i] = 0;
}
for (int j = 0; j < 10; ++j) {
C[arr[j]] = C[arr[j]] + 1;
}
for (int k = 10; k > 0; --k) {
C[k] = C[k] + C[k + 1];
}
int B[10];
for (int l = 0; l < 10; ++l) {
B[C[arr[l]] - 1] = arr[l];
C[arr[l]] = C[arr[l]] - 1;
}
for (int m = 0; m < 10; ++m) {
cout << B[m] << " ";
}
return 0;
}
The problem is in the third loop. You iterate only through 10 elements of the array C.
You had created small mistake in the code.....
#include <iostream>
using namespace std;
int main(){
int arr[10] = {1434, 1415, 1217, 4218, 3618, 176, 1021, 3785, 1891, 1522};
int C[4219];
for (int i = 0; i < 4219; ++i) {
C[i] = 0;
}
for (int j = 0; j < 10; ++j) {
C[arr[j]] = C[arr[j]] + 1;
}
for (int k = 1; k < 4219; ++k) { // mistake
C[k] = C[k] + C[k - 1];
}
int B[10];
for (int l = 9; l >=0; --l) { // suggestion
B[C[arr[l]] - 1] = arr[l];
C[arr[l]] = C[arr[l]] - 1;
}
for (int m = 0; m < 10; ++m) {
cout << B[m] << " ";
}
return 0;
}
Beside that I would like to give you one suggestion that in the loop traverse from right to left as it will maintain the stability of the sort..
Stability means suppose if array has two or more same element then in the stable sort,element which is before in unsorted array will occur first in sorted array.
I am working on a program that reads integers from file, stores it in vector and use count sort to sort the integers and write them in new file. My problem ocurs when i run Countsort function, the breakpoint happens at this for loop:
for (int i = 0; i < C.size(); i++) {
C[A[i]] = C[A[i]] + 1;
}
my code looks like this:
//COUNT SORT
void countsort() {
int max = A[0];
for (int i = 1; i < A.size(); i++) {
if (A[i] > max) {
max = A[i];
}
}
//cout << "NAJVECJE STEVILO JE: " << max << endl; SAMO ZA TEST
vector<int> C(max + 1);
vector<int> B(A.size());
for (int i = 0; i < C.size(); i++) {
C[A[i]] = C[A[i]] + 1;
}
for (int i = 1; i < C.size(); i++) {
C[i] = C[i] + C[i + 1];
}
for (int i = C.size() - 1; i >= 0; i--) {
B[C[A[i]] - 1] = A[i];
C[A[i]] = C[A[i]] - 1;
}
for (int i = 0; i < A.size(); i++) {
A[i] = B[i];
}
}
First you zero whole C vector
for (int i = 0; i < C.size(); i++)
{
C[i] = 0;
}
In second loop you may not change C[0] so it will remain 0
for (int i = 0; i < A.size(); i++)
{
C[A[i]] = C[A[i]] + 1;
}
In third loop in my analysis you never change C[0]
for (int i = C.size() - 1; i > 0; i-- )
{
C[i] = C[i] + C[i - 1];
}
In last loop
for (int i = A.size() - 1; i >= 0; i--)
{
B[C[A[i]] - 1] = A[i];
C[A[i]] = C[A[i]] - 1;
cout << B[i] << " ";
}
A[i] may equal 0, so C[A[i]] is C[0] and it might equal 0 from analysis of previous loops. When you subtract 1 from it, you'll end up with B[-1] which breaks your code.
Before you write something to B vector you should probably initialize it firt like you did with C.
B = vector<int>(A.size());
Also I don't see any point of printing B[i] as it may not be assigned any value when you print it.
Edit #1
Your loop is not correct. Take a look at this:
for (int i = 1; i < C.size(); i++) {
C[i] = C[i] + C[i - 1];
}
Edit #2
Try this code.
vector<int> A, B;
//COUNT SORT
void countsort() {
int max = A[0];
for (int i = 1; i < A.size(); i++) {
if (A[i] > max) {
max = A[i];
}
}
vector<int> C(max + 1);
B = vector<int>(A.size());
for (int i = 0; i < C.size(); i++) C[i] = 0;
for (int i = 0; i < A.size(); i++) C[A[i]] = C[A[i]] + 1;
for (int i = 1; i < C.size(); i++) C[i] = C[i] + C[i - 1];
for (int i = A.size() - 1; i >= 0; i--) {
B[C[A[i]] - 1] = A[i];
C[A[i]] = C[A[i]] - 1;
}
for (int i = 0; i < B.size(); i++) cout << B[i];
}
int main(void) {
A.push_back(1);
A.push_back(2);
A.push_back(3);
A.push_back(4);
A.push_back(2);
A.push_back(2);
A.push_back(1);
countsort();
}
I found this problem somewhere in a contest and haven't been able to come up with a solution yet.
The boy has apples and keeps in boxes. In one box no more than N/2.
How many methods he can put candies to boxes.
So what I'm trying to do is to implement solution using DP. Here is my code:
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <unistd.h>
#include <vector>
#define size 1002
using namespace std;
long long a[size][size];
int n, k;
int main()
{
cin >> n >> k;
int kk = n/2;
for(int i = 0; i <= k; ++i)
a[0][i] = 1;
a[0][0] = 0;
for(int i = 0; i <= kk; ++i)
a[i][1] = 1;
for(int i = 1; i <= n; ++i) {
for(int j = 2; j <= k; ++j) {
int index = 0;
long long res = 0;
while(1) {
res += a[i-index][j - 1];
index += 1;
if(index == kk + 1 || i-index < 0)
break;
}
a[i][j] = res;
}
}
cout << a[n][k] << endl;
}
But the problem is that we have large numbers in input like:
2 ≤ N ≤ 1000 is a quantity of the candies, N - even; 2 ≤ S ≤ 1000 - is a quantity of small boxes.
So, for input like N = 1000 and S = 1000, I have to spent 5*10^8 operations. And the numbers are very big, so I have to use BigInteger arithmetics?
Maybe there is algorithm to implement the problem in linear time? Thanks and sorry for my English!
You can easily decrease the time complexity from O(kn^2) into O(nk) by the following observation:
for(int i = 1; i <= n; ++i) {
for(int j = 2; j <= k; ++j) {
int index = 0;
long long res = 0;
while(1) {
res += a[i-index][j - 1];
index += 1;
if(index == kk + 1 || i-index < 0)
break;
}
a[i][j] = res;
}
}
for each a[i][j], we can easily see that
a[i][j] = sum a[k][j - 1] with k from (i - n/2) to i
So, if we create an array sum to store the sum from all indexes of the previous step, we can reduce one for loop from the above nested loop
a[i][j] = sum[i] - sum[i - (n/2) - 1];
Pseudo code:
long long sum[n + 1];
for(int j = 2; j <= k; ++j) {
long long nxt[n + 1];
for(int i = 1; i <= n; ++i) {
int index = 0;
long long res = sum[i] - sum[i - (n/2) - 1];
a[i][j] = res;
nxt[i] = nxt[i - 1] + a[i][j];//Prepare the sum array for next step
}
sum = nxt;
}
Note: This above code is not handled the initialization step for array sum, as well as not handle the case when i < n/2. Those cases should be obvious to handle.
Update:
My below Java solution get accepted by using similar idea:
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int s = in.nextInt();
BigInteger[][] dp = new BigInteger[n + 1][2];
BigInteger[][] count = new BigInteger[2][n + 1];
int cur = 1;
for (int i = 0; i <= n / 2; i++) {
dp[i][0] = BigInteger.ONE;
count[0][i] = (i > 0 ? count[0][i - 1] : BigInteger.ZERO)
.add(dp[i][0]);
}
for (int i = n / 2 + 1; i <= n; i++) {
dp[i][0] = BigInteger.ZERO;
count[0][i] = count[0][i - 1];
}
for (int i = 2; i <= s; i++) {
for (int j = 0; j <= n; j++) {
dp[j][cur] = dp[j][1 - cur].add((j > 0 ? count[1 - cur][j - 1]
: BigInteger.ZERO)
.subtract(j > n / 2 ? count[1 - cur][j - (n / 2) - 1]
: BigInteger.ZERO));
count[cur][j] = (j > 0 ? count[cur][j - 1] : BigInteger.ZERO)
.add(dp[j][cur]);
}
cur = 1 - cur;
}
out.println(dp[n][1 - cur]);
out.close();
}
I have written a solution for the above problem but can someone please suggest an optimized way.
I have traversed through the array for count(2 to n) where count is finding subarrays of size count*count.
int n = 5; //Size of array, you may take a dynamic array as well
int a[5][5] = {{1,2,3,4,5},{2,4,7,-2,1},{4,3,9,9,1},{5,2,6,8,0},{5,4,3,2,1}};
int max = 0;
int **tempStore, size;
for(int count = 2; count < n; count++)
{
for(int i = 0; i <= (n-count); i++)
{
for(int j = 0; j <= (n-count); j++)
{
int **temp = new int*[count];
for(int i = 0; i < count; ++i) {
temp[i] = new int[count];
}
for(int k = 0; k < count; k++)
{
for(int l = 0; l <count; l++)
{
temp[k][l] = a[i+k][j+l];
}
}
//printing fetched array
int sum = 0;
for(int k = 0; k < count; k++)
{
for(int l = 0; l <count; l++)
{
sum += temp[k][l];
cout<<temp[k][l]<<" ";
}cout<<endl;
}cout<<"Sum = "<<sum<<endl;
if(sum > max)
{
max = sum;
size = count;
tempStore = new int*[count];
for(int i = 0; i < count; ++i) {
tempStore[i] = new int[count];
}
//Locking the max sum array
for(int k = 0; k < count; k++)
{
for(int l = 0; l <count; l++)
{
tempStore[k][l] = temp[k][l];
}
}
}
//printing finished
cout<<"------------------\n";
//Clear temp memory
for(int i = 0; i < size; ++i) {
delete[] temp[i];
}
delete[] temp;
}
}
}
cout<<"Max sum is = "<<max<<endl;
for(int k = 0; k < size; k++)
{
for(int l = 0; l <size; l++)
{
cout<<tempStore[k][l]<<" ";
}cout<<endl;
}cout<<"-------------------------";
//Clear tempStore memory
for(int i = 0; i < size; ++i) {
delete[] tempStore[i];
}
delete[] tempStore;
Example:
1 2 3 4 5
2 4 7 -2 1
4 3 9 9 1
5 2 6 8 0
5 4 3 2 1
Output:
Max sum is = 71
2 4 7 -2
4 3 9 9
5 2 6 8
5 4 3 2
This is a problem best solved using Dynamic Programming (DP) or memoization.
Assuming n is significantly large, you will find that recalculating the sum of every possible combination of matrix will take too long, therefore if you could reuse previous calculations that would make everything much faster.
The idea is to start with the smaller matrices and calculate sum of the larger one reusing the precalculated value of the smaller ones.
long long *sub_solutions = new long long[n*n*m];
#define at(r,c,i) sub_solutions[((i)*n + (r))*n + (c)]
// Winner:
unsigned int w_row = 0, w_col = 0, w_size = 0;
// Fill first layer:
for ( int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
at(r, c, 0) = data[r][c];
if (data[r][c] > data[w_row][w_col]) {
w_row = r;
w_col = c;
}
}
}
// Fill remaining layers.
for ( int size = 1; size < m; size++) {
for ( int row = 0; row < n-size; row++) {
for (int col = 0; col < n-size; col++) {
long long sum = data[row+size][col+size];
for (int i = 0; i < size; i++) {
sum += data[row+size][col+i];
sum += data[row+i][col+size];
}
sum += at(row, col, size-1); // Reuse previous solution.
at(row, col, size) = sum;
if (sum > at(w_row, w_col, w_size)) { // Could optimize this part if you only need the sum.
w_row = row;
w_col = col;
w_size = size;
}
}
}
}
// The largest sum is of the sub_matrix starting a w_row, w_col, and has dimensions w_size+1.
long long largest = at(w_row, w_col, w_size);
delete [] sub_solutions;
This algorithm has complexity: O(n*n*m*m) or more precisely: 0.5*n*(n-1)*m*(m-1). (Now I haven't tested this so please let me know if there are any bugs.)
Try this one (using naive approach, will be easier to get the idea):
#include <iostream>
#include<vector>
using namespace std;
int main( )
{
int n = 5; //Size of array, you may take a dynamic array as well
int a[5][5] =
{{2,1,8,9,0},{2,4,7,-2,1},{5,4,3,2,1},{3,4,9,9,2},{5,2,6,8,0}};
int sum, partsum;
int i, j, k, m;
sum = -999999; // presume minimum part sum
for (i = 0; i < n; i++) {
partsum = 0;
m = sizeof(a[i])/sizeof(int);
for (j = 0; j < m; j++) {
partsum += a[i][j];
}
if (partsum > sum) {
k = i;
sum = partsum;
}
}
// print subarray having largest sum
m = sizeof(a[k])/sizeof(int); // m needs to be recomputed
for (j = 0; j < m - 1; j++) {
cout << a[k][j] << ", ";
}
cout << a[k][m - 1] <<"\nmax part sum = " << sum << endl;
return 0;
}
With a cumulative sum, you may compute partial sum in constant time
std::vector<std::vector<int>>
compute_cumulative(const std::vector<std::vector<int>>& m)
{
std::vector<std::vector<int>> res(m.size() + 1, std::vector<int>(m.size() + 1));
for (std::size_t i = 0; i != m.size(); ++i) {
for (std::size_t j = 0; j != m.size(); ++j) {
res[i + 1][j + 1] = m[i][j] - res[i][j]
+ res[i + 1][j] + res[i][j + 1];
}
}
return res;
}
int compute_partial_sum(const std::vector<std::vector<int>>& cumulative, std::size_t i, std::size_t j, std::size_t size)
{
return cumulative[i][j] + cumulative[i + size][j + size]
- cumulative[i][j + size] - cumulative[i + size][j];
}
live example