题目如下:
输出结果如下:
上述题目看起来需要用到动态规划的知识。 采用动态规划设计算法的话, 算法的时间复杂度估计是很有效的。 但是由于本人对动态规划的理解还处于探索阶段, 所以没有用。 而是选择了一个时间复杂度为O(n^3), 空间复杂度为O(1)简单地算法。步骤如下:
(1)排好序
(2)需要三个指针, 一个指向mid, 一个指向mid 的左边high, 一个指向mid 的右边low。 high 被初始化为mid + 1, low 被初始化为mid.
(3) 固定mid 在一个fixed value, 为 第二个元素(mid 的移动空间为第二个元素到倒数第二个元素)。
(4)对于每一个固定的元素, 开始对low 循环, 循环的范围为mid到第一个元素。
(4)对于每一个固定的low, 都需要对high 进行循环, 大于MAX, 计数就加一。
(5)直至所有的循环结束。
首先, 输入我是存放在D:\\sample.txt 文件夹下面:
程序如下:
在code::blocks 下创建工程文件, 主程序文件如下:
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
void Count(vector<int> &myVec, int &Total, int Max);
int main()
{
int number;
string filePath;
int numberOfInstances;
int Max;
int Rings;
cout << "please input your file path: " ; //ie, D:\\sample
cin >> filePath;
ifstream fin;
fin.open(filePath.c_str());
if(fin.fail()) {
cout << "sorry, fail to open" << endl;
exit(1);
}
fin >> numberOfInstances;
vector<int> vect1;
for(int i = 0; i < numberOfInstances; i++) {
fin >> Rings;
fin >> Max;
for(int i = 0; i < Rings; i++) {
fin >> number;
vect1.push_back(number);
}
int totalCount = 0;
Count(vect1, totalCount, Max);
cout << totalCount << endl;
vect1.clear();
}
fin.close();
return 0;
}
void Count(vector<int> &myVec, int & Total, int Max) {
sort(myVec.begin(), myVec.end());
vector<int>::iterator mid;
vector<int>::iterator low;
vector<int>::iterator high;
for(mid = myVec.begin() + 1; mid != myVec.end() -1 ; mid++) {
high = mid + 1; // ie, high is always in the right of mid
low = mid;
while(low != myVec.begin()) {
low--;
for(high = mid + 1; high != myVec.end(); high++) {
if(*low + *mid + *high >= Max) {
Total++;
}
}
}
}
}
运行结果如下: