7-2 How Many Ways to Buy a Piece of Land (25分)
The land is for sale in CyberCity, and is divided into several pieces. Here it is assumed that each piece of land has exactly two neighboring pieces, except the first and the last that have only one. One can buy several contiguous(连续的) pieces at a time. Now given the list of prices of the land pieces, your job is to tell a customer in how many different ways that he/she can buy with a certain amount of money.
Input Specification:
Each input file contains one test case. Each case first gives in a line two positive integers: N (≤104), the number of pieces of the land (hence the land pieces are numbered from 1 to N in order), and M (≤109), the amount of money that your customer has.
Then in the next line, N positive integers are given, where the i-th one is the price of the i-th piece of the land.
It is guaranteed that the total price of the land is no more than 109.
Output Specification:
For each test case, print the number of different ways that your customer can buy. Notice that the pieces must be contiguous.
Sample Input:
5 85
38 42 15 24 9
Sample Output:
11
Hint:
The 11 different ways are:
38
42
15
24
9
38 42
42 15
42 15 24
15 24
15 24 9
24 9
题目限制:
题目大意:
现有N块土地,总预算为M元,请问购买多少一连串的土地。
算法思路:
题目的提示很明显了,其实就是该数字串中的子串和有多少个是小于等于M的,那么我们使用price数组保存每一块土地的价格,然后遍历每一块土地作为一连串土地的起点,使用total_price保存当期土地price[i]作为起点的价格部分和,只要不大于M,那么就说明当前的数字子串为一种解,然后累加后面一块土地的价格,最终输出最终解决方案即可
提交结果:
AC代码:
#include<cstdio>
using namespace std;
int N,M;// 土地块数,总预算
int price[10005];
int main(){
scanf("%d %d",&N,&M);
for (int i = 0; i < N; ++i) {
scanf("%d",&price[i]);
}
int ways = 0;
for(int i=0;i<N;++i){// 每一块土地作为起点
if(price[i]>M) continue;
int total_price = price[i];
++ways;
for(int j=i+1;j<N;++j){
total_price += price[j];
if(total_price>M) break;
++ways;
}
}
printf("%d",ways);
return 0;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。