D - Halfway Gym - 101652Q

A friend of yours has written a program that compares every pair of a list of items. With n items,
it works as follows. First, it prints a 1, and it compares item 1 to items 2, 3, 4, . . . , n. It then prints
a 2, and compares item 2 to items 3, 4, 5, . . . , n. It continues like that until every pair of items has
been compared exactly once. If it compares item x to item y, it will not later compare item y to
item x. Also, it does not compare any item to itself.
Your friend wants to know when his program is halfway done. For a program that makes an odd
number of total comparisons, this is when it is doing the middle comparison. For a program that
makes an even number of total comparisons, this is when it is doing the first of the two middle
comparisons.
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 not
simply n/2.
Input
The input consists of a single line containing the integer n (2 ≤ n ≤ 109
).
Output
Print, on a single line, the last number your friend’s program prints when it is halfway done.
Sample Input and Output
4 1
2017 Pacific Northwest Region Programming Contest 11
7 2
10 3
1919 562
290976843 85225144
本来这个题我用的暴力,本以为会超时,但是没有,却在第45个样例wa了。
下面是WA的暴力代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
int main()
{
    ll i,n,ans=0,flag;
    cin>>n;
    ll sum=n*(n-1)/2;
    if(sum%2==0) flag=1;
    if(sum%2!=0) flag=0;
    for(i=1;i<=n;i++)
    {
        ans+=(n-i+1);
        if(flag==1&&ans>=sum/2) break;
        if(flag==0&&ans>=sum/2+1) break;
    }
    printf("%lld\n",i);
    return 0;
}

下面是AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define ull unsigned long long
#define ll long long
int main()
{
    ll n,ans=0,flag=0;
    ll i,x;
    cin>>n;
    ll sum=n*(n-1)/2;
    if(sum%2==0) x=sum/2;
    if(sum%2!=0) x=sum/2+1;//x求的是正确的。
    ll l=1,r=n,mid=0,kk;//外面这定义了里面就不要定义了
    while(l<r)
    {
       mid=(l+r)/2;
       kk=sum-(n-mid)*(n-mid-1)/2;
       if(kk==x) break;
       else if(kk>x) r=mid;
       else l=mid+1;
    }
    if(kk>=x) printf("%lld\n",mid);
    else printf("%lld\n",mid+1);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值