Jack and Daniel are friends.
They want to encrypt their conversation so that they can save themselves from interception by a detective agency. So they invent a new cipher.
Every message is encoded to its binary representation of length .
Then it is written down times, shifted by bits.
If and it looks so:
1001010
1001010
1001010
1001010
Then calculate XOR in every column and write it down. This number is called .
For example, XOR-ing the numbers in the above example results in1110100110
Then the encoded message and are sent to Daniel. Jack is using this encoding algorithm and asks Daniel to implement a decoding algorithm.
Can you help Daniel implement this?
Input Format
The first line contains two integers and .
The second line contains string of length consisting of ones and zeros.
Output Format
Decoded message of length , consisting of ones and zeros.
Constraints
It is guaranteed that is correct.
Sample Input#00
7 4
1110100110
Sample Output#001001010
Sample Input#016 2
1110001
Sample Output#01101111
ExplanationInput#00
1001010
1001010
1001010
1001010
----------
1110100110
Input#01 101111
101111
-------
1110001
this is O(n²) approach
)
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n , k ;
scanf("%d %d",&n,&k);
char a[n+k];
scanf("%s",a);
a[n]='\0';
char final[n+1];
final[0]= a[0];
final[n]= a[n];
printf("%c",final[0]);
for (int i = 1;i<n;i++)
{
final[i]='0';
int answer = 0;
for (int m = i-1;((m>=0)&&(m>=(i-k+1)));m--)
{answer = (final[m]-'0') ^ answer ;
}
final[i] = ( (a[i]-'0') ^ answer ) +'0';
final[i]
printf("%c",final[i]);
}
return 0;
}
approach (2) this is O(N)
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n , k ;
scanf("%d %d",&n,&k);
char a[n+k];
scanf("%s",a);
a[n]='\0';
char final[n+1];
final[0]= a[0];
final[n]= a[n];
printf("%c",final[0]);
int answer = 0;
for (int i = 1;i<n;i++)
{
final[i]='0';
answer = (final[i-1]-'0') ^ answer ;
if (i>=k)
{
answer = answer ^(final[i-k]-'0');
}
final[i] = ( (a[i]-'0') ^ answer ) +'0';
printf("%c",final[i]);
}
return 0;
}
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n , k ;
scanf("%d %d",&n,&k);
char a[n+k];
scanf("%s",a);
a[n]='\0';
char final[n+1];
final[0]= a[0];
final[n]= a[n];
printf("%c",final[0]);
int answer = 0;
for (int i = 1;i<n;i++)
{
final[i]='0';
answer = (final[i-1]-'0') ^ answer ;
if (i>=k)
{
answer = answer ^(final[i-k]-'0');
}
final[i] = ( (a[i]-'0') ^ answer ) +'0';
printf("%c",final[i]);
}
return 0;
}
No comments:
Post a Comment