Corral reservation [greedy + small root pile]

image

There is no doubt that this is a greedy idea, it should be an expansion of the question of the arrangement of activities,

The practice of this question is:

1. Sort all cows by the time they start eating grass

2. Use the small root pile to maintain the current time when the last cow of all corrals grazes

3. If the current cow can be arranged in the top corral, arrange it into it, otherwise create a new corral

The counter-evidence method assumes that there is a scheme that makes the number of corrals required less, and the number of corrals required is m.

Considering the above method, the moment when the m + 1th corral is newly built, it may be assumed that the i-th cow is currently being processed.

Since all cows are sorted in ascending order of start time, the start time of the last cow in the first m stalls must be less than or equal to the start time of the ii cow.

And the minimum end time of the first m stalls is greater than or equal to the start time of the iith cow, so the grazing interval of the last cow in the first m stalls must contain the start time of the ith cow, so we found Since there are intersections of m + 1 intervals, at least m + 1 corrals are needed, which is contradictory.

Therefore, the above method can obtain the optimal solution and prove it.

If the minimum end time is not met, then only a new corral can be added.

Paste the code


  1 #include <iostream>
  2 #include <algorithm>
  3 #include <cstring>
  4 #include <queue>
  5 using namespace std;
  6 typedef pair<int, int> PII;
  7 const int N = 5e5 + 5;
  8 int n, id[N];
  9 
 10 pair<PII, int> cows[N];
 11 
 12 int main(){
 13     cin >> n;
 14     for(int i = 0; i < n; ++ i){
 15         cin >> cows [i] .first.first >> cows [i] .first.second;
 16          cows [i] .second = i;
 17      }
 18  
19      sort (cows, cows + n); // according to the start time Sorting, almost as scheduled as the activity 
20      priority_queue <PII, vector <PII>, greater <PII>> heap; // This is a small root heap used to maintain the minimum end time of each corral 
21      for ( int i = 0 ; i <n; ++ i) {
 22          if (heap.empty () || heap.top (). first> = cows [i] .first.first) { // According to greed, it can be proved that when the minimum ends If the time does not meet the conditions, then a new 
23              PII stall = make_pair (cows [i] .first.second, heap.size ());
 24              id [cows [i] .second] = stall.second + 1;
 25             heap.push(stall);
 26         }
 27         else {
 28             auto stall = heap.top();
 29             heap.pop();
 30             stall.first = cows[i].first.second;
 31             id[cows[i].second] = stall.second + 1;
 32             heap.push(stall);
 33         }
 34     }
 35     cout << heap.size() << endl;
 36     for(int i = 0; i < n; ++ i) cout << id[i] << endl;
 37     return 0;
 38 }

Guess you like

Origin www.cnblogs.com/rstz/p/12702338.html