The comparison between tree array and segment tree is that the tree-like array is superior in both memory and time.
The idea of a big problem is to sort the V from small to large, before looking for (i.e., smaller coordinates than v)
V * SUM (ABS (XI-X)) so ABS cannot be processed, we use another tree-like array to record the number of cows in the X-y interval, before that record in the X-y interval of the cow's coordinates and
Tree-like array code:
#include <cstdio> #include <algorithm> #include <cstring>using namespace std;typedef long LL; const int MAXN = 22222;int c1[maxn],c2[maxn];int n = 20005,nn;struct cow{int v,x; friend bool operator < (Cow P,cow q) {return p.v < Q.V; }}cow[maxn];int lowbit (int x) {return x & x;} int sum (int c[],int x) {int ret = 0; while (x > 0) {ret + = c[x]; X-= Lowbit (x); } return ret;} void Add (int c[],int x,int d) {while (x <= N) {c[x] + = D; x + = Lowbit (x); }}int Main () {scanf ("%d", &nn); memset (c1,0,sizeof (C1)); memset (c2,0,sizeof (C2)); for (int i = 0; i < nn; i++) scanf ("%d%d", &cow[i].v,&cow[i].x); Sort (Cow,cow + nn); LL ans = 0; for (int i = 0; i < nn; i++) {int x = Cow[i].x,v = COW[I].V; int m1 = SUM (c1,x), N1 = SUM (c2,x); int m2 = SUM (c1,n)-m1,n2 = SUM (c2,n)-N1; Ans + = ((LL) N1 * x-m1) + ((LL) m2-n2 * x)) * V; Add (C1,X,X); Add (c2,x,1); } printf ("%i64d\n", ans); return 0;}
I |
Accepted |
932 |
110 |
C++ |
1723 |
|
Line segment Tree Code:
#include <cstdio> #include <cstring> #include <algorithm>using namespace std;const int maxn = 20005; typedef long Long ll;/* segment Tree solution */#define LSON (pos<<1) #define RSON (pos<<1|1) int V1[MAXN << 2],V2[MAXN < ;< 2];struct node{int x,v; friend bool operator < (Node P,node q) {return p.v < Q.V; }}node[maxn];void build () {memset (v1,0,sizeof (v1)); memset (V2,0,sizeof (v2));} void pushup (int v[],int pos) {V[pos] = V[lson] + V[rson];} void update (int v[],int l,int r,int aim,int pos,int value) {if (L = = R) {V[pos] + = value; Return } int mid = (L + R) >> 1; if (Aim <= mid) update (v,l,mid,aim,lson,value); else Update (V,mid + 1,r,aim,rson,value); Pushup (V,pos);} int query (int v[],int l,int r,int l,int r,int pos) {if (L <= l && R <= R) {return V[pos]; } int mid = (L + R) >> 1; int ans = 0; if (L <= mid) ans + = query (V,l,mid,l,r,lson); If(R > Mid) ans + = query (V,mid + 1,r,l,r,rson); return ans;} int main () {build (); int n,max_size = 0; scanf ("%d", &n); for (int i = 0; i < n; i++) {scanf ("%d%d", &node[i].v,&node[i].x); Max_size = max (max_size,node[i].x) + 1; } sort (Node,node + N); LL ans = 0; for (int i = 0; i < n; i++) {int x = Node[i].x,v = NODE[I].V; Ans + = ((ll) (x * Query (v2,1,max_size,1,x,1))-(ll) (query (v1,1,max_size,1,x,1))) * V; Ans + = ((ll) (query (v1,1,max_size,x,max_size,1))-(ll) (Query (v2,1,max_size,x,max_size,1) * x)) * V; printf ("%d%i64d\n", I,ans); Update (v2,1,max_size,x,1,1); Update (V1,1,MAX_SIZE,X,1,X); } printf ("%i64d\n", ans); return 0;}
"POJ" 1990-moofest (tree array or segment tree)