Title Description
In the past days, the farmer John's cow had no problem. But now they have a problem and a lot of questions. To be precise, they have P (1 <= P <= 300) The topic to be done. They also left the farm and found jobs like ordinary people. Their monthly salary is m (1 <= m <= 1000) yuan. Their title is a first-class problem, so they have to find help. The helpers are not free, but they can guarantee that they will do anything within one months. Each problem requires two payments, the first a_i (1 <= a_i <= M The yuan was paid at the beginning of the one months of the title, and the second b_i yuan (1 <= b_i <= M) was paid at the start of the next month after it was done. Every one months the Bulls pay with one months ' worth of money. Cows do not have any sense of deposit, so every month's savings are taken back to buy sugar to eat. Because the topics are interrelated, they must be solved in the approximate order. For example, topic 3 must be solved before the solution topic 4 or the same one months. Find out the minimum number of months that the cows have finished all the questions and paid all the money.
Input
* First line: N and P
* 2nd ... P+1 Line: Line I contains a_i and b_i, respectively, is to do the first question of the desire to pay and complete payment.
Output
* First line: The minimum number of months for the cows to finish the topic and pay the bill
Sample input
100 5
40 20
60 20
30 50
30 50
40 40
Sample output
6
Tips
Dynamic programming. At first sight this question thought is greedy. But greed is wrong, there is data 50 5 40 10 10 40 10 5 10 3 10 2 as a counter-example then think of dynamic planning. Set F[I][J] For a one-time election [I,j] within the title, and after the election of the month does not select the minimum number of other questions. Then the F[j][i]=min (f[k][j-1]+2) and F[j][i]=min (f[k][j-1]+1) can be introduced (condition: [K, J-1] the remainder of the next month is enough to select [J, I]) so the prefix and the interval and the time complexity of the compression to O (p^3), AC
1#include <cstdio>2#include <cstring>3#include <algorithm>4 #defineINF 0x3f3f3f3f5 using namespacestd;6 intf[302][302], a[302], b[302], suma[302], sumb[302];7 intMain ()8 {9 intN, p, I, J, k, ans =inf;Tenscanf"%d%d", &n, &p); One for(i =2; I <= p +1; i + + ) A { -scanf"%d%d", &a[i], &b[i]); -Suma[i] = suma[i-1] +A[i]; theSumb[i] = sumb[i-1] +B[i]; - } -Memset (F,0x3f,sizeof(f)); -f[1][1] =1; + for(i =2; I <= p +1; i + + ) - { + for(j =2; J <= I; J + + ) A { at for(k =1; K < J; K + + ) - { - if(F[k][j-1]! = INF && sumb[j-1]-Sumb[k-1] <=N) - { - if(n >= suma[i]-suma[j-1]) -F[j][i] = min (F[j][i], f[k][j-1] +2); in if(N-(Sumb[j-1]-Sumb[k-1]) >= Suma[i]-suma[j-1]) -F[j][i] = min (F[j][i], f[k][j-1] +1); to } + } - } the } * for(i =2; I <= p +1; i + + ) $ if(Sumb[p +1]-Sumb[i-1] <=N)Panax Notoginsengans = min (ans, f[i][p +1] +1); -printf"%d\n", ans); the return 0; +}
"bzoj1700" Problem solving problem solving