1. 程式人生 > 其它 >998. 起床困難綜合症

998. 起床困難綜合症

題目連結

998. 起床困難綜合症

一個 boss 的防禦戰線由 \(n\) 扇防禦門組成, 其中第 \(i\) 扇防禦門的屬性包括一個運 算 \(o p_{i}\) 和一個引數 \(t_{i}\), 運算一定是 OR、XOR、AND 中的一種, 引數是非負整數。若 在末通過這扇防禦門時攻擊力為 \(x\), 則通過這扇防禦門後攻擊力將變為 \(x o p_{i} t_{i}\) 。最終 boss 受到的傷害為玩家的初始攻擊力 \(x_{0}\) 依次經過所有 \(n\) 扇防禦門後得到的攻擊力。 由於水平有限, 玩家的初始攻擊力只能為 \([0, m]\) 之間的一個整數。玩家希望通過選擇 合適的初始攻擊力, 使他的攻擊能造成最大的傷害, 求這個傷害值。
資料範圍: \(n \leq 10^{5}, m, t_{i} \leq 10^{9}\)

解題思路

貪心,位運算

可以發現,位運算每一位之間相互獨立,互不影響,因此,可以從高位開始考慮,有兩種選擇:1. 當前位為 \(0\),2. 當前位為 \(1\),分類討論其結果:如果當前位為 \(0\) 的結果為 \(1\),則肯定選上,因為此時不增加當前數反而還使傷害增大了,如果當前位為 \(0\) 的結果為 \(0\),且當前位為 \(1\) 的結果為 \(0\),則此時傷害不變,當前數不變,否則如果當前位為 \(1\) 的結果為 \(1\) 且當前數不超過 \(m\),則選上

  • 時間複雜度:\(O(30n)\)

程式碼

// Problem: 起床困難綜合症
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/1000/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=1e5;
pair<string,int> a[N];
int n,m;
int cal(int bit,int x)
{
	for(int i=1;i<=n;i++)
	{
		int y=(a[i].se>>bit&1);
		if(a[i].fi=="AND")x&=y;
		else if(a[i].fi=="OR")x|=y;
		else
			x^=y;
	}
	return x;
}
int main()
{
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	{
		string s;
		int x;
		cin>>s>>x;
		a[i]={s,x};
	}
	int res=0,ans=0; 
	for(int i=29;i>=0;i--)
	{
		int res1=cal(i,1),res0=cal(i,0);
		if(res0==1||res1==0)
		{
			if(res0==1)
			    ans+=1<<i;
		}
		else if(res1==1)
		{
			if(res+(1<<i)<=m)res+=1<<i,ans+=1<<i;
		}
	}
	cout<<ans<<'\n';
    return 0;
}