- 对所有区间 [l_j,r_j],若 \text{get}(l_j,i)\le r_j,说明该区间能选出第 i 位为 1 的数;所有区间都满足则该位可保留,即 ans+=(1<<i),并将所有区间左边界更新为 \text{get}(l_j,i)(锁定该位为 1);否则跳过该位;最后输出 ans 即可
Code
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e7+10,inf=0x3f3f3f3f3f3f,mod=1e9+7;
int T,n,l[N],r[N];
int get(int x,int i)//将数的第i位强制置1,得到该位为1的最小数(若原数第i位已是1则不变)
{
if(((x>>i)&1)!=1)
{
x>>=i;
x|=1;
x<<=i;
}
return x;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>T;
while(T--)
{
int ans=0;
cin>>n;
for(int i=1;i<=n;i++) cin>>l[i]>>r[i];
for(int i=30;i>=0;i--)//优先保留高位为1
{
bool flag=false;
for(int j=1;j<=n;j++)
{
if(get(l[j],i)>r[j])
{
flag=true;
break;
}
}
if(!flag)
{
for(int j=1;j<=n;j++)
{
l[j]=get(l[j],i);
}
ans+=(1<<i);
}
}
cout<<ans<<"\n";
}
return 0;
}
-P9612 [CERC2019] Light Emitting Hindenburg-
思路
- 统计当前未被排除的音乐家中,第 i 位为 1 的数量,若 \ge k,说明能选出 k 个该位为 1 的音乐家;若该位可保留,即 ans+=(1<<i),排除所有该位为 0 的音乐家(后续仅在该位为 1 的音乐家中筛选);
最终 ans 即为选 k 个音乐家的最大空闲编码总和
Code
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e7+10,inf=0x3f3f3f3f3f3f,mod=1e9+7;
int n,k,a[N],ans=0;
bool vis[N];
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
memset(vis,true,sizeof(vis));
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=29;i>=0;i--)//优先保留高位为1
{
int cnt=0;
for(int j=1;j<=n;j++)
{
if(((a[j]>>i)&1) && vis[j]) cnt++;
}
if(cnt>=k)
{
ans+=(1<<i);
for(int j=1;j<=n;j++)
{
if(((a[j]>>i)&1)==0 && vis[j]) vis[j]=false;
}
}
}
cout<<ans;
return 0;
}
-P10114 [LMXOI Round 1] Size-
思路
- 对每对去重后的数 (num_i,num_j),计算两数和的二进制 1 的个数(\text{\_\_builtin\_popcount}(tmp1+tmp2))+ 两数差的二进制 1 的个数(\text{\_\_builtin\_popcount}(tmp1-tmp2)),即可得到单次数对的贡献;
- 该数对总贡献 = 单次贡献 \times t_{num_i}\times t_{num_j}(覆盖原数组中所有该数对的组合);所有数对的贡献累加即为最终答案
Code
#include<bits/stdc++.h>
#define int long long
#define pop __builtin_popcountll
using namespace std;
const int N=5e7+10,inf=0x3f3f3f3f3f3f,mod=1e9+7;
int n,a[N],t[N],num[N],cnt=0,ans=0;
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>n;
for(int i=1,x;i<=n;i++)
{
cin>>x;
if(t[x]==0) num[++cnt]=x;
t[x]++;
}
for(int i=1;i<=cnt;i++)
{
for(int j=1;j<=cnt;j++)
{
int tmp1=max(num[i],num[j]);
int tmp2=min(num[i],num[j]);
int cal=pop(tmp1+tmp2)+pop(tmp1-tmp2);
ans+=cal*t[tmp1]*t[tmp2];
}
}
cout<<ans;
return 0;
}