跳到正文

题解

P2962 Lights G 题解

Splay_trees约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前

link

直接暴搜显然超时。

考虑状压+双向搜索。我们先从全 0 开始搜前一半的灯,把每一个状态对应的步数存在 map 里,再从全 1 搜后一半的灯,如果在 map 里出现就更新答案的最小值。

注意 DFS 的写法和位运算操作的细节(比如long long)

C++
#include <iostream>
#include <map>
#include <string>
using namespace std;
long long g[50];
long long p=0;
map<long long,int> mp;
int n,m;
int maxd;
int ans=0x7fffffff;
string binary(long long x) {
	string ans;
	while(x!=0) {
		ans=(char)((x&1)+'0')+ans;
		x/=2;
	}
	while(ans.length()<n)
		ans='0'+ans;
	return ans;
}
void dfs(int x,int q = 0) {
	if(x>maxd+1)
		return;
	if(mp.find(p)!=mp.end()) {
		if(mp[p]>q)
			mp[p]=q;
	} else {
		mp[p]=q;
	}
//	cout<<binary(p).c_str()<<"->"<<x<<' '<<mp[p]<<endl;
	p^=g[x];
	dfs(x+1,q+1);
	p^=g[x];
	dfs(x+1,q);
}
void dfs2(int x,int q=0) {
	if(x>n+1)
		return;
	if(mp.find(p) != mp.end()) {
		if(ans>q+mp[p])
			ans=q+mp[p];
	}
//	cout<<binary(p)<<endl;
//	cout<<binary(p)<<"->"<<x<<' '<<(mp.find(p)==mp.end()?114514:mp[p])<<endl;
	p^=g[x];
	dfs2(x+1,q+1);
	p^=g[x];
	dfs2(x+1,q);
}

int main() {
//	freopen("C:\\users\\thomas\\downloads\\p2962_2.in","r",stdin);
//	freopen("C:\\users\\thomas\\desktop\\Help\\c\\test.in","r",stdin);
	scanf("%d %d",&n,&m);
	for(int i=1; i<=n; i++) {
		g[i]|=1ll*(1ll<<(i-1ll));
	}
	for(int i=1; i<=m; i++) {
		int a,b;
		scanf("%d %d",&a,&b);
		g[a]|=(1ll<<(b-1ll));
		g[b]|=(1ll<<(a-1ll));
	}
	maxd=(n>>1)+1;
	dfs(1);
//	for(auto i : mp)
//		cout<<binary(i.first)<<' '<<i.second<<endl;
	p=(1ll<<n)-1;
	dfs2(maxd+1);
	printf("%d\n",ans);
	return 0;
}
原文