Missing element in values entered in C++ - c++

The code takes an integer n and takes in n-1 elements. The elements entered are all the numbers from 1 to n, except one of them. We are supposed to find the missing element.
This solution is the fastest. However, I don't understand it.
Can anyone explain it ?
#include <iostream>
int main(){
int g,n,i,k;
std::cin>>n;
for(i=1; i<n; i++){
std::cin>>g;
k^=i^g;
}
std::cout<<(k^n);
}
Input:
10
3 8 10 1 7 9 6 5 2
Output:
4

This uses the fact that XOR is commutative and associative (so order doesn't matter), and that x^x == 0 for all x.
It takes the XOR of all numbers between 1 and n, and also xors it with all the input numbers. Any number that was input will be XORed twice into the final result, and therefore will be cancelled out. The only number remaining will be the number that wasn't input. This number was only XORed once, and therefore this will be the value of the result of all the XORs.
For the example you gave:
The input numbers are: 3 8 10 1 7 9 6 5 2
1^2^3^4^5^6^7^8^9^10 ^ 3^8^10^1^7^9^6^5^2 =
(1^1)^(2^2)^(3^3)^4^(5^5)^(6^6)^(7^7)^(8^8)^(9^9)^(10^10) =
4
Note that the code is written somewhat confusingly, because the order of XORs is not straightforward: it alternates between XORing an input and XORing the next number between 1 and n. This is only done to keep the code short. It would be clearer as:
k = 0;
for (i=1; i<=n; i++)
k ^= i;
for (i=0; i<n-1; i++) {
std::cin >> g;
k ^= g;
}
std::cout << k;

Related

what's wrong with my code [ Dfs , Dynamic programming ]

i tried to solve this problem with dfs and dynamic programming . then
i submit my code to my school grader but the answer is wrong .
am i implement something wrong with dfs .
what's wrong with my code.
PS.sorry for my bad english
The problem :
given a random number there's 2 different way you can do with this
number
1.divide it by 3 (it has to be divisible)
2.multiply it by 2
given n number find the original order before it was swapped
----EXAMPLE1---- INPUT : 6 4 8 6 3 12 9 OUTPUT : 9 3 6 12 4 8
----EXAMPLE2---- INPUT : 4 42 28 84 126 OUTPUT : 126 42 84 28
Here's my code
#include<iostream>
#include<cstdio>
#include<map>
using namespace std;
int n ;
int input[51];
map<int,int> order ;
map<int,int> memo ;
bool valid(int a){
for(int i=0;i<n;i++){
if(input[i]==a)return 1 ;
}
return 0 ;
}
void dfs(int st){
memo[st]=1;
if(valid(st/3)){
if(memo[st/3]==0){
dfs(st/3);
order[st]+=order[st/3];
}
else order[st]+=order[st/3];
}
if(valid(st*2)){
if(memo[st*2]==0){
dfs(st*2);
order[st]+=order[st*2];
}
else order[st]+=order[st*2];
}
}
int main(){
cin >> n ;
for(int i=0;i<n;i++){
cin >> input[i];
memo[input[i]]=0;
order[input[i]]=1;
}
for(int i=0;i<n;i++){
if(memo[input[i]]==0)dfs(input[i]);
}
for(int i=n;i>=1;i--){
for(int k=0;k<n;k++){
if(order[input[k]]==i){
printf("%d ",input[k]);
break;
}
}
}
}
Information the OP should have told us in the first place:
my code gave the correct answer only 7 of 10 test case .i've already
asked my teacher he only told me to be careful with the recursion .
but i couldn't figure it out what's wrong with my recursion or
something else
An example that "fails":
Here's a failing case: Say you have the sequence 3 1 2 4. valid will
return true for 4 / 3 because it sees 1 in the sequence. –
Calculuswhiz
the better solution
#include<bits/stdc++.h>
using namespace std;
struct number{
long long int r , f3 , f2 ;
};
vector<number> ans ;
bool cmp(number a,number b){
if(a.f3!=b.f3)return a.f3>=b.f3;
if(a.f2!=b.f2)return a.f2<=b.f2;
return true ;
}
int main(){
int n ;cin>> n ;
long long int input ;
for(int i=0;i<n;i++){
cin >> input ;
long long int r = input ;
long long int f3 = 0, f2 = 0 ;
while(input%3==0){
f3++;
input/=3;
}
while(input%2==0){
f2++;
input/=2;
}
ans.push_back({r,f3,f2});
}
sort(ans.begin(),ans.end(),cmp);
for(auto i : ans){
cout << i.r << " " ;
}
}
The darkest place is under the lamp.
Look at the problem definition:
1.divide it by 3 (it has to be divisible)
Where do you test for the divisibility?
So, one error is here:
if(valid(st/3)){
This test should read:
if(st % 3 == 0 && valid(st/3)){
With this simple improvement, all three test cases pass.
A hint to improve (simplify) the solution
Numbers that are not divisible by 3 must come after those divisible.
Similarly, those not divisible by 9 must be coming after those that does.
Similarly for 27, 81,...
Now, if you divide your numbers into subsets of numbers of the form n = 3^k*m, where m % 3 != 0, then in each such a subset the only operation allowed by your algorithm is "multiply by 2". So it suffices to order them in ascending order.
The problem can be solved without dfs, nor is recurnece really necessary. Just order the numbers in a funny way: in descending order with respect to the number of times the number is divisible by 3, and then in ascending order. So, a task for you: challenge your teacher with a solution that, once the numbers are read in, does just one instruction std::sort (or qsort, as I see you write in C), then tests the validity of the solution, and prints it.
Moreover, I've just proved that if a solution exists, it is unique.

Why this program does 35 percent accepted but rest is runtime errors?

Once, when Dino was solving a problem related to arrays, he saw that the size of all arrays is at most 106. Since Dino is a dinosaur, this number seemed very small to him. Therefore, he decided to create a big array.
Dino first creates an empty array and selects n pairs of numbers: (a1, b1), (a2, b2), ..., (an, bn). Then for each of these pairs he inserts into array the number bi ai times. For example,if the first pair is (3, 5), the number 5 will be inserted into array 3 times. After that, Dino decides to arrange this array in non-decreasing order, but since the array is very large, Dino's computer cannot perform this arrangement. He is interested in the k-th (the array is numbered starting from 1) number. Help Dino to find this number.
Input
First line contains number n (1 ≤ n ≤ 105). Each of the next n lines contains pair (ai, bi) (1 ≤ ai, bi ≤ 105). The last line contains number k. It is guaranteed that k-th number exists in array.
Output
Print the k-th number in non-decreasing array.
INPUT
First line contains number n (1 ≤ n ≤ 105). Each of the next n lines contains pair (ai, bi) (1 ≤ ai, bi ≤ 105). The last line contains number k. It is guaranteed that k-th number exists in array.
OUTPUT
Print the k-th number in non-decreasing array.
INPUT Examples
3
1 2
3 6
2 1
3
OUTPUT
2
I tried to code this my self but it got partially accepted. Can someone help me for doing this?
#include<iostream>
#include<algorithm>
#include<utility>
#include<vector>
using namespace std;
using ull = unsigned long long;
int main()
{
ull a, b, n, j, k;
cin >> n;
vector<ull> myvec;
for(int i = 0; i < n; i++)
{
cin >> a >> b;
for(j = 0; j < a; j++)
{
myvec.push_back(b);
}
}
cin >> k;
sort(myvec.begin(), myvec.end());
cout << myvec[k - 1];
return 0;
}
You don't need to recreate the array, and you don't need to sort anything (the description even tells you that you shouldn't: "Dino's computer cannot perform this arrangement").
Consider what happens if you turn the problem around slightly.
Instead of a[i] being the i:th number, let it say how many is there are in total.
(The arrangement of the input hints at this, although not as obviously as the "sorting won't work" hint.)
This essentially makes a run-length encoded sorted array, with the indices of a doubling as elements, and the elements of a are the run lengths.
Then consider that a linear search through 105 elements (bi ≤ 105) is way faster than sorting 106 elements.
Something like this:
int main()
{
// Keeps track of the total number of occurrences of each number.
// The values are all less than or equal to 100000.
// Add an extra element to simplify the rest of the code.
// (The zero will be unused.)
std::vector<int> counts(100001);
int n;
cin >> n;
for(int i = 0; i < n; i++)
{
int count, value;
cin >> count >> value;
counts[value] += count;
}
int k;
cin >> k;
// Now go looking for the k:th number, adjusting k as we go.
for (size_t number = 0; number < counts.size(); number++)
{
if (k <= counts[number])
{
std::cout << number << std::endl;
break;
}
// Adjust k for the rest of the sequence.
k -= counts[number];
}
}

Why am I getting two outputs in place of a single one?

I'm writing a simple program and I am getting 2 outputs of the same data with a single cout statement. I think something went wrong with my loop, but I am not able to find where the problem is. If possible, please show me what I need to change; otherwise, I'd at least like to know why my logic is wrong.
My code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n ;
cin >> n;
vector<int> arr(n);
vector<int> a(n);
for(int arr_i = 0;arr_i < n;arr_i++){
cin >> arr[arr_i];
a[arr_i]=1;
}
int i,least,flag,count=n;
do{
cout<<count<<endl;
count=0;
flag=1;
for(i=0;i<n;i++){ //for getting least number
if(a[i]){
if(flag){
least=arr[i];
flag=0;
}
if(arr[i]<least){
least=arr[i];
}
}
}
for(i=0;i<n;i++){ // for actual logic
if(arr[i]<=0||!a[i]){
a[i]=0;
//continue;
}
else{
arr[i]-=least;
count++;
}
}
}while(count);
return 0;
}
Sample input:
6
5 4 4 2 2 8
Expected output
6
4
2
1
Actual output:
6
6
4
4
2
2
1
1
Problem statement
You are given N sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick.
Suppose we have six sticks of the following lengths:
5 4 4 2 2 8
Then, in one cut operation we make a cut of length 2 from each of the six sticks. For the next cut operation four sticks are left (of non-zero length), whose lengths are the following:
3 2 2 6
The above step is repeated until no sticks are left.
Given the length of N sticks, print the number of sticks that are left before each subsequent cut operations.
Note: For each cut operation, you have to recalculate the length of the smallest sticks (excluding zero-length sticks).
One noticed error: when substracting least from arr[i] and arr[i] becoming <=0 a[i] still stays non-zero, and at next iteration you getting least number the same as at previous iteration.
Other problem: your count is count of previous turn. At first iteration it equals 6, because condition if(arr[i]<=0||!a[i]) dont fulfill for any number from input.
After fixing this part:
// for actual logic
if (a[i]) {
arr[i] -= least;
if (arr[i] <= 0)
a[i] = 0;
else
count++;
}
it looks working nice.

When I tried to run the code I was getting the 2nd output as garbage value. Can anyone tell fault in that code

#include <iostream>
using namespace std;
int main()
{
int T,i,j,N,K;
cin >> T;
int n[T],x;
for(i=1; i<=T; i++)
{
cin >> N >> K;
for(int j=1; j<=N; j++)
{
cin >> x;
n[i]+=x/K;
x=0;
}N=0;K=0;
}
for(i=1; i<=T; i++)
cout << n[i] << endl;
return 0;
}
question is "Your program will be tested on one or more test cases.The first line of the input will be a single integer T, the number of test cases (1 ≤ T ≤ 100). Followed by the test cases, each test case is on two lines. The first line of each test case contains two integers N, the number of different candies (1 ≤ N ≤ 100), and K, the minimum number of candies which will make a kid happy as described above (1 ≤ K ≤ 100). The second line of each test case contains N integers, separated by a single space, which are the available number of candies of each type. There will be at least 1 candy and at most 100 candies of each type."
sample input: 2
3 2
4 5 7
3 8
4 5 7
sample output:
7
0
when the i tried the above code the answer that i got like:
input:2
3 2
5 6 8
2 2
9 1
output:
9
-880625041
When i tried to run the code i was getting the 2nd output as garbage value. Can anyone tell me the fault in that code
Here is the problem:
n[i]+=x/K;
this is equivalent to n[i]=n[i]+x/K; So it uses a prior value of n[i]. However, you haven't set any prior value to elements of the array n. So, initialise the array to 0 first.
for(i=0;i<T;i++)
n[i] = 0;
Also, in this code:
for(int j=1; j<=N; j++)
are you sure that N will always be less than T, the size of array? (take care of 0-based indexing as well).
Arrays in C and C++ are zero-based. Run your loops from 0 to N - 1 and T - 1.
You don't initialise your array values before using them. Formally your program behaviour is undefined. (I think you mean n[i]= rather than n[i]+=.)
Variable length arrays like int n[T] are compiler extensions. Do bear this in mind as it could affect portability.

Number triangle using while loops

I'm having trouble with my C++ programming class homework.
Here is the assignment:
Write a program which reads in the number of rows and prints 'n' rows
of digits.
1
12
123
1234
12345
where the i’th row is 1234 . . . k where k = i mod 10. If a row
has more than 10 digits, the digit after 9 should start again from 0.
For instance, if the number of rows is 15, the output should be: 1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
12345678901
123456789012
1234567890123
12345678901234
123456789012345
This is what I have so far:
#include <iostream>
using namespace std;
int main()
{
int rows(0);
int i(0);
int j(0);
cout << "Enter number of rows: ";
cin >> rows;
int k=rows;
i=1;
while (i <= rows)
{
j=1;
while(j <= i)
{
cout << j;
j++;
}
cout << endl ;
i++;
}
return (0);
}
This works perfectly until I get to the 10th row. I'm not sure how to get the counter to reset back to 0 and go 1-9 again. I'm guessing an if statement, but I don't know how to correctly implement it. Any help would be greatly appreciated.
Using cout << j%10 will always print the ones digit of whatever j is equal to. So when j = 10, cout << j%10 will print 0, etc.
To expand on the other answer a bit:
% is referred to as the remainder operator. It is also sometimes called "modulo" or "modulus". It returns the remainder of the first argument divided by the second argument. So for this situation, since you want the number to be between 0 and 9, consider what happens when you have n % 10.
8 / 10 == 0 remainder 8
9 / 10 == 0 remainder 9
10 / 10 == 1 remainder 0
11 / 10 == 1 remainder 1
12 / 10 == 1 remainder 2
Etc.
In C++, as in most programming languages, you typically start counting at 0 and you exclude the final number in your range. So if you had n % 56, your output starting at 0 would go up to 55, and then reset to 0 again. The classical argument for this was written by Dijkstra:
http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html