1. 程式人生 > >Codeforces Round #544 (Div. 3) C. Balanced Team [暴力剪枝]

Codeforces Round #544 (Div. 3) C. Balanced Team [暴力剪枝]

repo ted 都是 最大值 移動 namespace The input ogr

You are a coach at your local university. There are
n
n
students under your supervision, the programming skill of the
i
i
-th student is
a
i
ai
.
You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maximum number of students. But you also know that a team should be balanced. It means that the programming skill of each pair of students in a created team should differ by no more than

5
5
.
Your task is to report the maximum possible number of students in a balanced team.
Input
The first line of the input contains one integer
n
n
(
1≤n≤2?
10
5
1≤n≤2?105
) — the number of students.
The second line of the input contains
n
n
integers
a
1
,
a
2
,…,
a
n
a1,a2,…,an
(
1≤
a
i

10
9
1≤ai≤109
), where
a
i
ai
is a programming skill of the
i
i
-th student.
Output
Print one integer — the maximum possible number of students in a balanced team.
Examples
Input
Copy
6
1 10 17 12 15 2
Output
Copy
3
Input
Copy
10
1337 1337 1337 1337 1337 1337 1337 1337 1337 1337
Output
Copy
10
Input
Copy
6
1 1000 10000 10 100 1000000000
Output
Copy
1

題解:題意給n個數,求子集的最小值和最大值之差不超過5,求最大的子集的元素數.
我的思路:先對數組排序,這裏如果直接暴力的話,O(n^2)的復雜度,肯定會tle,
優化一下,因為是排過序的,所以子集的左端和右端都是極值,如果右值與左值之差大於5,左值的位置右移,

再次優化,如果前一值與後一值之差大於5,I 移動的後一值的位置.

#include <bits/stdc++.h>
const int N=2e5+5;
using namespace std;
int a[N],b[N];
int ans=0,cnt=0,flag=0,maxn=0;
void check(int m){
    if(m>maxn) maxn=m;
}
int cal(int i,int j){
    return a[j]-a[i];
}
int main(){
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    sort(a+1,a+1+n);
    int i=1,j=i+1;
    while(i<=n-1&&j<=n){
        if(cal(j-1,j)>5){
            check(j-1-i);
            i=j;
            j++;
        }
        else if(cal(i,j)>5){
            check(j-1-i);
            i++;
            if(i==j) j++;
            //cout<<"jjg"<<endl;
        }
        else{
            j++;
            //cout<<"jj"<<endl;
        }
        //if(!flag) break;
    }
    check(j-1-i);
    printf("%d\n",maxn+1);
    return 0;
}

Codeforces Round #544 (Div. 3) C. Balanced Team [暴力剪枝]