Advertisement
asdfg0998

ewfdweq

Nov 5th, 2024
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. vector<int> timeOfInfection(int n, int m, vector<int>& initially_infected, vector<vector<int>>& updates) {
  2.         vector<int> parent(n), infectionTime(n, -1), vaccinated(n, 0);
  3.        
  4.         // Initialize Union-Find structure
  5.         for (int i = 0; i < n; ++i) parent[i] = i;
  6.  
  7.         // Set initial infection times
  8.         for (int person : initially_infected) infectionTime[person] = 0;
  9.        
  10.         // Define find function with an explicit return type
  11.         function<int(int)> find = [&](int x) {
  12.             if (x != parent[x]) parent[x] = find(parent[x]);
  13.             return parent[x];
  14.         };
  15.  
  16.         auto unionGroups = [&](int a, int b, int time) {
  17.             int rootA = find(a);
  18.             int rootB = find(b);
  19.             if (rootA != rootB) {
  20.                 if (infectionTime[rootA] != -1 && infectionTime[rootB] == -1 && !vaccinated[rootB]) {
  21.                     infectionTime[rootB] = time;  // Infect group B if A is infected
  22.                 } else if (infectionTime[rootB] != -1 && infectionTime[rootA] == -1 && !vaccinated[rootA]) {
  23.                     infectionTime[rootA] = time;  // Infect group A if B is infected
  24.                 }
  25.                 parent[rootB] = rootA; // Merge groups
  26.             }
  27.         };
  28.  
  29.         // Process updates
  30.         for (int t = 0; t < updates.size(); ++t) {
  31.             int type = updates[t][0];
  32.             int a = updates[t][1];
  33.             int b = updates[t][2];
  34.  
  35.             if (type == 0) { // Contact
  36.                 unionGroups(a, b, t + 1);
  37.             } else if (type == 1) { // Vaccination
  38.                 vaccinated[a] = 1;
  39.             }
  40.         }
  41.        
  42.         return infectionTime;
  43.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement