A student can do the things bellow:
a. Do his homework in 2 days
b. Write a poem in 2 days
c. Go on a trip for 2 days
d. Study for exams for 1 day
e. Play pc games for 1 day
A schedule of n days can be completed by any combination of the activities above. For example 3 possible schedules for 7 days are:
homework, poem, homework, play
poem, study, play, homework, study
trip, trip, trip, study
Find a recursive function T(n) that represents the number of all possible schedules for n days.
I have 2 questions...
firstly i had to write a c++ program for this..
#include<iostream>
using namespace std;
int Count(int n)
{
if (n < 1) return 0;
if (n == 2 || n == 1) return 1;
return (3*(Count(n-2))) + (2*(Count(n-1)));
}
int main()
{
cout<<Count(2);
}
For input 2 it's giving answer 1.. shouldn't it be 7? homework ; poem ; trip ; exams,pcgame ; pcgame,exams; pcgame,pcgame; exams,exams
Secondly, suppose i consider pcgame, trip and trip,pcgame as the same combinations. How do i formulate an recursive solution for that?
When n = 2 the following if condition find a true paths,
if (n == 2 || n == 1) return 1;
^^^^^
Hence it returns 1 and terminates the recursion.
Related
I am a beginner currently in first semester. I have been practising on Code Chef and am stuck at this problem. They are asking to reduce the execution time of my code. The problem goes as follows:
Meliodas and Ban are fighting over chocolates. Meliodas has X chocolates, while Ban has Y. Whoever has lesser number of chocolates eats as many chocolates as he has from the other's collection. This eatfest war continues till either they have the same number of chocolates, or at least one of them is left with no chocolates.
Can you help Elizabeth predict the total no of chocolates they'll be left with at the end of their war?
Input:
First line will contain T, number of testcases. Then the testcases follow.
Each testcase contains of a single line of input, which contains two integers X,Y, the no of chocolates Meliodas and Ban have, respectively.
Output:
For each testcase, output in a single line the no of chocolates that remain after Ban and Meliodas stop fighting.
Sample Input:
3
5 3
10 10
4 8
Sample Output:
2
20
8
My code is as follows:
#include <iostream>
using namespace std;
int main()
{
unsigned int t,B,M;
cin>>t;
while(t--)
{
cin>>M>>B;
if(B==M)
{
cout<<B+M<<endl;
}
else
{
for(int i=1;B!=M;i++)
{
if(B>M)
B=B-M;
else
M=M-B;
}
cout<<M+B<<endl;
}
}
return 0;
}
Assuming that Band Mare different from 0, this algorithm corresponds to one version of the Euclidean algorithm. Therefore, you can simply:
std::cout << 2 * std::gcd(B, M) << "\n";
If at least one of the quantity is equal to 0, then just print B + M.
After realizing that your code was correct, I wondered where could be any algorithmic improvement. And I realized that eating as many chocolate from the peer as one has was in fact close to a modulo operation. If both number are close, a minus operation could be slightly faster than a modulo one, but if one number is high, while the other is 1, you immediately get it instead of looping a great number of times...
The key to prevent stupid errors is to realize that if a modulo is 0, that means that the high number is a multiple of the small one and we must stop immediately writing twice the lower value.
And care should be taken that if one of the initial counts are 0, the total number will never change.
So the outer loop should become:
if(B==M || B == 0 || M == 0)
{
cout<<B+M<<"\0";
}
else {
for (;;) {
if (M < B) {
B = B % M;
if (B == 0) {
cout << M * 2 << '\n';
break;
}
}
else {
M = M % B;
if (M == 0) {
cout << B * 2 << '\n';
break;
}
}
}
}
...
Note: no infinite loop is possible here because a modulo ensures that for example is M > B > 0' after M = M % Byou will haveB > M >= 0and as the case== 0` is explicitely handled the number of loops cannot be higher than the lower number.
In C++, I should write a program where the app detects which numbers are divisible by 3 from 1 till 10 and then multiply all of them and print the result. That means that I should multiply 3,6,9 and print only the result, which is 162, but I should do it by using a "While" loop, not just multiplying the 3 numbers with each other. How should I write the code of this? I attached my attempt to code the problem below. Thanks
#include <iostream>
using namespace std;
int main() {
int x, r;
int l;
x = 1;
r = 0;
while (x < 10 && x%3==0) {
r = (3 * x) + 3;
cout << r;
}
cin >> l;
}
Firstly your checking the condition x%3 == 0 brings you out of your while - loop right in the first iteration where x is 1. You need to check the condition inside the loop.
Since you wish to store your answer in variable r you must initialize it to 1 since the product of anything with 0 would give you 0.
Another important thing is you need to increment the value of x at each iteration i.e. to check if each number in the range of 1 to 10 is divisible by 3 or not .
int main()
{
int x, r;
int l;
x = 1;
r = 1;
while (x < 10)
{
if(x%3 == 0)
r = r*x ;
x = x + 1; //incrementing the value of x
}
cout<<r;
}
Lastly I have no idea why you have written the last cin>>l statement . Omit it if not required.
Ok so here are a few hints that hopefully help you solving this:
Your approach with two variables (x and r) outside the loop is a good starting point for this.
Like I wrote in the comments you should use *= instead of your formula (I still don't understand how it is related to the problem)
Don't check if x is dividable by 3 inside the while-check because it would lead to an too early breaking of the loop
You can delete your l variable because it has no affect at the moment ;)
Your output should also happen outside the loop, else it is done everytime the loop runs (in your case this would be 10 times)
I hope I can help ;)
EDIT: Forget about No.4. I didn't saw your comment about the non-closing console.
int main()
{
int result = 1; // "result" is better than "r"
for (int x=1; x < 10; ++x)
{
if (x%3 == 0)
result = result * x;
}
cout << result;
}
or the loop in short with some additional knowledge:
for (int x=3; x < 10; x += 3) // i know that 3 is dividable
result *= x;
or, as it is c++, and for learning purposes, you could do:
vector<int> values; // a container holding integers that will get the multiples of 3
for (int x=1; x < 10; ++x) // as usual
if ( ! x%3 ) // same as x%3 == 0
values.push_back(x); // put the newly found number in the container
// now use a function that multiplies all numbers of the container (1 is start value)
result = std::accumulate(values.begin(), values.end(), 1, multiplies<int>());
// so much fun, also get the sum (0 is the start value, no function needed as add is standard)
int sum = std::accumulate(values.begin(), values.end(), 0);
It's important to remember the difference between = and ==. = sets something to a value while == compares something to a value. You're on the right track with incrementing x and using x as a condition to check your range of numbers. When writing code I usually try and write a "pseudocode" in English to organize my steps and get my logic down. It's also wise to consider using variables that tell you what they are as opposed to just random letters. Imagine if you were coding a game and you just had letters as variables; it would be impossible to remember what is what. When you are first learning to code this really helps a lot. So with that in mind:
/*
- While x is less than 10
- check value to see if it's mod 3
- if it's mod 3 add it to a sum
- if not's mod 3 bump a counter
- After my condition is met
- print to screen pause screen
*/
Now if we flesh out that pseudocode a little more we'll get a skeletal structure.
int main()
{
int x=1//value we'll use as a counter
int sum=0//value we'll use as a sum to print out at the end
while(x<10)//condition we'll check against
{
if (x mod 3 is zero)
{
sum=x*1;
increment x
}
else
{
increment x
}
}
//screen output the sum the sum
//system pause or cin.get() use whatever your teacher gave you.
I've given you a lot to work with here you should be able to figure out what you need from this. Computer Science and programming is hard and will require a lot of work. It's important to develop good coding habits and form now as it will help you in the future. Coding is a skill like welding; the more you do it the better you'll get. I often refer to it as the "Blue Collar Science" because it's really a skillset and not just raw knowledge. It's not like studying history or Biology (minus Biology labs) because those require you to learn things and loosely apply them whereas programming requires you to actually build something. It's like welding or plumbing in my opinion.
Additionally when you come to sites like these try and read up how things should be posted and try and seek the "logic" behind the answer and come up with it on your own as opposed to asking for the answer. People will be more inclined to help you if they think you're working for something instead of asking for a handout (not saying you are, just some advice). Additionally take the attitude these guys give you with a grain of salt, Computer Scientists aren't known to be the worlds most personable people. =) Good luck.
The problem sounds like that:
Kevin has N friends and one building. He wants to organize a
party in that building and he invites exacly 1 friend / day. Kevin
unfortunately has grumpy neighbors which aren't too happy with the
noise that Kevin's party does. For that, Kevin wants to minimize the
noise level of his party. (the noise level is equal to the number of
friends in the building) In order to do that, after some day he can
clear the building by asking his friends to leave (he can do that K times, for K different days). (ex: he clears the
building after day 2 so at day 3 when he invites another friend, for
day 3 the noise level will be 1 because the past day he cleared the
building; if he didn't clear the building at day 2, the noise level
for day 3 will have been 3 (1 from day 2, 1 from day 1 and the new invited friend) and the total noise level for day 1, 2 and 3 would have been 1+2+3=6).
For better understanding the task:
Input:
5 2 (N, K)
Output:
7
Explanation:
In the input example, N friends will be invited at the party, in the following order:
1 (day 1) 1 (day 1)
1 (day 2) so in the building for each day will be present 2 (day 2)
1 (day 3) -------------------------------------------------> 3 (day 3)
1 (day 4) (without clearing the building) 4 (day 4)
1 (day 5) 5 (day 5)
-----(+)
15
So, clearing the building 0 times (K=0), the noise level will be 15.
Clearing the building 1 time (K=1), the sum will be:
(0 times)
1 1
__ 2 __ clearing the building after day 2 2
3 -----------------------------------> 1
4 2
5 3
----(+)
9
At this case (K=1), another solution could be to clear after day 3, same sum.
Clearing 2 times (K=2):
(0 times)
1 1
__ 2 __ clearing the building after day 2 & 3 2
__ 3 __ --------------------------------------> 1
4 1
5 2
----(+)
7
I have the solution but I don't understand it!
I tried, took some other cases but still nothing, maybe you guys can explain me why the solution is the way it is.
This is how sum(N, K) is calculated:
sum(N, K) = minimum noise level clearing the building K times (K>=0)
C++ code:
int sum(int n)
{
return n * (n + 1) / 2;
}
int solve(int n, int k)
{
int p = k + 1;
int mp = n/p;
int bp = (n+p-1)/p;
int nmaj = n%p;
int nmic = p-nmaj;
return nmic * sum(mp) + nmaj*sum(bp);
}
What is the purpose of each variable?
What does nmic * sum(mp) and nmaj*sum(bp) computes?
!!!!
For the example above (at the beginning - N=5, K=2), I debugged the code and wrote for N=5, K=0..2 the value for each variable, hoping to get the idea but no succes. I am going to post them for you, maybe you'll get the idea and then explain to me (I am a novice in algorithmic problems).
Here is it:
variable values for each case
I repeat, I tried for some hours to understand but no succes. And it's not a homework. Thank you!
The code goes like this:
int p = k+1;
p is the number of "parts" in which you divide the days (Ex: Day1 + Day2 = part1, Day 3 + Day4 = part2, Day 5 = part3)
int mp = n/p;
mp is the amount of days the minor part has, in the example is 1 (Day5). It's calculated as the floor of the number of days over the number of parts.
int bp = (n+p-1)/p;
bp is the amount of days in the bigger part, in the example is 2 (Day1 + Day2 or Day3 + Day4). I don't really get the exact math behind but that's what it calculates
int nmaj = n%p;
int nmic = p-nmaj;
nmaj is the number of major parts, in the example is 2 (Day1 + Day2 and Day3 + Day4), the nmic is the number of minor parts (1 for Day5).
nmic * sum(mp) + nmaj*sum(bp);
This just returns the number of minor parts * the accumulated value in minor parts + number of major parts * the accumulated value in major parts
The sum function is just the formula for arithmetic series (Or summation of arithmetic progressions) for the special case of initial element = 1
Hope you all are having a great day!
I love programming, but these past days I am having sleepless nights, with CodeChef always returning SIGSEGV errors on my Dynamic Programming solutions.
I am solving this question right now. Here's the question -
In Byteland they have a very strange monetary system. Each Bytelandian
gold coin has an integer number written on it. A coin n can be
exchanged in a bank into three coins: n/2, n/3 and n/4. But these
numbers are all rounded down (the banks have to make a profit). You
can also sell Bytelandian coins for American dollars. The exchange
rate is 1:1. But you can not buy Bytelandian coins. You have one gold
coin. What is the maximum amount of American dollars you can get for
it?
Input
The input will contain several test cases (not more than 10). Each
testcase is a single line with a number n, 0 <= n <= 1 000 000 000. It
is the number written on your coin. Output
For each test case output a single line, containing the maximum amount
of American dollars you can make. Example
Input: 12 2
Output: 13 2 You can change 12 into 6, 4 and 3, and then change these
into $6+$4+$3 = $13. If you try changing the coin 2 into 3 smaller
coins, you will get 1, 0 and 0, and later you can get no more than $1
out of them. It is better just to change the 2 coin directly into $2.
Now I know that it's very easy. And I did get stuck initially when I was declaring a big 10^9 integer long array (Over 1GB of memory..whoo!), but coming back to my senses - I decided to do memoization till 10001, and after that simple recursion. But still - I am making a mistake, and it's giving SIGSEGV error.
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
long long n[100001];
long long calc(long long x) {
if (x < 10001) {
if(n[x] != 0) return n[x];
n[x] = max(x, calc(x/2) + calc(x/3) + calc(x/4));
return n[x];
}
else return max(x, calc(x/2) + calc(x/3) + calc(x/4));
}
int main() {
memset(n, 0, sizeof(n));
n[1] = 1;
n[2] = 2;
n[3] = 3;
n[4] = 4;
n[5] = 5;
n[6] = 6;
for (int i = 7; i < 10001; i++)
n[i] = calc(i);
int t = 10;
while (t--) {
long long c;
scanf("%lld", &c);
printf("%lld\n", calc(c));
}
return 0;
}
I have solved some previous questions too - and all of them gave me this error once or twice. I know this error means that I am trying to access memory that hasn't been allocated, but what is wrong in my approach that I always get this error?
The problem is with the corner case n=0.
calc(0) recurses indefinitely because 0<10001 and n[0]=0. You need to add the terminating condition that calc(0)=0.
Takeaways:
Always check your programming competition solutions on corner cases.
Always ensure that your recursion does not result in an infinite loop.
I've created a greedy algorithm to solve a problem (homework assignment) and since I'm learning c++ I would like to achieve the same thing but using sets.
Basically we submit the homework to an online platform, this platform as some test cases that we don't know of, and we get a score based on that. If we pass all test cases we have 100%;
The problem is like this.
We have an actor that wants to schedule appointments with the fans that answered an online questionnaire about him. Now he wants to choose the fan's that maximizes the sum of points in the questionnaire and respecting the fan's availability. He can see only one fan a day.
We have an input like this:
6
1 1 5
2 2 4
3 1 2
4 3 1
5 1 6
6 2 2
Where the first line is the number of fans and following, in each line, we have the fan id, the fan available days and the fan points achieved in the online questionnaire. I must print the ids of the fans that the actor will see and the sum of combined points of the fans. So for the above input I have the following output:
2
4
5
11
Note that if two fans have the same points, the fan prefered should be the one with the lower ID.
I've started by sorting the fans by the points of the questionnaire (decreasing order) and then by the lower id.
When reading the input, I'm adding the number of days to a set.
My idea was like this:
When iterating over the data, I check if the fan in study days available is in the set. If it is, add this fan and remove the days from the set. If the fan days is not in the set, then get the upper_bound and decrease the iterator to set the fan on the first day lower that the initial day. The algorithm stops wen the set is empty or I iterate all over the fans.
Here is my greedy function:
void greedy() {
fan_id.insert(questionnaire_result[0][0]);
days_available.erase(questionnaire_result[0][1]);
total_questionaire_sum += questionnaire_result[0][2];
int i;
for (i = 1; i < number_of_fans; i++) {
if (days_available.empty()) {
break;
} else if (days_available.count(questionnaire_result[i][1])) {
fan_id.insert(questionnaire_result[i][0]);
days_available.erase(questionnaire_result[i][1]);
total_questionaire_sum += questionnaire_result[i][2];
} else {
it = days_available.upper_bound(questionnaire_result[i][1]);
if (it == days_available.begin()) {
if (*it < questionnaire_result[i][1]) {
fan_id.insert(questionnaire_result[i][0]);
days_available.erase(*it);
total_questionaire_sum += questionnaire_result[i][2];
}
} else if (it == days_available.end()) {
it--;
if (*it < questionnaire_result[i][1]) {
fan_id.insert(questionnaire_result[i][0]);
days_available.erase(*it);
total_questionaire_sum += questionnaire_result[i][2];
}
} else {
it--;
if (*it < questionnaire_result[i][1]) {
fan_id.insert(questionnaire_result[i][0]);
days_available.erase(*it);
total_questionaire_sum += questionnaire_result[i][2];
}
}
}
}
}
I believe my problem is in this line:
it = days_available.upper_bound(questionnaire_result[i][1]);
I've tested many possibilities and this is working in all my test cases. Unfortunately, we don't have the test cases of the platform.
Does someone see an situation that my code fails? With this I'm getting 90% of the score.
EDIT:
As Edward pointed me out, I've managed to solve the problem like this:
When reading the input added this line of code:
max_days = max_days | questionnaire_result[i][1];
And then did this:
for (int j = 1; j < max_days + 1; j++) {
days_available.insert(j);
}
Problem solved
This input file will cause the program to generate an incorrect result:
2
1 2 6
2 2 5
Both fans are available either day, so it's clear that both fans could be visited and the total output score should be 11. Your algorithm, however, only chooses the first one and outputs a score of 6.