PROBLEM LINK:
Author:Shivam Rathore
Tester:Hanlin Ren
Editorialist:Hanlin Ren
DIFFICULTY:
CAKEWALK
PREREQUISITES:
None
PROBLEM:
Chef has a string consisting of only lowercase letters a-z
. He wants to pick $4$ consecutive letters from the string such that the $4$ letters can be arranged into the word chef
. Find the number of ways to do this.
EXPLANATION:
The solution is straightforward. Let the string be $s[0\dots(n-1)]$. Let's enumerate the start point of these letters, say $i$. Then $0\le i\le n-4$. The four letters are $s[i],s[i+1],s[i+2],s[i+3]$. To check if they can be arranged into chef
, we can sort these letters and check if they form cefh
in order. Let me explain in details.
Checking four letters
First, we need a subprocedure which given $4$ letters s1
, s2
, s3
, s4
, determine if they can be reordered into chef
. Let's call it check(s1, s2, s3, s4)
. A method to do this is to sort the letters, and the result of sorting should be cefh
. C++ code:
bool check(char s1, char s2, char s3, char s4) {
char s[5] = {s1, s2, s3, s4, 0};
sort(s, s + 4);
return strcmp(s, "cefh") == 0;//strcmp returns 0 if two strings are equal
}
The 0
at the end of array s
is necessary, since strcmp
recognizes it as the end of string. Or, if you don't like strcmp
, the last line can be written as
return s[0]=='c' && s[1]=='e' && s[2]=='f' && s[3]=='h';
The original problem
Given the subprocedure check
, the rest is easy:
- We enumerate the start $i$ of the four letters. Let $n$ be the length of string, we have $0\le i\le n-4$, and four letters are
s[i]
,s[i+1]
,s[i+2]
,s[i+3]
; - If
check(s[i],s[i+1],s[i+2],s[i+3])
, the answer is increased by $1$; - At last, if answer is $0$, output
normal
; otherwise outputlovely
and the answer.
Code:
n = strlen(s); //s[0..n-1]
answer = 0;
//check all possible i's
for (i = 0; i <= n - 4; i++)
if (check(s[i], s[i + 1], s[i + 2], s[i + 3]))
answer += 1;
//output answer
if (answer == 0) printf("normal\n");
else printf("lovely %d\n", answer);
AUTHOR'S AND TESTER'S SOLUTIONS:
Author's solution can be found here.
Tester's solution can be found here.