1. 程式人生 > >Cutting Out(二分)

Cutting Out(二分)

輸入

7 3
1 2 3 2 4 3 1

輸出

1 2 3

輸入

10 4
1 3 1 3 10 3 7 7 12 3

輸出

7 3 1 3

輸入

15 2
1 2 1 1 1 2 1 1 2 1 2 1 1 1 1
1 1

題意: 給定一個 n 和 n個數 問是否能夠儘可能多在原序列刪除的找出長度為k的序列 輸出序列

題解 二分 最多可以刪除的次數 最後 要更新一下結果 check(l-1) 因為二分的最後結果是 l-1次

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5+5;
int cnt[maxn];
int a[maxn], tot = 0;
int n, k;

int check(int x)//可以刪除的次數
{
    tot = 0;
    int sum = 0;
    for(int i=1; i<maxn; i++)//列舉 輸入的數值
    {
        for(int j=x; j<=cnt[i]; j+=x)// 列舉對於當前數值刪除的次數
        {
            sum++;
            a[++tot]=i;
        }
    }
    return sum;
}

int main()
{
    scanf("%d%d", &n, &k);
    for(int i=1; i<=n; i++)
    {
        int x;
        scanf("%d", &x);
        cnt[x]++;
    }
    int l = 1, r = 1e9;
    while(l <= r)
    {
        int mid = (l + r)/2;//二分可以刪除的次數
        if(check(mid) >= k) l = mid + 1;
        else r = mid - 1;
    }
    check(l-1);

    for(int i=1; i<=k; i++)
        printf("%d ", a[i]);
    return 0;
}