How to use large array size? - c++

I was trying this problem on spoj. www.spoj.com/problems/RRANGE.It requires segment tree.But the problem is with the size of array.Here (1 <= N <= 1,000,000,000).Any way to work around this problem?
Here is my implementation(gives correct answer for nearly N<1000000)
#include <stdio.h>
#include <math.h>
#include<iostream>
#include<string.h>
using namespace std;
//segment tree
long long a[1000000];
long long Mid(long long s,long long e)
{
return s+(e-s)/2;
}
long long Sum1(long long *st,long long ss,long long se,long long qs,long long qe,long long index)
{
if (qs<=ss&&qe>=se)
return st[index];
if (se<qs||ss>qe)
return 0;
long long mid=Mid(ss, se);
return Sum1(st,ss,mid,qs,qe,2*index+1) +Sum1(st,mid+1,se,qs,qe,2*index+2);
}
void update1(long long *st,long long ss,long long se,long long i,long long diff,long long index)
{
if (i<ss||i>se)
return;
st[index]=st[index]+diff;
if (se!=ss)
{
long long mid = Mid(ss,se);
update1(st,ss,mid,i,diff,2*index+1);
update1(st,mid+1,se,i,diff,2*index+2);
}
}
void update(long long arr[],long long *st,long long n,long long i,long long new_val)
{
if (i<0||i>n-1)
return;
long long diff = new_val - arr[i];
arr[i] = new_val;
update1(st,0,n-1,i,diff,0);
}
long long Sum(long long *st,long long n,long long qs,long long qe)
{
if (qs<0||qe>n-1||qs>qe)
return -1;
return Sum1(st,0,n-1,qs,qe,0);
}
long long segtree(long long arr[],long long ss,long long se,long long *st,long long si)
{
if (ss==se)
{
st[si]=arr[ss];
return arr[ss];
}
long long mid=Mid(ss, se);
st[si]=segtree(arr,ss,mid,st,si*2+1)+segtree(arr,mid+1,se,st,si*2+2);
return st[si];
}
long long *segt(long long arr[],long long n)
{
long long x = (long long)(ceil(log2(n)));
long long max_size = 2*(long long)pow(2, x) - 1;
long long *st = new long long[max_size];
segtree(arr,0,n-1,st,0);
return st;
}
int main()
{
//memset(a,0,sizeof(a));
long long n,u,v;
cin>>n>>u>>v;
for(long long i=0;i<n;i++)
a[i]=0;
long long *st=segt(a,n);
while(u--)
{
long long i,j;
cin>>i>>j;
long long z=1;
for(long long p=i-1;p<j;p++)
{
update(a,st,n,p,a[p]+z);
z++;
}
//for(int m=0;m<n;m++)
//cout<<a[m]<<endl;
}
while(v--)
{
long long i,j;
cin>>i>>j;
cout<<Sum(st,n,i-1,j-1)<<endl;
}
return 0;
}

In C or C++ local objects are generally or usually allocated on the stack. Since you are allocating a very large array on the stack. So you have a chance of getting a stack overflow. I would recommend you to use std::vector<int> and resize it to 1000000 elements.

Whatever solution you try you will need more than 8 GB of ram to solve the problem using this algorithm. Memory limit on spoj is way less. Think of an alternative solution that requires less memory.

You can try using a binary indexed tree instead of a segment tree-> here is a nive tutorial.
A BIT takes O(n) memory, compared to a segment tree's O(2^(logN+2)), and it can serve the same purpose.
Hope this helps...

Related

Bug in the following program could not be fixed C++

It might not be like other asked questions in stackoverflow. In this problem, it works fine, but in one case, it returns wrong answer. I'm trying to solve the logical issue of this program.
I wrote a program to calculate the sum of this:
x, n, a would be entered by the user:
Here is my program:
#include <iostream>
long long int unsigned fact (long long unsigned int a);
long long int unsigned comb (long long unsigned int n, long long unsigned int r);
long long unsigned intpower (long long unsigned int a, long long unsigned int n);
using namespace std;
int main()
{
int n;
long long unsigned int x, a;
cin >> a >> x >> n;
long long unsigned int sum = 0;
for (int i = 0; i <= n; i++) {
sum += comb(n, i)*intpower(x, i)*intpower(a, (n-i));
}
cout << sum;
return 0;
}
// Calculates Factorial
long long int unsigned fact (long long unsigned int a) {
long long int unsigned p = 1;
for (long long unsigned int i = 1; i <= a; i++) {
p *= i;
}
return p;
}
// Calculates the combination
long long int unsigned comb (long long unsigned int n, long long unsigned int r) {
return (fact(n)/fact(r)/fact(n-r));
}
long long unsigned intpower (long long unsigned int a, long long unsigned int n){
long long unsigned int p = 1;
for (long long unsigned int i = 1; i <=n ; i++){
p *= a;
}
return p;
}
But in one case, my program returns wrong answer. Here's the test done my a website that verifies the written programs for problems:
Do you guys have any idea why I got wrong answer in one test? The thing is I don't know what numbers would be entered in test 1, but there should be a logical issue that it gives wrong answer in one case.
Kind regards.
As the comments have pointed, the failing test case is most probably because of a corner-side with the maximum values of the inputs. The range that you can store in a long long int data type (if your compiler support the type) is from -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807. It means that if in your case you have x, a and n as their maximum values, you will have an overflow. For an example, the output of your code with the following inputs is the same:
for:
int n = 10;
long long unsigned int x = 9999999999;
long long unsigned int a = 1000000000;
output is: 9223372036854775808
int n = 10;
long long unsigned int x = 1000000000;
long long unsigned int a = 1000000000;
the output is again: 9223372036854775808

c++ segmentation fault, why using "long long" I dont get an answer?

Can somebody explain where the mistake is in this code? because when I use parameters like this a=425 b=9631 n=9876543215 I get "exited,segmentation fault code 139" :(
#include <iostream>
#include <iomanip>
using namespace std;
void ivedimas(long long &n, long long &a, long long &b);
long long fib(long long n, long long a, long long b);
void isvedimas(long long ats);
int main()
{
long long n,a,b;
ivedimas(n,a,b);
isvedimas(fib(n,a,b));
return 0;
}
void ivedimas(long long &n, long long &a, long long &b)
{
cin>>a>>b>>n;
}
long long fib(long long n,long long a, long long b)
{
long long c=b-a;
if (n==2)
return c;
return fib(n-1,b,c);
}
void isvedimas(long long ats)
{
cout<<ats<<endl;
}
Stack Overflow: every time the function calls itself it adds to the stack, so this solution works for small numbers, but anything too large it will fail.
Iterative solution:
long long fib(long long n, long long a, long long b)
{
if (n == 0) {return 0;}
if (n == 1) {return 1;}
long long t = 0;
long long j = 1;
for (int i = 2; i <= n; i++) {
int k = j;
j += t;
t = k;
}
return j;
}
This recursive version of Fibonacci is not good with large number. Each time it's called the recursion the stack increse and never decrese till the end. So you just terminate the process memory before the result is return.
You can try an iterative solution.
thank you, this is the solution:)) every 6th number in the sequence is the same :)
e.g. 10,8,-2,-10,-8,2|10,8,-2,-10,-8,2...
long long fib(long long n,long long a, long long b)
{ long long c=a;
if (n==0) return a;
if (n%6==1) return b;
for (int i=1;i<n%6;i++)
{
c=b-a;
a=b;
b=c;
}
return c;
}

Unsigned long long overflow

I'm trying to understand why this programm after 2^20-1 value goes in overflow. All my variables are declared unsigned long long, but when I enter 1048756 which is 2^20 it goes in overflow , instead of converting it in a binary number. I thought that the range of u-l-l was 2^64-1.
I included the limits.h library and the maximum value was 8 bytes.This is the code :
#include <stdio.h>
int main(){
unsigned long long n = 100000000;
printf("%llu \n",decimal_binary(n));
return 0;
}
unsigned long long decimal_binary(unsigned long long n)
{
unsigned long long rem, i=1, binary=0;
while (n!=0)
{
rem=n%2;
n/=2;
binary+=rem*i;
i*=10;
}
return binary;
}
And the output is :
14184298036271661312 (Which is not a binary number obviously)
18446744073709551615 // 2^64-1
100000000000000000000 // 2^20 in your funny "decimal binary"
See the problem now?
By the way, if you want to get platform dependence out of this, use uint64_t from stdint.h instead of unsigned long long.
It seems like what you really want is to output a number in binary format. You can't put the conversion back into an integer type like that. You need to construct a string:
void decimal_binary(unsigned long long n, char str[])
{
unsigned long long rem, len=0, temp, i;
while (n!=0)
{
rem=n%2;
n/=2;
// put the binary digit into the string
str[len++] = rem ? '1' : '0';
}
str[len] = '\x0';
// the digits were inserted in reverse order, so reverse the string.
for (i=0;i<=len/2;i++) {
temp = str[i];
str[i] = str[len-1-i];
str[len-1-i] = temp;
}
}
int main(void){
char buff[200];
unsigned long long n = 100000000;
decimal_binary(n,buff);
printf("%s \n",buff);
return 0;
}
Output:
101111101011110000100000000
Let your code detect about when math is getting too big.
#include <stdio.h>
#include <limits.h>
unsigned long long decimal_binary(unsigned long long n)
{
unsigned long long rem, i=1, binary=0, n0;
n0 = n;
while (n!=0)
{
rem=n%2;
n/=2;
binary+=rem*i;
if (i > ULLONG_MAX/10) {
printf("OF %llu %llu\n", n0 , i);
return 0;
}
i*=10;
}
return binary;
}
int main(){
unsigned long long n = 100000000;
printf("%llu %llu\n",n,decimal_binary(n));
n = 100000;
printf("%llu %llu\n",n, decimal_binary(n));
return 0;
}
Output
OF 100000000 10000000000000000000
100000000 0
100000 11000011010100000
main()
{
unsigned long long n = 100000000;
int i;
for(i=sizeof(unsigned long long int)*8-1;i>=0;printf("%llu",n>>i--&1));`
}
OUTPUT::00000000 00000000 00000000 00000000 00000101 11110101 11100001 00000000

Find the number of ways the N balls could be placed in the M boxes

You have N different balls numbered from 1 to N, and M different boxes numbered from 1 to M.
Input:
First line of input contains the number of test cases T. After that, next T lines contain the value of N and M.
Output:
For each test case, print the answer. As it can be very large, you should print it modulo 10^9 + 7.
I tried the below code, but it gives an error:
#include<iostream>
#include<cmath>
#include<math.h>
using namespace std;
int main()
{
unsigned short int T;
unsigned long int N,M;
cin>>T;
for (int i = 0; i < T; i++)
{
cin>>N>>M;
long int res;
res= pow(M,N);
int c=0;
c=pow(10,9);
res=res%(c + 7);
cout<<res<<endl;
}
return 0;
}
You must be facing integer overflow problem, that's why you must have been getting wrong answer.
Do the following steps to fix this problem.
change the unsigned long to long long or unsigned long long. (Why? Think).
Use the logarithmic user-defined function to calculate the value of the res = pow(M,N) along with the modulo consideration side-by-side. This will boost up your program.
See my code snippet to check what changes to be made:
#include<iostream>
#define MOD 1000000007
int main() {
unsigned short int T;
unsigned long long N , M , result;
unsigned long long power(unsigned long long, unsigned long long); /*prototype of power*/
std::cin>>T;
for (int i = 0; i < T; i++) {
std::cin >> N >> M;
result = power(M , N);
std::cout << result << std::endl;
}
return 0;
}
unsigned long long power(unsigned long long M, unsigned long long N) {
if(N == 0) {
return 1;
}
unsigned long long result = power(M , N/2);
result = (result * result) % MOD;
if(N%2 == 1) {
result = (result * M) % MOD;
}
return result;
}

fibonacci number generation trouble

I have to generate the n-th fibonacci number from the first (zero-th) number being a and second being b. Below is my code for calculating this. I have been using matrix exponentiation method:
But the solution is wrong.
costum input:509618737 460201239 229176339(in order a,b,n)a=zeroth value,b=first value,n=Nth value to be found.
output:995159166
correct output:945141656
What is the problem with my code?
#include<iostream>
using namespace std;
void multiply(long long F[2][2], long long M[2][2]);//prototype of function multiplying 2 matrices.
void power(long long F[2][2],long long n);//prototype for incresing power
long long fib(long long n,long long a,long long b)//function that returns result as answer modulo 10^9+7(since answer is too long).
{
long long F[2][2] = {{1,1},{1,0}};
if (n == 0)
return a;
else if(n==1)
return b;
else if(n>1)
power(F, n-1);
return (F[0][0]*a+F[0][1]*b)%1000000007;//here's where i am confused ,whether i should multyply a first or b first i.e.f[0][0]*a+f[0][1]*b or f[0][0]*b+f[0][1]*a.plz explain this point too.
}
void power(long long F[2][2], long long n)
{
if( n == 0 || n == 1)
return;
long long M[2][2] = {{1,1},{1,0}};
power(F, n/2);
multiply(F, F);
if (n%2 != 0)
multiply(F, M);
}
void multiply(long long F[2][2], long long M[2][2])//matrices multiplied.
{
long long x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
long long y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
long long z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
long long w = F[1][0]*M[0][1] + F[1][1]*M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
int main()
{
long long t, a, b, n, ans;
cin>>t;//# of test cases
while(t--)
{
cin>>a;//zeroth value
cin>>b;//first value
cin>>n;//Nth fibonaaci no. to be generated
ans=fib(n,a,b);//value of Nth no.
cout<<ans<<"\n";
}
return 0;
}