Halfway ( 二分 )

Halfway  ( 二分 )

A friend of yours has written a program that compares every pair of a list of items. Withnitems,it works as follows. First, it prints a 1, and it compares item 1 to items 2,3,4, . . . , n. It then printsa 2, and compares item 2 to items 3,4,5, . . . , n. It continues like that until every pair of items hasbeen compared exactly once. If it compares itemxto itemy, it will not later compare itemytoitemx. Also, it does not compare any item to itself.

Your friend wants to know when his program ishalfway done. For a program that makes an oddnumber of total comparisons, this is when it is doing the middle comparison. For a program thatmakes an even number of total comparisons, this is when it is doing the first of the two middlecomparisons.

What will the last number printed be when the program is halfway done?

Note that since the earlier items have more comparisons than the later items, the answer is notsimplyn/2.

Input

The input consists of a single line containing the integern(2≤n≤109).

Output

Print, on a single line, the last number your friend’s program prints when it is halfway done.

Sample Input

4

7

10

1919

290976843

Sample Output

1

2

3

562

85225144

 

题意:给一个数n, 现在有序列n-1个1 , n-2个2 , n-3个3 ....  1个n-1。( n=4, 111223 ), 求序列中间的数是什么。

思路:二分查找。当n=6时, 有 5 4 3 2 1, 即找中间的数在第几堆。

注: 奇数的中间值是 x/2+1  !!!!!

 

代码:

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

int main()
{
    ll n;
    cin >> n;
    ll sum = n*(n-1)/2;
    sum /= 2;  // 需要舍弃的值, 即后面的值
    ll left = 1, right = n-1;
    while ( left<=right ) {
        ll mid = (left+right)/2;
        if ( (n-mid)*(n-mid-1)/2>sum ) { // 中间及其后面的值的和
            left = mid+1;
        }
        else {
            right = mid-1;
        }
    }
    cout << left << endl;

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值