Introduction to the Blue Bridge Cup

Example 1

The analysis shows that the numbers of briquettes in each layer are:

1

1 + 2

1 + 2 + 3

1 + 2 + 3 + 4

...

Here is the code I wrote at the beginning:

#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;
}

 But obviously, the time complexity will be very high if you do this. Here is the code with a relatively low complexity for a period of time:

 The results of both codes are 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;
}

 

 

 

Example 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;
}

 

The focus of this question is to find out the relationship between spaces, strings and number of lines

 

 

Example 3

 

 

 

About the syntax of string splicing 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;
}

 

After the character array is defined globally, the output format is normal

#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;
}

 

Guess you like

Origin blog.csdn.net/smallrain6/article/details/106234408