Algorithm to improve the problem of queue fetching water
Time limit: 1.0s memory limit: 256.0MB
Submit this question
Problem description
There are n people queuing up to r taps to fetch water, they fill buckets of time T1, t2...........tn are integers and unequal, how to arrange their water order so that they spend the least amount of time.
Input format
First line N,r (n<=500,r<=75)
Second act n the time taken by the individual to fetch Ti (TI<=100);
Output format
Minimum time to spend
Sample input
3 2
1 2 3
Sample output
7
Data size and conventions
80% of these data guarantee n<=10
The total time required to spend is minimal, because everyone's water time is immutable, so we have to start from the waiting time, fortunately, everyone has a different time to fetch water,
The person I waited for was the time to add water to the time he waited from the number of R people he was moving forward.
#include <iostream>
#include <algorithm>
using namespace std;
int wait[505],spend[505];
int main ()
{
int n,r;
int sum=0;
cin>>n>>r;
for (int i=0;i<n;i++)
cin>>spend[i];
Sort (spend,spend+n);
for (int i=0;i<r;i++)
wait[i]=0;
for (int i=r;i<n;i++)
wait[i]=spend[i-r]+wait[i-r];
for (int i=0;i<n;i++)
sum+=wait[i]+spend[i];
cout<<sum;
return 0;
}
After writing it out, you can further refine the spend array and the wait array to merge.
The following procedure was obtained:
#include <iostream>
#include <algorithm>
using namespace std;
int spend[505];
int main ()
{
int n,r;
int sum=0;
cin>>n>>r;
for (int i=0;i<n;i++)
cin>>spend[i];
Sort (spend,spend+n);
for (int i=r;i<n;i++)
spend[i]+=spend[i-r];
for (int i=0;i<n;i++)
sum+=spend[i];
cout<<sum;
return 0;
}