CodeForces 1095A - Solution and Explanation

You can find problem statement here : CodeForces 1095A

Problem statement explanation :

You will be given a encrypted string 's' , you have to decrypt it.

To encrypt the string Polycarp uses the following algorithm :

1. He writes first letter once , second letter twice , third letter three times , fourth letter four times ...and continues the process to the last letter. For example to encrypt "abc" , he first writes 'a' once then 'b' twice and 'c' three times. So the encrypted ="abc" is "abbccc".

Solution :

From the problem statement we know how to encrypt the string , Now we need to figure out how we can decrypt the string. To decrypt the the string S = "abbcccddddeeeee" at first we take the first letter 'a' then take the second letter 'b' then take the fourth letter 'c' then take the seventh letter 'd' and then take the eleventh letter 'e' . So the decrypted string is "abcde".

from above example we can see , after taking first letter 'a' we didn't skip any number of index to take 'b', then we skipped 1 index to take 'c' , 2 index to take 'd' and 3 index to take 'e'. we can see a pattern here.
 
let's see the code :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
int main(){

  int n;
  cin >> n;
  string s = "";
  int k = 0;
  string s1 ;
  cin >> s1;
  for(int i = 0; i<s1.size(); i++) {

    char c = s1[i];
    s+=c;
    i+=k;
    k++;

  }

  cout << s <<endl;

  return 0;
}

Here variable k keeps track of the number of index we have to skip. s is the decrypted string.
We loop through the string and concatenate s with the character we want to take. and add i with k to skip indexes of those character we don't want to add to s. we also increment k so at first we skip '0' number of index then '1' index then '2' index and so on.

Comments

Popular Posts