1 solutions
-
0
C++ :
#include<iostream> #include<algorithm> #include<cstring> #include<ctime> #include<cmath> #include<string> #include<cstdio> typedef long long LL; using namespace std; typedef struct node{ int num, size; LL cnt; struct node *lson, *rson, *next; }*Node; void build(Node rt) { int v; scanf("%d", &v); rt->cnt = 0; rt->next = NULL; if(v != 0) { rt->num = v; rt->size = 1; rt->lson = rt->rson = NULL; } else { rt->num = 0; rt->lson = new node; build(rt->lson); rt->rson = new node; build(rt->rson); rt->next = rt->lson; rt->size = rt->lson->size + rt->rson->size; } } void Merge(Node rt) { Node p = rt->lson, q = rt->rson, t1, t2, t3; if(q->size > p->size) { rt->lson = q; rt->rson = p; p = rt->lson; q = rt->rson; } LL lnum = 0, rnum = 0, l = rt->lson->size, r = rt->rson->size, c1 = 0, c2 = 0; rt->next = p; t1 = rt; t2 = t3 = NULL; //处理结点为0的情况 if(!p->num) p = p->next, rt->next = p, t1 = rt; if(!q->num) q = q->next; //cout<<l<<"**"<<r<<endl; while(p && q) { if(p->num < q->num) { t1 = p; p = p->next; ++c1; lnum += r - c2; } else if(p->num > q->num) { t2 = q; while(q && p->num > q->num) ++c2, rnum += l - c1, t3 = q, q = q->next; t1->next = t2; t3->next = p; t1 = t3; } //不存在两个数相等的情况 // else // { // int t = p->num, ll = 0, rr = 0; // while(p && p->num == t) // { // t1 = p; // p = p->next; ++ll; ++c1; // } // while(q && q->num == t) // { // t1->next = q; // t2 = q->next; // q->next = p; // q = t2; // t1 = t1->next; ++rr; ++c2; // } // lnum += ll * (r - c2); // rnum += rr * (l - c1); // } } if(!p) t1->next = q; rt->cnt = rt->lson->cnt + rt->rson->cnt + (lnum < rnum ? lnum : rnum); //cout<<rt->cnt<<"--->"; //Node t = rt; //while(t) cout<<t->num<<" ", t = t->next; //cout<<endl; } void Travel(Node rt) { if(rt->num) return; Travel(rt->lson); Travel(rt->rson); Merge(rt); } int main() { //freopen("逆序对2.txt", "r", stdin); int n; scanf("%d", &n); Node root = new node; build(root); Travel(root); printf("%lld\n", root->cnt); return 0; }
- 1
Information
- ID
- 16306
- Time
- 2000ms
- Memory
- 128MiB
- Difficulty
- (None)
- Tags
- # Submissions
- 0
- Accepted
- 0
- Uploaded By