Books:
题目大意:(文末有原题)
给出n个整数,第i个数代表看第i本书所需时间,给出总时间t,从i本书开始看,直到时间用完,或者看到最后一本书(看完最后一本书如果还有时间不会再去看第一本);求最多能够看几本书;
思路:(代码②是直接暴力二重循环,会TLE)
其实是求最多有几个连续数的和小于t;
从第i本开始看,如果看到第x本时间超过t,则把第i本删去(等价于从第i+1本开始看;这样实现可以节省从i+1加到x的运行时间),再去加上第x本,如果仍然超过t,就继续删第i+2本,直到x=n;并且如果在t之内,每次都与max比较,取最大;
代码①:
#include <iostream> using namespace std; const int maxn = 1e5 + 10; int a[maxn]; int main() { int n, t; cin >> n >> t; for(int i = 0; i < n; i++) cin >> a[i]; int j = 0, i = 0, max = 0, s = 0, b = 0; while(j != n) { if(s + a[j] <= t) { //用j记录当前位置; b++; s += a[j++]; if(b > max) max = b; }else { b--; //要记住看书的数量也要减少; s -= a[i++]; //用i记录起始位置; } } cout << max << endl; return 0; }
代码②:
TLE on test 9 #include <iostream> using namespace std; const int maxn = 1e5 + 10; int a[maxn]; int main() { int n, t, max = 0; cin >> n >> t; for(int i = 0; i < n; i++) { cin >> a[i]; } for(int i = 0; i < n; i++) { int s = 0, b = 0; for(int j = 0; j < n; j++) { int x = i + j; if(x >= n) break; if(s + a[x] <= t) { b++; s += a[x]; }else { break; } } if(b > max) { max = b; } } cout << max << endl; return 0; }
原题:
题目:
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.
Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
输入:
The first line contains two integers n and t (1 ≤ n ≤ 105; 1 ≤ t ≤ 109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 104), where number ai shows the number of minutes that the boy needs to read the i-th book.
输出:
Print a single integer — the maximum number of books Valera can read.
样例:
Input:
4 5
3 1 2 1Output:
3
Input:
3 3
2 2 3Output:
1