Best Factory HRBUST-2171 Greedy Algorithm + Fast Sorting

Topic link

The factory received n orders, each with two values ​​(ai, bi), which means that ai tons of steel need to be produced before the time bi. The factory's output is always 1 ton per second, and if the order is received too much, it will be too late to complete. So the boss of the factory decided to reject the minimum number of orders, so that all the remaining orders could be satisfied through proper order arrangement. Can you help him calculate how many orders can be met at most?
Input
Multiple sets of test data, for each set of test data: Enter an integer n (n<=1000) in the first line, and two integers ai, bi in each line of the next n lines, indicating the amount of steel required for the task and the deadline . (ai, bi <= 2*10^6)
Output
For each set of test data, output an integer to indicate the maximum number of orders that can be satisfied, and each set of output occupies one line.
Sample Input

6
7 15
8 20
6 8
4 9
3 21
5 22

Sample Output

4

This is a greedy algorithm question. In order to satisfy the meaning of the question and reject the smallest number of orders, we will reject the order that requires the most output among the currently selected orders. For the deleted orders, we will set this order tonnage to -1 to avoid impact Follow-up sorting.
Every time it is judged whether the time of course is less than the deadline of the order, if it is greater than we start to delete the order that requires the largest output among the selected orders.
Very typical greedy algorithm.

code show as below:

#include<iostream>
#include<algorithm> 
#include<string>
#include<cstring>
using namespace std;
struct muban
{
    
    
 	int a;//a吨钢铁 
 	int b;//b时刻之前 
}que[1005];
bool cmp(muban x,muban y)
{
    
    
 	return x.b<y.b;
}
int main()
{
    
    
 	int n;
 	while(cin>>n)
 	{
    
    
  		for(int i=0;i<n;i++)
  		cin>>que[i].a>>que[i].b;
  		sort(que,que+n,cmp);
  		int now=0;
  		int count=0;
  		for(int i=0;i<n;i++)
  		{
    
    
   			now+=que[i].a;
   			count++; 
   			if(now>que[i].b)//如果时间超过截止时间 
   			{
    
    
    				while(1)//开始删除订单,删到合适再跳出循环 
    				{
    
    
     					int max=i;//设置最大订单下标max 
     					for(int j=i-1;j>=0;j--)
     					{
    
    
      						if(que[j].a>que[max].a)
      						{
    
     
       							max=j;
      						}
     					}
     					now-=que[max].a;//删除最大订单产量
     					que[max].a=-1; //将最大订单产量设置为-1 
     					count--;
     					if(now<=que[i].b) 
     					{
    
    
      						break;//符合要求跳出循环,否则再删除一个订单。 
     					}
    				}
   			}
  		}
  		cout<<count<<endl;
 	}
 	return 0;
} 

Guess you like

Origin blog.csdn.net/Huo6666/article/details/107246162