k-Multiple Free Set - CodeForces 274A - Virtual Judge (csgrandeur.cn)
题意:给你一个数组和一个值k,定义一个集合表示的是一组整数,其中没有一个整数等于另一个整数乘以k,求这个整数的最大数量。
思路:集合里如果有x,一定不能有k倍的x。
解法1:set
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+10;
set<int> st;
int a[N],n,k;
signed main()
{
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i];
sort(a+1,a+n+1);
int res=0;
for(int i=1;i<=n;i++)
{
int x=a[i];
if(st.count(x)==0)
{
res++;
st.insert(x*k);
}
}
cout<<res<<endl;
return 0;
}
解法2:二分找a[i]的k倍,找到到了res--
#include<bits/stdc++.h>
#define int long long
#define x first
#define y second
#define mak make_pair
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define debug(a) cout<<a<<'\n'
#define endl '\n'
#define umap unordered_map
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int N=1e5+10,M=1,inf=0x3f3f3f3f,mod=1e9+7;
int a[N],n,k;
bool st[N];//某个数的k倍有没有被找到
signed main()
{
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i];
sort(a+1,a+n+1);
int res=n;
for(int i=1;i<=n;i++)
{
if(st[i]) continue;
int l=i,r=n;
while(l<r)
{
int mid=l+r+1>>1;
if(a[mid]==a[i]*k)
{
res--;
st[mid]=true;
break;
}
if(a[mid]<a[i]*k) l=mid;
else r=mid-1;
}
}
cout<<res<<endl;
return 0;
}