Not displaying any output for the second loop of the function even though it is displaying the output for the cout statements in between the first and the second loop of the function. Enter 3 4 8 5 for cin. I need the scores to be 0 5 1. And the total score to be 6.
Code:
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
using namespace std;
long getMaxScore(vector < long > a){
// Complete this function
long runningSum = 0;
int n = a.size();
vector<long> scores(n);
int j=0;
long totalScore;
for(int i = 0; i < n;)
{
scores[j] = runningSum%a[n-1];
runningSum = runningSum + a[n-1];
n--;
j++;
}
cout<<scores[0]<<endl;
cout<<scores[1]<<endl;
cout<<scores[2]<<endl;
for(long k=0; k<n; k++)
{
totalScore = 0;
totalScore+=scores[k];
cout<<totalScore<<endl;
}
//return totalScore;}
int main() {
int n;
cin >> n;
vector<long> a(n);
for(int a_i = 0; a_i < n; a_i++){
cin >> a[a_i];
}
long maxScore = getMaxScore(a);
return 0;}
Problem
The loop
for(int i = 0; i < n;)
{
scores[j] = runningSum%a[n-1];
runningSum = runningSum + a[n-1];
n--;
j++;
}
ends when n is equal to zero.
Hence, by the time the program encounters the loop
for(long k=0; k<n; k++)
{
totalScore = 0;
totalScore+=scores[k];
cout<<totalScore<<endl;
}
nothing inside the loop executed since k < n is false.
Solution
I suggest adding a line to reset the value of n before the second loop.
n = a.size();
for(long k=0; k<n; k++)
{
...
}
Move the line
totalScore = 0;
outside the loop to accumulate the score.
totalScore = 0;
for(long k=0; k<n; k++)
{
totalScore += scores[k];
cout << totalScore << endl;
}
Related
So the problem asked me to find the greatest product from a given sequence of non-negative integers. What I did was I tried to find the greatest two integers from the sequence (for which I used a vector, by taking an input of n numbers) and multiplied them, since there are no negative integers. I used the long long type as well, since just an int type would not be enough for huge numbers. I kept getting a random huge number as the output whenever I tried to run the program :
#include <iostream>
#include <vector>
using namespace std;
long long max_prod(const vector<int>& numbers) {
int max1 = -1;
int max2 = -1;
int n = numbers.size();
for (int i = 0; i<n; i++){
if (numbers[i] > numbers[max1])
max1 = i;
}
for (int j = 0; j < n; j++) {
if (numbers[j] > numbers[max2] && j!=max1)
max2 = j;
}
return ((long long)(numbers[max1])) * ((long long)(numbers[max2]));
}
int main(){
int n;
cin >> n;
vector<int> numbers(n);
for (int i = 0; i<n; i++){
cin >> numbers[i];
}
long long result = max_prod(numbers);
cout << result << "\n";
return 0;
}
the last line is the output given by the program
You haver undefined behavior right here
long long max_prod(const vector<int>& numbers) {
int max1 = -1; <<<<<====
int max2 = -1;
int n = numbers.size();
for (int i = 0; i < n; i++) {
if (numbers[i] > numbers[max1]) <<<<<==
max1 = i;
}
for (int j = 0; j < n; j++) {
if (numbers[j] > numbers[max2] && j != max1)
max2 = j;
}
return ((long long)(numbers[max1])) * ((long long)(numbers[max2]));
}
You try to access numbers[-1] (twice once in the j loop and once in the i loop).
Set maxi and maxj to 0
I have to input numbers into an array and at the end get the number that has the most divisors, or if there are more numbers with the same amount, print out the first one.
Example: 4 numbers, 6 12 48 108. 108 has the most divisors, so this one needs to show up. if there were numbers after 108 with the same amount of divisors, 108 would have still been the only one to show up.
#include <iostream>
using namespace std;
int main()
{
int n = 0, d, largestCnt = 0;
int cntA=0, cntB=0;
cout << "How many elements?\n";
cin >> n;
int* v = new int[n];
for(int i=0; i<n; i++)
cin >> v[i];
for(int i=0; i<n; i++){
for(d=2; d<v[i]/2; d++)
if(v[i]%d==0)
cntA++;
for(d=2; d<v[i+1]/2; d++)
if(v[i+1]%d==0)
cntB++;
if(cntA > largestCnt)
largestCnt = cntA;
if(cntB > largestCnt)
largestCnt = cntB;
}
cout << largestCnt;
return 0;
}
this is the most I've done the past 2 hours, and I can't get past it
EDIT:
#include <iostream>
using namespace std;
int main()
{
int n = 0, d;
int mostDivisors=0, number_with_most_divisors=0;
int currentDivisors = 0;
cout << "How many elements?\n";
cin >> n;
int* v = new int[n];
for(int i=0; i<n; i++)
cin >> v[i];
number_with_most_divisors = v[0];
for(d=2; d<=v[0]/2; d++){
if(v[0]%d == 0)
mostDivisors++;
}
for(int i=1; i<n; i++){
for(d=2; d<=v[i]/2; d++)
if(v[i]%d == 0)
currentDivisors++;
if(currentDivisors > mostDivisors){
mostDivisors = currentDivisors;
number_with_most_divisors = v[i];
}
}
cout << number_with_most_divisors;
return 0;
}
Here is the algorithm of what you have to do:
Count the number of divisors of the first element in array. Save this value in mostDivisors. Set number_with_most_divisors as the first element in the array.
Start from the second element in array (position 1) and for each element, count how many divisors it has, save it in currentDivisors. If currentDivisors > mostDivisors then set mostDivisors to be equal to currentDivisors and update number_with_most_divisors to be the current element in the array.
The result is number_with_most_divisors at the end of the loop.
UPDATE
You are forgetting to initialize currentDivisors for each element after the first loop:
for(int i=1; i<n; i++){
currentDivisors = 0; // You forgot to put this line!
for(d=2; d<=v[i]/2; d++)
if(v[i]%d == 0)
currentDivisors++;
if(currentDivisors > mostDivisors){
mostDivisors = currentDivisors;
number_with_most_divisors = v[i];
}
// function to count the divisors
int countDivisors(int n)
{
int cnt = 0;
for (int i = 1; i <= sqrt(n); i++) {
if (n % i == 0) {
// If divisors are equal,
// count only one
if (n / i == i)
cnt++;
else // Otherwise count both
cnt = cnt + 2;
}
}
return cnt;
}
You can loop to enter the numbers into an array
#include <iostream>
int main() {
int n = 0, max_divs = 0, count = 0, max_divs_index = 0;
std::cin >> n;
int *v = new int[n];
for (int i = 0; i < n; ++i) std::cin >> v[i];
for (int i = 0; i < n; ++i) {
count = 0; // resetting count to 0 in each iteration
for (int j = 2; j < v[i]/2; ++j)
if (v[i] % j == 0) count++; // checking if the number is divisible by numbers between 1 and number itself/2 (1 and num/2 exclusive)
if (count > max_divs) { // checking if current count is greater than the maximum divisors
max_divs = count; // updating maximum divisors
max_divs_index = i; // updating the index of array element with maximum divisors
}
}
std::cout << v[max_divs_index];
delete[] v;
return 0;
}
I am trying to remove double elements in an array. I developed a simple code, but it is still not working. Is it possible to hint for some input maybe I haven't tried. I tried corner and test cases. The following is the problem statement:
A sequence of numbers given. Remove element’s doubles, leaving first copy.
Input: Contains a natural n (n ≤ 100000) – the n quantity numbers in a sequence, then n non-negative numbers – elements of the sequence which module is not greater than 999.
output: changed sequence.
It seems I can't get what might be the problem
#include <iostream>
//#include <cmath>
//#include <climits>
#define SIZE 100000
using namespace std;
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n, k, p;
bool tag; tag = false;
cin >> n;
long long int *a = new long long int[n];
long long int b[SIZE];
for (int i = 0; i < n; i++) { cin >> a[i]; }
for (int i = 0; i < n; i++) { k = 0;
for (int j = i + 1; j < n; j++) {
if (a[i] == a[j]) { b[k] = j-k; k++; tag = true; }
}
if (tag) {
for (int i = 0; i < k; i++) {
p = b[i];
for (int i = p; i < n; i++) { a[i] = a[i + 1]; }
n--;
}
tag = false;
}
}
for (int i = 0; i < n; i++) { cout << a[i] << " "; }
return 0;
}
Input: 6 1 2 2 4 3 4 Output: 1 2 4 3
You can use unordered_set and vector
int n; cin >> n;
long long int x;
unordered_set<long long int>myset;
vector<long long int>v1;
for (int i = 0; i < n; i++)
{
cin>>x;
if(myset.find(x)==myset.end())
{
myset.insert(x);
v1.push_back(x);
}
}
for(int i=0;i<v1.size();i++)
{
cout<<v1[i]<<" ";
}
You could use in you advantage the fact that input values are in the range from 0 to 999.
A simple bool used[1000]{} could be used to flag if the current value has been used already before pushing it to cout, thus ensuring both O(n) complexity and limited memory usage (1000 bytes for the bool[]}.
Here's a sample solution around this idea:
#include<iostream>
#define MAX_VALUE 999
using namespace std;
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
bool used[MAX_VALUE + 1]{};
size_t n;
cin >> n;
for (size_t num, i = 0; i < n; ++i) {
cin >> num;
if (!used[num]) {
cout << num << " ";
used[num] = true;
}
}
return 0;
}
You could try creating a second array of unique numbers as you go. I will demonstrate with a vector for the sake of simplicity.
std::vector<int> v;
for (int i = 0; i < n; i++) {
if (std::find(v.begin(), v.end(), arr[i]) == v.end()) {
v.push_back(arr[i]);
}
}
Then, you just write the contents of the vector to the output file.
Here is my version of O(n) complexity. Your solution may exceed time-limit ( if it is low )
bool check[2000];
for (int i = 0; i < 2000; i++) check[i] = 0;
for (int i = 0; i < n; i++) {
cin >> a[i];
// +999 to avoid negative numbers
check[a[i] + 999] = 1;
}
bool isPrint = false;
for (int i = 0; i < n; i++) {
if (check[a[i] + 999]) {
// mark false if already printed
check[a[i] + 999] = 0;
if (isPrint) printf(" ");
printf("%d", a[i]);
isPrint = true;
}
}
I have been struggling with it for 2 days.Please, could anyone tell me why does it exceed the time limit when i use as input 20000 and 0 and 40000 numbers afterwards ? I tried to make the variables type as large as possible, but that does not seem to help either.
#include <bits/stdc++.h>
using namespace std;
int main()
{
/*freopen("file.in", "r", stdin);
freopen("file.out", "w" , stdout);*/
long long int aux,i, n, k, j, total = 0;
cin >> n >> k;
long long int a[n], b[n], order[n];
signed long long int profit[n];
for(i = 0; i < n; i++)
cin >> a[i];
for(i = 0; i < n; i++)
cin >> b[i];
for(i = 0; i < n; i++)
profit[i] = a[i] - b[i];
for(i = 0; i < n; i++)
order[i] = i;
for(i = 0; i < n; i++)
for(j = i + 1; j < n; j++)
if(profit[order[i]] > profit[order[j]])
{
aux = order[i];
order[i] = order[j];
order[j] = aux;
}
if(k > 0)
for(i = 0; i < k; i++)
{
total += a[order[i]];
}
for(i = k; i < n; i++)
{
if(profit[order[i]] < 0)
total += a[order[i]];
else
total += b[order[i]];
}
cout << total;
return 0;
}
The complexity of your code is O(n^2), which is too much for N=20000. Reduce the complexity, replacing your bubble sort with Qsort. Try std::sort with custom comparison function.
I cannot understand/think of a case where my code fails to give correct output.
Link to the problem: http://www.spoj.pl/problems/MKBUDGET/
The problem clearly has a DP solution. I am posting my solution below:
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<vector <int> > opt;
void compute_opt(vector<int> A,int n,int hire,int fire,int sal,int max_a)
{
for(int i = A[0]; i <= max_a; i++) //for num workers in 1st month
opt[0][i] = i*(hire + sal);
for(int i = 1; i < n; i++) //num of months
for(int j = A[i]; j <= max_a; j++) //num of workers for ith month >=A[i] and <= max_a
{
opt[i][j] = opt[i-1][A[i-1]] + j*sal + (A[i] > A[i-1] ? (A[i]-A[i-1])*hire : (A[i-1] - A[i])*fire);
for(int k = A[i-1]; k <= max_a; k++)
opt[i][j] = min(opt[i][j], opt[i-1][k] + j*sal + (j>k ? (j-k)*hire : (k-j)*fire));
}
}
int ans(vector<int> A, int n, int max_a)
{
int ret = opt[n-1][A[n-1]];
for(int i = A[n-1]; i <= max_a; i++)
ret = min (ret, opt[n-1][i]);
return ret;
}
int main()
{
vector<int> A;
int n, hire, fire, sal,max_a, c = 1;
while(1)
{
cin >> n;
if(n == 0)
break;
A.clear();
opt.clear();
max_a = 0;
cin >> hire >> sal >> fire;
A.resize(n);
for(int i = 0; i < n; i++)
{cin >> A[i];
max_a = max(max_a,A[i]);
}
opt.resize(n);
for(int i = 0; i < n; i++)
opt[i].resize(max_a + 2);
compute_opt(A,n,hire,fire,sal,max_a);
cout << "Case " << c << ", cost = $" << ans(A,n,max_a) << endl;
c++;
}
return 0;
}
I am getting correct answers for the two sample test cases but I get a WA when I submit. Any help ?
OK, so your problem is that you disallow the case where you hire any number of employees between A[i] and A[i - 1]. Maybe it's a good idea to fire some unneeded employees, but not all. That's why you get WA. I modified your code and got it accepted:
void compute_opt(vector<int> A,int n,int hire,int fire,int sal,int max_a)
{
// Fill all disallowed entries with infinity
for (int i = 0; i < A[0]; ++i)
opt[0][i] = 1000000000;
for(int i = A[0]; i <= max_a; i++) //for num workers in 1st month
opt[0][i] = i*(hire + sal);
for(int i = 1; i < n; i++)
for(int j = 0; j <= max_a; j++)
{
// No need for special case handling,
//just check all previous numbers of employees
opt[i][j] = 1000000000;
if (A[i] > j) continue;
for(int k = 0; k <= max_a; k++)
opt[i][j] = min(opt[i][j],
opt[i-1][k] + j*sal + (j>k ? (j-k)*hire : (k-j)*fire));
}
}
By the way, there's a "greedier" solution than the one you have that does not depend on the number of employees being small (so that the table can be allocated).