Advertisement
achulkov2

Untitled

Sep 30th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. int n;
  8. bool used[10];
  9. int m[10][10];
  10. int ans = 1000000000;
  11.  
  12. void work(vector<int>& p) {
  13.     int curr = 0;
  14.     for (int i = 0; i < n; ++i) {
  15.         int val = m[p[i]][p[i + 1]];
  16.         if (val != 0) curr += val;
  17.         else return;
  18.     }
  19.     ans = min(curr, ans);
  20. }
  21.  
  22. void go(vector<int>& p) {
  23.     if (p.size() == n) {
  24.         p.push_back(p[0]);
  25.         work(p);
  26.         p.pop_back();
  27.     } else {
  28.         for (int i = 0; i < n; ++i) {
  29.             if (!used[i]) {
  30.                 used[i] = true;
  31.                 p.push_back(i);
  32.                 go(p);
  33.                 p.pop_back();
  34.                 used[i] = false;
  35.             }
  36.         }
  37.     }
  38. }
  39.  
  40. int main() {
  41.     freopen("input.txt", "r", stdin);
  42.     freopen("output.txt", "w", stdout);
  43.     cin >> n;
  44.     for (int i = 0; i < n; ++i) {
  45.         for (int j = 0; j < n; ++j) {
  46.             cin >> m[i][j];
  47.         }
  48.     }
  49.     vector<int> p;
  50.     memset(used, 0, n * sizeof(bool));
  51.     go(p);
  52.     if (ans != 1000000000) {
  53.         cout << ans;
  54.     } else if (n == 1 ){
  55.         cout << "0";
  56.     } else {
  57.         cout << "-1";
  58.     }
  59.     cout << "\n";
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement