Even Odds
Being a nonconformist, Volodya is displeasedwith the current state of things, particularly with the order of naturalnumbers (natural number is positive integer number). He is determined torearrange them. But there are too many natural numbers, so Volodya decided tostart with the first n. He writes down the following sequence of numbers:firstly all odd integers from 1 to n (in ascending order), then all evenintegers from 1 to n (also in ascending order). Help our hero to find out whichnumber will stand at the position number k.
Input
The only line of input contains integers nand k (1≤k≤n≤1e14).
Output
Print the number that will stand at the position number kafter Volodya's manipulations.
Sample test(s)
input
10 3
7 7
output
5
6
Note
In the first sample Volodya's sequence willlook like this: {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}. The third place in thesequence is therefore occupied by the number 5.
Hint
注意数据的类型
use __int64 to read data and use %I64d tooutput data
分析:题意就是一组从1到n的连续自然数,从新排列后奇数从小到大排,排完后是偶数从小到大排,输出排列后的第K个数。当然首先想到的就是用数组,奇数偶数在数组中按要求排列后,输出第k-1个就行了,但是!!!是10^14,显然用for循环对数组赋值时会严重超时!不得不找其他方法了。
代码如下:
#include <iostream>using namespace std;
int main()
{
long long n,k;//long long在vc上编译会有错误。
while(cin>>n>>k)
{
if(n%2==0)//如果是偶数,则奇数偶数个数相等,输出分为两部分。
{
if(k<=n/2)//当k是在奇数部分时,就是2*k-1;
cout<<2*k-1<<endl;
else cout<<2*k-n<<endl;//当k在偶数部分时,是(k-n/2)*2=2*k-n;
}
else//如果是奇数,奇数个数比偶数多一个;
{
if( k<=(n/2+1) )//当k在奇数部分时,是n/2+1
cout<<2*k-1<<endl;
else
cout<<2*k-n-1<<endl;//当k在偶数部分时,为2*k-n-1
}
}
return 0;
}