跳到正文

题解

题解:P15476 [CERC2012] Kingdoms

Stick_Man_约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年2月28日
更新
2026年2月28日
篇幅
约 2 分钟
题目
P15476

版本

  1. v2当前
  2. v1

P15476 [CERC2012] Kingdoms

题目思路

注意到 n≤20n \le 20,可以用状压 dp。

复杂度: O(T×2n×n2)O(T\times 2^n \times n^2)

完整代码

抄袭私募

C++
#include<bits/stdc++.h>
using namespace std
#define int long long
const int N=20;
int n,d[N][N];
bitset<1<<N> ok;
void init(){
	cin>>n;
	for(int i=0;i<(1<<n);i++) ok[i]=0;
	for(int i=0;i<n;i++)
		for(int j=0;j<n;j++)
			cin>>d[i][j];
}
int tmp[N],tcnt;
int ban[N],bcnt;
void solve(){
	init();
	ok[(1<<n)-1]=1;
	for(int i=(1<<n)-1;i>=0;i--)
		if(ok[i]){
			tcnt=bcnt=0;
			for(int j=0;j<n;j++)
				if(i&(1<<j))
					tmp[tcnt++]=j;
			for(int x=0;x<tcnt;x++){
				int sum=0;
				for(int y=0;y<tcnt;y++) sum+=d[tmp[x]][tmp[y]];
				if(sum>0) ban[bcnt++]=tmp[x];
			}
			for(int j=0;j<bcnt;j++) ok[i-(1<<ban[j])]=1;
		}
	tcnt=0;
	for(int i=0;i<n;i++)
		if(ok[1<<i])
			tmp[tcnt++]=i;
	if(tcnt>0){
		for(int i=0;i<tcnt;i++)
			cout<<tmp[i]+1<<" ";
		cout<<"\n";
	}
	else cout<<"0\n";
}
/*
1
3
0 -3 1
3 0 -2
-1 2 0
*/
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	int T=1;
	cin>>T;
	while(T--) solve();
	return 0;
}
原文