状压dp
#include<cstdio> #include<cstdlib> #include<algorithm> #include<cstring> #include<vector> #include<queue> #define MAXN 20 #define ll long long using namespace std; int n; vector<int> G[MAXN]; ll f[1<<MAXN]; int vis[1<<MAXN]; void solve(){ for(int i=0;i<MAXN;i++) G[i].clear(); memset(f,0,sizeof(f)); memset(vis,0,sizeof(vis)); scanf("%d",&n); for(int i=0;i<=n;i++){ char ch[10]={0}; scanf("%s",ch+1); for(int j=1;j<=n;j++){ if(ch[j]-48){ G[i].push_back(j); } } } queue<int> q; f[(1<<n)-1]=1; vis[(1<<n)-1]=1; q.push((1<<n)-1); while(!q.empty()){ int S=q.front();q.pop(); int b[MAXN]={0}; for(int i=0;i<G[0].size();i++){ b[G[0][i]]=1; } int t=S,cnt=1; for(int i=0;i<n;i++){ if(~(S>>i)&1){ for(int j=0;j<G[i+1].size();j++){ b[G[i+1][j]]=1; } } } for(int i=0;i<n;i++){ if(((S>>i)&1)&&b[i+1]){ int dS=S^(1<<i); f[dS]+=f[S]; if(!vis[dS]){ vis[dS]=1; q.push(dS); } } } } printf("%lld\n",f[0]); } int main() { // freopen("data.in","r",stdin); // freopen("my.out","w",stdout); int T; scanf("%d",&T); for(int i=1;i<=T;i++){ printf("Case %d: ",i); solve(); } return 0; }
UVA11795 Mega Man's Mission
时间: 2024-10-09 12:30:17