位运算 数学优化 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^{xj} 2xj,那么a[i]更新之后肯定不可以整除 2 x j 2^{xj} 2xj,举一个例子i,比如说8本来可以整除4,现在加上2之后就不能整除4了

归纳推理可知,被 2 x j 2^{xj} 2xj更新之后,就只能被比 2 x j 2^{xj} 2xj更小的数字更新,所以最多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

相关推荐
武子康5 小时前
驾驶轨迹换个坐标,就能给移动机器人用吗?
人工智能·算法·机器学习
David猪大卫6 小时前
【C++修炼】map 和 set 的使用
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
vvilkim7 小时前
数据结构类型、区别与应用场景:一篇讲透选型逻辑
数据结构
lisw0511 小时前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
阿卡好可爱12 小时前
Lua 热更新不生效:改完文件线上仍是旧逻辑,package.loaded 与 upvalue 重绑定详解
数据结构·分布式·后端·架构·lua
一起学安全技术12 小时前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs13 小时前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信1504130575914 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法