【Codeforces】[274A]k-Multiple Free Set

Problem Description

Loading...

Problem Analysis

We need the maximum number of set elements such that y=x*k is not in the same set as x
So we can consider removing one of each pair with a k-multiple relationship
Since a larger number may also be a k-multiple of another smaller number
We prioritize removing the larger number

Binary Search can be used here to check whether a k-multiple of x exists
Thus reducing the lookup time complexity to O(logn)

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[100200],flag[100200];
int main() {
    int n,k;
    while(scanf("%d %d",&n,&k)!=EOF) {
        for(int i=0; i<n; i++)
            scanf("%d",&a[i]);
        sort(a,a+n);
        memset(flag,0,sizeof(flag));
        int res=n;
        for(int i=0; i<n; i++) {
            if(!flag[i]) {
                __int64 t=(__int64)a[i]*k;
                if(a[n-1]<t)
                    continue;
                int l=i+1,r=n-1;
                while(l<=r) {
                    int mid=(l+r)/2;
                    if(a[mid]>t)
                        r=mid-1;
                    else if(a[mid]<t)
                        l=mid+1;
                    else {
                        flag[mid]=1;
                        res--;
                        break;
                    }
                }
            }
        }
        printf("%d\n",res);
    }
    return 0;
}

Loading...