题解:P17110 「FAOI-R13」XOR and Less
「FAOI-R13」XOR and Less 题解
规定
为了方便描述,做出以下规定:
::::info[规定 1]{open} 我们把最大化不大于两个数的两个数的异或和的运算暂用合并这个词来表示。
有点绕,形式化就是
如何进行这个操作呢?显然,两个数合并最起码你需要先把两个数按位或在一起记作
接着我们倒序枚举每一个二进制位如果,当前这一位在
:::info[本操作的代码]
int Q(int p,int q) {
for(int h=30; h>=0; h--) {
if(q>=(1<<h)&&((p>>h)&1)==0) {
p|=(1<<h);
q-=(1<<h);
}
}
return p;
}
::: :::info[闲话] 我是怎样想到这个操作的呢,请见这篇未通过的题解。
| 几乎一样的操作…… |
|---|
::::info[规定 2]{open}
我们用
思路
首先,看到题目非常容易写出
思路不需要说了吧。
::::info[30 分]{open}
枚举
然后每次从
:::info[code]
#include<bits/stdc++.h>
#define int long long
using namespace std;
int T=1;
const int N=500005;
const int mod=998244353;
class qst {
private:
int n;
int a[N];
public:
void solve() {
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
// a[i]^=a[i-1];
}
int ans=0;
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++){
int res=0,x=0;
for(int k=i;k<=j;k++){
int tmp=res&a[k];
res|=a[k];
for(int h=30;h>=0;h--){
if(tmp>=(1<<h)&&((res>>h)&1)==0){
res|=(1<<h);
}
}
}
ans+=res;
ans%=mod;
}
}
cout<<ans;
}
};
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);//cout.tie(0);
while(T--) {
qst a;
a.solve();
}
}
| ::: |
|---|
写完你发现
::::info[45 分]
#include<bits/stdc++.h>
#define int long long
using namespace std;
int T=1;
const int N=500005;
const int mod=998244353;
class qst {
private:
int n;
int a[N];
public:
void solve() {
cin>>n;
for(int i=1; i<=n; i++) {
cin>>a[i];
}
int ans=0;
for(int i=1; i<=n; i++) {
int res=0;
for(int j=i; j<=n; j++) {
int tmp=res&a[j];
res|=a[j];
for(int h=30; h>=0; h--) {
if(tmp>=(1<<h)&&((res>>h)&1)==0) {
res|=(1<<h);
tmp-=(1<<h);
}
}
ans+=res;
ans%=mod;
}
}
cout<<ans;
}
};
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);//cout.tie(0);
while(T--) {
qst a;
a.solve();
}
}
::::
接着怎么优化呢?
把每个
当我们计算完
但是上一层可是有
::::info[如何理解]
对于上一层
::::
知道了这一点,我们只需要开一个桶装每一个状态的数量,枚举之前的状态合并更新即可。
时间复杂度 也许是吧。
::::success[100 分]
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int mod=998244353;
class qst {
int n,a[500005];
int Q(int p,int q) {
for(int h=30; h>=0; h--) {
if(q>=(1<<h)&&((p>>h)&1)==0) {
p|=(1<<h);
q-=(1<<h);
}
}
return p;
}
public:
void solve() {
cin>>n;
for(int i=1; i<=n; i++)cin>>a[i];
int ans=0;
map<int,int> cur;
for(int i=1; i<=n; i++) {
map<int,int> t;
t[a[i]]++;
for(auto [val,cnt]:cur) {
int tmp=val&a[i];
int r=Q(val|a[i],tmp);
t[r]=(t[r]+cnt)%mod;
}
cur.swap(t);
for(auto [x,y]:cur) ans=(ans+x*y%mod)%mod;
}
cout<<ans%mod;
}
};
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
qst a;
a.solve();
}
::::