• 牛客练习赛16 F 选值【二分/计数】


    链接:https://www.nowcoder.com/acm/contest/84/F
    来源:牛客网
    
    题目描述 
    给定n个数,从中选出三个数,使得最大的那个减最小的那个的值小于等于d,问有多少种选法。
    输入描述:
    第一行两个整数n,d(1 <= n <= 100,000,1 <= d <= 1000,000,000);
    第二行n个整数满足abs(ai) <= 1,000,000,000。数据保证a单调递增。
    输出描述:
    输出一个整数表示满足条件的选法。
    示例1
    输入
    4 3
    1 2 3 4
    输出
    4
    示例2
    输入
    4 2
    -3 -2 -1 0
    输出
    2
    示例3
    输入
    5 19
    1 10 20 30 50
    输出
    1
    

    【分析】:

    对于a[i], a[i]必取,有多少种情况,令c = a[i] + d, 找到j,a[j] > c && a[j - 1] <= c, 这样(i, j)就为可选区间,注意是选取两个,记得用组合数的公式。

    【出处】:
    CodeForces 251A. Points on
    【类似】:HDU 5101 Select

    【代码】:

    #include<bits/stdc++.h>
    using namespace std;
    #define ll long long
    int a[100005];
    
    
    int main()
    {
        int n,d;scanf("%d%d",&n,&d);
        for(int i=0;i<n;i++)scanf("%d",&a[i]);
        a[n]=1e9+7;
        ll ans=0;
        for(int i=0;i<n;i++)
        {
            int x=upper_bound(a+i,a+n,a[i]+d)-(a+i+1); //这之间有多少个值
            ans+=1LL*x*(x-1)/2;  //C(x,2)
        }
        printf("%lld
    ",ans);
        return 0;
    }
    /*
    using namespace std;
    int n,d,a[100010];
    int main(){
    	scanf("%d%d",&n,&d);
    	for(int i=0; i<n; i++)
    		scanf("%d",&a[i]);
    	sort(a,a+n);
    	long long int ans=0;
    	for(int i=0; i<n; i++){
    		int x=upper_bound(a,a+n,a[i]+d)-(a+i+1);//比a[i]+d小的元素的个数,排除a[i]之前的那些元素,共有i+1
    		ans+=1LL*x*(x-1)/2;
    	}
    	printf("%lld
    ",ans);
    	return 0;
    }
    */
    
    
  • 相关阅读:
    变量与作用域
    安装node和grunt
    神奇的万维网
    大小写字母的转换
    跨域的方法
    选择器中含有空格的注意事项
    Tools
    jquery中innerWidth(),outerWidth(),outerWidth(true)和width()的区别
    网页中的foot底部定位问题
    CSS hack
  • 原文地址:https://www.cnblogs.com/Roni-i/p/8965897.html
Copyright © 2020-2023  润新知