Charging HRBUST-1674 Greedy Algorithm + Fast Row

Topic link
There are n power strips in the glass house, m machines that need power supply, and k sockets on the wall that can be used directly. Know the number of sockets on each socket, and all plugs and sockets can be matched. Q. How many power strips can you use to power on all machines?
Input
Multiple sets of test data, enter n, m, k in the first line of each group. (1 ≤ n, m, k ≤ 50) There are n numbers in the second row, which respectively indicate the number of sockets on each socket.
Output
At least a few sockets are required for output. If there are appliances that cannot be charged, -1 is output. Each group of output occupies one line.
Sample Input

3 5 3
3 1 2
4 7 2
3 3 2 4
5 5 1
1 3 1 2 1

Sample Output

1
2
-1

The problem is to use the least number of sockets. When the number of sockets on the wall is not enough for the machine, the socket with the most sockets on the socket shall be used first.
Sort the sockets in descending order according to the number of sockets.

code show as below:

#include<iostream>
#include<algorithm> 
#include<string>
#include<cstring>
using namespace std;
bool cmp(int a,int b)
{
    
    
 	return a>b;
}
int main()
{
    
    
 	int n,m,k;
 	while(cin>>n>>m>>k)
 	{
    
    
  		int a[n+5];
  		for(int i=0;i<n;i++)
  		{
    
    
   			cin>>a[i];
  		}
  		sort(a,a+n,cmp);
  		if(k>=m)
  		{
    
    
   			cout<<0<<endl;
   			continue;
  		}
  		else
  		{
    
    
   			int sum=k;
   			int flag=0;
   			for(int i=0;i<n;i++)
   			{
    
    
    				sum=sum-1+a[i];
    				if(sum>=m)
    				{
    
    
     					cout<<i+1<<endl;
     					flag=1;
     					break;
    				}
   			}
   			if(flag==0)
   			cout<<-1<<endl;
  		}
 	} 
 	return 0;
} 

Guess you like

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