一开始大家的解法肯定是,遍历一遍数组,排序它,统计一下 ,因为排完序后 是最大的,所以只要 就
#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分
但这很显然是错的,因为它还可以中间便来算
#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