题目:小Z组织训练营同学进行一次拔河比赛,要从n(2≤n≤60,000)个同学中选出两组同学参加(两组人数可能不同)。对每组同学而言,如果人数超过1人,那么要求该组内的任意两个同学的体重之差的绝对值不超过k(包含k)。问最多有几个同学能参加比赛?
我的超时了
#include <bits/stdc++.h>
using namespace std;
const int maxn = 60010;
int data[maxn] = {0};
int main()
{
int n, k;
scanf("%d %d", &n, &k);
for(int i = 0; i < n; i++)
{
scanf("%d", &data[i]);
}
sort(data, data + n);
int flag = 0;
// 0~flag-1 flag~n-1
int maxxxx = 0;
for (int flag = 1; flag <= n - 1; flag++)
{
int i = 0; int j = 0;
int res1 = 0; int maxn1 = 1;
for (i = 0; i < flag; i++)
{
for (j = i; j < flag; j++)
{
if ( data[j] - data[i] <= k )
{
res1 = j - i + 1;
maxn1 = max(maxn1, res1);
}
if ( data[j] - data[i] > k)
{
break;
}
}
}
int res2 = 0; int maxn2 = 1;
for (i = flag; i <= n - 1; i++)
{
for (j = i; j <= n - 1; j++)
{
if ( data[j] - data[i] <= k )
{
res2 = j - i + 1;
maxn2 = max(maxn2, res2);
}
if ( data[j] - data[i] > k)
{
break;
}
}
}
// cout << maxn1 << " " << maxn2 << endl;
maxxxx = max(maxxxx, (maxn1 + maxn2));
}
cout << maxxxx << endl;
system("pause");
}
看通过了的大佬是这样写的
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
const int maxn = 1e5+10;
const ll mod = 100000007;
int n;
ll a[maxn];
ll k;
ll Max[maxn];
ll ans;
ll mMax[maxn];
void wk(int x)
{
int mid,bns=x,lb=x,ub=n;
while(ub>=lb)
{
mid=(lb+ub)/2;
if(a[mid]-a[x]<=k)
{
bns=mid; lb=mid+1;
}
else ub=mid-1;
}
Max[x]=bns;
}
int main()
{
scanf("%d%lld",&n,&k);
for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
sort(a+1,a+1+n);
for(int i=1;i<=n;i++) wk(i);
for(int i=n;i;i--) mMax[i]=max(mMax[i+1],Max[i]-i+1);
for(int i=1;i<=n;i++)
{
ans=max(ans,(Max[i]-i+1) + mMax[(int)Max[i]+1]);
}
printf("%lld",ans);
return 0;
}