【ACWing】913. Queue to fetch water

Subject address:

https://www.acwing.com/problem/content/description/915/

Have nnn people line up to fetch water,iii It takes time for an individual to fetch waterti t_iti, Ask how to arrange the order of fetching water to minimize the total waiting time for everyone.

Input format: the
first line contains the integer nnn . The second line containsnnn integers, where theiithi integers represent theiithi the time it takes for an individual to fill the bucketti t_iti

Output format:
output an integer, representing the sum of the minimum waiting time.

Data range:
1 ≤ n ≤ 1 0 5 1\le n\le 10^51n105
1 ≤ ti ≤ 1 0 4 1 \ le t_i \ le 10 ^ 41ti104

First to ti t_itiSorting from small to large, the total waiting time for fetching water in this order is the least.

Proof of algorithm correctness:
method of proof by contradiction. If the order of arrangement is not ti t_itiMonotonically increasing, then there must be a certain kkk such thattk> tk + 1 t_k>t_{k+1}tk>tk+1, Then swap the order in which these two people fetch water, the total fetch time will be reduced by tk − tk + 1> 0 t_k-t_{k+1}>0tktk+1>0 , contradiction.

code show as below:

#include <iostream>
#include <algorithm>
using namespace std;

const int N = 100010;
int a[N];

int main() {
    
    
    int n;
    cin >> n;

    for (int i = 0; i < n; i++) cin >> a[i];

    sort(a, a + n);

    long res = 0;
    for (int i = 0; i < n; i++) res += (long) (n - i - 1) * a[i];

    cout << res << endl;

    return 0;
}

Time complexity O (n log ⁡ n) O(n\log n)O ( nlogn ) , spaceO (1) O(1)O ( 1 )

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/114133788