hdu 2227(树状数组优化dp)

来源:互联网 发布:mac怎么安装第三方软件 编辑:程序博客网 时间:2024/05/19 10:35

Find the nondecreasing subsequences

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Problem Description
How many nondecreasing subsequences can you find in the sequence S = {s1, s2, s3, ...., sn} ? For example, we assume that S = {1, 2, 3}, and you can find seven nondecreasing subsequences, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}.
 

Input
The input consists of multiple test cases. Each case begins with a line containing a positive integer n that is the length of the sequence S, the next line contains n integers {s1, s2, s3, ...., sn}, 1 <= n <= 100000, 0 <= si <= 2^31.
 

Output
For each test case, output one line containing the number of nondecreasing subsequences you can find from the sequence S, the answer should % 1000000007.
 

Sample Input
31 2 3
 

Sample Output
7
 
解题思路:dp[i]表示前i个数里面非递增子序列个数,则dp[i] = sum{dp[k]} + 1,a[k] <= a[i],+1表示自己单独也是一个非递增序列。O(n²)超时,这里需要用树状数组优化它。具体的做法就不多说了,前面做过几个了。排序,离散化即可。
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<set>#include<map>using namespace std;const int maxn = 100005;const int mod = 1e9+7;int n,tree[maxn<<1],a[maxn],dp[maxn];set<int> Set;map<int,int> Map;int lowbit(int x){return x & -x;}void update(int x,int c){for(int i = x; i <= n; i += lowbit(i))tree[i]  = (tree[i] + c) % mod;}int getsum(int x){int sum = 0;for(int i = x; i > 0; i -= lowbit(i))sum = (sum + tree[i]) % mod;return sum;}int main(){while(scanf("%d",&n)!=EOF){Set.clear();Map.clear();for(int i = 1; i <= n; i++){scanf("%d",&a[i]);Set.insert(a[i]);}int cnt = 0;for(set<int>::iterator it = Set.begin(); it != Set.end(); it++)Map[*it] = ++cnt; memset(tree,0,sizeof(tree));int ans = 0;for(int i = 1; i <= n; i++){int tmp = getsum(Map[a[i]]);dp[i] = (tmp + 1) % mod;update(Map[a[i]],dp[i]);}for(int i = 1; i <= n; i++)ans = (ans + dp[i]) % mod;printf("%d\n",ans);}return 0;}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 中铁快运职工拒绝提货要怎么办 奇瑞a3暖风水箱爆了怎么办 别人挖鱼塘占了我的山土怎么办 自己的鱼塘让别人强行占住了怎么办 公路扩路占地占了鱼塘怎么办? 玉米皮编垫子编好后玉米绳怎么办 入户门门框未预留纱窗位怎么办 门和墙有2cm缝隙怎么办 支座预埋钢板忘记埋了怎么办 做完线雕一边紧一边松怎么办 卖家把没发货的填写了单号怎么办 买的人民币白银亏了好多钱怎么办 带控制线的三相四线开关怎么办 覆膜除尘布袋风拉不动怎么办 家里装修把暖气管道打破了怎么办 冷水管与热水管接错了怎么办 磨砂皮的鞋子打湿变硬了怎么办 等离子淡化热处理层渗不够厚怎么办 寄快递快递公司把东西弄坏了怎么办 寄美国的快递客人拒绝清关怎么办 国际e邮宝几天没物流信息了怎么办 石家庄小学网上报名填错了怎么办 去医院看病不知道挂什么科怎么办 深水井深水泵埋了2米怎么办 请问我捡的手机不是我的指纹怎么办 宝宝把塑料子弹塞到了鼻子里怎么办 坐便池上面的小孔不出水怎么办 还没离职已经找好工作怎么办 因火车晚点而耽误下趟火车怎么办 在广州坐的士丢了东西怎么办 找兼职的话他要求交押金怎么办 08vip不给提现了怎么办 点击订阅号所收到内容字太大怎么办 我的小叶栀子花老是黄叶该怎么办? 联币金融倒闭了我投资的钱怎么办 新单位交养老保险不接收档案怎么办 高铁发车十小时没赶上怎么办 饿了么被阿里收购员工怎么办? 爱疯4s密码忘了怎么办 研究生论文盲审一直不出结果怎么办 查重报告有疑似剽窃观点怎么办