赞
踩
/*
[题目描述]给定一个无序数列,求每个元素前面比它的元素个数。例如:4 5 1 3 2,则输出0 0 2 2 3- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <iostream>
- #include <algorithm>
- using namespace std;
-
-
- #define num 200005
- int input[num], input2[num];
- int tmp[num], res[num];
-
-
- void merge(int l,int mid,int r) {
- int i=l;
- int j=mid+1;
- int k=1;
-
-
- while (i <= mid && j <= r) {
- if (input[i] > input[j]) {
-
- //第i个比j大 由于i已经从小到大排过序了 那么i+1到mid的也会比j大
- res[input[j]] += mid - i + 1;
- //cout<< input[i]<< " zz " << input[j] << " ";
- tmp[k++] = input[j++];
- } else {
- tmp[k++] = input[i++];
- }
- }
- while (i <= mid)
- tmp[k++] = input[i++];
- while (j <= r)
- tmp[k++] = input[j++];
- for (i = l, k = 1; i <= r; i++, k++) {
- input[i] = tmp[k];
- }
- }
-
-
- void merge_sort(int l,int r) {
- if(l < r) {
- int mid = (l + r) / 2;
- merge_sort(l, mid);
- //cout << l << " - " << mid << endl;
- merge_sort(mid + 1, r);
- //cout << mid + 1 << " -- " << r << endl;
- merge(l, mid, r);
- }
- }
-
-
- int main() {
- int n,i;
- scanf("%d", &n);
- for (i = 0; i < n; i++){
- scanf("%d", &input[i]);
- input2[i] = input[i];
- }
-
-
- merge_sort(0, n - 1);
-
- for (int i = 0; i < n - 1; ++i)
- printf("%d ", res[input2[i]]);
- printf("%d\n", res[input2[n - 1]]);
-
- return 0;
-
- }
/*
[分析]线段树解法,将问题转化为查询某个区间和问题。e.g.序列4 5 1 3 2
1.更新4时,更新4所在区间和+1,查询[5,20w]的区间和即代表前序列中大于4的元素的个数。
2.同理
3.更新1时,即所有区间和都+1,然后再查询[2, 20w]的区间和。
...
*/
- #include <iostream>
- #include <string>
- #include <cstring>
- #include <cstdio>
- using namespace std;
-
- #define N 200010
-
- int sum[N*4];
-
- void pushup(int rt) {
- sum[rt] = sum[rt*2] + sum[rt*2 + 1];
- }
-
- void build(int l,int r,int rt) {
- if (l==r) {
- sum[rt] = 0;
- return;
- }
- int m = (l + r) >> 1;
- build(l,m,rt*2);
- build(m + 1,r,rt * 2 + 1);
- pushup(rt);
- }
-
- void update(int p,int add,int l,int r,int rt) {
- if(l==r) {
- sum[rt] += add;
- return;
- }
- int m = (l + r) >> 1;
- if(p <= m) update(p,add,l,m,rt*2);
- else update(p,add,m + 1,r,rt * 2 + 1);
-
- pushup(rt);
- }
-
- int query(int L,int R,int l,int r,int rt) {
- if (L <= l && r <= R) {
- return sum[rt];
- }
- int m = (l + r) >> 1;
- int ans1 = 0, ans2 = 0;
- if (L <= m) ans1 += query(L,R,l,m,rt * 2);
- if (R > m) ans2 += query(L,R,m + 1,r,rt * 2 + 1);
- return ans1 + ans2;
- }
-
- int main() {
- //freopen("data/xianduanshu.txt","r",stdin);
- int n;
- scanf("%d",&n);
- build(1,200000,1);
- for(int i=1; i<=n; ++i) {
- int a;
- scanf("%d",&a);
- update(a,1,1,200000,1);
- //printf("rt = %d\n", sum[1]);
- printf("%d%c",query(a + 1,200000,1,200000,1), i==n?'\n':' ');//统计当前序列中大于a的元素的个数
- }
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。