Mehulcoder

Friends

Nov 1st, 2020 (edited)
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 505;
  5. vector<int> edges[N];
  6. int n;
  7. int vis[N];
  8.  
  9. int dfs(int root) {
  10.     vis[root] = 1;
  11.     set<int> s;
  12.     for (auto &child : edges[root]) {
  13.         s.insert(child);
  14.     }
  15.  
  16.     /*
  17.         Here we just check that if the child of a child
  18.         is from the set of children of the root, if so that means
  19.         This is a cycle. You can simply get the score of this trio
  20.         By removing 2*3 edges(due to trio members)
  21.     */
  22.     int ans = INT_MAX;
  23.     for (auto &child : edges[root]) {
  24.         for (auto &cchild : edges[child]) {
  25.             if (s.find(cchild) != s.end()) {
  26.                 int cnt = edges[root].size() + edges[child].size() + edges[cchild].size() - 6;
  27.                 ans = min(ans, cnt);
  28.             }
  29.         }
  30.     }
  31.  
  32.     return ans;
  33. }
  34.  
  35. int bestTrio(int friends_node, vector<int> friends_from, vector<int> friends_to) {
  36.     n  = friends_node;
  37.     for (int i = 0; i < N; ++i) {
  38.         edges[i].clear();
  39.     }
  40.     memset(vis, -1, sizeof(vis));
  41.     for (int i = 0; i < friends_from.size(); ++i) {
  42.         edges[friends_from[i]].push_back(friends_to[i]);
  43.         edges[friends_to[i]].push_back(friends_from[i]);
  44.     }
  45.  
  46.     int ans = INT_MAX;
  47.     for (int i = 0; i < n; ++i) {
  48.         if (!vis[i]) {
  49.             ans = min(ans, dfs(i));
  50.         }
  51.     }
  52.  
  53.  
  54.     return ans;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment