题目:给出两个自然数N和n,找到一组连续的自然数,其长度大于等于n,其和等于N。
输入:N(空格)n
输出:自然数列,每个数之间有空格,最后一个数后无空格 | 没有答案则输出:No answer
解答:
1 #include <iostream> 2 #include <vector> 3 using std::cout; using std::endl; using std::cin; 4 using std::vector; 5 6 int main() { 7 8 int N, n, sum = 0; //sum为总和 9 vector<int> answer; //答案以vector形式保存,因为不确定会有多少 10 cin >> N >> n; //输入参数 11 for (auto i = 1; i <= N/2; i++) //遍历1到N/2,考虑到(N/2)+(N/2)+1 > N 12 { 13 for (auto j = i; sum < N ; j++) //从i开始遍历,直到数列和不小于N 14 { 15 sum += j; 16 answer.push_back(j); 17 } 18 if (sum == N && ((answer.end() - answer.begin()) > n)) //如果sum等于N,并且answer长度大于n 19 { 20 for (auto beg = answer.begin(); beg != answer.end();beg++) //输出answer 21 { 22 cout << *beg; 23 if (beg+1 != answer.end()) 24 { 25 cout << " "; 26 } 27 } 28 break; 29 } 30 else //如果sum不等于N或者answer长度小于等于n 31 { 32 answer = {}; //清空答案,sum清零 33 sum = 0; 34 } 35 } 36 if (answer.begin() == answer.end()) //如果answer为空,没有答案 37 { 38 cout << "No answer" << endl; 39 } 40 }
第二版
1 #include <iostream> 2 #include <vector> 3 using std::cout; using std::endl; using std::cin; 4 using std::vector; 5 6 int main() { 7 8 int N, n, sum = 0; 9 vector<int> answer; 10 cin >> N >> n; 11 for (auto i = 1; i <= N/n; i++) //数学改进,n(N/n) + n-1 > n 12 { 13 for (auto j = i; sum < N ; j++) 14 { 15 sum += j; 16 answer.push_back(j); 17 } 18 if (sum == N && (answer.size() > n)) //刚才脑残了,把size忘了 19 { 20 for (auto beg = answer.begin(); beg != answer.end();beg++) 21 { 22 cout << *beg; 23 if (beg+1 != answer.end()) 24 { 25 cout << " "; 26 } 27 } 28 break; 29 } 30 else 31 { 32 answer = {}; 33 sum = 0; 34 } 35 } 36 if (answer.begin() == answer.end()) 37 { 38 cout << "No answer" << endl; 39 } 40 }
时间: 2024-10-11 22:58:42