跳到正文

个人记录

小信分糖果

_olisht_Wxw约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年8月4日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

传送门

一开始大家的解法肯定是,遍历一遍数组,排序它,统计一下 a[i]+a[i+1]<=a[n]a[i] + a[i + 1] <= a[n] ,因为排完序后 a[n]a[n] 是最大的,所以只要 a[i]+a[i+1]<=a[n]a[i] + a[i + 1] <= a[n] 就 ans++ans++

C++
#include <bits/stdc++.h>
#define int long long
#define endl '\n'

using namespace std;

const int N = 1e5 + 5;
int T;
int n, a[N];

signed main () {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	
	cin >> T;
	
	while (T--) {
		memset(a, 0, sizeof a);
		cin >> n;
		
		for (int i = 1; i <= n; i++) {
			cin >> a[i];
		}
		
		sort(a + 1, a + n + 1); //排序
		
		int cnt = 0;
		for (int i = 1; i < n; i++) {
			if (a[i] + a[i + 1] <= a[n]) { //如果小于最大
				cnt++;
			}
		}
		
		cout << cnt << endl;
	}
	
	return 0;
}

只能WA10分

但这很显然是错的,因为它还可以中间便来算

C++
#include <bits/stdc++.h>
#define int long long
#define endl '\n'

using namespace std;

const int N = 1e5 + 5;
int T, n;

signed main () {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	
	cin >> T;
	
	while (T--) {
		cin >> n;
		
		vector<int> v(n);
		for (int i = 0; i < n; i++) {
			cin >> v[i];
		}
		
		sort(v.begin(), v.end());
		
		int ans = 1e18;
		for (int i = 0; i < n - 1; i++) {
			int x = v[i] + v[i + 1];
			int j = lower_bound(v.begin(), v.end(), x) - v.begin();
			ans = min(ans, i + n - j);
		}
		
		cout << ans << endl;
	}
	
	return 0;
}

用二分来做就可以解决了

虽然本人很懒,用的lower_bound

这样就能顺利AC100

原文