与或
2024年12月25日大约 1 分钟
60 分
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN = 200000;
int n, k;
int a[MAXN + 5];
// 初始是 now,从 pos 开始,x 个 &,y 个 |,
int cal(int now, int pos, int x, int y)
{
for(int i=0;i<x;i++)
now = now & a[pos+i];
for(int i=0;i<y;i++)
now = now | a[pos+x+i];
return now;
}
signed main()
{
cin >> n >> k;
for(int i = 1; i <= n; i++)
cin >> a[i];
int xx = n - k - 1, yy = k;
int ans = cal(a[1], 2, xx, yy);
cout << ans << "\n";
int now = a[1];
for(int i = 2; i <= n; i++)
{
if (yy > 0 && cal(now|a[i], i+1, xx, yy - 1) == ans)
{
// a[i] 使用 |
yy --;
now |= a[i];
cout << "|";
}
else
{
now &= a[i];
xx --;
cout << "&";
}
}
return 0;
}
100 分
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN = 200000;
int n, k;
int a[MAXN + 5];
// a[1]~a[i] 在 2^j 有几个 1
int cnt1[MAXN+5][65];
// 初始是 now,从 pos 开始,x 个 &,y 个 |,
int cal(int now, int pos, int x, int y)
{
int tempX = 0;
int tempY = 0;
for(int i=0;i<60;i++){
int nowX = cnt1[pos+x-1][i]-cnt1[pos-1][i];
if(nowX == x)
tempX |= 1LL<<i;
int nowY = cnt1[pos+x+y-1][i]-cnt1[pos+x-1][i];
if(nowY > 0)
tempY |= 1LL<<i;
}
now &= tempX;
now |= tempY;
return now;
}
signed main()
{
cin >> n >> k;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
for(int j=0;j<60;j++)
if(a[i]&(1LL<<j))
cnt1[i][j] = cnt1[i-1][j] + 1;
else
cnt1[i][j] = cnt1[i-1][j];
}
int xx = n - k - 1, yy = k;
int ans = cal(a[1], 2, xx, yy);
cout << ans << "\n";
int now = a[1];
for(int i = 2; i <= n; i++)
{
if (yy > 0 && cal(now|a[i], i+1, xx, yy - 1) == ans)
{
// a[i] 使用 |
yy --;
now |= a[i];
cout << "|";
}
else
{
now &= a[i];
xx --;
cout << "&";
}
}
return 0;
}