How does this code works in c++? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I participated in Codeforces Round #396 (Div. 2) yesterday.
The (A) problem seemed pretty advanced in my opinion when I read it.
I tried solving it all the competition time yesterday and some time today.
I came up with a 200 lines long(half-working) solution. And then I gave up.
I looked what other people wrote there and I saw max 20 lines long code that seems magic to me.
The problem asks you to output the length of the longest uncommon subsequence of letters from two strings.
You can read the full problem here:
http://codeforces.com/contest/766/problem/A
#include<bits/stdc++.h>
using namespace std;
string a,b;
int main(){
cin>>a>>b;
printf("%d",a==b?-1:max(a.size(),b.size()));
return 0;
}
This is all the code used to solve the problem, and I really want to know how that one line of code
printf("%d",a==b?-1:max(a.size(),b.size()));
can solve this "advanced" task?

If the two strings are equal, there is no "uncommon subsequence". If they are not equal, neither one is a subsequence of the other, but each one is a subsequence of itself, so each one is an "uncommon subsequence". The longer of the two is the longest "uncommon subsequence", and its length is the correct answer. If the two are not equal but have the same length, then each one is an "uncommon subsequence" and the length of the longest is just the length of either one.
Don't get tangled up in what you (or any other reasonable person) think a "subsequence" is. The problem defines "uncommon subsequence", and all you have to do is apply its definition. This "problem" is about word play, not coding.

It does not seem to solve the task at hand. It just outputs -1 when the strings are equal and the length of the longer string when they are not different. However, the problem asks for the longest uncommon sequence. It would fail with the inputs abc and abcd to give the answer 1 would rather give 4.
What the line does is the following:
It checks whether a == b, whether the strings are equal.
If they are equal, the condition A is true in the ternary operator A ? B : C, so that expression will evaluate to B which is just -1 here.
If they are not equal, it will evaluate to C which is the maximum of the two string lengths, so it will be length of the longer string.
The value of the ternary expression is then printed, albeit without a newline, which is a bit bad.
So the code is so short because it only solves the problem for a few cases but not the general case.

printf ("%d", a == b ? -1 : max (a.size (), b.size ()));
is equivalent to
if (a == b) {
printf ("%d", -1);
}
else {
if (a.size () > b.size ()) {
printf ("%d", a.size ());
}
else {
printf ("%d", b.size());
}
}
BTW That's only a small step in solving the problem...
[CORRECTION]
IT DOES SOLVE THE WHOLE PROBLEM (See answer of Pete Becker)

Related

How Gcd works in this code? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I tried solving a question on hackerearth and i was not able to solve it so i saw editorial.They gave only code without explanation.Can u expain logic behind why gcd used here?
Question:
Scooby and all of his friends have gathered for a party. There are N friends present. Scooby is really happy to see all of his friends in one place and is excited to greet them.
All N friends are seated in a circle, and are numbered from 0 to N-1. Scooby is initially sitting beside the Ath friend. After greeting one friend, he goes clockwise to the Bth next friend, sits next to him and greets him. He repeats this till he returns to the Ath friend.
In his excitement, it is possible that Scooby misses out on greeting some friends. Your job is to find the number of friends (including A) that Scooby will have greeted before reaching back to A.
Solution given:
int main()
{
int T;
cin>>T;
while(T--)
{
long long N,A,B;
cin>>A>>B>>N;
long long g=gcd(B,N);
cout<<N/g<<endl;
}
return 0;
}
To explain the solution of the above problem I will first show that the answer is - LCM(B,N)/B and then show you how this is equal to N/GCD(B,N).
First Part-
Now assume that when it again reaches A after following the above mentioned steps he would have greeted f friends.(Note no two friends greeted through the above mentioned procedure can be same). Moreover, assume that when he reached A he would have made r rounds of the circle.
Now we can say that -
f * B = r * N = C.
Let this be equal to some constant C. Clearly C is some multiple of B and N moreover, it is the Lowest Common Multiple(LCM) of B and N(as we want to give answer as soon as it reaches for the first time).
So f = LCM(B,N)/B. Note f is the number of friends he greeted so it is the required answer.
Second Part-
For two positive integers a and b with their GCD and LCM g and l respectively, we have the following relation - a*b = g*l.
From the above relation we can say that -
LCM(B,N)*GCD(B,N) = B*N
=> LCM(B,N)/B = N/GCD(B,N)
So finally we have our answer = LCM(B,N)/B = N/GCD(B,N).

C++ User defined sequence integers without using arrays [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to figure this one out on my own and I can't.
The professor is asking for this.
User will define the length of the sequence.
User will then enter numbers from any range being both neg and pos.
The program:
Find the two largest numbers and display in descending order.
Find the two smallest numbers and display in ascending order.
Can't use sort or arrays.
I have an outline but, my head just wants to use arrays..... I don't see this simple without an array. Confused. I'm a beginner. I just want help. Advice? Tutor?
Start with a solution to an easier problem, and grow it into a solution to the actual problem that you are solving:
Write a program that finds and prints the largest number entered by the user. This is easy to do with a single variable keeping track of "high watermark"
Modify your program to keep track of the smallest number as well. You can do it by adding another variable, and keeping track of the "low watermark".
The challenge in both tasks above is the initial value of the high/low watermark. This is a common source of errors; there are multiple Q&As on SO explaining the fix.
Now for the fun part:
Modify your program to keep track of the second-largest number by "demoting" the number that was previously considered largest to second-largest each time that you find a number that is larger than the largest one, and by replacing the second-largest when you find a value above it that does not exceed the largest value.
This would require you to write a couple of if statements.
Finally, modify your program to keep track of the second-smallest number by applying the "mirror image" of the algorithm above.
Algorithm ("Find the two largest numbers in a sequence without storing the sequence")
(I decided to undelete this answer. It might be helpful to OP to get away from the array frame of mind)
Input: A sequence of values S.
Output: Values Max and SecondMax.
The consumed, current value of S is E
1 : Set Max to E
2 : Set SecondMax to E (Second value in S)
3 : If Max < SecondMax -> Swap Max and SecondMax.
4 : while ( e:= E exists)
4.1 : If ( e > Max ) SecondMax := Max, Max := e
4.1.1 : Else If ( e > SecondMax ) SecondMax := e
This is trivially extended to the minimums.

C++ : How to arrange 4 values in an ascending order? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hello I know it may be a beginners question but I need help.
I need to compare between 4 values added by the user and arrange them in am ascending order by using a function that takes 2 inputs and return the smaller one. I know it can be done by arrays but I must not do it. I already have the function but I don't know how to use to do the trick without having a very long code. Thanks
This seems to me to be an obvious "homework question," so let me answer it cryptically in order to maybe push you in the right direction.
First, the hint: divide and conquer.
Second hint: the "Towers of Hanoi" problem.
You have a function that can compare two values. Okay, then: "four elements" can be viewed as "two groups of two values each." Given that either of the two input to your comparison-function can be the result obtained by a nested call to the same function . . . you can, indeed, solve this problem, in one line of code, without using arrays.
I'm trying here to "teach you to fish," so I'm not handing you the fish on a platter.
If you know c++ then you can use sort function. But for this you have to include algorithm as:
#include <algorithm>
and sort function will be used as:
sort(array, array+N);
where array is the array name and N is the size of array.After this operation you will get a sorted array in ascending order and return first element.Now the function will look like as:
int smallest(int *array) {
int size = sizeof(array) / sizeof(array[0]);
sort(array, array+size);
return (array[0]);
}
And now call this function from main()

How to apply mask to string in C/C++? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've been asigned with a homework, but I don't know what to do exactly.
Input file is randomly generated from letter from 'a' to 'z'. User will type a mask only with 0/1, for example 011011, where 1 means vowel and 0 means consonant.
Output will be all matches found in input that match the user-given mask (for example for 011011 output will be abbezz).
Any idea how to make this? I don't ask for code, but only for easiest way how to make this possible in c/c++.
Thanks
My understanding is that the requirements are to find all sequences of letters that match the mask.
Given the mask: 010 (consonant, vowel, consonant)
Here are the matches for a couple of words:
"are" - fail, first character is a vowel.
"mat" - pass, 'm' is a consonant, 'a' is a vowel, 't' is a consonant.
"mate" - fail, too many letters.
You will need to have some functions that test a letter for vowel or consonant.
Also consider using a state machine. If a test fails, you want to go back to the starting state.
Write down your algorithm first, step by step. Come up with a few test cases to verify your algorithm. After algorithm works, code it up. Use your same test cases for verifying the program.
Map the string to 0/1 according to the rules you have and search for substrings in the new string that match the mask.
I still do not know exactly what you are trying to accomplish, but maybe it helps to know that once you have your input in a std::string, you can iterate over the characters using iterators and any algorithm. Here is an example with std::for_each:
#include <algorithm>
#include <iostream>
#include <string>
void applyMask(std::string::reference aCharacter)
{
// apply your mask here, character by character
if ('a' == aCharacter) {
aCharacter = 'A';
}
}
int main()
{
std::string s("stackoverflow");
std::for_each(s.begin(), s.end(), &applyMask);
std::cout << s << std::endl;
}
You might want to have a look at std::transform, e.g. http://www.cplusplus.com/reference/algorithm/transform/

what's number anagram which are palindromes in string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is the number of anagrams which are palindromes in a string?
Example : string = "aaabbbb";
Possible anagram's which are palindromes "abbabba" , "bbaaabb" and "bababab".
The problem here is the time, i have string of size 10^9.
here's my final code can anybody tell me what's the wrong with it ?
Every letter in your input string has to appear in an even amount, execpt one letter can appear in an odd amount. This letter has a fixed position in the palindron. It has to be exactly in the middle. Lets say the amounts of the letter a,b,c,... are #a, #b, #c, ...
You only care about half of those letters, because in an palindron, the second half depands of the first half. So we only use half of the letters:
I used the floor function, so I calculate the letter, which appears in an odd amount, correct.
So how many permutations are in the first half? This is a case of distinct permutation, so we get
possibilities.
For your example:
string = "aaabbbb";
We get: #a=3, #b=4. Therefore
We get 3 palindroms, these are "abbabba" , "bbaaabb" and "bababab", like you posted.
So, if you have a very large string:
Count the amounts of each letter
Check, if there is only 1 letter that appears in an odd amount. It there are more, you can't create palindroms.
Use the formular to calculate the number of different palindroms.
Since each side of the anagram must be a mirror image of the other, the number of anagrams we care about is basically just the number of anagrams we can form on one side, so:
group the characters in the string so identical characters are together (e.g., by sorting).
Check for an odd number of more than one character (of so, # anagrams = 0).
Take half the characters of each group of identical (truncating in the case of odd number).
Compute the number of unique permutations of those characters.