【叉姐的魔法训练第一课_初级魔法练习】poj 3244 Difference between Triplets (数学)

题目链接

题意:

For every pair of triplets, Ta = (Ia, Ja, Ka) and T__b = (Ib, Jb, Kb), we define the difference value between Ta and_T__b_ as follows:

D(Ta,_ Tb_) = max {IaIb, JaJb, KaKb} − min {IaIb, JaJb, KaKb}

Now you are given N triplets, could you write a program to calculate the sum of the difference values between every unordered pair of triplets?

思路:转化要求的式子,如果把_Ia_ − Ib, JaJb, KaKb 看成数轴上的点,所求的式子就变成了求三个点构成的线段的距离。

**设X=IaIb,Y=JaJb,Z=KaKb,那么该距离D = (|X-Y| + |Y-Z| + |Z-X|  )/2(该式子是此题最关键的一部,可以通过画图直观得到)  **

D=|(ia-ja)-(ib-jb)| + |(ja-ka)-(jb-kb)| + | (ka-za)+(kb-zb) |

设a = ia-ja,b =ja-ka,c = ka-ia,然后分别排序类似于bzoj1604_拆点求曼哈顿距离

考虑第i个a,对于其他的n-1个a,有i-1个比它小,n-i个比它大,因此对答案的贡献为(i-1)个a[i]和 (n-i)个-a[i]

b,c同理。

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2016年11月17日 星期四 20时05分54秒
 4File Name :code/hdu/3244.cpp
 5************************************************ */
 6#include <cstdio>
 7#include <cstring>
 8#include <iostream>
 9#include <algorithm>
10#include <vector>
11#include <queue>
12#include <set>
13#include <map>
14#include <string>
15#include <cmath>
16#include <cstdlib>
17#include <ctime>
18#define fst first
19#define sec second
20#define lson l,m,rt<<1
21#define rson m+1,r,rt<<1|1
22#define ms(a,x) memset(a,x,sizeof(a))
23typedef long long LL;
24#define pi pair < int ,int >
25#define MP make_pair
26using namespace std;
27const double eps = 1E-8;
28const int dx4[4]={1,0,0,-1};
29const int dy4[4]={0,-1,1,0};
30const int inf = 0x3f3f3f3f;
31const int N=2E5+7;
32int n;
33int x,y,z;
34int a[N],b[N],c[N];
35int main()
36{
37	#ifndef  ONLINE_JUDGE 
38	freopen("code/in.txt","r",stdin);
39  #endif
40	while (~scanf("%d",&n))
41	{
42	    if (n==0) break;
43	    for ( int i = 1; i  <= n ; i++)
44	    {
45		scanf("%d%d%d",&x,&y,&z);
46		a[i] = x - y;
47		b[i] = y - z;
48		c[i] = z - x;
49	    }
50	    sort(a+1,a+n+1);
51	    sort(b+1,b+n+1);
52	    sort(c+1,c+n+1);
53	    LL ans = 0 ;
54	    for (  int i = 1 ; i <= n ; i++)
55	    {
56		ans += 1LL*(i-1)*a[i];
57		ans +=-1LL*(n-i)*a[i];	
58		ans += 1LL*(i-1)*b[i];
59		ans +=-1LL*(n-i)*b[i];	
60		ans += 1LL*(i-1)*c[i];
61		ans +=-1LL*(n-i)*c[i];
62	    }
63	    printf("%lld\n",ans/2);
64	}
65  #ifndef ONLINE_JUDGE  
66  fclose(stdin);
67  #endif
68    return 0;
69}