蓝桥杯入门例题

例1

分析得到,各层煤球的个数分别为:

1

1 + 2

1 + 2 + 3

1 + 2 + 3 + 4

...

下面是本人自己一开始写的代码:

#include<iostream>
using namespace std;
int main()
{
    int ans = 0;
    for (int i = 1;i <= 100;i++)
    {
        for (int j = 1;j <= i;j++)
        {
            ans += j;
        }
    }
    cout << ans << endl;
}

 但是很明显,这样做的话时间复杂度会很高,下面是一段时间复杂度较低的代码:

 两种代码结果均为171700

#include<iostream>
using namespace std;
int main()
{
    int sum = 0,tmp = 0;
    for (int i = 1;i <= 100;i++)
    {
        tmp += i;
        sum += tmp;
    }
    cout << sum << endl;
    return 0;
}

 

例2

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
    int n;
    cin >> n;
    //n表示行数
    for (int i = 1;i <= n;i++)
    {
        //space = string(n,s)表示space由n个字符串s组成
        //space表示空格,ch表示字符串
        string space = string(n - i,' ');
        string ch = string(2 * i - 1,'A' + i - 1);
        cout << space + ch << endl;
    }
    return 0;
}

 

本题的重点是要找出空格、字符串和行数的关系

例3

关于字符串拼接strcat的语法:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int main()
{
    char res[30];
    char *str1 = "hello",*str2 = " ",*str3 = "world";
    strcat(res,str1);
    strcat(res,str2);
    strcat(res,str3);
    cout << res << endl;
    printf("%s\n",res);
    return 0;
}

 

将字符数组定义在全局之后,输出格式就正常了

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;


char res[30];

int main()
{
    char *str1 = "hello",*str2 = " ",*str3 = "world";
    strcat(res,str1);
    strcat(res,str2);
    strcat(res,str3);
    cout << res << endl;
    printf("%s\n",res);
    return 0;
}

 

猜你喜欢

转载自blog.csdn.net/smallrain6/article/details/106234408