1348:数组中的逆序对(树状数组 or 归并)
来源:互联网 发布:下载贵金属软件 编辑:程序博客网 时间:2024/05/16 09:29
OJ题目:click here~~
题目分析:经典题目,求逆序对。两种方法:
一、离散化+树状数组
二、归并排序
利用归并排序,已A:
AC_CODE
#include<stdio.h>#include<string.h>using namespace std ;typedef long long LL ;const int maxn = 100008 ;int n ;LL ans ;int x[maxn] ;void Merge(int low , int high){ int mid = (low + high)/2 ; int i = low, j = mid + 1, k = 0 ; int xx[maxn] ; while(i <= mid && j <= high){ if(x[i] > x[j]){ xx[k++] = x[j++] ; ans += (mid - i + 1) ; } else{ xx[k++] = x[i++] ; } } if(j <= high) while(j <= high) xx[k++] = x[j++] ; if(i <= mid) while(i <= mid) xx[k++] = x[i++] ; k = 0 ; i = low ; while(i <= high) x[i++] = xx[k++] ;} void MergSort(int low , int high){ if(high <= low) return ; int mid = (low + high)/2 ; MergSort(low , mid) ; MergSort(mid + 1 , high) ; Merge(low , high) ;} int main(){ int i , j , k ; while(scanf("%d",&n) != EOF){ ans = 0 ; for(i = 0;i < n;i++) scanf("%d",&x[i]) ; MergSort(0 , n - 1) ; printf("%lld\n",ans) ; } return 0 ;}
树状数组,不能A,但是在POJ2299能A。。。。。
#include <stdio.h>#include <stdlib.h>#include <iostream>#include <algorithm>#include <math.h>#include <string.h>using namespace std;typedef long long LL ;const int maxn = 100005 ; int n ;int x[maxn] ;LL c[maxn] ; struct Node{ int x,order ;}node[maxn]; bool cmp(const Node &A ,const Node &B){ return A.x < B.x ;} int lowbit(int x){ return x&(-x) ;} void update(int t , int x){ int i ; for(i = t;i <= n;i += lowbit(i)){ c[i] += x ; }} int getsum(int x){ int i ,sum = 0 ; for(i = x;i > 0;i -= lowbit(i)){ sum += c[i] ; } return sum ;} int main(){ int i ; while(scanf("%d",&n) != EOF){ memset(c , 0 , sizeof(c)) ; for (i = 1;i <= n;i++){ scanf("%d",&node[i].x) ; node[i].order = i ; } sort(node + 1 , node + 1 + n , cmp) ; for(i = 1;i <= n;i++) x[node[i].order] = i ; LL sum = 0 ; for(i = 1;i <= n;i++){ update(x[i] , 1) ; sum += (i - getsum(x[i])) ; } cout << sum << endl ; } return 0;} /************************************************************** Problem: 1348 Language: C++ Result: Wrong Answer****************************************************************/
0 0
- 1348:数组中的逆序对(树状数组 or 归并)
- 逆序对(树状数组/归并)
- POJ_3067 Japan[ 逆序数 树状数组 or 归并排序)
- 数组中的逆序对(归并排序)
- poj 2299(逆序对(树状数组||归并排序))
- ural1090 逆序对(归并排序和树状数组)
- poj 2299 树状数组+离散化 or 归并排序 求逆序对
- poj 2299 Ultra-QuickSort 【线段树 or 线段树+lazy or 树状数组 or 归并排序】 求逆序对
- hdoj 1394 Minimum Inversion Number 【线段树 or 线段树lazy or 树状数组 or 归并排序】【逆序对】
- 【树状数组or归并排序求逆序数】HDU 1394
- 归并排序求数组中的逆序对
- 归并排序-数组中的逆序对
- 数组中的逆序对(归并排序)
- 树状数组逆序对
- 九度OJ 1348 数组中的逆序对 -- 归并排序
- 数组中的逆序对(归并排序+剑指offer)
- 数组中的逆序对(归并的思想)
- 数组中的逆序对(归并排序思想解题)
- POJ训练计划3422_Kaka's Matrix Travels(网络流/费用流)
- TIME_WAIT
- hdoj.1391 Number Steps 20140821
- 浏览器、apache的连接超时详解
- EL表达式
- 1348:数组中的逆序对(树状数组 or 归并)
- 淘宝海量数据产品技术架构
- 用 GDB 调试程序---很全面,我觉得可以叫GDB大全了
- IO流中字节流的应用
- HDU 1181 变形记 (BFS)
- 老农猫、狗、鱼过河问题 黑马测试题,个人的解答.靠程序搜索答案 只给判断条件,无人为辅助判断
- Container With Most Water
- SQL Server -为代码减负之触发器
- 跨服务器修改数据