Codeforces Round #251 (Div. 2)-D. Devu and his Brother

来源:互联网 发布:nba球员生涯数据 编辑:程序博客网 时间:2024/04/29 22:07

原题链接

D. Devu and his Brother
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and bby their father. The array a is given to Devu and b to his brother.

As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b.

Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.

You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.

Input

The first line contains two space-separated integers nm (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).

Output

You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.

Examples
input
2 22 33 5
output
3
input
3 21 2 33 4
output
4
input
3 24 5 61 2
output
0

经过分析可获得,假若a数组的最小值小于b数组的最大值,那么a或b数组必定存在一个值c,使得a的最小值,达到c,b的最大值达到c,使得操作数达到最小

#include <bits/stdc++.h>#define maxn 1000005using namespace std;typedef long long ll;struct Node{friend bool operator < (const Node&a, const Node&b){return a.m < b.m;}int i, m;}node[maxn];ll sum1[maxn], sum2[maxn];int cnt1[maxn], cnt2[maxn];int main(){//freopen("in.txt", "r", stdin);int n, m;scanf("%d%d", &n, &m);for(int i = 1; i <= n; i++){ scanf("%d", &node[i].m); node[i].i = 0;    }    for(int i = n+1; i <= n+m; i++){    scanf("%d", &node[i].m);    node[i].i = 1;    }    sort(node+1, node+1+n+m);    int l, r;    for(int i = 1; i <= n + m; i++)     if(node[i].i == 0){     l = i;     break;     }     for(int i = n + m; i >= 1; i--){    if(node[i].i == 1){    r = i;    break;    }    }    if(node[l].m >= node[r].m){    puts("0");    return 0;    }     for(int i = l; i <= r; i++){    sum1[i] = sum1[i-1];    sum2[i] = sum2[i-1];    cnt1[i] = cnt1[i-1];    cnt2[i] = cnt2[i-1];    if(node[i].i == 0){    cnt1[i]++;    sum1[i] += node[i].m;    }    else{    cnt2[i]++;    sum2[i] += node[i].m;    }    }    ll ans = 1e18;    for(int i = l; i <= r; i++){    ans = min(ans, (ll)node[i].m * cnt1[i] - sum1[i] + (sum2[r] - sum2[i]) - (ll)node[i].m * (cnt2[r] - cnt2[i]));    }    cout << ans << endl;    return 0;}


0 0