分析:
把每一个人的个数表示出来,如第一个人:A1 - X1 + X2 = M
可得X2 =M - A1 + X1 = X1 - C1(令C1 = M - A1)
以此类推。
最后找到规律,转化为数轴上一个点到N个点之间距离的问题。
发现当x取得c的中位数时最小,累加距离得出答案。
#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <string>
#include <numeric>
#include <algorithm>
#include <functional>
#include <iterator>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <complex>
#include <ctime>
typedef long long LL;
const double pi = acos(-1.0);
const long long mod = 1e9 + 7;
using namespace std;
LL a[1000005];
LL c[1000005];
int main()
{
//freopen("int.txt","r",stdin);
//freopen("out.txt","w",stdout);
int N;
while(scanf("%d",&N) == 1)
{
LL sum = 0;
for(int i = 1;i <= N;i++)
{
scanf("%I64d",&a[i]);
sum += a[i];
}
LL M = sum / N;
c[0] = 0;
for(int i = 1;i < N;i++)
c[i] = c[i - 1] + a[i] - M;
sort(c,c + N);
LL x1 = c[N / 2];
LL ans = 0;
for(int i = 0;i < N;i++)
ans += abs(x1 - c[i]);
printf("%I64d\n",ans);
}
return 0;
}
//a数组事实上能够不要
#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <string>
#include <numeric>
#include <algorithm>
#include <functional>
#include <iterator>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <complex>
#include <ctime>
typedef long long LL;
const double pi = acos(-1.0);
const long long mod = 1e9 + 7;
using namespace std;
LL c[1000005];
int main()
{
//freopen("int.txt","r",stdin);
//freopen("out.txt","w",stdout);
int N;
LL M,sum;
while(scanf("%d",&N) == 1)
{
sum = 0;
LL a;
c[0] = 0;
for(int i = 1;i <= N;i++)
{
scanf("%lld",&a);
sum += a;
c[i] = sum;
}
M = sum / N;
for(int i = 1;i < N;i++)
c[i] -= M * i;
sort(c,c + N);
LL x1 = c[N / 2],ans = 0;
for(int i = 0;i < N;i++)
ans += abs(x1 - c[i]);
printf("%lld\n",ans);
}
return 0;
}
时间: 2024-10-28 16:30:36