Algorithm idea: the
three arrays are the value of the job p [i], the time d [i], the most recent previous insertable job f [i], and the parent [i] whose initial value is -1
will be output The result is saved in std :: vector <int> res
First sorted according to p [i], every time you use greedy to find the largest p [i] value, you can
traverse the array from 1 to determine whether d [i] meets the conditions
Judgment method:
find the root j through the find method, which is the closest possible insertion point, and then judge whether f [j] can be inserted, if it cannot be inserted, discard it, otherwise save i in res and then put Union in front The nearest root and this value
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int parent[1005], d[1005] = {0, 2, 2, 1, 3, 3}, f[1005];
void unionArray(int i, int j) {
int x = parent[i] + parent[j];
if(parent[i] > parent[j]) { // i的节点少
parent[i] = j;
parent[j] = x;
} else {
parent[j] = i;
parent[i] = x;
}
}
int find(int i) {
int j = i;
while (parent[j] > 0) {
j = parent[j];
}
int k = i;
while (parent[k] > 0) {
int temp = parent[k];
parent[k] = j;
k = temp;
}
return j;
}
int main() {
int size = 5;
vector<int> res;
for (int i = 0; i <= size; ++i) {
parent[i] = -1;
f[i] = i;
}
for (int i = 1; i <= size; ++i) {
int j = find(min(size, d[i]));
if(f[j]!= 0) {
res.push_back(i);
int l = find(f[j]-1);
unionArray(l, j);
f[j] = f[l];
}
for (int k = 0; k <= size; ++k) {
cout << f[k] << ends;
}
cout << endl;
}
for (int re : res) {
cout << re << ends;
}
return 0;
}