排序然后贪心吧,自己也有点忘记了。地址:http://acm.pku.edu.cn/JudgeOnline/problem?id=2231

#include "stdio.h"

__int64 num[
10005];

void swap(int a,int b)
{
    __int64 t;
    t
=num[a];
    num[a]
=num[b];
    num[b]
=t;

}


int partion(int low,int high,int p)
{
    
while(low<=high)
    
{
        
if(low<p)
        
{
            
if(num[low]>num[p]){swap(low,p);p=low;}
            low
++;
        }

        
else
        
{
            
if(high>p)
            
{
                
if(num[high]<num[p]){swap(high,p);p=high;}
            }

            high
--;
        }

    }

    
return p;
}


void qsort(int left,int right)
{
    
int middle;
    
if(left<right)
    
{
        middle
=(left+right)/2;
        middle
=partion(left,right,middle);
        qsort(left,middle
-1);
        qsort(middle
+1,right);
    }

}


int main()
{
    
int n,i;
    __int64 value,sum;

    
while(scanf("%d",&n)!=EOF)
    
{
        
for(i=0;i<n;i++)
        
{
            scanf(
"%I64d",&num[i]);
        }


        qsort(
0,n-1);

        value
=0;
        
for(i=0;i<n;i++)
        
{
            value
+=num[i]-num[0];
        }


        sum
=value;
        
for(i=1;i<n;i++)
        
{
            value
=value+(num[i]-num[i-1])*i-(num[i]-num[i-1])*(n-i);
            sum
+=value;
        }


        printf(
"%I64d\n",sum);
    }

    
return 0;
}