看了一个树状数组的题,看了半天没看懂,很烦躁。就来看这题了。题目看懂了,思路有一点,就拿别人的代码来看了看。
http://www.cnblogs.com/GO-NO-1/p/3707853.html
x坐标和高度离散化之后,分别按照x和h排个序,记录下来。然后高度从大到小排序,每次都保证当前高度是最小的。然后计算比当前x坐标小的那些树和当前树的F * S的和,再加上比当前树的x坐标大的那些树和当前树F * S和,这样分开两半,也好算,也不用管绝对值了。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN = 1e5+10;
int n;
struct node
{
int x,h;
int id,xid,hid;
}tree[MAXN],tt[MAXN];
bool cmpx(const node& a, const node& b)
{
return a.x < b.x;
}
bool cmph(const node& a, const node& b)
{
return a.h < b.h;
}
bool rcmph(const node& a, const node& b)
{
return a.h > b.h;
}
LL cnum[MAXN],clen[MAXN];
#define lowbit(x) (x&(-x))
void add(LL c[], int i, int x)
{
while(i <= n)
{
c[i] += x;
i += lowbit(i);
}
}
LL sum(LL c[], int i)
{
LL ret = 0;
while(i)
{
ret += c[i];
i -= lowbit(i);
}
return ret;
}
int main()
{
while(scanf("%d",&n) != EOF)
{
memset(cnum,0,sizeof(cnum));
memset(clen,0,sizeof(clen));
for(int i = 1; i <= n; ++i)
{
scanf("%d %d",&tree[i].x,&tree[i].h);
tree[i].id = i;
tt[i] = tree[i];
}
sort(tt+1,tt+1+n,cmpx);
int rk = 1;
for(int i = 1; i <= n; ++i)
{
if(tt[i].x != tt[i-1].x) rk = i;
tree[tt[i].id].xid = rk;
}
sort(tt+1,tt+1+n,cmph);
rk = 1;
for(int i = 1; i <= n; ++i)
{
if(tt[i].h != tt[i-1].h) rk = i;
tree[tt[i].id].hid = rk;
}
sort(tree+1,tree+1+n,rcmph);
LL res = 0;
add(cnum, tree[1].xid, 1);
add(clen, tree[1].xid, tree[1].xid);
for(int i = 2; i <= n; ++i)
{
LL cnt = ::sum(cnum,tree[i].xid);
LL sum = ::sum(clen,tree[i].xid);
LL tsum = ::sum(clen,n);
res += tree[i].hid * (cnt*tree[i].xid - sum + tsum - sum - (i-cnt-1)*tree[i].xid);
add(cnum,tree[i].xid,1);
add(clen,tree[i].xid,tree[i].xid);
}
printf("%I64d\n",res);
}
return 0;
}