For the code below in Ubuntu 16.04
For custom testcase
4 3
1 2 3 7
My runtime is infinite and there is no output. (No output means that 'a' is also not printed on console). However when I comment the function call foo
// int temp = foo(ab, 0, n-1);
I get output
a##
What can be the reason of infinite run time and no output that I am missing?
#include<bits/stdc++.h>
using namespace std;
int a[1000000];
int foo(int x, int f, int l)
{
int m = (f+l)/2;
while(f<=l)
{
if(a[m]==x)
return 1;
else if(a[m]<x)
f = m+1;
else if(a[m]>x)
l = m-1;
}
return 0;
}
int main()
{
int n, x;
cin >> n;
cin >> x;
int i=0;
for (i = 0; i < n; i++)
{
cin >> a[i];
}
cout<<'a';
sort(a,a+n);
for(i=0; i<n-1; i++)
{
if(a[i]==a[i+1])
{
cout << 0;
return 0;
}
}
cout<<'#';
int ab = a[i];
int temp = foo(ab, 0, n-1);
cout<<'#';
return 0;
}
The reason you're not getting any output (not even the 'a') is that stdout is buffered. Typically it is line-buffered, meaning it will only be printed when a new line is written.
You can force whatever's in the buffer to print out immediately by doing std::cout << std::flush;, or for example in your case, std::cout << 'a' << std::flush; would work.
The reason of infinite loop is that your f and l values are updated at most once. initially m points to the middle of array (i.e. (n-1)/2) and from that moment,
-if the element a[m] is less than x, you infinitely assign m+1 i.e. (n-1)/2 + 1to f
-if the element a[m] is larger than x, you infinitely assign (n-1)/2 - 1 to l
In either case, f never gets larger than l and l never gets smaller than f (unless array has a single element or it has two elements and x<a[0])
Try updating the function in the following way:
int foo(int x, int f, int l)
{
int m = (f+l)/2;
while(f<=l)
{
if(a[m]==x)
return 1;
else if(a[m]<x)
{
f = m+1; m = f;
}
else if(a[m]>x)
{
l = m-1; m = l;
}
}
return 0;
}
Related
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);
#include <iostream>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
using std::sort;
int main()
{
int x = 0;
int n; // Enter Size of 2 array
cin >> n; // enter 5
long long *ptr1 = new long long[n - 1]; // size of array must be less than 5 by one n-1
for (int x = 0; x < n - 1; x++)
{
cin >> ptr1[x];
}
sort(ptr1, ptr1 + (n - 1));
for (int z = 1; z < n; z++)
{
if (z != ptr1[x])
{
cout << z;
break;
}
x++;
}
return 0;
}
You're given all positive integers from 1,2,…,n except one integer. Find the missing integer.
Input
The first line of input contains an integer n (2≤n≤2×105).
The second line of input contains n−1 distinct integers from 1 to n (inclusive).
Output
Print the missing integer.
when i try to sumbit this code i get wrong in test 10 but i don't know why! and he didn't show the test so what is wrong?
I have a three-fold answer:
This program leaks memory
You included <algorithm> please use it. (Look on cppreference)
Spoilers vector, iota, mismatch
Also, you don't reset x before the second loop.
That's never going to work unless the missing integer is the last of the array, and not equal to 1
// for (... z)
if (z != ptr1[x] /* Here */) {
// print 1, end loop OR invoke undefined behavior
}
x++; // Now x is equal to (n - 1)
There are some problems with your code:
long long *ptr1 = new long long[n - 1];
You call new, without delete. This will create a memory leak.
You haven't reinitialized x, so any access to ptr1[x] is out-of-bounds.
Slove all of that, and your code will look like:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
int n;
cin >> n;
std::vector<int> vec(n-1); // std::vector instead
for (int x = 0; x < n - 1; x++)
{
std::cin >> vec[x];
}
std::sort(vec.begin(), vec.end());
int x = 0; // use another variable instead of reused the old one.
for (int z = 1; z < n; z++)
{
if (z != vec[x])
{
std::cout << z;
break;
}
x++;
}
return 0;
}
But, this isn't the best approach anyway. As #molbdnilo suggest:
#include <iostream>
int main()
{
int n;
std::cin >> n;
int sum{};
for (int i = 0; i < n - 1; ++i)
{
int tmp;
std::cin >> tmp;
sum += tmp;
}
std::cout << (n + 1) * n / 2 - sum;
}
You can solve this in a more straightforward way if you subtract the numbers that were entered from the expected sum of all numbers 1, 2, ..., n (see comments by #molbdnilo, #Aconcagua and #marcus-müller):
#include <iostream>
int main() {
std::size_t n;
std::cin >> n;
std::size_t sum{ n*(n + 1)/2 };
for (std::size_t idx = 1; idx != n; ++idx) {
std::size_t thisNumber;
std::cin >> thisNumber;
sum -= thisNumber;
}
std::cout << "Missing number: " << sum << std::endl;
}
Building blocks:
The expected sum: int expected_sum = n * (n + 1) / 2;
The sum of all integers fed to the test after you've read n:
#include <iterator> // istream_iterator
#include <numeric> // accumulate
int sum = std::accumulate(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>{}, 0);
Now, expected_sum - sum should give you the missing value.
#include <iostream>
using namespace std;
void aUnionB(int A[], int B[], int a, int b)
{
int n = a + b;
int aUb[n]{0}; // n is max num of elements aUb can have
// filling elements of a in aUb
for (int i = 0; i < a; i++)
{
aUb[i] = A[i];
}
int z = sizeof(aUb) / sizeof(aUb[0]);
int temp = z;
// compare element from set B with aUb and if not fount add it in aUb
for (int i = 0; i < z; i++)
{
for (int j = 0; j < b; j++)
{
if (aUb[i] == B[j])
{
continue;
}
else
{
aUb[temp] = B[j];
temp++;
}
}
}
//print a union b
for (int i : aUb)
{
cout << i << " ";
}
}
int main()
{
int TestCases = 1, NoOfElementsInA, NoOfElementsInB, element;
while (TestCases--) //testing for just one test case
{
cin >> NoOfElementsInA >> NoOfElementsInB;
int A[NoOfElementsInA], B[NoOfElementsInB];
//assigning elements in array A
for (int i = 0; i < NoOfElementsInA; i++)
{
cin >> element;
A[i] = element;
}
//assigning elements in array B
for (int i = 0; i < NoOfElementsInB; i++)
{
cin >> element;
B[i] = element;
}
aUnionB(A, B, NoOfElementsInA, NoOfElementsInB);
}
return 0;
}
I am trying for past 1 hour what's the problem but unable to find why the program is not running despite not having any error or warning after execution , I'm not able to pass inputs.
This the numerical question:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consist of three lines. The first line of each test case contains two space separated integers N and M, where N is the size of array A and M is the size of array B. The second line of each test case contains N space separated integers denoting elements of array A. The third line of each test case contains M space separated integers denoting elements of array B.
Recently I am writing a program to generate a fixed number of permutation of alphabets inputted. For example, I inputted 3, 3, ABC, the program will output ABC, ACB, BAC, according to lexicographical order. But the program cannot get through all the test case and i cant find out where is the bug. Please help.
#include <iostream>
using namespace std;
int used[26], cou = 0, k, n, i;
string output;
string sorting(string x, int y)
{
char temp;
int i, j;
for (i = 0; i < y; ++i)
{
for (j = 0; j < y-1; ++j)
{
if (x[j]-'0' > x[j+1]-'0')
{
temp = x[j];
x[j] = x[j+1];
x[j+1] = temp;
}
}
}
return x;
}
void out(int x, string y)
{
int i;
if (cou == k)
{
return;
}
if (x == n+1)
{
cout << output << endl;
++cou;
}
else
{
for (i = 0; i < n; ++i)
{
if (used[i] == 0)
{
used[i] = 1;
output[x-1] = y[i];
out(x+1, y);
used[i] = 0;
}
}
}
}
int main()
{
char inpi;
string inp, ha;
cin >> n >> k >> inp;
output.resize(n);
for (i = 0; i < 26; ++i)
{
used[i] = 0;
}
inp = sorting(inp, n);
out(1, inp);
}
I am not sure that I understood the question.
Leaving the algorithm aside, you should know that a standard string is able to tell how long is. Therefore the y parameter in sorting is redundant. Use x.size() to find the size.
Another problem is output[x] = y[i];. You did not set output's size: it is zero. Since you are looking for permutations, I assume its size must equal y's size: output.resize( y.size() );.
One last thing: use meaningful identifiers. y may be good for a compiler; for a human, it may define a bad day.
There doesn't seem to be a need to create a global as you have done
string output;
Create a string to capture the output either within main() and pass it by reference to the functions which need them, in this case fill()
or
create it within fill() and return it by value once its populated
I'm practicing ACM problems to become a better programmer, but I'm still fairly new to c++ and I'm having trouble interpreting some of the judges code I'm reading. The beginning of a class starts with
public:
State(int n) : _n(n), _p(2*n+1)
{
and then later it's initialized with
State s(n);
s(0,0) = 1;
I'm trying to read the code but I can't make sense of that. The State class only seems to have 1 argument passed, but the programmer is passing 2 in his initialization. Also, what exactly is being set = to 1? As far as I can tell, the = operator isn't being overloaded but just in case I missed something I've included the full code below.
Any help would be greatly appreciated.
Thanks in advance
/*
* D - Maximum Random Walk solution
* ICPC 2012 Greater NY Regional
* Solution by Adam Florence
* Problem by Adam Florence
*/
#include <cstdio> // for printf
#include <cstdlib> // for exit
#include <algorithm> // for max
#include <iostream>
#include <vector>
using namespace std;
class State
{
public:
State(int n) : _n(n), _p(2*n+1)
{
if (n < 1)
{
cout << "Ctor error, n = " << n << endl;
exit(1);
}
for (int i = -n; i <= n; ++i)
_p.at(i+_n) = vector<double>(n+1, 0.0);
}
void zero(const int n)
{
for (int i = -n; i < n; ++i)
for (int m = 0; m <= n; ++m)
_p[i+_n][m] = 0;
}
double operator()(int i, int m) const
{
#ifdef DEBUG
if ((i < -_n) || (i > _n))
{
cout << "Out of range error, i = " << i << ", n = " << _n << endl;
exit(1);
}
if ((m < 0) || (m > _n))
{
cout << "Out of range error, m = " << m << ", n = " << _n << endl;
exit(1);
}
#endif
return _p[i+_n][m];
}
double& operator()(int i, int m)
{
#ifdef DEBUG
if ((i < -_n) || (i > _n))
{
cout << "Out of range error, i = " << i << ", n = " << _n << endl;
exit(1);
}
if ((m < 0) || (m > _n))
{
cout << "Out of range error, m = " << m << ", n = " << _n << endl;
exit(1);
}
#endif
return _p[i+_n][m];
}
static int min(int x, int y)
{
return(x < y ? x : y);
}
static int max(int x, int y)
{
return(x > y ? x : y);
}
private:
int _n;
// First index is the current position, from -n to n.
// Second index is the maximum position so far, from 0 to n.
// Value is probability.
vector< vector<double> > _p;
};
void go(int ds)
{
// Read n, l, r
int n, nds;
double l, r;
cin >> nds >> n >> l >> r;
const double c = 1 - l - r;
if(nds != ds){
cout << "Dataset number " << nds << " does not match " << ds << endl;
return;
}
// Initialize state, probability 1 at (0,0)
State s(n);
s(0,0) = 1;
State t(n);
State* p1 = &s;
State* p2 = &t;
for (int k = 1; k <= n; ++k)
{
// Compute probabilities at step k
p2->zero(k);
// At step k, the farthest from the origin you can be is k
for (int i = -k; i <= k; ++i)
{
const int mm = State::min( State::max(0, i+k), k);
for (int m = 0; m <= mm; ++m)
{
// At step k-1, p = probability of (i,m)
const double p = p1->operator()(i,m);
if (p > 0)
{
// Step left
p2->operator()(i-1, m) += p*l;
// Step right
p2->operator()(i+1, State::max(i+1,m)) += p*r;
// Stay put
p2->operator()(i, m) += p*c;
}
}
}
swap(p1, p2);
}
// Compute expected maximum position
double p = 0;
for (int i = -n; i <= n; ++i)
for (int m = 0; m <= n; ++m)
p += m * p1->operator()(i,m);
printf("%d %0.4f\n", ds, p);
}
int main(int argc, char* argv[])
{
// Read number of data sets to process
int num;
cin >> num;
// Process each data set identically
for (int i = 1; i <= num; ++i)
go(i);
// We're done
return 0;
}
You are confusing a call to state::operator()(int, int) with an initialization. That operator call lets you set the value of an element of the class instance.
State s(n); // this is the only initialization
s(0,0) = 1; // this calls operator()(int, int) on instance s
In this line:
s(0,0) = 1;
it's calling this:
double& operator()(int i, int m)
and because it returns a reference to a double, you can assign to it.
The second line is no longer initialization. The constructor was invoked in line 1, the second line invokes
double& operator()(int i, int m)
with n=0 and m=0 and writing 1 to the reference that is returned.
This part:
State(int n) : _n(n), _p(2*n+1)
...is a member initializer list. It's sort of similar to if you'd written the construct like:
state(int n) { _n = n; _p = 2*n+1; }
...except that it initializes _n and _p instead of starting with them unitialized, then assigning values to them. In this specific case that may not make much difference, but when you have things like references that can only be initialized (not assigned) it becomes crucial.
The s(0,0) = 1 looks like s is intended to act a little like a 2D array, and they've overloaded operator() to act as a subscripting operator for that array. I posted a class that does that in a previous answer.