Algorithm to improve the problem of queue fetching water

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.