175. Encoding
time limit per test: 0.25 sec.
memory limit per test: 4096 KB
memory limit per test: 4096 KB
input: standard
output: standard
output: standard
Let phi(W) is the result of encoding for algorithm:
1. If the length of W is 1 then phi(W) is W;
2. Let coded word is W = w 1w 2...w N and K = N / 2 (rounded down);
3. phi(W) = phi(w Nw N-1...w K+1) + phi(w Kw K-1...w 1).
For example, phi('Ok') = 'kO', phi('abcd') = 'cdab'.
Your task is to find position of letter w q in encoded word phi(W).
1. If the length of W is 1 then phi(W) is W;
2. Let coded word is W = w 1w 2...w N and K = N / 2 (rounded down);
3. phi(W) = phi(w Nw N-1...w K+1) + phi(w Kw K-1...w 1).
For example, phi('Ok') = 'kO', phi('abcd') = 'cdab'.
Your task is to find position of letter w q in encoded word phi(W).
Input
Given integers N, q (1 <= N <= 10^9; 1<= q <= N), where N is the length of word W.
Output
Write position of letter w
q in encoded word phi(W).
Sample test(s)
Input
9 4
Output
8
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
int n,q;
scanf("%d%d",&n,&q);
int a=n,b=1;
int l=1,r=n;
while(l<r){
// cout<<l<<" "<<r<<endl;
// cout<<a<<" "<<b<<endl;
int c=(l+r)/2;
int w=(r-l+2)/2;
if(a<b){
if(q<=a+w-1){
r=c;
b=a+w-1;
swap(a,b);
}
else{
l=c+1;
a=a+w;
swap(a,b);
}
}
else{
if(q>=a-w+1){
r=c;
b=a-w+1;
swap(a,b);
}
else{
l=c+1;
a=a-w;
swap(a,b);
}
}
}
printf("%d",l);
return 0;
}