题目
题目是听朋友叙述的,特地记录下来,以备日后参考。
有n个按编号连续的罪犯(不可排序),管理者想将他们从C监狱转移到D监狱, 每次转连续的移c个罪犯,要求这c个罪犯的罪行值之和不能超过t;
现在给定,罪犯个数n,给定他们的罪行值w[] , 给定每次转移的个数c , 给定每次转移罪行值上限; 求转移次数?
分析
计算一个序列中有几个满足要求的子序列问题!
一次遍历即可!
程序
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;
int fun(int w[], int n ,int t, int c)
{
int count = 0;
for (int i = 0; i < n - c + 1; i++)
{
if (w[i] >= t)
continue;
int sum = 0;
for (int j = i; j < i + c; j++)
{
sum += w[j];
}//for
//满足罪行值条件
if (sum <= t)
count++;
}//for
return count;
}
int main()
{
int w[] = { 2, 2, 0, 7, 3, 2, 2, 4, 9, 1, 4 };
int n = 11;
int t = 4;
int c = 3;
cout << fun(w, n, t, c) << endl;
system("pause");
return 0;
}