kolbka_

Untitled

Dec 16th, 2021
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1.  
  2.  
  3.  
  4. #include <iostream>
  5. #include <cassert>
  6. #include <algorithm>
  7. #include <vector>
  8. #include <unordered_map>
  9. #include "optimization.h"
  10. #include <unordered_map>
  11.  
  12. #define all(a) a.begin, a.end()
  13. using namespace std;
  14.  
  15. int main() {
  16. int64_t n;
  17. cin >> n;
  18. vector<vector<int64_t>> cost(n, vector<int64_t>(n));
  19. for (int64_t i = 0; i < n; i++) {
  20. for (int64_t j = 0; j < n; j++) {
  21. cin >> cost[i][j];
  22. }
  23. }
  24. vector<vector<int64_t>> dp((1 << n), vector<int64_t>(n, INT32_MAX));
  25. vector<vector<int64_t>> last((1 << n), vector<int64_t>(n, INT16_MAX));
  26. for (int64_t i = 0; i < n; i++) {
  27. dp[1 << i][i] = 0;
  28. }
  29. for (int64_t A = 1; A < (1 << n); A++) {
  30. for (int64_t v = 0; v < n; v++) {
  31. for (int64_t x = 0; x < n; x++) {
  32. if ((A & (1 << x)) == 0 && dp[A][v] != INT32_MAX && dp[A][v] + cost[v][x] < dp[A | (1 << x)][x]) {
  33. dp[A | (1 << x)][x] = dp[A][v] + cost[v][x];
  34. last[A | (1 << x)][x] = v;
  35. }
  36. }
  37. }
  38. }
  39. int64_t cur = INT32_MAX;
  40. int64_t res = INT32_MAX;
  41. for (int64_t v = 0; v < n; v++) {
  42. if (dp[(1 << n) - 1][v] < res) {
  43. res = dp[(1 << n) - 1][v];
  44. cur = v;
  45. }
  46. }
  47. cout << dp[(1 << n) - 1][cur] << "\n";
  48.  
  49. vector<int64_t> way(n);
  50. int64_t j = n - 1;
  51. int64_t A = (1 << n) - 1;
  52. int pref = 0;
  53. way[j--] = cur + 1;
  54. while (j != -1){
  55. int pref = last[A][cur];
  56. A = A - (1 << cur);
  57. way[j--] = pref + 1;
  58. cur = pref;
  59. }
  60. for (auto x: way) {
  61. cout << x << " ";
  62. }
  63. }
  64.  
  65.  
  66.  
Advertisement
Add Comment
Please, Sign In to add comment