首先题意非常简单。其次暴力非常简单。但是过不了。
暴力代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <iomanip>
using namespace std;
typedef long long ll;
ll a[1000003];
int main(){
ll n, x;
cin >> n >> x;
for(ll i = 1; i <= n; ++i){
cin >> a[i];
}
ll ans = 0;
for(ll i = 1; i < n; ++i){
for(ll j = i + 1; j <= n; ++j){
if(a[i] + a[j] <= x){
ans++;
}
}
}
ll tot = 0;
for(ll i = 1; i < n; ++i){
tot += i;
}
cout << fixed << setprecision(2) << (ans * 1.0) / tot << endl;
return 0;
}
简单易懂,不说了。
现在咱们想一下正解,也就是保证时间复杂度在 内的。
首先,考虑到值域的特殊性,我们尝试拆数组,也就是把原数组拆成——
-
只有值 ->
srt[] -
出现次数(桶) ->
a[]
然后排序去重。暂不考虑时间复杂度,先保证正确性。
然后我们就有一个思路了:找到一个当前元素 可以匹配的最大值 这样 就都是可行的方案。然后就是统计贡献:
- 当 时,贡献就是两元素出现次数之积。
- 当 时,贡献其实利用排列组合就是这个东西 。
然后再处理一些细节,测试后发现正确性就有了,代码如下。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <iomanip>
using namespace std;
typedef long long ll;
ll a[1000003];
ll srt[1000003];
int main() {
ll n, x;
cin >> n >> x;
for(ll i = 1, tmp; i <= n; ++i) {
cin >> tmp;
if(tmp > x) {
continue;
}
srt[i] = tmp;
++a[tmp];
}
sort(srt + 1, srt + n + 1);
ll tot = unique(srt + 1, srt + n + 1) - srt - 1;
ll ans = 0;
for(ll i = 1; i <= tot; ++i) {
ll tgt = x - srt[i];
ll pos = lower_bound(srt + 1, srt + tot + 1, tgt) - srt;
if(srt[pos] != tgt){
pos--;
}
if(pos < i){
continue;
}
if(a[srt[i]] >= 2){
ans += (a[srt[i]] * (a[srt[i]] - 1)) / 2;
}
if(i + 1 > tot){
continue;
}
for(ll j = srt[i + 1]; j <= srt[pos]; ++j) {
ans += a[srt[i]] * a[j];
}
}
ll sum = 0;
for(ll i = 1; i < n; ++i) {
sum += i;
}
cout << fixed << setprecision(2) << (ans * 1.0) / sum << endl;
return 0;
}诶!你就会发现还是过不了,我们来计算一下时间复杂度。
排序去重 ,枚举元素+计算贡献 。那么这个代码的复杂度也是 并且带了一个大常数,还不如不优化。
我们定睛一看,复杂度这么高出现在这里!
for(ll j = srt[i + 1]; j <= srt[pos]; ++j) {
ans += a[srt[i]] * a[j];
}我们换一种表现形式:
你会发现 a[srt[i]] 是不受遍历影响的,所以把它提出去,变成:
而 是一个前缀和!所以我们可以用 的时间预处理出来。
最后就很容易AC了。
Code:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <iomanip>
using namespace std;
typedef long long ll;
ll a[1000003];
ll srt[1000003];
ll _sum[1000003];
int main() {
ll n, x;
cin >> n >> x;
for(ll i = 1, tmp; i <= n; ++i) {
cin >> tmp;
if(tmp > x) {
continue;
}
srt[i] = tmp;
++a[tmp];
}
sort(srt + 1, srt + n + 1);
ll tot = unique(srt + 1, srt + n + 1) - srt - 1;
ll ans = 0;
for(ll i = 1; i <= tot; ++i){
_sum[i] = _sum[i - 1] + a[srt[i]];
}
for(ll i = 1; i <= tot; ++i) {
ll tgt = x - srt[i];
ll pos = lower_bound(srt + 1, srt + tot + 1, tgt) - srt;
if(srt[pos] != tgt){
pos--;
}
if(pos < i){
continue;
}
if(a[srt[i]] >= 2){
ans += (a[srt[i]] * (a[srt[i]] - 1)) / 2;
}
if(i + 1 > tot){
continue;
}
ans += (a[srt[i]] * (_sum[pos] - _sum[i]));
/*for(ll j = srt[i + 1]; j <= srt[pos]; ++j) {
ans += a[srt[i]] * a[j];
}*/
}
ll sum = (n * (n - 1)) / 2;
cout << fixed << setprecision(2) << (ans * 1.0) / sum << endl;
return 0;
}难度:上位绿。
如果觉得写得好球球点个赞吧呜呜呜呜