今天上午还是做树状数组专题,有一道动态规划+树状数组的题目,可能是好久没做动态规划的题目了,状态转移方程一直没理解~~~话不多说,看看让我痛苦了一上午的题:
题意:给定一个长度为n(n <= 100000)的整数序列,求其中的非降子序列的个数。
分析:如果n的值比较小,那么就是一个纯粹的dp题。设dp[i]表示以a[i]为结尾非降子序列的个数,其状态转移方程为:
可以看出,这样做的时间复杂度是,很显然不能这样做。
那么实际上,我们看到会想到逆序数,自然也会想到求逆序数最经典的做法就是树状数组,所以问题可以转化为求逆序数的对数,那么我们可以利用dp的思想递推下去,最终求得答案,可以看出这样做的时间复杂度为。
1. #include
2. #include
3. #include
4. #include
5.
6. using namespace std;
7. const int N = 100005;
8. const int MOD = 1000000007;
9.
10.struct node
11.{
12. int id,val;
13.};
14.
15.int n;
16.node a[N];
17.int aa[N],c[N],t[N];
18.
19.bool cmp(node a,node b)
20.{
21. return a.val < b.val;
22.}
23.
24.int Lowbit(int x)
25.{
26. return x & (-x);
27.}
28.
29.void Update(int t,int val)
30.{
31. for(int i=t; i<=n; i+=Lowbit(i))
32. {
33. c[i] += val;
34. c[i] %= MOD;
35. }
36.}
37.
38.int getSum(int x)
39.{
40. int ans = 0;
41. for(int i=x; i>0; i-=Lowbit(i))
42. {
43. ans += c[i];
44. ans %= MOD;
45. }
46. return ans;
47.}
48.
49.
50.int main()
51.{
52. while(scanf("%d",&n)!=EOF)
53. {
54. memset(c,0,sizeof(c));
55. memset(aa,0,sizeof(aa));
56. for(int i=1;i<=n;i++)
57. {
58. scanf("%d",&a[i].val);
59. a[i].id = i;
60. }
61. sort(a+1,a+n+1,cmp);
62. aa[a[1].id] = 1;
63. for(int i=2;i<=n;i++)
64. {
65. if(a[i].val != a[i-1].val)
66. aa[a[i].id] = i;
67. else
68. aa[a[i].id] = aa[a[i-1].id];
69. }
70. for(int i=1;i<=n;i++)
71. {
72. t[i] = getSum(aa[i]);
73. Update(aa[i],t[i]+1);
74. }
75. printf("%d\n",getSum(n));
76. }
77. return 0;
78.}
下午是团队练习赛,我自己一个人做了一道二维费用的背包问题,还是看看这道题,感觉题目还是挺好的:
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 2900 | Accepted: 1146 |
Description
The cows are building a roller coaster! They want your help to design as fun a roller coaster as possible, while keeping to the budget.
The roller coaster will be built on a long linear stretch of land of length L (1 ≤ L ≤ 1,000). The roller coaster comprises a collection of some of the N (1 ≤ N ≤ 10,000) different interchangable components. Each component i has a fixed length Wi (1 ≤ Wi ≤ L). Due to varying terrain, each component i can be only built starting at location Xi (0 ≤ Xi ≤ L - Wi). The cows want to string together various roller coaster components starting at 0 and ending at L so that the end of each component (except the last) is the start of the next component.
Each component i has a "fun rating" Fi (1 ≤ Fi ≤ 1,000,000) and a cost Ci (1 ≤ Ci ≤ 1000). The total fun of the roller coster is the sum of the fun from each component used; the total cost is likewise the sum of the costs of each component used. The cows' total budget is B (1 ≤ B ≤ 1000). Help the cows determine the most fun roller coaster that they can build with their budget.
Input
Output
Sample Input
5 6 10 0 2 20 6 2 3 5 6 0 1 2 1 1 1 1 3 1 2 5 4 3 2 10 2
Sample Output
17
Hint