Even Odds代码与分析,有注释

 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

七刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值