fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int n, m, reaction[8][8], power[8][8], tube[12], dp[1<<12][12];
  5.  
  6. int solve(int mask, int prev){
  7. if(mask == ((1<<m)-1)) return 0;
  8. if(dp[mask][prev] != -1) return dp[mask][prev];
  9. int ans = 1<<30, res;
  10. for(int i = 0; i<m; i++){
  11. res = 0;
  12. if(!(mask & (1<<i))){
  13. res += power[prev][i] + solve(mask | (1<<i), reaction[prev][i]);
  14. }
  15. ans = min(ans, res);
  16. }
  17. return dp[mask][prev] = ans;
  18. }
  19.  
  20. int main() {
  21. int t;
  22. string str;
  23. scanf("%d", &t);
  24. for(int i = 1; i<=t; i++){
  25. scanf("%d", &n);
  26. for(int j = 0; j<n; j++){
  27. for(int k = 0; k<n; k++){
  28. scanf("%d %d", &reaction[j][k], &power[j][k]); reaction[j][k]--;
  29. }
  30. }
  31. scanf("%d", &m);
  32. for(int j = 0; j<m; j++){
  33. scanf("%d", &tube[j]); tube[j]--;
  34. }
  35.  
  36. int ans = 1<<30;
  37. for(int j = 0; j<m; j++){
  38. for(int k = j+1; k<m; k++){
  39. memset(dp,-1,sizeof(dp));
  40. int x = tube[j], y = tube[k];
  41. ans = min(ans,power[x][y] + solve(0 | (1<<j) | (1<<k), reaction[x][y]));
  42. }
  43. }
  44. cin >> str;
  45. printf("%d\n", ans);
  46. }
  47. cin >> str;
  48. return 0;
  49. }
Success #stdin #stdout 0s 3608KB
stdin
2
3
1  0
3  -10
3  3000
3  -10
2  0
1  -500
3  3000
1  -500
3  0
4
1  2  2  3
/
3
1  0
3  500
3  -250
3  500
2  0
1  10
3  -250
1  100
3  0
6
1  1  1  2  2  3
.
stdout
-510
-750