uva10604 Chemical Reaction(DP)
#include <iostream> #include <cstring> #include <cstdio> #include <vector> #include <queue> #define ll long long using namespace std; int change[12][12]; ll w[12][12],dp[11][11][11][11][11][11]; bool vis[12]; int a[12]; vector<int> v; int t,n,m; void read(){ scanf("%d",&n); for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ scanf("%d%lld",&change[i][j],&w[i][j]); } } v.clear(); for(int i=0;i<=8;i++) v.push_back(0); scanf("%d",&m); for(int i=1;i<=m;i++){ scanf("%d",&a[i]); v[a[i]]++; } char str; cin>>str; } ll DP(){ if(v[1]+v[2]+v[3]+v[4]+v[5]+v[6]==1) return 0; if(dp[v[1]][v[2]][v[3]][v[4]][v[5]][v[6]]!=-1) return dp[v[1]][v[2]][v[3]][v[4]][v[5]][v[6]]; ll ret=1e17; for(int i=1;i<=6;i++){ if(v[i]==0) continue; for(int j=1;j<=6;j++){ v[i]--; if(v[j]==0) {v[i]++;continue;} v[j]--; v[change[i][j]]++; //cout<<i<<" "<<j<<" "<<change[i][j]<<endl; ret=min(ret,DP()+w[i][j]); v[i]++; v[j]++; v[change[i][j]]--; } } return dp[v[1]][v[2]][v[3]][v[4]][v[5]][v[6]]=ret; } void gao(){ memset(dp,-1,sizeof dp); printf("%lld\n",DP()); } int main(){ //freopen("10604","r",stdin); scanf("%d",&t); for(int ca=1;ca<=t;ca++){ read(); gao(); } return 0; }