Analysis of C/C++ (Level 2) real questions in September 2020#China Electronics Society#National Youth Software Programming Level Examination

Insert image description here

C/C++ Programming (Levels 1~8) All real questions・Click here

Question 1: Cycle number

An n-digit number string is called a cyclic number if it satisfies the following conditions: treat the number string as an integer (possibly with leading 0), and use any number between 1 and n (including 1 and n ) is multiplied by an integer, you will get an integer corresponding to the new number string obtained by connecting the original number string end to end and then breaking it somewhere. For example, the number 142857 is a cyclic number
because:
142857 *1 = 142857
142857 *2 = 285714
142857 *3 = 428571
142857 *4 = 571428
142857 *5 = 714285
142857 *6 = 857142.
Please write a program to determine whether a given number is a cyclic number.
Note: In this question, the input numeric string is allowed to have leading 0s, and the leading 0s cannot be ignored. For example, "01" is a two-digit string, and "1" is a one-digit string. However, when converting a numeric string into an integer for multiplication or comparison operations, the leading 0 can be ignored.
Time limit: 10000
Memory limit: 65536
Input
One line, a numeric string between 2 and 60 digits in length.
Output
an integer. If the input number string is a cyclic number, output 1, otherwise output 0.
sample input
142857
sample output
1

You can write a program in C language to determine whether a given number is a cyclic number. Here is sample code:

#include <stdio.h>
#include <string.h>

int isCyclicNumber(const char* num) {
    
    
    int n = strlen(num);
    char concatenated[2 * n + 1]; // 存储首尾相接的新数字串
    int i, j;

    for (i = 1; i <= n; i++) {
    
    
        // 将原数字串首尾相接拼接成新数字串
        strncpy(concatenated, num + i - 1, n - i + 1);
        strncpy(concatenated + n - i + 1, num, i);
        concatenated[2 * n] = '\0';

        // 将新数字串转化为整数并与原数字串进行比较
        int original = atoi(num);
        int multiplied = atoi(concatenated);
        if (original * i != multiplied) {
    
    
            return 0; // 不满足循环数条件,返回0
        }
    }

    return 1; // 满足循环数条件,返回1
}

int main() {
    
    
    char num[61]; // 数字串最大长度为60
    scanf("%s", num);

    int result = isCyclicNumber(num);

    printf("%d\n", result);

    return 0;
}

In the main function, we declare the character array num to store the input numeric string.

Next, we define an auxiliary function isCyclicNumberto determine whether a given number is a cyclic number. The parameter of the function is a pointer to a character array.

Inside the function, we first obtain the length n of the number string and declare a new character array concatenatedto store the new number string connected end to end.

Then, we use a loop to concatenate the new number string from 1 to n and convert it into an integer.

In each loop, we concatenate the original number string end to end into a new number string and convert it into an integer. We then compare the original number to this integer. If they are not equal, it means that the cycle number condition is not met and 0 is returned.

If the loop number condition is met after the loop ends, 1 is returned.

Finally, in the main function, we call isCyclicNumberthe function, pass in the input number string as a parameter, get the judgment result, and output it.

You can save the above code as a .c file, compile and run it using a C language compiler, and input a number string to get the output of the judgment result.

Question 2: Photo effect

Xiaoyun and her friends went to climb Xiangshan Mountain. They were intoxicated by the beautiful scenery and wanted to take a group photo. If they stand in a row, the boys are all on the left (from the perspective of the photographer), and arranged from left to right in order from short to tall, and the girls are all on the right, and arranged in order from tall to short, from left to right. , what is the effect of their group photo (all people have different heights)?
Time limit: 1000
Memory limit: 65536
input
The first line is the number of people n (2 <= n <= 40, and there is at least 1 boy and 1 girl). Followed by n lines, each line enters a person's gender (male or female) and height (floating point number, in meters), and the two data are separated by a space.
Output
n floating point numbers to simulate the height of each person from left to right in the eyes of the photographer after standing in line. Each floating point number must be retained to 2 decimal places, and two adjacent numbers should be separated by a single space.
Sample input
6
male 1.72
male 1.78
female 1.61
male 1.65
female 1.70
female 1.56
Sample output
1.65 1.72 1.78 1.70 1.61 1.56

You can use C language to write a program to simulate the effect of Xiaoyun taking a photo with his friends. Here is sample code:

#include <stdio.h>
#include <string.h>

typedef struct {
    
    
    char gender[10]; // 性别
    float height; // 身高
} Person;

int compareHeight(const void* a, const void* b) {
    
    
    const Person* personA = (const Person*)a;
    const Person* personB = (const Person*)b;

    if (strcmp(personA->gender, "male") == 0 && strcmp(personB->gender, "female") == 0) {
    
    
        return -1; // 男生排在前面
    } else if (strcmp(personA->gender, "female") == 0 && strcmp(personB->gender, "male") == 0) {
    
    
        return 1; // 女生排在后面
    } else if (personA->height < personB->height) {
    
    
        return -1; // 身高矮的排在前面
    } else if (personA->height > personB->height) {
    
    
        return 1; // 身高高的排在后面
    } else {
    
    
        return 0; // 身高相同,保持原有顺序
    }
}

int main() {
    
    
    int n;
    scanf("%d", &n);

    Person people[n];
    int i;

    for (i = 0; i < n; i++) {
    
    
        scanf("%s %f", people[i].gender, &people[i].height);
    }

    qsort(people, n, sizeof(Person), compareHeight);

    for (i = 0; i < n; i++) {
    
    
        printf("%.2f ", people[i].height);
    }
    printf("\n");

    return 0;
}

In the program, we first define a structure Personto represent a person's gender and height.

Then, we define a helper function compareHeightto compare the height of two people. In the comparison process, we first determine the gender, with boys ranking in front and girls in the back. If two people are of the same gender, their heights are compared, and the shorter person is ranked in front and the taller person is ranked in the back. If two people have the same gender and height, the original order is maintained.

In the main function, we first read the input number n, and declare an Personarray of size n to store the information of each person.

Then we use a loop to read each person's gender and height one by one and store it in an array.

Next, we qsortsort the array using a function that uses the previously defined compareHeightfunction as the sorting rule.

Finally, we use a loop to output the sorted height of each person, with two decimal places and a single space between adjacent numbers.

You can save the above code as a .c file, compile and run it with a C language compiler, and input the number of people and the gender and height of each person as required to get the output result that simulates the effect of a group photo.

Question 3: Addition of large integers

Find the sum of two non-negative integers with no more than 200 digits.
Time limit: 1000
Memory limit: 65536
input
There are two lines, each line is a non-negative integer of no more than 200 digits, possibly with extra leading 0s.
Output
one line, which is the result of the addition. There cannot be any extra leading 0s in the result, that is, if the result is 342, it cannot be output as 0342.
Sample input
22222222222222222222
33333333333333333333
Sample output
55555555555555555555

For large integer addition, you can use arrays or strings to represent and calculate. Here is sample code using strings:

#include <stdio.h>
#include <string.h>

void removeLeadingZeros(char* num) {
    
    
    int len = strlen(num);
    int i, j;

    // 找到第一个非零字符的位置
    for (i = 0; i < len; i++) {
    
    
        if (num[i] != '0') {
    
    
            break;
        }
    }

    // 移动非零字符到数组的起始位置
    for (j = 0; i < len; i++, j++) {
    
    
        num[j] = num[i];
    }

    num[j] = '\0'; // 设置新的字符串结束符
}

void reverseString(char* str) {
    
    
    int len = strlen(str);
    int i, j;

    for (i = 0, j = len - 1; i < j; i++, j--) {
    
    
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
}

void addBigIntegers(const char* num1, const char* num2, char* result) {
    
    
    int len1 = strlen(num1);
    int len2 = strlen(num2);
    int maxLength = (len1 > len2) ? len1 : len2;

    int carry = 0; // 进位
    int i;

    for (i = 0; i < maxLength; i++) {
    
    
        int digit1 = (i < len1) ? (num1[len1 - i - 1] - '0') : 0;
        int digit2 = (i < len2) ? (num2[len2 - i - 1] - '0') : 0;

        int sum = digit1 + digit2 + carry;
        result[i] = sum % 10 + '0'; // 计算当前位的数字
        carry = sum / 10; // 计算进位
    }

    if (carry > 0) {
    
    
        result[maxLength] = carry + '0'; // 添加最高位的进位
        result[maxLength + 1] = '\0';
    } else {
    
    
        result[maxLength] = '\0';
    }

    reverseString(result); // 反转字符串得到正确的结果
}

int main() {
    
    
    char num1[201]; // 存储第一个大整数
    char num2[201]; // 存储第二个大整数

    scanf("%s", num1);
    scanf("%s", num2);

    char result[202]; // 存储计算结果

    addBigIntegers(num1, num2, result);

    removeLeadingZeros(result);

    printf("%s\n", result);

    return 0;
}

In the program, we first define a series of helper functions:

  • removeLeadingZerosFunction removes leading zeros from the result.

  • reverseStringFunction used to reverse a string.

  • addBigIntegersFunction is used to calculate the sum of two large integers.

In addBigIntegersthe function, we first find the length of the input numbers and determine the longest length. We then add them bit by bit and store the result in the result string. We use carrythe variable to track carry.

Finally, we read the two input numbers in the main function and call addBigIntegersthe function to calculate their sum. We then use removeLeadingZerosthe function to remove leading zeros from the result and print the result.

You can save the above code as a .cfile, compile and run it using a C language compiler. Then, enter two non-negative integers as required to get their sum.

Question 4: Bacterial reproduction and spread

In a square petri dish with side length 9, there are m bacteria in the center. Assume that the lifespan of a bacterium is only one day, but it can reproduce 10 offspring every day, and of these 10 offspring, two are distributed in the original cell, and the rest are evenly distributed in the eight adjacent cells around it. Find the distribution of bacteria in the petri dish after n (1≤n≤4) days.
Time limit: 10000
Memory limit: 65536
Input
The input is two integers. The first integer m represents the number of bacteria in the center (2 ≤ m ≤ 30), and the second integer n represents the number of days that have passed (1 ≤ n ≤ 4 ).
Output
Output a matrix of integers with nine rows and nine columns. The integers in each row are separated by spaces. The entire matrix represents the distribution of bacteria on the petri dish after n days.
Sample Input
2 1
Sample Output
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0
0 0 0
0 0 0 0 2 2 2 0 0 0 0 0
0 2 4 2 0 0 0
0 0 0 2 2 2 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0

To solve this problem, we can use a two-dimensional array to represent the petri dish and simulate the reproduction and diffusion process of bacteria. Here is sample code to solve the problem:

#include <stdio.h>

#define SIZE 9 // 培养皿的边长

void printDish(int dish[SIZE][SIZE]) {
    
    
    for (int i = 0; i < SIZE; i++) {
    
    
        for (int j = 0; j < SIZE; j++) {
    
    
            printf("%d ", dish[i][j]);
        }
        printf("\n");
    }
}

void simulateBacteria(int dish[SIZE][SIZE], int m, int n) {
    
    
    int temp[SIZE][SIZE]; // 临时数组用于保存每一天的细菌分布情况

    // 将初始细菌分布复制到临时数组
    for (int i = 0; i < SIZE; i++) {
    
    
        for (int j = 0; j < SIZE; j++) {
    
    
            temp[i][j] = dish[i][j];
        }
    }

    // 模拟细菌的繁殖与扩散过程
    for (int day = 1; day <= n; day++) {
    
    
        // 遍历培养皿上的每个单元格
        for (int i = 0; i < SIZE; i++) {
    
    
            for (int j = 0; j < SIZE; j++) {
    
    
                // 如果当前单元格有细菌
                if (temp[i][j] > 0) {
    
    
                    // 细菌繁殖数量
                    int offspring = temp[i][j] * 10;

                    // 将两个后代细菌分布在原来的单元格
                    temp[i][j] += 2;

                    // 将剩余的细菌均匀分布在相邻的八个单元格
                    if (i > 0) {
    
    
                        temp[i - 1][j] += offspring / 8;
                    }
                    if (i < SIZE - 1) {
    
    
                        temp[i + 1][j] += offspring / 8;
                    }
                    if (j > 0) {
    
    
                        temp[i][j - 1] += offspring / 8;
                    }
                    if (j < SIZE - 1) {
    
    
                        temp[i][j + 1] += offspring / 8;
                    }
                    if (i > 0 && j > 0) {
    
    
                        temp[i - 1][j - 1] += offspring / 8;
                    }
                    if (i > 0 && j < SIZE - 1) {
    
    
                        temp[i - 1][j + 1] += offspring / 8;
                    }
                    if (i < SIZE - 1 && j > 0) {
    
    
                        temp[i + 1][j - 1] += offspring / 8;
                    }
                    if (i < SIZE - 1 && j < SIZE - 1) {
    
    
                        temp[i + 1][j + 1] += offspring / 8;
                    }
                }
            }
        }

        // 将临时数组复制回培养皿数组
        for (int i = 0; i < SIZE; i++) {
    
    
            for (int j = 0; j < SIZE; j++) {
    
    
                dish[i][j] = temp[i][j];
            }
        }
    }
}

int main() {
    
    
    int m, n;
    scanf("%d %d", &m, &n);

    int dish[SIZE][SIZE] = {
    
    0}; // 初始化培养皿为全0

    // 将中心位置的细菌数设置为m
    int center = SIZE / 2;
    dish[center][center] = m;

    simulateBacteria(dish, m, n);

    printDish(dish);

    return 0;
}

In the program, we first define a printDishfunction, which is used to print the bacterial distribution of the petri dish.

Then, we defined a simulateBacteriafunction that simulates the bacterial reproduction and diffusion process. The function accepts a two-dimensional array dishrepresenting the petri dish, an integer mrepresenting the number of bacteria in the center, and an integer nrepresenting the number of days that have passed.

In simulateBacteriathe function, we first copy the initial bacterial distribution to a temporary array temp. Then, we simulated the bacterial reproduction and diffusion process each day in turn. For each cell on the petri dish, if there are bacteria in the current cell, we calculate the reproduction number of bacteria and the distribution of offspring bacteria according to the rules, and update the temporary array temp.

After completing the simulation, we tempcopy the temporary array back to the Petri dish array dishand then call printDishthe function to print the bacterial distribution.

In the main function, we first read mthe sum of the inputs n. Then, we initialize the bacterial distribution of the petri dish and set the number of bacteria in the center to m. Next, we call simulateBacteriathe function to simulate the reproduction and diffusion process of bacteria and output the final bacterial distribution.

You can save the above code as a .cfile, compile and run it using a C language compiler. Then, enter the number of bacteria in the center mand the number of days that have passed nas required to get the distribution of bacteria in the petri dish.

Question 5: Word inversion

Write a program to read a line of English (containing only letters and spaces, with words separated by single spaces), reverse the order of all words and output them, still separated by single spaces.
Time limit: 10000
Memory limit: 65536
Input
The input is a string (string length is at most 100).
Output
The output is a string sorted as required.
Sample input
I am a student
Sample output
student a am I

To solve this problem, we can use string processing to achieve word inversion. Here is sample code to solve the problem:

#include <stdio.h>
#include <string.h>

#define MAX_LENGTH 100

void reverseWords(char *str) {
    
    
    int length = strlen(str);
    int start = 0;
    int end = length - 1;

    // 去除开头和结尾的空格
    while (str[start] == ' ') {
    
    
        start++;
    }

    while (str[end] == ' ') {
    
    
        end--;
    }

    // 反转整个字符串
    for (int i = start; i <= (start + end) / 2; i++) {
    
    
        char temp = str[i];
        str[i] = str[start + end - i];
        str[start + end - i] = temp;
    }

    int wordStart = start;
    int wordEnd = start;

    // 反转每个单词
    for (int i = start; i <= end; i++) {
    
    
        if (str[i] == ' ') {
    
    
            // 当遇到空格时,反转单词
            for (int j = wordStart; j <= (wordStart + wordEnd) / 2; j++) {
    
    
                char temp = str[j];
                str[j] = str[wordStart + wordEnd - j];
                str[wordStart + wordEnd - j] = temp;
            }

            wordStart = i + 1;
            wordEnd = i + 1;
        } else {
    
    
            wordEnd = i;
        }
    }

    // 反转最后一个单词
    for (int j = wordStart; j <= (wordStart + wordEnd) / 2; j++) {
    
    
        char temp = str[j];
        str[j] = str[wordStart + wordEnd - j];
        str[wordStart + wordEnd - j] = temp;
    }
}

int main() {
    
    
    char str[MAX_LENGTH];
    fgets(str, MAX_LENGTH, stdin);

    // 去除换行符
    if (str[strlen(str) - 1] == '\n') {
    
    
        str[strlen(str) - 1] = '\0';
    }

    reverseWords(str);

    printf("%s\n", str);

    return 0;
}

In the program, we first define a reverseWordsfunction that is used to reverse the order of words in the input string. The function accepts a character array stras input.

In reverseWordsthe function, we first remove the spaces at the beginning and end of the string. We then reverse the entire string, swapping the beginning and end of the string, and so on until the middle. Next, we record the starting position and ending position of each word through the sum of two wordStartpointers . wordEndWhen a space is encountered, we reverse the current word and then update the sum wordStartto wordEndthe starting position of the next word. Finally, we reverse the last word again.

In the main function, we use fgetsthe function to read the input string and remove the newline character at the end of the string. Then, we call reverseWordsthe function to reverse the order of the words and use printfthe function to output the result.

You can save the above code as a .cfile, compile and run it using a C language compiler. Then, enter the string to be sorted by words, and you can get the string sorted as required.

おすすめ

転載: blog.csdn.net/gozhuyinglong/article/details/132700673