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.算法
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.ide
It is guaranteed that the total price of the land is no more than 109.spa
For each test case, print the number of different ways that your customer can buy. Notice that the pieces must be contiguous.code
5 85 38 42 15 24 9
11
The 11 different ways are:blog
38 42 15 24 9 38 42 42 15 42 15 24 15 24 15 24 9 24 9
現有N塊土地,總預算爲M元,請問購買多少一連串的土地。ci
題目的提示很明顯了,其實就是該數字串中的子串和有多少個是小於等於M的,那麼咱們使用price數組保存每一塊土地的價格,而後遍歷每一塊土地做爲一連串土地的起點,使用total_price保存當期土地price[i]做爲起點的價格部分和,只要不大於M,那麼就說明當前的數字子串爲一種解,而後累加後面一塊土地的價格,最終輸出最終解決方案便可input
#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; }