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

相关推荐
顾小玙4 分钟前
数据结构进阶:AVL树与红黑树
数据结构
小刘要努力呀!4 分钟前
嵌入式开发学习(第二阶段 C语言基础)
c语言·学习·算法
野曙1 小时前
快速选择算法:优化大数据中的 Top-K 问题
大数据·数据结构·c++·算法·第k小·第k大
Codeking__1 小时前
”一维前缀和“算法原理及模板
数据结构·算法
休息一下接着来1 小时前
C++ 条件变量与线程通知机制:std::condition_variable
开发语言·c++·算法
Code哈哈笑2 小时前
【机器学习】支持向量回归(SVR)从入门到实战:原理、实现与优化指南
人工智能·算法·机器学习·回归·svm
努力学习的小廉2 小时前
【C++】 —— 笔试刷题day_29
开发语言·c++·算法
小羊在奋斗2 小时前
【LeetCode 热题 100】搜索插入位置 / 搜索旋转排序数组 / 寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
meisongqing2 小时前
【软件工程】符号执行与约束求解缺陷检测方法
人工智能·算法·软件工程·软件缺陷
莫叫石榴姐2 小时前
如何为大模型编写优雅且高效的提示词?
人工智能·算法