跳到正文

题解

题解:P11951 [科大国创杯初中组 2023] 数数

NoctMote约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 1 分钟
题目
P11951

版本

  1. v1当前

这题也是非常的水,看的第一眼,暴力呀, O(n3)O(n^3) ,但是再看一眼, n≤8×103n\le 8\times 10^3 ,超时了呀!

所以我开始想起了优化,发现只需要枚举两根短的,只需要第三根的长度小于这两根的和就行了(三角形的性质),那二分不就行了。

Code

C++
#include<bits/stdc++.h>
using namespace std;
int a[8005];
long long sum;
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	int n;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	sort(a+1,a+n+1);
	for(int i=1;i<=n;i++){
		for(int j=i+1;j<=n;j++){
			int pos=lower_bound(a+j+1,a+n+1,a[i]+a[j])-a-1;//系统自带的二分函数
			sum+=pos-j;
		}
	}
	cout<<sum;
	return 0;
}
原文