P15476 [CERC2012] Kingdoms
题目思路
注意到 ,可以用状压 dp。
复杂度:
完整代码
抄袭私募
#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;
}