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;
}