Description
She finds that trees maybe disharmony and the Disharmony Value between two trees is associated with two value called FAR and SHORT.
The FAR is defined as the following:If we rank all these trees according to their X Coordinates in ascending order.The tree with smallest X Coordinate is ranked 1th.The trees with the same X Coordinates are ranked the same. For example,if there are 5 tree with X Coordinates 3,3,1,3,4. Then their ranks may be 2,2,1,2,5. The FAR of two trees with X Coordinate ranks D1 and D2 is defined as F = abs(D1-D2).
The SHORT is defined similar to the FAR. If we rank all these trees according to their heights in ascending order,the tree with shortest height is ranked 1th.The trees with the same heights are ranked the same. For example, if there are 5 tree with heights 4,1,9,7,4. Then their ranks may be 2,1,5,4,2. The SHORT of two trees with height ranks H1 and H2 is defined as S=min(H1,H2).
Two tree’s Disharmony Value is defined as F*S. So from the definition above we can see that, if two trees’s FAR is larger , the Disharmony Value is bigger. And the Disharmony value is also associated with the shorter one of the two trees.
Now give you every tree’s X Coordinate and their height , Please tell Sophia the sum of every two trees’s Disharmony value among all trees.
Input
For each test case, the first line contain one integer N (2 <= N <= 100,000) N represents the number of trees.
Then following N lines, each line contain two integers : X, H (0 < X,H <=1,000,000,000 ), indicating the tree is located in Coordinates X and its height is H.
Output
Sample Input
Sample Output
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
#define ll long long
typedef struct abcd
{
ll x,f,i;
} abcd;
abcd a[];
bool cmp1(abcd x,abcd y)
{
return x.x<y.x;
}
bool cmp2(abcd x,abcd y)
{
return x.f<y.f;
}
typedef struct abc
{
ll sum,ci;
}abc;
abc aa[];
ll need,need1,n;
ll lowbit(ll x)
{
return x&(-x);
}
void update(ll x)
{
ll y=x;
while(x<=n)
{
aa[x].ci++;
aa[x].sum+=y;
x+=lowbit(x);
}
}
ll fun(ll x,ll y)
{
ll ans,nu=,sum=,z=x;
while(x>)
{
nu+=aa[x].ci;
sum+=aa[x].sum;
x-=lowbit(x);
}
ans=y*((need-sum)-(need1-nu)*z)+y*(nu*z-sum);
return ans;
}
int main()
{
int i,j,now,noww;
ll ans;
while(~scanf("%d",&n))
{
for(i=; i<n; i++)
scanf("%I64d%I64d",&a[i].x,&a[i].f);
sort(a,a+n,cmp1);
now=a[].x,a[].x=,noww=;
for(i=; i<n; i++)
{
if(a[i].x==now)a[i].x=a[i-].x;
else now=a[i].x,a[i].x=noww;
noww++;
}
sort(a,a+n,cmp2);
now=a[].f,a[].f=,noww=;
for(i=; i<n; i++)
{
if(a[i].f==now)a[i].f=a[i-].f;
else now=a[i].f,a[i].f=noww;
noww++;
}
need=,need1=;
ans=;
memset(aa,,sizeof(aa));
for(i=n-;i>=;i--)
{
ans+=fun(a[i].x,a[i].f);
update(a[i].x);
need+=a[i].x;
need1++;
}
cout<<ans<<endl;
}
}