I have been trying to solve this simple problem in C++ but every time I submit, it says wrong answer. I am pretty sure I have got the logic right. Any help is appreciated.
Question: Find the sum of distances between the inputted numbers.
Ex. Input: 2 5 8 2 1
Distance=2+2+5+0
=9, (1 < n < 1000000)
PS: Input can't have the same number consecutively.
PSS: Subtask two is giving Wrong Answer
Code:
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t,a[100000],n,sum=0;
cin>>t;
for(int i=0;i<t;i++)
{
cin>>n;
for(int j=0;j<n;j++)
{
cin>>a[j];
}
for(int j=0;j<n-1;j++)
{
if(a[j]!=a[j+1])
{
sum = sum + abs(a[j]-a[j+1])-1;
}
}
cout<<sum<<endl;
sum=0;
}
}
The problem with your code is that you are using int type for sum whose maximum value (1E11) can exceed the upper limit of int(if it's 32-bit or less). Use long long(atleast 64-bit) instead to store your sum.
Well, you can also optimize the code because you don't exactly need an array of 100000 integers and store the values in it. You can do so using only two variables.
Here is a modified implementation of your logic:
#include <iostream>
int main() {
int t, n, first, second;
long long sum; // or better use std::int_fast64_t sum;
std::cin >> t;
while (t--) {
sum = 0;
std::cin >> n >> first;
for (int i = 0; i < n - 1; ++i) {
std::cin >> second;
sum += std::abs(first - second) - 1;
first = second;
}
std::cout << sum << std::endl;
}
}
PS: In competitive coding checking the provided constraints like if(a[j]!=a[j+1]) is useless. The problem statement simply guarantees it that it will never be false.
Related
When i run the source code on sample cases of their example it runs fine but when I submit the question It says runtime error.
Here is my Source code and link of the question.
Question link - https://www.codechef.com/SEPT21C/submit/MNDIGSM2
Below is the code.
#include <iostream>
#include <vector>
// #include <bits/stdc++.h>
using namespace std;
// #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int converter(int n , int b){
vector<int> vec;
int sum = 0;
while(n>0){
vec.push_back(n%b);
n = n / b;
}
int vecSize = vec.size();
for(int i = 0;i<vecSize;i++){
// cout<<
sum = sum + vec[i];
}
return sum;
}
int minVal(vector<int> arr , int len){
int min = arr[0], c = 0;
// if(arr)
for(int i = 1 ; i< len;i++){
if (arr[i] < min){
min = arr[i];
c = i;
}
}
return c;
}
int main() {
// your code goes here
// fast;
int test;
cin>>test;
while(test--){
int n ,r;
cin>>n>>r;
int l = 2;
// ll copy = l;
int arSize = (r-2)+1;
vector<int> arr(arSize);
for(int i = 0;i< arSize ;i++){
arr[i] = converter(n,l);
l++;
}
int tobe = minVal(arr , arSize);
cout<<tobe + 2<<endl;
}
return 0;
}
Maybe I do not understand the question fully. There is not enough information available.
It could be that the program slows down because the usage of the std::vector. First you calculate, then store the values and then iterate again over all values.
This is not necessary. You can do all calculations inline without the need for additional storage.
And, additionally, all these "contest" questions do not have the intention, to improve your programming skills.
Basically the language doesn't matter. The important thing is the algorithm. They want you to find a "good" algorithm.
Bruteforcing is nearly never a feasible solution. If you read about big numbers like 10^12, then you know already in advance that you will get a TLE with the brute force solution.
Regarding this horrible and non compliant C++ slang that is used on this "competetion" sides, please note that this is nearly never necessary. You have no time contraints to submit a solution. So, you could use also real C++ code.
Anyway. I corrected your code and added meaningful varibale names, comments and formatting. So, logically, the approach is the same, but it is readable.
Of course it may fail as well, because it is still brute forcing . . .
#include <iostream>
#include <limits>
constexpr unsigned long long BaseStart = 2ull;
int main() {
// Get number of test cases
unsigned int numberOfTestCases{};
std::cin >> numberOfTestCases;
// Work on all test cases
for (unsigned int testCase{}; testCase < numberOfTestCases; ++testCase) {
// Get the value to check and the upper limit for the base
unsigned long long valueToCheck{}, upperLimitBase{};
std::cin >> valueToCheck >> upperLimitBase;
// Here we will store the minimum sum to check
unsigned long long minimumsumOfDigits{std::numeric_limits<unsigned long long>::max()};
// Here we will store the result
unsigned long long minimumBase{};
for (unsigned long long base{BaseStart}; base <= upperLimitBase; ++base) {
// And this will be the running sumOfDigits
unsigned long long runningSumOfDigits{};
// get the digits of the value and calculate the running sum
unsigned long long value{valueToCheck};
while (value > 0) {
// Get digits via modulo division and add up
runningSumOfDigits += value % base;
value /= base;
}
// Get current minimum
if (runningSumOfDigits < minimumsumOfDigits) {
minimumsumOfDigits = runningSumOfDigits;
minimumBase = base;
}
}
std::cout << minimumBase << '\n';
}
return 0;
}
This code can of course be optimized further, but for this I would need more information . . .
I wrote this piece of code, which has t test cases, and for every test cases it would input 3 digits. I want this program to then identify the minimum element among those three inputs, and then print the minimum element. What should I do?
int main()
{
int t;
cin>>t;
while(t--)
{
for(int i=0;i<3;i++)
{
int n;
cin>>n;
}
}
return 0;
}
Here's a example of finding the minimum of three digits, using a running minimum:
#include <iostream>
int main()
{
unsigned int test_case_quantity = 0U;
std::cin >> test_case_quantity;
while(test_case_quantity--)
{
char minimum;
std::cin >> minimum;
char digit;
std::cin >> digit;
if (digit < minimum) minimum = digit;
std::cin >> digit;
if (digit < minimum) minimum = digit;
std::cout << " minimum: " << minimum << "\n";
std::cin.ignore(100000, '\n'); // Synchronize to next line.
}
return 0;
}
For a more robust program, you can add validation that the character read is actually numeric.
We can make use of an extra variable say small and when we are inputting the very first number, we can assign that first number to the small and in all other cases we can compare whether the current number is less than small, if yes then update small.
Finally outside the loop we can print the value of small and this will be our answer.
int main()
{
int t;
cin>>t;
while(t--)
{
int small;
for(int i=0;i<3;i++)
{
int n;
cin>>n;
if (i == 0)
small = n;
else {
if (n < small)
small = n;
}
}
cout<<"Smallest number is :" << small;
}
return 0;
}
input :
1
10 2 3
output :
Smallest number is :2
Flow :
At first the value 10 will be assigned as small, then for the next element 2, we compare whether 2 is less than small which is 10 in that case, and reassign small to 2. Then this small is checked with 3, but 2 < 3, so small value remains unchanged.
I assume there will be only integer values as input.
I have been given some integers and I have to count the frequency of a specific digit in the number.
example input:
5
447474
228
6664
40
81
The first number says number of integers in the list. I am finding frequency of 4 in this case. I tried to change the integer to an array, but it is not working.
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
int main() {
int n;
cin>>n;
for (int i=0; i<n; i++)
{
int x;
cin>>x;
int frequency=0;
int t=log10(x);
int arr[t];
for (i=t; i>0; i--)
{
arr[i]=x%10;
x=x/10;
}
for(int i=0; i<t; i++)
{
if(arr[i]==4)
{
frequency++;
}
}
std::cout << frequency << std::endl;
}
return 0;
}
No need to create an array, or to determine the number of digits. Just loop until the number reaches zero.
int digitCount(int n, int d) {
if(n < 0) n = -n;
int count = 0;
for(; n != 0; n /= 10)
if(n % 10 == d) count++;
return count;
}
Test:
cout << digitCount(447474, 4) << endl;
cout << digitCount(-447474, 4) << endl;
Output:
4
4
Your code uses VLAs which are not standard C++. See Why aren't variable-length arrays part of the C++ standard?.
log10(x) is not the number of digits. For example log10(1234) == 3.09131516 but it is 4 digits. Also you are accessing the array out of bounds in the first iteration of the loop: arr[t]. Valid indices in an array of size t are 0,1,2,...,t-1. Trying to access arr[t] is undefined behavior.
Actually you dont need any array. Instead of storing the digits in an array you can immediately check whether it is a 4 and count.
Even simpler would be to read the user input as a std::string:
#include <string>
#include <algorithm>
#include <iostream>
int main() {
std::string input;
std::cin >> input;
std::cout << std::count(input.begin(),input.end(),'4');
}
Perhaps you should add some checks to verify that the user input is actually a valid number. However, also when reading an int you should validate the input.
N pairs of numbers are given. Print the sum of each pair.
The first line of the standard input is N (1≤N≤100000). The following N lines contain exactly two integers, separated by a space whose absolute values are less than 1,000,000,000.
INPUT
2
1 1
-1 0
OUTPUT:
2
-1
I've written this:
#include<iostream>
using namespace std;
int main()
{
unsigned short int n;
long int n2,n3, rez;
rez=0;
//Uneseno broj linija:
cin>>n;
for(int i=0;i<n;i++)
{
if(rez==0)
{
cin>>n2>>n3;
rez=n2+n3;
cout<<rez<<endl;
}
rez=0;
}
return 0;
}
Now this would be perfectly fine, but I don't get required output.
I can't think of the other idea, because I don't know how many exactly of N's will be there, so I can't predict numbers of variables that I should create, which will store result of two numbers entered.
Your program is almost working. All you need to do is make n larger. An unsigned short caps out at 65,535. Bump it up to an unsigned int so it can handle values up to 100,000.
Aside from that, the rez variable isn't needed. You can delete it.
Also, there's no need to store all the numbers first and then calculate the sums afterwards. Calculating them as you go will work just fine. cin and cout are independent streams of data and it's fine to interlace reads and writes. Avoid storing them in a vector or an array as that just chews up a lot of memory for no benefit.
#include <iostream>
int main()
{
unsigned n;
std::cin >> n;
for (unsigned i = 0; i < n; i++)
{
long n2, n3;
std::cin >> n2 >> n3;
std::cout << (n2 + n3) << std::endl;
}
return 0;
}
Style notes:
Avoid using namespace std;. It's better to write out std:: everywhere.
I moved n2 and n3 inside the loop. Try to declare variables as late as possible to limit their scope rather than declaring them all at the top of the function. It makes it obvious that they're only used inside the loop and that their values don't persist across iterations.
Add some whitespace around operators. Cramming everything together is hard to read.
I have changed some of the numeric types you've used. Does this work?
int main()
{
vector<long long int> results;
unsigned long int n;
long long int n2, n3, rez;
cin >> n;
for (unsigned long int i = 0; i < n; i++)
{
cin >> n2 >> n3;
rez = n2 + n3;
results.push_back(rez);
rez = 0;
}
for (auto result: results)
{
cout << result << endl;
}
return 0;
}
I am suppossed to sum the squares of the all the natural numbers until it reaches some input, but the result becomes larger than it should. As I set 3 as input, the outcome becomes 3*10⁹ or so, could you please tell if I am missing a mistake with data types or operations?
BTW, when does using functions become more efficient than writing whatever in the main code? I have quite a few doubts on when I should or should not use them.
Thanks to whomever might read it.
#include <iostream>
using namespace std;
int main(){
int input, sum;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
You should initialize the variable sum with 0 and then the program will be run successfully. When you use sum without initializing it, the behaviour of your program is undefined.
Also you can use below formula instead of the for loop:
sum = n * (n + 1) * (2 * n + 1) / 6
You never initialize sum, so there is no guarantee that the value starts at 0. In fact, it's initial value is essentially undefined. You should simply add the line sum = 0; before your for loop.
#include <iostream>
using namespace std;
int main(){
int input, sum;
sum = 0;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
"BTW, when does using functions become more efficient than writing whatever in the main code"
It isn't necessarily more efficient, but for larger projects it is easier to read code when common functionality has been grouped into reusable functions. As a general rule of thumb, if you are writing the same code/algorithm more than once, you should write a function for that code/algorithm.
NOTE - As pointed out by others there happens to be a formula for calculating the sum of squares without a loop.
sum = n * (n + 1) * (2 * n + 1) / 6
This is what is known as an order of 1, or O(1), solution because a single atomic operation can be performed to achieve the results you are looking for. On the other hand, the loop solution is considered order of n, or O(n), since n iterations of the loop must be performed to achieve the results of the routine. The O(1) solution is considered optimal. If you use large values as your input then you will see why. However, if you are new to programming then your teachers will not expect you to know much about algorithm analysis and the original solution above should be fine.
There are two approaches to resolve your problem.
The first one is to place the declaration of the variable sum before main. For example
#include <iostream>
using namespace std;
int sum;
int main(){
int input;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
In this case the variable will have the static storage duration and will be initislized by the compiler with 0.
Otherwise the variable have the automatic storage duration and must be initialized explicitly like
#include <iostream>
using namespace std;
int main(){
int input, sum = 0;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
Pay attention to that it is better to declare the variable as having the type long long int because the sum of squares can be too big and will not fit into an object of the type int. For example
#include <iostream>
using namespace std;
int main(){
int input;
long long int sum =0;
cin >> input;
for(int i = 1; i <= input; i++){
sum += ( long long int )i*i;
}
cout << sum << endl;
}
You do not initialize sum. So whenever you do sum += i * i, you are adding numbers to a trash value.
This is the reason you get incorrect results.
To fix this, simply replace int input, sum; with int input, sum(0);.