位运算 数学优化 1891 B. Deja Vu

cpp 复制代码
#include<bits/stdc++.h>

using namespace std;

void solve()
{
	int n;
	cin>>n;
	
	int q;
	cin>>q;
	
	vector<long long> a(n);
	vector<int> x(q);
	
	for(int i=0;i<n;i++)	cin>>a[i];
	for(int i=0;i<q;i++)	cin>>x[i];
	
	for(int i=0;i<q;i++)
		for(int j=0;j<n;j++)
			if(a[j]%(1<<x[i])==0)
				a[j]+=1<<(x[i]-1);
	
	for(int i=0;i<n;i++)	
		cout<<a[i]<<" ";
	cout<<endl;
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	int t;
	cin>>t;
	
	while(t--)
		solve();
	
	return 0;
}

本来以为秒了,结果在第三个测试点超时了。

cpp 复制代码
#include<bits/stdc++.h>

using namespace std;

void solve()
{
	int n,q;
	cin>>n>>q;
	
	vector<long long> a(n);
	for(int i=0;i<n;i++)	cin>>a[i];
	
	int m=30+10;
	while(q--)
	{
		int x;
		cin>>x;
		if(x<m)
		{
			m=x;
			for(int i=0;i<n;i++)
				if(a[i]%(1<<m)==0)
					a[i]+=1<<(m-1);
		}
	}
	
	for(auto e:a)
		cout<<e<<" ";
	cout<<endl;
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	int t;
	cin>>t;
	
	while(t--)
		solve();
	
	return 0;
}

需要考虑一个优化,不然肯定超时

假设原来有一个数字a[i]可以整除数字 2 x [ j ] 2^{x[j]} 2x[j],那么a[i]更新之后肯定不可以整除 2 x [ j ] 2^{x[j]} 2x[j],举一个例子i,比如说8本来可以整除4,现在加上2之后就不能整除4

归纳推理可知,被 2 x [ j ] 2^{x[j]} 2x[j]更新之后,就只能被比 2 x [ j ] 2^{x[j]} 2x[j]更小的数字更新,所以最多30次操作,时间复杂度是 30 ⋅ n 30\cdot n 30⋅n

1 < < n 1<<n 1<<n表示 2 n 2^n 2n
n < < 1 = 2 ⋅ n n<<1=2\cdot n n<<1=2⋅n

数据比较大,a数组需要开long long

相关推荐
惯导马工1 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农2 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了3 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo3 小时前
322:零钱兑换(三种方法)
算法
NAGNIP21 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队1 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法
博笙困了1 天前
AcWing学习——差分
c++·算法