Vector goes wrong [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
So basically, I'm doing this problem (sorry if you can't read Vietnamese, please use Google Translate cuz the translation is pretty good though): http://vinhdinhcoder.net/Problem/Details/4914
#include <bits/stdc++.h>
#define int long long
#define fi first
#define se second
#define endl "\n"
#define mod 1000000007
#define inf LLONG_MAX
#define gcd(a,b) __gcd(a,b)
using namespace std;
struct knight{
int order, strength, money;
};
const int MAX=10;
int n, k, ans[MAX];
knight a[MAX];
vector<int> maxk;
bool comp(knight x, knight y) { return x.strength < y.strength; }
signed main(){
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n >> k;
for (int i=1; i<=2*n; i++){
a[i].order=i;
if (i<=n) cin >> a[i].strength; else cin >> a[i-n].money;
}
sort(a+1,a+n+1,comp);
ans[a[1].order]+=a[1].money;
for (int i=2; i<=n; i++){
if (i<=k+1) maxk.push_back(a[i-1].money);
else
if (maxk[maxk.size()-1]<a[i-1].money){
maxk.pop_back();
maxk.push_back(a[i-1].money);
}
sort(maxk.begin(),maxk.end(),greater<int>());
ans[a[i].order]=a[i].money;
for (int x:maxk) ans[a[i].order]+=x;
}
for (int i=1; i<=n; i++) cout << ans[i] << ' ';
}
(yes, I set the size of all arrays to 10 for testing purposes but changed to 1e5+1 when submit the solution)
I tested with the second sample test:
5 1 1 2 3 4 5 1 2 3 4 5
And it gave me an error:
`
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
`
Since n = 5 in the test case and the debugger failed when executing if (i<=k+1) maxk.push_back(a[i-1].money);, Since MAX = 10 then I think there's something wrong with the vector. Can anyone help me fix this please?
(Even when I set MAX = 1e5+1, the OJ gives me a TLE).

#define int long long
#define endl "\n"
#define inf LLONG_MAX
These will simply break everything. Do not ever do those.
for (int i=1; i<=2*n; i++){
a[i].order=i;
if (i<=n) cin >> a[i].strength; else cin >> a[i-n].money;
}
sort(a+1,a+n+1,comp);
This loop sets order for 10 knights. Knights 0-4 have their strength set, leaving their money property as the default value, and knights 5-9 have their money set, leaving their strength as the default value. I suspect you meant to first read in the strength of 0-4 and then the money of 0-4, but that's not what this does.
Then you sort knights 1-5 by their strength. The last of which always has a strength of 0, because you never read it in. I suspect you meant to sort knights 0-4?
I haven't read further, but you really need to step through line by line with a debugger and watch what happens in slow-motion.

Related

c++ how to store a variable and string that is 2^1 000 000 large? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to solve an exercise. It says that i need to output 3 last digits of a number that is 2 raised to the power of n (2^n).
But input is n=1000000.
The code works with lower values, but when the input is 1 000 000 the number gets too large.
My code:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
unsigned long long n;
cin >> n;
unsigned long long sk = pow(2, n);
if (sk < 1000) cout << sk;
else {
string ats = to_string(sk); // converting the number to string
// so I could output 3 last digits
// probably not the best solution
// for this exercise
n = ats.length();
for (unsigned long long i = n - 3; i < n; i++) {
cout << ats[i];
}
}
return 0;
}
Thank you for your help.
Try something like:
Initialize result to 1
Within a loop from 1 to n:
result *= 2
result %= 1000
This because the result of the last 3 digits does not depend upon the greater digits
You can calculate your number modulo 1000. Just saving the three least significant digits and trashing the more significant ones does not alter the result.
Just do:
int result = 1;
for(int i = 0; i < n; i++){
result = (result * 2) % 1000;
}

c++ getting a negative value when adding two absolute (positive) values [duplicate]

This question already has answers here:
Adding two positive integers gives negative answer.Why?
(4 answers)
Closed 5 years ago.
I am getting a strange problem. I am getting a negative value when adding two absolute (positive) values. I am trying to solve this exercise from codingame (link: https://www.codingame.com/ide/puzzle/network-cabling).
I tried debugging and I got this:
X[i]: 19715507 X[j]: 938059973 // This one is good
temp: 918344466
Y[i]: 470868309 Y[j]: -816049599 //Something is wrong here
temp: -2089704922
This code is probably not a good solution to the exercise and I will need to improve it, but I still can't figure it out why the value is negative.
Please help.
Thank you.
Code:
int main()
{
int N;
int X[100000];
int Y[100000];
cin >> N; cin.ignore();
for (int i = 0; i < N; i++) { //reading all input
cin >> X[i] >> Y[i]; cin.ignore();
}
int ilgis=0; //ilgis means length
for(int i=0; i<N-1; i++){ //"min" is set to a very high value
//so it could find a lower value later
// "not the best solution"
int min=99999999999999999999; //shortest distance between houses
for(int j=0; j<N; j++){ // here I am trying to find the shortest
// distance from one house to another
if(j!=i){ //I can't count distance from the same house because
// it would be 0
int temp=0;
//counting the distance differently if the
//value is negative or positive
if(X[i]<=0&&X[j]<=0) temp+=abs(abs(X[i])-abs(X[j]));
else if(X[i]<=0&&X[j]>=0) temp+=abs(X[i])+abs(X[j]);
else if(X[i]>=0&&X[j]>=0) temp+=abs(X[i]-X[j]);
else if(X[i]>=0&&X[j]<=0) temp+=(X[i])+abs(X[j]);
//same with y axis
if(Y[i]<=0&&Y[j]<=0) temp+=abs(abs(Y[i])-abs(Y[j]));
else if(Y[i]<=0&&Y[j]>=0) temp+=abs(Y[i])+abs(Y[j]);
else if(Y[i]>=0&&Y[j]>=0) temp+=abs(Y[i]-Y[j]);
else if(Y[i]>=0&&Y[j]<=0) temp+=(Y[i])+abs(Y[j]);
if(min>temp) min=temp;
}
} //if i found the shortesst distance between
//houses I add that value to overall distance
// and continue until all houses are checked
ilgis+=min;
}
cout<<ilgis<<endl;
}
Input of the exercise:
8
-28189131 593661218
102460950 1038903636
938059973 -816049599
-334087877 -290840615
842560881 -116496866
-416604701 690825290
19715507 470868309
846505116 -694479954
The maximum value for int is 2147483647 (which is 2^31-1, assuming int has 32 bits width). You can check it with
std::numeric_limits<int>::max();
You might want to min with this value here. And also use long long as your type for calculations here.

Factorial CodeChef error (C++) [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 6 years ago.
Improve this question
I'm getting WRONG ANSWER on CodeChef for the following problem even though my answer exactly matches the output. Please help.
PROBLEM:
For any positive integer N, Z(N) is the number of zeros at the end of the decimal form of number N!.
Input
There is a single positive integer T on the first line of input (equal to about 100000). It stands for the number of numbers to follow. Then there are T lines, each containing exactly one positive integer number N, 1 <= N <= 1000000000.
Output
For every number N, output a single line containing the single non-negative integer Z(N).
Example
Sample Input:
6
3
60
100
1024
23456
8735373
Sample Output:
0
14
24
253
5861
2183837
My code:
`#include<iostream>
#include<math.h>
#include<vector>
using namespace std;
long long int z(long long int n)
{ long long int p = 1, count = 0;
while(n>(pow(5,p)))
{
count = count + n/(pow(5,p));
p++;
}
return count;
}
int main()
{
long long int T,n;
cin>>T;
vector<long long int> myVector;
for (int i=0; i<T; i++)
{
cin>>n;
myVector.push_back(z(n));
}
for(int k=0; k<T; k++)
{
cout<<myVector[k]<<endl;
}
}
while(n>(pow(5,p)))
while(n>=(pow(5,p)))
Also:
You can use n/=5 while n instead of using pow.
You don't need extra braces in condition.
You can output result without pushing it into vector.

algorithm optimization - smallest number having n divisiors [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This problem is a programming version of Problem 12 from projecteuler.net..
The sequence of triangle numbers is generated by adding the natural numbers. So the 7'th triangle number would be 1+2+3+4+5+6+7=28. The first ten terms would be:
1,3,6,10,15,21,28,36,45,55,...
triangle number 28 would be having following factors
28 = 1,2,4,7,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over N divisors?
(1 <= N <= 1000)
I have written code which is working for N=750.But it is taking long time for N=1000.
#include <iostream>
#include <stdio.h>
#include <vector>
#define LL long long
using namespace std;
int main()
{
int test;
scanf("%d",&test);
int v[10001]={0};
int tnum=1,num=1;
while(1)
{
int c=0;
for(int i=1;i*i<=tnum;++i)
{
if(tnum%i==0)
{
++c;
if(i!=(tnum/i))
{
++c;
}
}
}
if(v[c]==0)
v[c]=tnum;
// cout << "c = "<<c<<" tnum = " << tnum << endl;
if(c>1000)
{
break;
}
++num;
tnum += num;
}
while(test--)
{
int n;
scanf("%d",&n);
++n;
while(v[n]==0)
{
++n;
}
printf("%d\n",v[n]);
}
return 0;
}
Any help or suggestions would be appreciated. Thanks.
Edit 1 = Answer for this question - As we have to find the next triangle number having over n divisiors,we can brute force all triangle number and find their number of divisiors. Then we will see that a pattern for larger value of n(n>240)
If I told you how many divisors the number 938,839 has, and how many divisors the number 938,840 has, how would you find out the number of divisors of 938,839 * 938,840, using just the information that I gave you?
And how can you use that idea to make your algorithm run about 100 times faster?

Finding maximum Collatz sequence between 1-1000000 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I'm trying to find maximum the Collatz sequence between 1 and 1000000. I wrote the following code below. I guess it is correct but it is extremely slow. Can you give me a few hints to make it faster? Thanks.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool myfn(int i, int j) { return i<j; }
int collatz(int x);
int main()
{
vector <int> myvector;
for(int i = 1; i < 1000000; i++)
{
myvector.push_back(collatz(i));
}
cout<<*max_element(myvector.begin(),myvector.end(),myfn);
return 0;
}
int collatz(int x)
{
int counter = 1;
while(1)
{
if(x == 1)
break;
if(x % 2 == 0)
{
x = x / 2;
counter++;
}
else
{
x = 3 * x + 1;
counter++;
}
}
return counter;
}
Actually, I just tested, and your code isn't just "extremely slow", but infinitely looping. No, you didn't just disprove the Collatz conjecture, but as far as I can see, you're suffering from an integer overflow.
More specifically, during the collatz(113383) the int x variable becomes negative due to an overflow:
551580299 1654740898 827370449 -1812855948 -906427974 -453213987
Shortly after that, it starts looping on the following sequence and thus consequently never exits the loop
-37 -110 -55 -164 -82 -41 -122 -61 -182 -91 -272 -136 -68 -34 -17 -50 -25 -74 -37 ...
After I changed the int x argument to a long long, the program quite quickly finishes.
The question then of course still is whether no overflows occur that don't cause infinite loops and go unnoticed, as you would then still end up with the wrong answer. However, after putting
if (x < 0) {
cout << "ERROR" << endl;
}
at the end of the while(1) loop and seeing nothing being output extra, I think you can be confident that a long long is big enough for the Collatz sequences for the numbers 1 to 1000000 (8 bytes, on my computer, compared to 4 bytes for an int, if you'd be interested).
EDIT:
As a side note: I don't see any reason to keep a vector of all results if you only need the maximum. Following code would eat less memory:
int maxCollatz = 0;
for(int i = 1; i < 1000000; i++) {
if (i % 10000 == 0)
cout << i << endl;
maxCollatz = max(maxCollatz, collatz(i));
}
And another note: you're actually only looping from 1 to 999999, so if the Collatz sequence for 1000000 would be the longest one, you might be missing that one...
Here are some tips:
Initialize vector to your capacity.
The vector may be expanding while you are pushing elements. Worst case, one reallocation per push_back.
Treat vector as array
After you have initialized your vector to its capacity, you can use the operator [] to access the vector slot instead of calling push_back.
Optimize collatz
This is probably your bottleneck. Try placing into a separate file and cranking up the compiler optimizations on it.
There may be a more optimal algorithm.