HDU2227
来源:互联网 发布:淘宝换购活动怎么设置 编辑:程序博客网 时间:2024/06/07 12:22
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=2227
O(n^2)的算法:f[i]表示a[1]~a[i]中包含a[i]的递增序列的个数。f[i]=∑f[j](j<i,a[i]>a[j])+1。所求结果即为∑f[i]。
这样处理会超时。需要用树状数组进行优化。
用类似树状数组求逆序对的个数的方法。
需要离散化。先将数组a进行排序,按数据a[i]的大小依次处理更新f[i]的值。再将f[i]的值累加起来,即为结果。
特别注意的一点是,algorithm里的sort函数是不稳定的,一开始做的时候WA了好多次,生成了好多组数据对拍才找到错误所在。
可通过cmp函数将sort改为稳定的排序算法。详见代码。
代码:
#include <cstdio>#include <iostream>#include <algorithm>#include <cstring>#include <cstdlib>using namespace std;const int maxn=1e5+10;const int mod=1000000007;int n;int a[maxn];int r[maxn];int tree[maxn];int lb(int x){return x&-x;}int read(int x){int tot=0;for(int i=x;i;i-=lb(i)){tot+=tree[i];tot%=mod;}return tot;}void add(int num,int x){for(int i=x;i<=n;i+=lb(i)){tree[i]+=num;tree[i]%=mod;}}const int cmp(const int i,const int j){return a[i]==a[j]?i<j:a[i]<a[j];}//将sort改为稳定的函数int main(){ios::sync_with_stdio(0);cin.tie(0);while(cin>>n){memset(a,0,sizeof(a));memset(tree,0,sizeof(tree));for(int i=1;i<=n;i++)cin>>a[i];for(int i=1;i<=n;i++)r[i]=i;sort(r+1,r+1+n,cmp);//排序后,r[i]即为第i大的数所处的位置for(int i=1;i<=n;i++){int x=r[i];int tot=0;tot+=read(x);tot++;tot%=mod;add(tot,x);}cout<<read(n)<<endl;}return 0;}
阅读全文
0 0
- HDU2227
- HDU2227:Find the nondecreasing subsequences
- HDU2227(非降子序列的个数)
- 树状数组专题(十二)之hdu2227
- 树状数组 hdu2227 Find the nondecreasing subsequences
- HDU2227(Find the nondecreasing subsequences)
- HDU2227非递减子序列(树状数组)
- HDU2227 - Find the nondecreasing subsequences(线段树优化DP)
- hdu2227---Find the nondecreasing subsequences(dp+树状数组)
- HDU2227 Find the nondecreasing subsequences(树状数组+DP+离散化)
- hdu2227 Find the nondecreasing subsequences(dp+线段树or树状数组优化)
- oracle常用命令(11g)
- java使用反射机制进行对象间数据赋值获取
- NIO中的File文件操作
- java递归查询分类及分类下所有子分类
- HIVE—索引、分区和分桶的区别
- HDU2227
- java 异步 同步应用
- 滴滴打车2017年秋招笔试题-输出指定的最大数
- noi国家集训队论文分类
- vim常用命令总结
- C++ 将数据写入链表,将链表写入文件,再将文件中的内容读出
- 使用node-supervisor自动重启node程序
- 滴滴打车2017年秋招编程题:子串和最大问题
- 你真的懂JAVA吗