【贪心】习题集
122. 糖果传递
写法一:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 1e6 + 10;
int n;
LL s[N], c[N];
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i ++ )
{
scanf("%lld", &s[i]);
s[i] += s[i - 1];
}
LL b = s[n] / n;
int k = 0;
for(int i = 1; i < n; i ++ ) c[k ++ ] = i * b - s[i];
c[k ++ ] = 0;
nth_element(c, c + k / 2, c + k);
LL res = 0;
for(int i = 0; i < k; i ++ )
res += abs(c[i] - c[k / 2]);
printf("%lld\n", res);
return 0;
}
作者:Once.
链接:https://www.acwing.com/activity/content/code/content/3430736/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
写法二
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 1e6 + 10;
int n;
int a[N];
LL c[N];
LL sum;
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i ++ )
{
scanf("%d", &a[i]);
sum += a[i];
}
LL avg = sum / n;
for(int i = n; i > 1; i -- )
{
c[i] = c[i + 1] + avg - a[i];
}
c[1] = 0;
sort(c + 1, c + n + 1);
LL res = 0;
for(int i = 1; i <= n; i ++ ) res += abs(c[i] - c[(i + 1) / 2]);
printf("%lld\n", res);
return 0;
}
作者:Once.
链接:https://www.acwing.com/activity/content/code/content/1774442/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
写法三
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 1e6 + 10;
int n;
LL s[N], c[N];
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i ++ )
{
scanf("%lld", &s[i]);
s[i] += s[i - 1];
}
LL avg = s[n] / n;
for(int i = 2; i <= n; i ++ ) c[i] = (i - 1) * avg - (s[i] - s[1]);
sort(c + 1, c + n + 1);
LL md = c[(n + 1) / 2];
LL res = 0;
for(int i = 1; i <= n; i ++ ) res += abs(c[i] - md);
printf("%lld\n", res);
return 0;
}
作者:Once.
链接:https://www.acwing.com/activity/content/code/content/3430855/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。