Advertisement
Guest User

Špijuni

a guest
Nov 23rd, 2017
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct talk {
  5.     int who, withWhom, price;
  6.     bool operator<(const talk& rhs) const
  7.     {
  8.         return price < rhs.price;
  9.     }
  10. };
  11.  
  12. struct noden {
  13.     int parent;
  14.     int rank;
  15. };
  16.  
  17. // Varijablen
  18. int n;
  19. vector<talk> talks;
  20. noden nodens[1010];
  21. talk result[1010];
  22. int spyPrice[1010];
  23.  
  24. void load() {
  25.     ios_base::sync_with_stdio(false);
  26.     cin >> n;
  27.     for (int i = 0; i < n; i++) {
  28.         for (int j = 0; j < n; j++) {
  29.             int val;
  30.             cin >> val;
  31.             if (i == j) continue;
  32.             talk t;
  33.             t.who = min(i, j);
  34.             t.withWhom = max(i, j);
  35.             t.price = val;
  36.  
  37.             if (j < i) {
  38.                 talks.push_back(t);
  39.             }
  40.  
  41.         }
  42.     }
  43.     for (int i = 0; i < n; i++) {
  44.         cin >> spyPrice[i];
  45.         talk mission;
  46.         mission.who = n;
  47.         mission.withWhom = i;
  48.         mission.price = spyPrice[i];
  49.         talks.push_back(mission);
  50.     }
  51. }
  52.  
  53. int finden(int i)
  54. {
  55.     if (nodens[i].parent != i)
  56.         nodens[i].parent = finden(nodens[i].parent);
  57.  
  58.     return nodens[i].parent;
  59. }
  60.  
  61. void unionen(int x, int y)
  62. {
  63.     int xroot = finden(x);
  64.     int yroot = finden(y);
  65.  
  66.     if (nodens[xroot].rank < nodens[yroot].rank)
  67.         nodens[xroot].parent = yroot;
  68.     else if (nodens[xroot].rank > nodens[yroot].rank)
  69.         nodens[yroot].parent = xroot;
  70.     else {
  71.         nodens[yroot].parent = xroot;
  72.         nodens[xroot].rank++;
  73.     }
  74. }
  75.  
  76. void solve() {
  77.     sort(talks.begin(), talks.end());
  78.     for (int i = 0; i <= n; i++) {
  79.         nodens[i].parent = i;
  80.         nodens[i].rank = 0;
  81.     }
  82.  
  83.     int e = 0;
  84.     int i = 0;
  85.     while (e < n) {
  86.         talk t = talks[i++];
  87.  
  88.         int x = finden(t.who);
  89.         int y = finden(t.withWhom);
  90.  
  91.         if (x != y) {
  92.             result[e++] = t;
  93.             unionen(x, y);
  94.         }
  95.     }
  96.     int rez = 0;
  97.     for (int i = 0; i < e; i++) {
  98.         rez += result[i].price;
  99.     }
  100.     cout << rez;
  101. }
  102.  
  103. int main() {
  104.     load();
  105.     solve();
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement