题解 AT2281 【[ABC051B] Sum of Three Integers】
遇到这种题目,尽管是红题,但也要注意复杂度,O()是过不去的。
那么我们先想想有没有O()的方法。如果已经循环了两层,那么第三层的数加上去要为s,那么第三层的数不就是:
s - 第一层 - 第二层
那么就不用第3层循环了
代码如下:
#include <iostream>
using namespace std;
int main()
{
int k, s, ans = 0;
cin >> k >> s;
for(register int i = 0; i <= k; i++)
{
for(register int j = 0; j <= k; j++)
{
if(s - i - j <= k && s - i - j >= 0) //注意判断越界
{
ans++;
}
}
}
cout << ans << endl;
return 0;
}