Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- vector<int> timeOfInfection(int n, int m, vector<int>& initially_infected, vector<vector<int>>& updates) {
- vector<int> parent(n), infectionTime(n, -1), vaccinated(n, 0);
- // Initialize Union-Find structure
- for (int i = 0; i < n; ++i) parent[i] = i;
- // Set initial infection times
- for (int person : initially_infected) infectionTime[person] = 0;
- // Define find function with an explicit return type
- function<int(int)> find = [&](int x) {
- if (x != parent[x]) parent[x] = find(parent[x]);
- return parent[x];
- };
- auto unionGroups = [&](int a, int b, int time) {
- int rootA = find(a);
- int rootB = find(b);
- if (rootA != rootB) {
- if (infectionTime[rootA] != -1 && infectionTime[rootB] == -1 && !vaccinated[rootB]) {
- infectionTime[rootB] = time; // Infect group B if A is infected
- } else if (infectionTime[rootB] != -1 && infectionTime[rootA] == -1 && !vaccinated[rootA]) {
- infectionTime[rootA] = time; // Infect group A if B is infected
- }
- parent[rootB] = rootA; // Merge groups
- }
- };
- // Process updates
- for (int t = 0; t < updates.size(); ++t) {
- int type = updates[t][0];
- int a = updates[t][1];
- int b = updates[t][2];
- if (type == 0) { // Contact
- unionGroups(a, b, t + 1);
- } else if (type == 1) { // Vaccination
- vaccinated[a] = 1;
- }
- }
- return infectionTime;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement