Difference between triplets
Time limit:3000 Ms |
|
Memory limit:65536 K |
Total submissions:2476 |
|
Accepted:800 |
Description
For every pair of triplets,Ta= (IA,Ja,Ka) AndTB= (IB,JB,KB), We defineDifference valueBetweenTaAndTBAs follows:
D(Ta,TB) = Max {IA?IB,Ja?JB,Ka?KB}? Min {IA?IB,Ja?JB,Ka?KB}
Now you are given
NTriplets, cocould you write a program to calculate the sum of the Difference values between every unordered pair of triplets?
Input
The input consists of several test cases.
Each test case begins with a line containing an integer
N, Denotes the number of triplets. Assume that we number the triplets
T1,
T2,...,
TN. Then, there are following
NLines, each line contains three integers, giving the elements of each triplet.
A case
N= 0 indicates the end of the input.
Output
For each case, output a line with the sum of Difference values between every unordered pair of triplets.
Sample Input
21 2 33 2 131 3 24 0 72 2 90
Sample output
420
Hint
Case 1:
D(
T1,
T2) = 4
Case 2:
D(
T1,
T2) +
D(
T1,
T3) +
D(
T2,
T3) = 8 + 8 + 4 = 20
You can assume that
N, The number of triplets in each case, will not exceed 200,000 and the elements in triplets fit into [-106,106].
The size of the input will not exceed 5 MB.
Source
Poj monthly -- 2007.07.08, Yuan, xinhao
The meaning of the question is very easy to understand.
The N ^ 2 algorithm must be used. It must be O (n)
Max {a, B, c}-min {a, B, c} = (| a-B | + | B-c | + | C-A |) /2
Suppose A> B> C, then max {a-B-c}-min {a-B-c} = a-c}
While (| a-B | + | B-c | + | C-A |)/2 = (a-B + B-C + C-) /2 = a-c = max {a-B-c}-min {a-B-c}
However, regardless of the relationship between A, B, and C, we can always exchange the like A', B ', and C' to maintain a'> B'> C ', at the same time, the results are always consistent.
| (IA-ka)-(IB-KB) | = | (IA-Ib)-(Ka-KB) |
Therefore, for Ti = (IA, IB, IC), we can calculate Ia-Ib, IB-ic, IC-Ia first.
In this case, we need to calculate d (Ti, TJ), which is (| a-B | + | B-c | + | C-A |)/2. It can be linear. You can remove the absolute values of A> B, B> C, C>.
After sorting, The Headers A [I], B [I], C [I], and a [I] are I-times, the number of times the n-i-1 is reduced (coordinates from 0)
In this way, ANS = sum (I * (a [I] + B [I] + C [I])-(n-i-1) * (a [I] + B [I] + C [I])
For details, see the code. The idea is indeed a pitfall.
#include <iostream>#include <algorithm>using namespace std;#define N 200005long long a[N],b[N],c[N];int main(){ int i,n; long long x,y,z; cin.sync_with_stdio(false); while(cin>>n,n){ for(i=0;i<n;i++){ cin>>x>>y>>z; a[i]=x-y,b[i]=y-z,c[i]=z-x; } sort(a,a+n); sort(b,b+n); sort(c,c+n); long long ans=0LL; for(i=0;i<n;i++){ ans+=(i*(a[i]+b[i]+c[i])-(n-i-1)*(a[i]+b[i]+c[i])); } cout<<ans/2<<endl; } return 0;}
Poj3244 (formula)