You are given two strings S and T. An infinitely long string is formed in the following manner:
You will also be given an integer K, you need to tell the Kth Character of this infinitely long string.
b
The string formed will be "abcbcaaabcbcbcbcaaaaa...". So the 4th character is "b".
S, T N, MSo, the string in terms of length parameters looks like this (Blocks of N and M).
NMMNNNMMMMNNNNNMMMMMMNNN......Which can be split into this
NM MN NNMM MMNN NNNMMM MMMNNN..........Which implies, the composite block lengths are,
N+M N+M 2(N+M) 2(N+M) 3(N+M) 3(N+M).......
2(N+M) 4(N+M) 6(N+M)........From here follows a pretty standard binary search solution. I guess there's some issue with the markdown.. @Admin User-1
Neat observation @vaibhavr . I think this is an alternative solution?
Posted solution doesn't require any creativity like you employeed.
In posted solution after getting F(x) = ceil(x/2) * |S| + floor(x/2) * |T|, which is clearly an increasing function we can directly bseasrch on F(x) w/o making any further observation.
Yes, we have disabled markdown temporarily to support html..
so you can use usual html tags like <\blockquote> <\b>, <\i>, <\p> etc.
#include<bits/stdc++.h>
using namespace std;
long long int f(long long int x, int m, int n)
{
long long int length=(((x+1)/2)*((x+1)/2))*m+((x/2)*(x/2+1))*n;
return length;
}
bool isGood(long long int x, long long int k, int m, int n)
{
long long int length=f(x, m, n);
if(length>=k)
return true;
return false;
}
int main()
{
string s,t;
cin>>s>>t;
int m=s.length();
int n=t.length();
long long int k;
cin>>k;
int lo=1, hi=1e8;
while(lo<hi)
{
int mid=lo+(hi-lo)/2;
if(isGood(mid, k, m, n))
{
hi=mid;
}
else
lo=mid+1;
//lo tells on which string i need to do work
}
int length2=k-f(lo-1, m, n);
length2--;
char ans;
if(lo%2)
{
ans=s[(length2)%m];
}
else
{
ans=t[(length2)%n];
}
cout<<ans;
}