位运算 数学优化 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

相关推荐
Q741_1479 小时前
每日一题 力扣 3655. 区间乘法查询后的异或 II 模拟 分治 乘法差分法 快速幂 C++ 题解
c++·算法·leetcode·模拟·快速幂·分治·差分法
The_Ticker10 小时前
印度股票实时行情API(低成本方案)
python·websocket·算法·金融·区块链
夏乌_Wx10 小时前
剑指offer | 2.4数据结构相关题目
数据结构·c++·算法·剑指offer·c/c++
AI成长日志10 小时前
【笔面试算法学习专栏】哈希表基础:两数之和与字母异位词分组
学习·算法·面试
minji...10 小时前
Linux 线程同步与互斥(二) 线程同步,条件变量,pthread_cond_init/wait/signal/broadcast
linux·运维·开发语言·jvm·数据结构·c++
abant211 小时前
leetcode 239 单调队列 需要一些记忆
算法·leetcode·职场和发展
漫霂11 小时前
二叉树的统一迭代遍历
java·算法
炽烈小老头11 小时前
【每天学习一点算法 2026/04/08】阶乘后的零
学习·算法
Mr_Xuhhh11 小时前
算法刷题笔记:从滑动窗口到哈夫曼编码,我的算法进阶之路
开发语言·算法
游乐码11 小时前
C#Queue
数据结构·游戏·c#