Advertisement
atitoa93

feedingTime

Apr 19th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. bool isIncompatible(vector <string> &v1, vector <string> &v2) {
  2.     set <string> animals;
  3.     for (string s : v1) {
  4.         animals.insert(s);
  5.     }
  6.     for (string s : v2) {
  7.         if (animals.count(s)) {
  8.             return true;
  9.         }
  10.     }
  11.     return false;
  12. }
  13.  
  14. bool isValidColor(vector <vector <int>> &adj, vector <int> &color, int chosenColor, int u) {
  15.     for (int i = 0; i < adj[u].size(); ++i) {
  16.         int v = adj[u][i];
  17.         if (color[v] == chosenColor) {
  18.             return false;
  19.         }
  20.     }
  21.     return true;
  22. }
  23.  
  24. bool isGraphColorable(vector <vector <int>> &adj, vector <int> &color, int numOfColors, int u) {
  25.     if (u == adj.size()) return true;
  26.    
  27.     for (int i = 1; i <= numOfColors; ++i) {
  28.         if (isValidColor(adj, color, i, u)) {
  29.             color[u] = i;
  30.            
  31.             if (isGraphColorable(adj, color, numOfColors, u + 1)) {
  32.                 return true;
  33.             }
  34.            
  35.             color[u] = 0;
  36.         }
  37.     }
  38.    
  39.     return false;
  40. }
  41.  
  42. int feedingTime(std::vector<std::vector<std::string>> classes) {
  43.     int n = classes.size();
  44.    
  45.     vector <vector <int>> adj(n);
  46.     for (int i = 0; i < n; ++i) {
  47.         for (int j = i + 1; j < n; ++j) {
  48.             if (isIncompatible(classes[i], classes[j])) {
  49.                 adj[i].push_back(j);
  50.                 adj[j].push_back(i);
  51.             }
  52.         }
  53.     }
  54.    
  55.     vector <int> color(n);
  56.     for (int i = 1; i <= 5; ++i) {
  57.         if (isGraphColorable(adj, color, i, 0)) {
  58.             return i;
  59.         }
  60.     }
  61.    
  62.     return -1;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement