【拆位法】P9277 [AGM 2023 资格赛] 反转|普及+

本文涉及知识点

位运算、状态压缩、枚举子集汇总

P9277 [AGM 2023 资格赛] 反转

题目描述

给定长度为 N N N 的序列 a a a 满足每个数都小于 2 K 2^K 2K。你需要执行恰好 P P P 次操作,每次操作是把其中一个数的某一个二进制位反转。最终你需要使得

∑ i ∑ j a i ⊕ a j ( i < j ) \sum_i\sum_j a_i\oplus a_j(i<j) i∑j∑ai⊕aj(i<j)

最大,其中 ⊕ \oplus ⊕ 为按位异或运算。

输入格式

第一行包含整数 N 、 K 、 P N、K、P N、K、P,保证 1 ≤ N ≤ 10 5 , 1 ≤ K ≤ 30 , 1 ≤ P ≤ N × K 1≤N≤10^5,1≤K≤30,1≤P≤N\times K 1≤N≤105,1≤K≤30,1≤P≤N×K。

下一行包含 N N N 个整数,即序列 a a a。对于所有 1 ≤ i ≤ N 1≤i≤N 1≤i≤N,保证 0 ≤ a i < 2 K 0≤a_i<2^K 0≤ai<2K。

输出格式

P P P 行,每行包含两个整数 i i i 和 j j j,满足 1 ≤ i ≤ N , 0 ≤ j < K 1≤i≤N, 0≤j<K 1≤i≤N,0≤j<K,表示数字 a i a_i ai 的第 j j j 位反转。即 a i ← a i ⊕ 2 j a_i\leftarrow a_i \oplus 2^j ai←ai⊕2j。

你可以多次反转同一个位。如果有多个使总和最大化的解输出任意一个即可。

输入输出样例 #1

输入 #1

复制代码
2 5 1
0 31

输出 #1

复制代码
1 0

输入输出样例 #2

输入 #2

复制代码
4 2 2
0 0 2 2

输出 #2

复制代码
4 0
3 0

输入输出样例 #3

输入 #3

复制代码
5 6 4
63 15 0 10 5

输出 #3

复制代码
5 5
4 5
4 4
5 4

P9277 [AGM 2023 资格赛] 反转

从高位开始处理。如果处理完所有位,还有剩余次数。如果是偶数,对任意数任意位处理;如果剩余次数是奇数,则最低位某个数翻转一次,

其它次数翻转任意数任意位,偶数次。

单独处理某一位时,相当于N各0、1。异或为1的数对数为:y1=(N-1)*N/2 - 异或为0的数量(y0)。令1的数量为n1,则异或为0的数量:

y0= (n1-1)n1/2 + (N - n1 -1 ) (N-n1)/2 即2y0 = n1n1-n1+NN-n1N-N-Nn1+n1n1+n1=2n1n1-2n1N+NN-N=-2n1(N-n1)+NN-N

要想2y最小,必须n1(N-n1)最大。即周长一定矩形面积最大。需要n1和N-n1最接近。

v0和v1记录各位0和1的下标。空间复杂度:O(n) 时间复杂度:O(nk)

担心证明错误

故暴力了 n <=10000。数据证明没有错误。结果是山顶数组。

cpp 复制代码
	for (int i = 1; i <= 10000; i++) {
			vector<long long> v;
			for (long long j = 0; j <= i; j++) {
				const long long k = i - j;
				const long long cur = j * (j - 1) / 2 + k * (k - 1) / 2;
				v.emplace_back(cur);
			}
			if (i & 1) {
				for (int k = 0; k + 1 <= i/2; k++) {
					assert(v[k] > v[k + 1]);
				}
				assert(v[i / 2] == v[i / 2 + 1]);
				for (int k = i / 2 + 1; k + 1 <= i; k++) {
					assert(v[k] < v[k + 1]);
				}
			}
			else {
				for (int k = 0; k + 1 <= i / 2; k++) {
					assert(v[k] > v[k + 1]);
				}

				for (int k = i / 2 ; k + 1 <= i; k++) {
					assert(v[k] < v[k + 1]);
				}
			}
		
		}

进一步分析

剩余p是奇数。

如果N是偶数,各位都是N/2个0和N/2个1。翻转最低位和变小。

如果N是奇数,N/2个0(1)或N/2+1个1(0)。反正N/2+1个的,结果不变。
结论:剩余次数全部用来翻转最低位多的数。如果0多,翻转0;1多翻转1。相等翻转0或1。

错误代码

cpp 复制代码
class Solution {
		public:
			vector<pair<int,int>> Ans(const int N ,const int K,int P,const vector<int>& a) {
				vector<pair<int, int>> ans;
				for (int bit = K - 1; bit >= 0; bit--) {
					vector<int> v0, v1;
					auto Do = [&]() {
						P--;
						if (v0.size() < v1.size()) {
							swap(v0, v1);
						}
						ans.emplace_back(v0.back()+1, bit);
						v1.emplace_back(v0.back());
						v0.pop_back();
					};		
					for (int i = 0; i < N; i++) {
						if ((1 << bit) & a[i]) {
							v1.emplace_back(i);
						}
						else {
							v0.emplace_back(i);
						}			
					}
					while (P && (fabs(v0.size() - v1.size()) > 1)) {
						Do();
					}
					while (P &&(0==bit)) {
						Do();
					}
				}
				return ans;
			}
		};

错误原因:不能从高到低位处理

第bit位有c0个0,c1个1。mi= min(c0,c1) ma=max(c0,c1)。

则此位之和是: c 0 ∗ c 1 ∗ ( 1 L L < < b i t ) c0*c1*(1LL<<bit) c0∗c1∗(1LL<<bit)精简

如果ma-mi > 1,则ma--,mi++是更优解。增加: f ( m i ) = ( m i + 1 ) × ( m a − 1 ) − m i × m a = m i × m a + m a − m i − 1 − m i × m a = m a − m i − 1 = m a − ( N − m a ) − 1 = 2 m a − N − 1 f(mi)=(mi+1)\times(ma-1)- mi \times ma=mi \times ma +ma - mi-1- mi \times ma =ma-mi-1=ma-(N-ma)-1=2ma-N-1 f(mi)=(mi+1)×(ma−1)−mi×ma=mi×ma+ma−mi−1−mi×ma=ma−mi−1=ma−(N−ma)−1=2ma−N−1

将各位的f(mi)*(1LL<<bit)放到大根堆中。

vv0[bit] 记录第bit位是0的下标,vv1[bit] 记录第bit位是1的下标。每次Do函数之前,如果vv0[bit].size() < vv1[bit].size() 则swap(vv[0],vv[1])。

代码

核心代码

cpp 复制代码
#include <iostream>
#include <sstream>
#include <vector>
#include<map>
#include<unordered_map>
#include<set>
#include<unordered_set>
#include<string>
#include<algorithm>
#include<functional>
#include<queue>
#include <stack>
#include<iomanip>
#include<numeric>
#include <math.h>
#include <climits>
#include<assert.h>
#include<cstring>
#include<list>
#include<array>

#include <bitset>
using namespace std;

template<class T1, class T2>
std::istream& operator >> (std::istream& in, pair<T1, T2>& pr) {
	in >> pr.first >> pr.second;
	return in;
}

template<class T1, class T2, class T3 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3>& t) {
	in >> get<0>(t) >> get<1>(t) >> get<2>(t);
	return in;
}

template<class T1, class T2, class T3, class T4 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3, T4>& t) {
	in >> get<0>(t) >> get<1>(t) >> get<2>(t) >> get<3>(t);
	return in;
}

template<class T = int>
vector<T> Read() {
	int n;
	cin >> n;
	vector<T> ret(n);
	for (int i = 0; i < n; i++) {
		cin >> ret[i];
	}
	return ret;
}
template<class T = int>
vector<T> ReadNotNum() {
	vector<T> ret;
	T tmp;
	while (cin >> tmp) {
		ret.emplace_back(tmp);
		if ('\n' == cin.get()) { break; }
	}
	return ret;
}

template<class T = int>
vector<T> Read(int n) {
	vector<T> ret(n);
	for (int i = 0; i < n; i++) {
		cin >> ret[i];
	}
	return ret;
}

template<int N = 1'000'000>
class COutBuff
{
public:
	COutBuff() {
		m_p = puffer;
	}
	template<class T>
	void write(T x) {
		int num[28], sp = 0;
		if (x < 0)
			*m_p++ = '-', x = -x;

		if (!x)
			*m_p++ = 48;

		while (x)
			num[++sp] = x % 10, x /= 10;

		while (sp)
			*m_p++ = num[sp--] + 48;
		AuotToFile();
	}
	void writestr(const char* sz) {
		strcpy(m_p, sz);
		m_p += strlen(sz);
		AuotToFile();
	}
	inline void write(char ch)
	{
		*m_p++ = ch;
		AuotToFile();
	}
	inline void ToFile() {
		fwrite(puffer, 1, m_p - puffer, stdout);
		m_p = puffer;
	}
	~COutBuff() {
		ToFile();
	}
private:
	inline void AuotToFile() {
		if (m_p - puffer > N - 100) {
			ToFile();
		}
	}
	char  puffer[N], * m_p;
};

template<int N = 1'000'000>
class CInBuff
{
public:
	inline CInBuff() {}
	inline CInBuff<N>& operator>>(char& ch) {
		FileToBuf();
		while (('\r' == *S) || ('\n' == *S) || (' ' == *S)) { S++; }//忽略空格和回车
		ch = *S++;
		return *this;
	}
	inline CInBuff<N>& operator>>(int& val) {
		FileToBuf();
		int x(0), f(0);
		while (!isdigit(*S))
			f |= (*S++ == '-');
		while (isdigit(*S))
			x = (x << 1) + (x << 3) + (*S++ ^ 48);
		val = f ? -x : x; S++;//忽略空格换行		
		return *this;
	}
	inline CInBuff& operator>>(long long& val) {
		FileToBuf();
		long long x(0); int f(0);
		while (!isdigit(*S))
			f |= (*S++ == '-');
		while (isdigit(*S))
			x = (x << 1) + (x << 3) + (*S++ ^ 48);
		val = f ? -x : x; S++;//忽略空格换行
		return *this;
	}
	template<class T1, class T2>
	inline CInBuff& operator>>(pair<T1, T2>& val) {
		*this >> val.first >> val.second;
		return *this;
	}
	template<class T1, class T2, class T3>
	inline CInBuff& operator>>(tuple<T1, T2, T3>& val) {
		*this >> get<0>(val) >> get<1>(val) >> get<2>(val);
		return *this;
	}
	template<class T1, class T2, class T3, class T4>
	inline CInBuff& operator>>(tuple<T1, T2, T3, T4>& val) {
		*this >> get<0>(val) >> get<1>(val) >> get<2>(val) >> get<3>(val);
		return *this;
	}
	template<class T = int>
	inline CInBuff& operator>>(vector<T>& val) {
		int n;
		*this >> n;
		val.resize(n);
		for (int i = 0; i < n; i++) {
			*this >> val[i];
		}
		return *this;
	}
	template<class T = int>
	vector<T> Read(int n) {
		vector<T> ret(n);
		for (int i = 0; i < n; i++) {
			*this >> ret[i];
		}
		return ret;
	}
	template<class T = int>
	vector<T> Read() {
		vector<T> ret;
		*this >> ret;
		return ret;
	}
private:
	inline void FileToBuf() {
		const int canRead = m_iWritePos - (S - buffer);
		if (canRead >= 100) { return; }
		if (m_bFinish) { return; }
		for (int i = 0; i < canRead; i++)
		{
			buffer[i] = S[i];//memcpy出错			
		}
		m_iWritePos = canRead;
		buffer[m_iWritePos] = 0;
		S = buffer;
		int readCnt = fread(buffer + m_iWritePos, 1, N - m_iWritePos, stdin);
		if (readCnt <= 0) { m_bFinish = true; return; }
		m_iWritePos += readCnt;
		buffer[m_iWritePos] = 0;
		S = buffer;
	}
	int m_iWritePos = 0; bool m_bFinish = false;
	char buffer[N + 10], * S = buffer;
};

class Solution {
public:
	vector<pair<int, int>> Ans(const int N, const int K, int P, const vector<int>& a) {
		vector<pair<int, int>> ans;
		vector<vector<int>> vv0(K), vv1(K);
		priority_queue<pair<long long, int>> maxHeap;
		for (int bit = K - 1; bit >= 0; bit--) {
			for (int i = 0; i < N; i++) {
				if ((1 << bit) & a[i]) {
					vv1[bit].emplace_back(i);
				}
				else {
					vv0[bit].emplace_back(i);
				}
			}
			auto& v0 = vv0[bit];
			auto& v1 = vv1[bit];
			if (v0.size() < v1.size()) {
				swap(v0, v1);
			}
			if (v0.size() - v1.size() > 1)
			{
				maxHeap.emplace((1LL << bit) * (2 * v0.size() - N - 1), bit);
			}
		}
		auto Do = [&](int bit) {
			P--;
			auto& v0 = vv0[bit];
			auto& v1 = vv1[bit];
			if (v0.size() < v1.size()) {
				swap(v0, v1);
			}
			ans.emplace_back(v0.back() + 1, bit);
			v1.emplace_back(v0.back());
			v0.pop_back();
			if (v0.size() - v1.size() > 1)
			{
				maxHeap.emplace((1LL << bit) * (2 * v0.size() - N - 1), bit);
			}
		};
		while (maxHeap.size() && P) {
			const auto [tmp, bit] = maxHeap.top();
			maxHeap.pop();
			Do(bit);
		}
		while (P) {
			Do(0);
		}
		return ans;
	}
};

int main() {
#ifdef _DEBUG
	freopen("a.in", "r", stdin);
#endif // DEBUG	
	ios::sync_with_stdio(0); cin.tie(nullptr);
	CInBuff<> in; COutBuff<10'000'000> ob;	
	int N,K,P;
	in >> N >> K >> P ;
	auto a = in.Read<int>(N);
	
#ifdef _DEBUG		
		printf("N=%d,K=%d,P=%d", N,K,P);
		Out(a, ",a=");
		//Out(ab, ",ab=");
		//Out(B, "B=");
		//Out(que, "que=");
		//Out(B, "B=");
#endif // DEBUG	
		auto res = Solution().Ans(N,K,P,a);
		for (const auto& [i, j] : res) {
			cout << i << " " << j << "\n";
		}
	return 0;
};

单元测试

cpp 复制代码
	int N, K,P;
		vector<int> a;
		void Check(const vector<int>& a, const vector<pair<int,int>>& act, vector<pair<int, int>>& res) {
			AssertEx(Cal(a, act), Cal(a, res));
		}
		long long Cal( vector<int> a,const vector<pair<int, int>>& res) {
			for (const auto& [i, j] : res) {
				a[i - 1] ^= (1 << j);
			}
			long long ans = 0;
			for (int i = 0; i < a.size(); i++) {
				for (int j = i + 1; j < a.size(); j++) {
					ans += a[i] ^ a[j];
				}
			}
			return ans;
		}
		TEST_METHOD(TestMethod01)
		{
			a = { 0,31 };
			auto res = Solution().Ans(2,5,1,a);
			Check(a,{ { 1,0 } }, res);
		}
		TEST_METHOD(TestMethod02)
		{
			a = { 0,0,2,2 };
			auto res = Solution().Ans(4,2,2,a);
			Check(a,{ { 4,0 },{3,0} }, res);
		}
		TEST_METHOD(TestMethod03)
		{
			N = 5, K = 6, P = 4, a = { 63,15,0,10,5 };
			auto res = Solution().Ans(N,K,P, a);
			Check(a, { { 5,5 },{5,4},{4,3},{4,3} }, res);
		}	
		TEST_METHOD(TestMethod04)
		{
			N = 2, K = 2, P = 3, a = { 1,2 };
			auto res = Solution().Ans(N, K, P, a);
			AssertV({ { 2,0 },{2,0},{1,0} }, res);
		}
		TEST_METHOD(TestMethod05)
		{
			N = 2, K = 2, P = 4, a = { 1,2 };
			auto res = Solution().Ans(N, K, P, a);
			Check(a, {  }, res);
		}
		TEST_METHOD(TestMethod06)
		{
			N = 3, K = 3, P = 4, a = { 1,2,4 };
			auto res = Solution().Ans(N, K, P, a);
			Check(a, {  }, res);
		}
		TEST_METHOD(TestMethod07)
		{
			N = 3, K = 3, P = 1, a = { 1,2,4 };
			auto res = Solution().Ans(N, K, P, a);
			Check(a, { {2,0} }, res);
		}
		TEST_METHOD(TestMethod08)
		{
			N = 6, K = 2, P = 1, a = { 2,2,0,0,0,0 };
			auto res = Solution().Ans(N, K, P, a);
			Check(a, { {1,0} }, res);
		}

扩展阅读

我想对大家说的话
工作中遇到的问题,可以按类别查阅鄙人的算法文章,请点击《算法与数据汇总》。
学习算法:按章节学习《喜缺全书算法册》,大量的题目和测试用例,打包下载。重视操作
有效学习:明确的目标 及时的反馈 拉伸区(难度合适) 专注
闻缺陷则喜(喜缺)是一个美好的愿望,早发现问题,早修改问题,给老板节约钱。
子墨子言之:事无终始,无务多业。也就是我们常说的专业的人做专业的事。
如果程序是一条龙,那算法就是他的是睛
失败+反思=成功 成功+反思=成功

视频课程

先学简单的课程,请移步CSDN学院,听白银讲师(也就是鄙人)的讲解。
https://edu.csdn.net/course/detail/38771

如何你想快速形成战斗了,为老板分忧,请学习C#入职培训、C++入职培训等课程
https://edu.csdn.net/lecturer/6176

测试环境

操作系统:win7 开发环境: VS2019 C++17

或者 操作系统:win10 开发环境: VS2022 C++17

如无特殊说明,本算法用**C++**实现。

相关推荐
maplewen.1 小时前
C++ 多态原理深入理解
开发语言·c++·面试
tbRNA2 小时前
C++ string类
开发语言·c++
ccLianLian2 小时前
算法基础·C++常用操作
开发语言·数据结构·c++
柒儿吖2 小时前
基于 lycium 在 OpenHarmony 上交叉编译 komrad36-CRC 完整实践
c++·c#·harmonyos
草莓熊Lotso2 小时前
Linux 程序地址空间深度解析:虚拟地址背后的真相
java·linux·运维·服务器·开发语言·c++·人工智能
郝学胜-神的一滴2 小时前
使用Linux命名管道(FIFO)实现无血缘关系进程间通信
linux·服务器·开发语言·c++·程序人生
HAPPY酷2 小时前
std::pair` 与 `std::map` 基础
开发语言·c++·算法
柒儿吖2 小时前
基于 lycium 在 OpenHarmony 上交叉编译 cppDES 完整实践
c++·harmonyos
爱搞事的程小猿2 小时前
qml自定义扩展模块
c++·qt·qml