数轴上有N个点,任意两点连线得到n(n-1)条线段,试求线段的总长。
第一行,一个整数N,表示点数。 接下来N行,每行一个整数X_i,表示点的坐标。 一个整数,表示线段的总长。
5
1
5
3
2
4
40
提示
N < = 10000 , 0 < = X_i < = 1000000000
求处理。
int n; scanf("%d",&n); int X_i[1000]={0}; int i,j; for(i=1;i<=n;i++) { scanf("%d",&X_i[i-1]); } int sum=0; for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) { sum+=abs(X_i[j]-X_i[i]); } } printf("\n%d\n",sum);
[此贴子已经被作者于2016-2-29 19:49编辑过]
#include <stdio.h> #include <stdlib.h> static int compare_unsigned_( const void* a_, const void* b_ ) { unsigned a = *(unsigned*)a_; unsigned b = *(unsigned*)b_; if( a < b ) return -1; if( a > b ) return +1; return 0; } unsigned long long foo( unsigned x[], unsigned n ) { if( n < 2 ) return 0; qsort( x, n, sizeof(*x), &compare_unsigned_ ); unsigned long long length = 0; for( unsigned i=1; i<=n-1; ++i ) length += i*(n-i) * 1ull * (x[i]-x[i-1]); return length*2; } int main( void ) { unsigned x[10000], n; scanf( "%u", &n ); for( unsigned i=0; i!=n; ++i ) scanf( "%u", x+i ); printf( "%llu\n", foo(x,n) ); return 0; }
#include <stdio.h> unsigned long long foo( unsigned x[], unsigned n ) { if( n < 2 ) return 0; unsigned long long length = 0; for( unsigned i=0; i!=n-1; ++i ) for( unsigned j=i+1; j!=n; ++j ) length += x[j]>=x[i] ? x[j]-x[i] : x[i]-x[j]; return length*2; } int main( void ) { unsigned x[10000], n; scanf( "%u", &n ); for( unsigned i=0; i!=n; ++i ) scanf( "%u", x+i ); printf( "%llu\n", foo(x,n) ); return 0; }