NOIP2015普及组金币

NOIP2015普及组金币

题目数据 (n <= 10000)

根据题目要求与我们原来学过的打印数字三角形图形很相似。

数字三角形如下,数字可以对应成天数:

1

2   3

4   5   6

7   8   9   10

每天加的金币就是行坐标即可:

1

2   2

3   3   3

4   4   4   4

代码如何:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int n;
    cin >> n;
    int s = 0, cnt = 0;//cnt记作天数
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= i; j++)
        {
            s += i;
            ++cnt;
            if (cnt == n)
            {
                cout << s << endl;
                return 0;
            }
        }
    }
    return 0;
}

题目虽然是双重循环,但算法复杂度依旧是:O(N)。

用数学方法做:O(1)
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int t, n;
    cin >> n;
    t = 0;
    while (t * (t + 1) <= 2 * n)
        t++;
    t--;
    int sum = (2 * t + 1) * (1 + t) * t / 6;
    n = n - t * (t + 1) / 2;
    int ans = sum + n * (t + 1);
    cout << ans << endl;
    return 0;
}

 

posted @ 2023-12-07 09:49  陆留生信奥艺术  阅读(56)  评论(0)    收藏  举报