[PTA] basic programming problem set programming part

Posted by plautzer on Mon, 17 Feb 2020 11:54:03 +0100

Article directory

7-1 cm to FT in (15 points)

If the foot foot foot and inch inch values of the imperial length are known, the corresponding meter is (foot+inch/12) × 0.3048. Now, if the user is typing in centimeters, what are the feet and inches corresponding to the imperial length? Don't forget that one foot is 12 inches.

  • Input format:
    Enter to give a positive integer in one line, in centimeters.
  • Output format:
    Output the whole value of the centimeter corresponding to the inch and foot of the English length in one line, separated by spaces.

Input example:

170

Output example:

5 6

Answer: push backward according to the formula given in the question.

#include <stdio.h>

int main() {
    int cm;
    scanf("%d", &cm);
    double m = cm * 1.0 / 100.0;
    int foot = m / 0.3048;
    int inch = (m / 0.3048 - foot) * 12;
    printf("%d %d\n", foot, inch);
    return 0;
}

7-2 and then what time (15 points)

Sometimes people use four digits to represent a time, such as 1106 for 11:06. Now, your program calculates the end time based on the start time and elapsed time.

Read in two numbers. The first number represents the current time in such four digits, and the second number represents the minutes. Calculate the time after so many minutes, and the result is also expressed in four digits. When the hour is a single digit, there is no leading zero, that is, 5:30 is 530. Note that the second number may be more than 60 minutes or negative.

  • Input format:
    Input two integers in a row, which are the start time represented by four digits and the number of minutes elapsed, separated by spaces. Note: in the starting time, when the hour is a single digit, the zero without leading, that is, 5:30 represents 530; the number of minutes passed may be more than 60 or negative.

  • Output format:
    Output the termination time represented by four digits. When the hour is a single digit, there is no leading zero. The starting time and ending time of the topic shall be within the same day.

Input example:

1120 110

Output example:

1310

Answer: count the basic unit of minutes. Add or subtract the start time in each minute.

#include <cstdio>

int main() {
    int begin, end, elipse;
    scanf("%d%d", &begin, &elipse);
    int min = begin % 100, hour = begin / 100; // start time
    if (elipse >= 0) {
        while (elipse) {
            min++, elipse--;
            if (min >= 60) hour++, min = 0;
        }
    } else {
        while (elipse) {
            min--, elipse++;
            if (min < 0) hour--, min = 59;
        }
    }
    printf("%d%02d", hour, min);
    return 0;
}

7-3 three digits in reverse order (10 points)

The program reads in one positive three digits at a time, and then outputs the digits in reverse order. Note: when the input number contains an ending 0, the output should not have a leading 0. For example, input 700, output should be 7.

  • Input format: each test is a 3-bit positive integer.
  • Output format: output the number of bits in reverse order.

Input example:

123

Output example:

321

Answer: get the number in reverse order and output.

#include <cstdio>

int main() {
    int n;
    scanf("%d", &n);
    int ans = 0; 
    while (n) {
        ans = ans * 10 + n % 10;
        n /= 10;
    }
    printf("%d\n", ans);
    return 0;
}

7-4 BCD decryption (10 points)

BCD number is a two digit decimal number represented by one byte, and every four bits represents one bit. So if the hexadecimal of a BCD number is 0x12, it represents the decimal 12. But Xiaoming didn't learn BCD. He converted all BCD numbers into decimal output as binary numbers. So 0x12 of BCD is output as 18 decimal!

Now, your program will read in the wrong decimal number and output the correct decimal number. Tip: you can convert 18 back to 0x12 and then back to 12.

  • Input format:
    Input a positive integer in the range of [0, 153] in a row to ensure that it can be converted back to a valid BCD number, that is, when the integer is converted to hexadecimal, there will be no A-F number.
    Output format:
    Output the corresponding decimal number.

Input example:

18

Output example:

12

Answer: simple base conversion, here we use recursive writing.

#include <cstdio>
// It's decimal to hexadecimal
void solve(int n) {
    if (n / 16 == 0) printf("%d", n);
    else {
        solve(n / 16);
        printf("%d", n % 16);
    }
}
int main() {
    int n;
    scanf("%d", &n);
    solve(n);
    return 0;
}

7-5 table output (5 points)

This question requests to write the procedure, according to the stipulation format output form.

  • Input format:
    There is no input for this topic.
  • Output format:
    It is required to output the following tables in strict accordance with the given format:
------------------------------------
Province      Area(km2)   Pop.(10K)
------------------------------------
Anhui         139600.00   6461.00
Beijing        16410.54   1180.70
Chongqing      82400.00   3144.23
Shanghai        6340.50   1360.26
Zhejiang      101800.00   4894.00
------------------------------------

Answer: just output directly.

#include <cstdio>

int main() {
    printf("------------------------------------\n");
    printf("Province      Area(km2)   Pop.(10K)\n");
    printf("------------------------------------\n");
    printf("Anhui         139600.00   6461.00\n");
    printf("Beijing        16410.54   1180.70\n");
    printf("Chongqing      82400.00   3144.23\n");
    printf("Shanghai        6340.50   1360.26\n");
    printf("Zhejiang      101800.00   4894.00\n");
    printf("------------------------------------\n");
    return 0; 
}

7-6 mixed type data format input (5 points)

This problem requires writing a program to read in floating-point number 1, integer, character, floating-point number 2, and then output in the order of character, integer, floating-point number 1, floating-point number 2.

  • Input format:
    Input the floating-point number 1, integer, character and floating-point number 2 in a row, separated by 1 space.
  • Output format:
    Output in the order of character, integer, floating-point number 1 and floating-point number 2 in one line, and the floating-point number retains two decimal places.

Input example:

2.12 88 c 4.7

Output example:

c 88 2.12 4.70

Answer: input and output according to the format.

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

int main() {
    double d;
    int i;
    char c;
    double d2;
    cin >> d >> i >> c >> d2;
    printf("%c %d %.2f %.2f\n", c, i, d, d2); 
    return 0;
}

7-7 12-24 hour system (15 points)

Write a program to ask the user to input the 24-hour time, and then display the 12-hour time.

  • Input format:
    Enter the 24-hour time with the middle: symbol (colon of half angle) in one line, for example, 12:34 means 12:34. When the hours or minutes are less than 10, there is no leading zero. For example, 5:6 means 5:06.
    Tip: add:, to scanf's format string and let scanf handle the colon.
  • Output format:
    Output the 12 hour time corresponding to this time in one line. The format of the number part is the same as that of the input, and then keep up with the space, and then keep up with the string AM representing the morning or the string PM representing the afternoon. For example, 5:6 PM means 5:06 PM. Note that in English, 12:00 noon is considered as afternoon, so 12:00 in 24-hour system is 12:0 PM in 12-hour system; 0:00 is considered as the time of the next day, so it is 0:0 AM.

Input example:

21:11

Output example:

9:11 PM

Answer: simply judge in the morning and afternoon.

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

int main() {
    int hours, mins;
    scanf("%d:%d", &hours, &mins);
    int am = hours < 12 ? 1 : 0;
    if (am) printf("%d:%d AM\n", hours, mins); 
    else printf("%d:%d PM\n", hours == 12 ? 12 : hours % 12, mins); // 12 point special judgement
    return 0;
}

7-8 overspeed judgment (10 points)

Radar speedometer simulating traffic police. Enter the vehicle speed. If the speed exceeds 60 mph, "speed" will be displayed, otherwise, "OK" will be displayed.

  • Input format:
    Input a non negative integer of no more than 500 in one line, i.e. the vehicle speed measured by the radar.
  • Output format:
    Output the speedometer display results in one line, the format is: Speed: V - S, where V is the vehicle speed, S is speed, or OK.

Enter example 1:

40

Output example 1:

Speed: 40 - OK

Enter example 2:

75

Output example 2:

Speed: 75 - Speeding

Answer: simple judgment.

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    cout << "Speed: " << n << (n > 60 ? " - Speeding" : " - OK");
    return 0;
}

7-9 use the balance to find the ball (10 points)

Three balls A, B and C have the same size and shape, and one of them has different weight from other balls. Ask for A different ball.

  • Input format:
    Input three positive integers in A row, and the order corresponds to the weight of balls A, B and C.
  • Output format:
    Output the only different ball in a row.

Input example:

1 1 2

Output example:

C

Answer:

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

int main() {
    int i, j, k;
    cin >> i >> j >> k;
    if (i == j) printf("C");
    else if (i == k) printf("B");
    else printf("A");
    return 0;
}

7-10 salary calculation (15 points)

The salary calculation method of a company's employees is as follows: if the working hours are less than 40 hours in a week, the salary shall be calculated according to the normal working hours; if the working hours are more than 40 hours, the salary shall be calculated according to 1.5 times of the normal working hours. The employees are divided into new employees and old employees according to the time of entering the company. The employees who have been in the company for at least 5 years are old employees, and the employees who have been in the company for less than 5 years are new employees. The normal wage of new employees is 30 yuan / hour, and that of old employees is 50 yuan / hour. Please calculate the employee's salary according to the remuneration method.

  • Input format:
    Enter 2 positive integers in a row, which are the number of years an employee has been employed and the working hours of a week, separated by spaces.
  • Output format:
    Output the weekly salary of the employee in one line, accurate to 2 decimal places.

Enter example 1:

5 40

Output example 1:

2000.00

Enter example 2:

3 50

Output example 2:

1650.00

Answer: segment calculation.

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

int main() {
    int y, w;
    cin >> y >> w;
    double ans = 0;
    int t = y >= 5 ? 50 : 30; 
    if (w <= 40) ans = w * t;
    else ans = 40 * t + (w - 40) * t * 1.5;
    printf("%.2lf", ans);
    return 0;
}

7-11 segment calculation of residential water fee (10 points)

In order to encourage residents to save water, the water company adopts the step pricing method based on water consumption. The water fee y (yuan) that residents should pay is related to the monthly water consumption x (ton): when x is not more than 15 tons, y=4x/3; when x is more than 15 tons, y=2.5x − 17.5. Please write a program to calculate the water fee.

  • Input format:
    The input gives a non negative real number x in one line.
  • Output format:
    Output the water fee to be paid in one line, accurate to 2 decimal places.

Enter example 1:

12

Output example 1:

16.00

Enter example 2:

16

Output example 2:

22.50

Answer: segment calculation.

#include <iostream>
using namespace std;

int main() {
    double x;
    cin >> x;
    printf("%.2lf", x <= 15 ? 4.0 * x / 3.0 : 2.5 * x - 17.5); 
    return 0;
}

7-12 two number simple calculator (10 points)

This question requests to write a simple calculator program, which can add, subtract, multiply, divide or calculate the two integers according to the input operator. The input and output shall not exceed the integer range.

  • Input format:
    Input input operands 1, operator, and 2 in a row, separated by a space. The data type of operands is integer, and the denominator of division and remainder is nonzero.
  • Output format:
    When the operators are +, -, *, /,%, the corresponding operation results are output in one line. If the input is an illegal symbol (i.e. other symbols except the five operators of addition, subtraction, multiplication, addition and remainder), ERROR is output.

Enter example 1:

-7 / 2

Output example 1:

-3

Enter example 2:

3 & 6

Output example 2:

ERROR

Answer:

#include <iostream>
using namespace std;

int main() {
    int p, q;
    char op;
    cin >> p >> op >> q;
    int a;
    switch (op) {
        case '+': a = p + q; break;
        case '-': a = p - q; break;
        case '*': a = p * q; break;
        case '/': a = p / q; break;
        case '%': a = p % q; break;
        default: 
            cout << "ERROR";
            return 0;
    }
    cout << a;
    return 0;
}

7-13 K candle chart (15 points)

The trend of stock price rise and fall is usually represented by K-line chart in candle chart technology, which is divided into daily K-line, weekly K-line and monthly K-line. Take the daily K-line as an example. Every day, the stock price goes from the opening to the closing one day, corresponding to a small candle chart, which represents four prices: the opening price Open (the first price of the opening transaction just in the morning), the closing price Close (the last price of the closing transaction in the afternoon), the highest price in the middle and the lowest price Low.

If Close < Open, it means BW solid; if Close > Open, it means R-Hollow; if Open equals Close, it means R-Cross. If Low is lower than Open and Close, it is called "Lower Shadow" (i.e. with Lower Shadow), and if High is higher than Open and Close, it is called "Upper Shadow" (i.e. with Upper Shadow). Please program, according to the given four price combinations, to determine what kind of candle the day is.

  • Input format:
    Input four positive real numbers in a row, corresponding to Open, High, Low and Close, separated by spaces.
  • Output format:
    Output the type of day K candle in one line. If there are up and down hatches, add with hatches after the type. If there are both hatches, output with Lower Shadow and Upper Shadow.

Enter example 1:

5.110 5.250 5.100 5.105

Output example 1:

BW-Solid with Lower Shadow and Upper Shadow

Enter example 2:

5.110 5.110 5.110 5.110

Output example 2:

R-Cross

Enter example 3:

5.110 5.125 5.112 5.126

Output example 3:

R-Hollow

Answer: first judge the type of candle, and then judge whether there is shadow.

#include <iostream>
using namespace std;

int main() {
    double o, h, l, c;
    cin >> o >> h >> l >> c;
    if (o > c) cout << "BW-Solid";
    else if (o < c) cout << "R-Hollow";
    else cout << "R-Cross";
    
    if ((l < o && l < c) && (h > o && h > c)) cout << " with Lower Shadow and Upper Shadow";
    else if (l < o && l < c) cout << " with Lower Shadow";
    else if (h > o && h > c) cout << " with Upper Shadow";
    return 0;
}

7-14 integral segment sum (15 points)

Given two integers A and B, output all integers from A to B and the sum of these numbers.

  • Input format:
    The input gives two integers A and B in A row, where − 100 ≤ A ≤ B ≤ 100, separated by spaces.
  • Output format:
    First, all integers from A to B are output in sequence, with each 5 digits in A row and each digit in 5 character width, aligned to the right. Finally, output the sum X of all numbers in the form of Sum = X in one line.

Input example:

-3 8

Output example:

   -3   -2   -1    0    1
    2    3    4    5    6
    7    8
Sum = 30

Answer: according to the calculation:

#include <iostream>
using namespace std;

int main() {
    int a, b;
    cin >> a >> b;
    int num = 0, sum = 0;
    int flag = 0;
    for (int i = a; i <= b; ++i) {
        printf("%5d", i);
        sum += i;
        num++;
        if (num % 5 == 0) { // Wrap every 5 lines 
			printf("\n");
			if (i == b) flag = 1; // When you output the last number, if you want to wrap, you will not wrap 
		}
    }
    printf(flag ? "" : "\n");
    printf("Sum = %d", sum);
    return 0;
}

7-15 calculate the PI (15 points)

According to the following relationship, calculate the value of the PI until the value of the last term is less than the given threshold value.

  • Input format:
    The input gives a threshold of less than 1 on a single line.
  • Output format:
    Output the approximate PI that meets the threshold condition in one line to 6 decimal places.

Input example:

0.01

Output example:

3.132157

Answer: simulate according to the formula.

#include <iostream>
using namespace std;

int main() {
    double eps, pi = 1, term = 1; // int is not enough long, double is not enough
    double up = 1, down = 3, upNum = 2, downNum = 5;
    cin >> eps;
    while (term >= eps) {
        term = up / down; // Find out the value of each item 
        pi += term;
        up *= upNum; // Accumulate, and find the molecular denominator of the next term respectively 
        down *= downNum;
        upNum++;
        downNum += 2;
    }
    printf("%.6lf", pi * 2);
    return 0;
}

★ 7-16 find the integer set meeting the given conditions (15 points)

Given A positive integer A of no more than 6, consider four consecutive numbers starting with A. Please output 3 digits of all non repeating numbers composed of them.

  • Input format:
    Enter A on one line.
  • Output format:
    Output 3 digits that meet the conditions, from small to large, 6 integers per line. Integers are separated by spaces, but no extra spaces are allowed at the end of the line.

Input example:

2

Output example:

234 235 243 245 253 254
324 325 342 345 352 354
423 425 432 435 452 453
523 524 532 534 542 543

Answer: three levels of cyclic violence search. You can also write A43=4!=24 in an arrangement.

#include <iostream> 
using namespace std;

int main() {
    int A; // <= 6 && > 0
    cin >> A;
    int arr[10] = {0};
    for (int i = A; i < A + 4; ++i) {
        arr[i] = 1;
        int flag = false; // Control format 
        for (int j = A; j < A + 4; ++j) {
            if (arr[j] == 1) continue; // If the number is already selected, skip
            arr[j] = 1;
            for (int k = A; k < A + 4; ++k) {
                if (arr[k] == 1) continue; // If the number is already selected, skip 
                arr[k] = 1;
                if (flag) printf(" ");
                printf("%d%d%d", i, j, k);
                flag = true;
                arr[k] = 0;
            }
            arr[j] = 0;
        }
        arr[i] = 0;
        printf("\n");
    } 
    return 0;
}

7-17 crawling worms (15 points)

A worm is one inch long, at the bottom of an N-inch well. It is known that worms can climb U-inch every minute, but they must rest for 1 minute before they can continue to climb. During the rest, the worm slipped another D inch. In this way, climbing and sliding are repeated. How long does it take for the worm to climb out of the well?

This requires less than one minute to be counted as one minute, and it is assumed that as long as the head of the worm reaches the top of the well in a certain climbing process, the worm will complete the task. Initially, the worm was lying at the bottom of the well (i.e., 0 in height).

  • Input format:
    Input three positive integers N, U, D in a row, where d < U, N is not more than 100.
  • Output format:
    Output the worm's time out of the well in minutes in one line.

Input example:

12 3 1

Output example:

11

Answer: simulation question, calculation time, just a few minutes.

#include <iostream>
using namespace std;

int main() {
    int n, u, d;
    cin >> n >> u >> d;
    int min = 0, dist = 0;
    while (1) {
        dist += u;
        ++min;
        if (dist >= n) break;
        dist -= d;
        ++min;
    }
    cout << min;
    return 0;
}
/*
minutes distance
1        3
2        2
3        5
4        4
5        7
6        6
7        9
8        8
9        11
10       10
11       13 
*/

★ 7-18 dichotomy for single root of polynomial (20 points)

The principle of dichotomy to find the root of a function is: if the value of continuous function f(x) is different at the two ends of interval [a,b], that is, f (a) f (b) < 0, then it has at least one root r in this interval, that is, f(r)=0.

The steps of dichotomy are as follows:

Check the length of the interval, if it is less than the given threshold, stop and output the midpoint of the interval (a+b)/2; otherwise
 If f (a) f (b) < 0, then calculate the value of the midpoint f((a+b)/2);
If f((a+b)/2) is exactly 0, then (a+b)/2 is the required root; otherwise
 If f((a+b)/2) and f(a) are the same sign, then the root is in the interval [(a+b)/2,b], let a=(a+b)/2, repeat the cycle;
If f((a+b)/2) and f(b) are the same sign, then the root is in the interval [a,(a+b)/2], let b=(a+b)/2, repeat the cycle.

In this paper, we need to write a program to calculate the roots of a given polynomial of order 3 f(x)=a 3 x 3 + a 2 x 2 + a 1 x+a 0 in a given interval [a,b].

  • Input format:
    Input the 4 coefficients a 3, a 2, a 1, a 0 of the polynomial in the first row, and the end points a and b of the interval in the second row. The problem guarantees that the polynomial has a unique single root in a given interval.
  • Output format:
    Output the root of the polynomial in the interval in one line, accurate to 2 decimal places.

Input example:

3 -1 -3 1
-0.5 0.5

Output example:

0.33

Answer: it should be noted that the description of the question is not complete:

Check the length of the interval, if it is less than the given threshold, stop and output the midpoint of the interval (a+b)/2; otherwise
 If f (a) f (b) < 0, then calculate the value of the midpoint f((a+b)/2);
If f(a) or f(b) is exactly 0, then output a or B as the required root;
If f((a+b)/2) is exactly 0, then (a+b)/2 is the required root; otherwise
 If f((a+b)/2) and f(a) are the same sign, then the root is in the interval [(a+b)/2,b], let a=(a+b)/2, repeat the cycle;
If f((a+b)/2) and f(b) are the same sign, then the root is in the interval [a,(a+b)/2], let b=(a+b)/2, repeat the cycle.
#include <iostream>
#include <cmath>
using namespace std;
double a3, a2, a1, a0;

double f(double x) {
	return a3 * x * x * x + a2 * x * x + a1 * x + a0;
}
// There are some problems in the dichotomy description of the topic
int main() {
    cin >> a3 >> a2 >> a1 >> a0;
    double a, b;
    cin >> a >> b;
    double x;
    while ((b - a) >= 0.01) {
    	double fa = f(a), fb = f(b);
        if (fa * fb < 0) x = (a + b) / 2;
        else if (fa == 0.0 || fb == 0.0) {
            printf("%.2lf", fa == 0.0 ? a : b);
            return 0;
        } 
        double v = f(x); 
        if (v == 0.0) { // (a+b)/2 is the root of the requirement
			printf("%.2lf", x);
			return 0;
		} 
		else if (v * fa > 0) a = x;
		else if (v * fb > 0) b = x; 
    }
    printf("%.2lf", (a + b) / 2.0); // Midpoint of output interval (a+b)/2
    return 0;
}

★ 7-19 check face value (15 points)

A buyer went to the bank to exchange a check for y yuan and f Fen. As a result, the cashier gave f yuan and Y Fen by mistake. After using n points, the buyer found out that there was a mistake, so he counted the balance and still had 2 y yuan and 2 F points, and asked how much was the face value of the check?

  • Input format:
    Enter a positive integer n less than 100 in one line.
  • Output format:
    Output the original face value of the check in the format y.f in one line. If there is No Solution, No Solution is output.

Enter example 1:

23

Output example 1:

25.51

Enter example 2:

22

Output example 2:

No Solution

Answer: pay attention to the implicit conditions in the questions, y and F can't be greater than 100, n can't be less than 100, then according to the notes in the program, we can get 199y-98f+n=0, search for the answer in the corresponding space, and finally we need to pay attention to that y and F can't be 0, otherwise, which is a positive integer n?

#include <iostream> 
#include <algorithm>
#include <vector>
using namespace std;
struct yuan {
	int y, f, n;
};

int main() {
    int n;
    cin >> n;
	// Y yuan f score f < 100 / / F yuan y score y < 100 N < 100
	// F-y-n = 2y-2f 
    // 199y-98f+n=0 
    vector<yuan> vi(101);
    for (int i = 0; i < 100; ++i) {
		for (int j = 0; j < 100; ++j) {
			int ans = 199 * i - 98 * j;
			if (ans < 0 && ans > -100) 
				vi[-ans] = yuan{i, j, -ans};
		}
	} 
    if (vi[n].y != 0 || vi[n].f != 0) printf("%d.%d", vi[n].y, vi[n].f); // The calculated y and f are not 0.0
    else printf("No Solution");
    return 0;
}

7-20 print the Jiu Jiu formula table (15 points)

Here's a complete list of the bottom triangle and the ninth formula:

1*1=1   
1*2=2   2*2=4   
1*3=3   2*3=6   3*3=9   
1*4=4   2*4=8   3*4=12  4*4=16  
1*5=5   2*5=10  3*5=15  4*5=20  5*5=25  
1*6=6   2*6=12  3*6=18  4*6=24  5*6=30  6*6=36  
1*7=7   2*7=14  3*7=21  4*7=28  5*7=35  6*7=42  7*7=49  
1*8=8   2*8=16  3*8=24  4*8=32  5*8=40  6*8=48  7*8=56  8*8=64  
1*9=9   2*9=18  3*9=27  4*9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81  

For any given positive integer N, it is required to output part of the formula table from 11 to NN.

  • Input format:
    The input gives a positive integer N (1 ≤ N ≤ 9) in one line.
  • Output format:
    Output the lower triangle N*N part of the formula table, where the number on the right side of the equal sign occupies 4 digits, left aligned.

Input example:

4

Output example:

1*1=1   
1*2=2   2*2=4   
1*3=3   2*3=6   3*3=9   
1*4=4   2*4=8   3*4=12  4*4=16  

Answer: just type the form.

#include <iostream>
#include <string>
using namespace std;
string s[] = {
    "1*1=1   ",   
    "1*2=2   2*2=4   ", 
    "1*3=3   2*3=6   3*3=9   ",   
    "1*4=4   2*4=8   3*4=12  4*4=16  ", 
    "1*5=5   2*5=10  3*5=15  4*5=20  5*5=25  ", 
    "1*6=6   2*6=12  3*6=18  4*6=24  5*6=30  6*6=36  ",
    "1*7=7   2*7=14  3*7=21  4*7=28  5*7=35  6*7=42  7*7=49  ",
    "1*8=8   2*8=16  3*8=24  4*8=32  5*8=40  6*8=48  7*8=56  8*8=64  ",
    "1*9=9   2*9=18  3*9=27  4*9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81  "
};
// There are 4 digits after the equal sign, the numbers are aligned to the left, and the remaining space is filled with spaces
int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n - 1; ++i) 
        cout << s[i] << endl;
    cout << s[n - 1];
    return 0;
}

7-21 positive integer solution of special equation (15 points)

This problem requires all positive integer solutions of equation X 2 + Y 2 = N for any given positive integer N.

  • Input format:
    The input gives a positive integer N (< 10000) in one line.
  • Output format:
    All positive integer solutions of output equation x 2 + Y 2 = N, where x ≤ Y. Each group of solutions takes up one line, the two numbers are separated by one space, and the output is in the increasing order of X. If there is No Solution, output No Solution.

Enter example 1:

884

Output example 1:

10 28
20 22

Enter example 2:

11

Output example 2:

No Solution

Answer: both X and Y are less than or equal to 100. You can search directly in the data.

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int n;
    cin >> n;
    int sqr = sqrt(n);
    bool flag = true;
    for (int x = 1; x <= sqr; ++x) {
        for (int y = 1; y <= sqr; ++y) {
            if (x <= y && x * x + y * y == n) {
                cout << x << " " << y << endl;
                flag = false;
            }
        }
    }
    if (flag) cout << "No Solution";
    return 0;
}

★ 7-22 tortoise rabbit race (20 points)

Tortoise and rabbit race, the running field is a rectangular track, the edge of the track can rest anywhere. The tortoise can advance 3 meters every minute, and the rabbit can advance 9 meters every minute. The rabbit thinks the tortoise runs slowly, and thinks it can definitely beat the tortoise. So, every 10 minutes, he looks back at the tortoise. If he finds that he exceeds the tortoise, he will rest at the roadside for 30 minutes each time, or else he will continue to run for 10 minutes. The tortoise works hard and runs all the time without rest. Suppose the tortoise and the rabbit start running at the same time at the same starting point, who can run fast in T minutes?

  • Input format:
    Enter the match time T (minutes) on one line.
  • Output format:
    Output the result of the game in one line: tortoise wins and output @ @, rabbit wins and output ﹐ in a draw, output --- followed by a space, and then output the distance the winner has run.

Input example:

242

Output example:

@_@ 726

Answer: the key is when the rabbit will rest and whether the rabbit will see the tortoise and other details. Here, a flag is used. When it is true, the rabbit will run and observe the tortoise every ten minutes; when it is false, the rabbit will rest.

#include <iostream>
using namespace std;
/* t      w
1  9      3  The hare wins in the run, the tortoise loses in the run
10  90     30 
...           The hare wins in the break, the tortoise loses in the run
30  90     90 Rabbit rest in the draw, tortoise run in the draw
...           The hare loses in the rest and the tortoise wins in the run
40  90     120 
...           The hare loses in the run, the tortoise wins in the run
45  135    135 Rabbit, tortoise, running, draw
...            The hare wins in the run, the tortoise loses in the run
50  180    150 
...            The hare wins in the break, the tortoise loses in the run
60  180    180 Rabbit rest in the draw, tortoise run in the draw
*/  
int main() {
    int T;
    cin >> T; 
    int tdis = 0, wdis = 0; // The distance a rabbit runs, the distance a tortoise runs
    int tflag = true; // Does the rabbit rest
    int tmin = 0; // Temporary timer to record the last time
    for (int i = 1; i <= T; ++i) { // A minute passed
        wdis += 3;
        if (tflag) tdis += 9;
        if (tflag && i % 10 == 0 && tdis > wdis) { // Compare distances every 10 minutes in a run
            tflag = false; // Rabbit rest if it exceeds
            tmin = i; // Record this time
        }
        if (i - tmin == 30) tflag = true; // 30 minutes off each time 
    }
    if (tdis > wdis) printf("^_^ %d", tdis);
    else if (wdis > tdis) printf("@_@ %d", wdis);
    else printf("-_- %d", tdis); // Followed by a space, and then output the distance the winner ran / / hell, even a draw also needs to output the distance
    return 0;
}

★★ 7-23 currency conversion (20 points) Chinese reading habits

Enter an integer (no more than 9 digits) to represent a RMB value (unit: RMB). Please convert it to the capital Chinese format required by the financial department. For example, 23108 yuan will become "twenty-three thousand one hundred and eight" yuan after conversion. In order to simplify the output, lowercase English letters a-j are used to represent capital numbers 0-9, and S, B, Q, W and Y are used to represent one hundred, ten, ten, ten, and one hundred million respectively. Therefore, 23108 yuan should be converted and output as "cWdQbBai" yuan.

  • Input format:
    Enter to give a non negative integer of no more than 9 bits in a row.
  • Output format:
    Output the converted result in one line. Note that the usage of "zero" must conform to the Chinese custom.

Enter example 1:

813227345

Output example 1:

iYbQdBcScWhQdBeSf

Enter example 2:

6900

Output example 2:

gQjB
#include <iostream>
#include <string>
using namespace std;
// a 0; b 1; c 2; d 3; e 4; f 5; g 6; h 7; i 8; j 9
int main() { 
    string s;
    cin >> s;
	if (s.size() == 1 && s[0] == '0') {
		cout << 'a';
		return 0;
	}
    string ans; 
    char c[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
    for (int i = s.size() - 1; i >= 0; --i) {
    	int j = s.size() - i - 1, n = s[j] - '0';
    	if (n == 0) {
    		int endPos, flag = false;
    		switch (i) { // i is digit. 
    			case 8: endPos = 0; break;
    			case 7:
    			case 6:
    			case 5:
    			case 4: endPos = s.size() - 1 - 4; break;
    			case 3:
    			case 2:
    			case 1:
    			case 0: endPos = s.size() - 1; break;
    		}
    		for (int k = j + 1; k <= endPos; ++k) {
    			if (s[k] != '0') {
    				flag = true;
					break;
				}
			}
			if (flag && ans[ans.size() - 1] != 'a') ans += 'a';
			if (i == 4 && s.size() <= 8) ans += 'W';
			continue;
    	} else ans += c[n];
    	
    	if (i == 8) { 
    		ans += 'Y';
    	} else if (i == 7 || i == 3) {
    		ans += 'Q';
    	} else if (i == 6 || i == 2) {
    		ans += 'B';
		} else if (i == 5 || i == 1) {
			ans += 'S';
		} else if (i == 4) 
			ans += 'W';
	}
	cout << ans; 
    return 0;
}

7-24 reduced minimum fraction (15 points)

Fractions can be expressed in the form of numerator / denominator. Write a program, ask the user to input a score, and then reduce it to the simplest fraction. The simplest fraction means that the numerator and denominator have no reducible components. For example, 6 / 12 can be roughly divided into 1 / 2. When the numerator is larger than the denominator, it does not need to be expressed in the form of integer and fraction, i.e. 11 / 8 or 11 / 8; when the numerator and denominator are equal, it is still expressed in the form of 1 / 1 fraction.

  • Input format:
    Input a fraction in a row, and the numerator and denominator are separated by a slash / separator. For example, 12 / 34 means 12 out of 34. Both numerator and denominator are positive integers (excluding 0, if the definition of positive integers is unclear).
    Tip: Add / to scanf's format string and let scanf handle the slash.
  • Output format:
    Output the simplest fraction corresponding to this fraction in one line. The format is the same as that of the input, that is, use the form of numerator / denominator to represent the fraction. For example, 5 / 6 means 5 / 6.

Input example:

66/120

Output example:

11/20

Answer: directly.

#include <iostream>
using namespace std;
using ll = long long;
ll gcd(ll a, ll b) {
    return !b ? a : gcd(b, a % b);
}

int main() {
    ll a, b;
    scanf("%lld/%lld", &a, &b);
    ll c = gcd(a, b);
    printf("%lld/%lld", a / c, b / c);
    return 0;
}

Read numbers from 7 to 25 (15 points)

Input an integer and output the Pinyin corresponding to each number. When the integer is negative, output the fu word first. The Pinyin corresponding to the ten numbers is as follows:

0: ling
1: yi
2: er
3: san
4: si
5: wu
6: liu
7: qi
8: ba
9: jiu

Input format:

Enter an integer on a line, such as 1234.

Tip: integers include negative, zero, and positive numbers.
Output format:

Output the Pinyin corresponding to the integer in one line. Separate the Pinyin of each number with a space. There is no last space at the end of the line. Such as yi er san si.
Input example:

-600

Output example:

fu liu ling ling

Answer: here is a very simple number reading.

#include <iostream>
#include <map>
#include <string>
using namespace std;
map<char, string> m = {
    {'-', "fu"}, {'0', "ling"}, {'1', "yi"}, {'2', "er"}, {'3', "san"}, {'4', "si"},
    {'5', "wu"}, {'6', "liu"}, {'7', "qi"}, {'8', "ba"}, {'9', "jiu"}
};

int main() {
    string s;
    cin >> s;
    for (int i = 0; i < s.size(); ++i) { 
        if (i != 0) cout << ' ';
        cout << m[s[i]];
    }
    return 0;
}

★ 7-26 word length (15 points)

Your program will read a line of text, separated by spaces into several words, ending with. You have to output the length of each word. The words here are not related to the language, and can include various symbols, such as it's to calculate a word with a length of 4. Note that consecutive spaces may appear in rows; the last. Is not counted.

  • Input format:
    Input gives a line of text in a line, ending with
    Tip: use scanf("%c",... " ); to read in a character until it reaches.
  • Output format:
    Output the length of the word corresponding to this line of text in one line. Each length is separated by spaces. There is no last space at the end of the line.

Input example:

It's great to see you here.

Output example:

4 5 2 3 3 4

Answer: this question is very strict on the judgment of blank space. You should pass the following tests, and pay attention to the output format.

hello world       .
.
      hello    world  .
       . 
5 5
 (this group can output nothing)
5 5
 (this group can output nothing) 
#include <iostream> 
using namespace std;

int main() { 
    char c, prec = ' ';
    int len = 0;
    bool flag = false;
    while (scanf("%c", &c)) {
    	if (c == '.') { 
            if (prec != ' ') {
                if (flag) cout << " ";
                cout << len << endl; //Last word length
            }
			break;
		} else if (c == ' ' && prec == ' ') continue;
        else if (c == ' ' && prec != ' ') {
            if (flag) cout << " "; 
            cout << len;
            flag = true;
            len = 0;
        }
        else if (c != ' ') len++;
        prec = c;
    }
    return 0;
}

7-27 bubble sorting (20 points)

Bubble sorting, which sorts N integers from small to large, works by comparing two adjacent elements from beginning to end and swapping them if the preceding element is larger than the following one. After a scan, the last element must be the largest. The first N − 1 element is then scanned a second time in the same way. In the end, only two elements need to be processed to sort N numbers.

For any given K (< n), output the middle result sequence after the k-th scan.

  • Input format:
    Input n and K (1 ≤ K < n ≤ 100) in line 1, and N integers to be sorted in line 2. The numbers are separated by spaces.
  • Output format:
    Output bubble sorting method in a row to scan the middle result sequence after the K-th pass. The numbers are separated by spaces, but no extra spaces are allowed at the end.

Input example:

6 2
2 3 5 1 6 4

Output example:

2 1 3 4 5 6

Answer: only K sorting processes.

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int n, k;
    cin >> n >> k;
    int arr[n];
    for (int i = 0; i < n; ++i) cin >> arr[i];
    
    for (int i = n - 1; i > n - 1 - k; --i) {
        int flag = true; // Sign of exit or not
        for (int j = 0; j < i; ++j) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
                flag = false;
            }
        }
        if (flag) break;
    }
    for (int i = 0; i < n - 1; ++i) cout << arr[i] << " ";
    cout << arr[n - 1];
    return 0;
}

[Joseph Ring] 7-28 monkey chooses King (20 points)

[PTA] [Josephus ring] basic programming problem set programming part 7-28 Monkey chooses King (20 points)

★ 7-29 delete the substring in the string (20 points)

Input 2 strings S1 and S2. It is required to delete all substrings S2 in string S1, that is, S2 cannot be included in the result string.

  • Input format:
    Input 2 non empty strings ending with carriage return with no more than 80 characters in 2 lines, corresponding to S1 and S2.
  • Output format:
    Output the result string after deleting all substrings S2 in string S1 in one line.

Input example:

Tomcat is a male ccatat
cat

Output example:

Tom is a male 

Answer: you can perform violent string matching and write by yourself; you can also use the find function of string, but the latter is too simple.

#include <iostream>
using namespace std;

// int bf(const string &s, const string &t) {
//     int i = 0, j = 0;
//     while (i < s.size() && j < t.size()) {
//         if (s[i] == t[j]) {
//             ++i;
//             ++j;
//         } else {
//             i = i - j + 1;
//             j = 0;
//         }
//     }
//     if (j >= t.size()) return i - t.size();
//     else return -1;
// }

int main() {
    string s, t;
    getline(cin, s);
    getline(cin, t);
    int index;
    // while ((index = bf(s, t)) != -1) { 
    //     s.erase(index, t.size());
    // }
    while ((index = s.find(t)) != s.npos) {
        s.erase(index, t.size());
    }
    cout << s;
    return 0;
}

Bubble sorting of 7-30 strings (20 points)

We have learned the bubble sorting method of sorting N integers from small to large. It is required to use this method in string sequence and output the intermediate result sequence after the k-th scan for any given K (< N).

  • Input format:
    Input N and K (1 ≤ K < N ≤ 100) in the first line, and then N lines, each line contains a non empty string composed of only lowercase English letters with a length of no more than 10.
  • Output format:
    The output bubble sorting method scans the intermediate result sequence after the K-th pass, and each line contains a string.

Input example:

6 2
best
cat
east
a
free
day

Output example:

best
a
cat
day
east
free

Answer: the comparison between string s is in the order of dictionaries, which is much simpler.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int n, k;
    cin >> n >> k;
    vector<string> vi;
    string t;
    for (int i = 0; i < n; ++i) {
        cin >> t;
        vi.push_back(t);
    }
    for (int i = n - 1; i > n - 1 - k; --i) 
        for (int j = 0; j < i; ++j)  
            if (vi[j] > vi[j + 1]) 
                swap(vi[j], vi[j + 1]);
    for (int i = 0; i < vi.size(); ++i) cout << vi[i] << endl;
    return 0;
}

7-31 string cycle left shift (20 points)

Enter a string and a non negative integer N, which requires the string to be rotated left N times.

  • Input format:
    Enter a non empty string ending with carriage return with a length of no more than 100 characters in line 1, and a non negative integer N in line 2.
  • Output format:
    Output the string after N left shifts of the loop in one line.

Input example:

Hello World!
2

Output example:

llo World!He

Answer: the old way.

#include <iostream>
#include <string>
using namespace std;
void reverse(string &s, int lo, int hi) {
    while (lo < hi) {
        char t = s[lo];
        s[lo] = s[hi];
        s[hi] = t;
        lo++;
        hi--;
    }
}

int main() {
    string s;
    int k;
    getline(cin, s);
    cin >> k;
    k %= s.size(); // k is greater than string length
    reverse(s, 0, k - 1);
    reverse(s, k, s.size() - 1);
    reverse(s, 0, s.size() - 1);
    cout << s;
    return 0;
}

7-32 irony - enhanced version (20 points)

Given a sentence in English, you are required to write a program to reverse the order of all the words in the sentence.

  • Input format:
    The test input contains a test case giving a string with a total length of no more than 500000 in one line. The string consists of several words and several spaces, among which the word is a string composed of English letters (case sensitive), and the words are separated by several spaces.
  • Output format:
    The output of each test case takes up one line, output the sentences in reverse order, and ensure that there is only one space between words.

Input example:

Hello World   Here I Come

Output example:

Come I Here World Hello

Answer: record each word and output in reverse.

#include<iostream>
#include<vector>
#include<string>
using namespace std;

int main() {
    string s;
    vector<string> v;
    while (cin >> s) v.push_back(s);
    for (int i = v.size() - 1; i > 0; --i) cout << v[i] << " ";
    if (v.size() > 0) cout << v[0];
    return 0;
}

7-33 rational addition (15 points)

This question requires writing a program to calculate the sum of two rational numbers.

  • Input format:
    Input two rational numbers in the form of a 1 / B 1 a 2 / B 2 in a row, where the numerator and denominator are all positive integers in the range of shaping.
  • Output format:
    Output the sum of two rational numbers in the form of a/b in one line. Note that it must be the simplest fraction form of the rational number. If the denominator is 1, only the numerator will be output.

Enter example 1:

1/3 1/6

Output example 1:

1/2

Enter example 2:

4/3 2/3

Output example 2:

2

Answer: it can be calculated directly by adding the scores. Pay attention to simplification.

#include <iostream>
using namespace std;
using ll = long long;
ll gcd(ll a, ll b) {
    return !b ? a : gcd(b, a % b);
}

int main() {
    ll a, b, c, d;
    scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d);
    ll down = b * d, up = a * d + c * b;
    ll g = gcd(up, down);
    if (down / g != 1) printf("%lld/%lld", up / g, down / g);
    else printf("%lld", up / g);
    return 0;
}

7-34 entry and display of address book (10 points)

A record in the address book contains the following basic information: a friend's name, date of birth, gender, fixed phone number, mobile phone number. This question requires to write a program, input N records, and display any record according to the requirements.

  • Input format:
    Enter the positive integer N (≤ 10) in the first line, and then N lines, each line will give a record according to the format name, birthday gender fixed line phone. The name is a non empty string with no more than 10 characters and no spaces; the date of birth is given in the format of yyyy/mm/dd; the gender is M for "male" and F for "female"; the fixed line telephone and mobile phone are all consecutive numbers with no more than 15 digits, which may appear +.

    After the address book record is input, the last line gives a positive integer k, and then K integers, indicating the record number to query (from 0 to N − 1 sequential number). Numbers are separated by spaces.

  • Output format:
    For each record number to be queried, the record is output in a row according to the format of gender birthday of name fixed line mobile phone. If the record to be queried does not exist, the output is Not Found.

Input example:

3
Chris 1984/03/10 F +86181779452 13707010007
LaoLao 1967/11/30 F 057187951100 +8618618623333
QiaoLin 1980/01/01 M 84172333 10086
2 1 7

Output example:

LaoLao 057187951100 +8618618623333 F 1967/11/30
Not Found

Answer: simple search.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct note {
    string name;
    string solid, phone;
    char c;
    int y, m, d;
    note(string &na, int _y, int _m, int _d, char _c, string &s, string &p) 
        :name(na), solid(s), phone(p), c(_c), y(_y), m(_m), d(_d) { }
};

int main() {
    int n;
    cin >> n;
    vector<note> vi;
    string na, s, p;
    char c;
    int y, m, d;
    while (n--) {
        cin >> na;
        scanf("%d/%d/%d", &y, &m, &d);
        cin >> c >> s >> p;
        vi.emplace_back(note(na, y, m, d, c, s, p)); 
    }
    int k, i;
    cin >> k;
    while (k--) {
        cin >> i;
        if (i >= vi.size()) cout << "Not Found\n";
        else {
            cout << vi[i].name << " ";
            cout << vi[i].solid << " " << vi[i].phone;
            printf(" %c %04d/%02d/%02d\n",  vi[i].c, vi[i].y, vi[i].m, vi[i].d); 
        }
    }
    return 0;
}

[rational number template] 7-35 average value of rational number (20 points)

This question requests to write a program to calculate the average value of N rational numbers.

  • Input format:
    Enter the first line to give a positive integer n (≤ 100); in the second line, press a1/b1 a2/b2 In the form of N fractions, the numerator and denominator are all integers within the scope of shaping; if they are negative, the negative sign must appear at the front.
  • Output format:
    Output the average value of N rational numbers in the form of a/b in one line. Note that it must be the simplest fraction form of the rational number. If the denominator is 1, only the numerator will be output.

Enter example 1:

4
1/2 1/6 3/6 -5/10

Output example 1:

1/6

Enter example 2:

2
4/3 2/3

Output example 2:

1

Answer: in the normal rational number template, simplification and fractional addition, it should be noted that simplification must be carried out after each addition, or "floating point error" may occur.

#include <iostream>
using namespace std;
using ll = long long;
struct frac {
    ll u, d;
    frac() { }
    frac(ll up, ll down) : u(up), d(down) { }
};

ll gcd(ll a, ll b) {
    return !b ? a : gcd(b, a % b);
}

void add(frac &a, const frac &b) {
    ll d = a.d * b.d;
    ll u = a.u * b.d + b.u * a.d;
    a.u = u, a.d = d;
} 
void reduce(frac &a) {
    ll g = gcd(a.u, a.d);
    a.u /= g, a.d /= g;
}

int main() {
    int n;
    cin >> n;
    frac ans, temp;
    scanf("%lld/%lld", &ans.u, &ans.d);
    for (int i = 1; i < n; ++i) {
        scanf("%lld/%lld", &temp.u, &temp.d);
        add(ans, temp);
        reduce(ans);
    }
    ans.d *= n;
    reduce(ans);
    if (ans.d != 1) cout << ans.u << "/" << ans.d;
    else cout << ans.u;
    return 0;
}

[complex operation] 7-36 four complex operations (15 points)

This problem requires programming to calculate the sum, difference, product and quotient of two complex numbers.
Input format:

Input two real and imaginary parts of complex C1=a1+b1i and C2=a2+b2i in the form of a1 b1 a2 b2 in one line. Topic guarantee C2 is not 0.
Output format:

The sum, difference, product and quotient of two complex numbers are output in the order of (a1+b1i) operator (a2+b2i) = result in four lines, and the number is accurate to one decimal place. If the real part or virtual part of the result is 0, it is not output. If the result is 0, 0.0 is output.
Enter example 1:

2 3.08 -2.04 5.06

Output example 1:

(2.0+3.1i) + (-2.0+5.1i) = 8.1i
(2.0+3.1i) - (-2.0+5.1i) = 4.0-2.0i
(2.0+3.1i) * (-2.0+5.1i) = -19.7+3.8i
(2.0+3.1i) / (-2.0+5.1i) = 0.4-0.6i

Enter example 2:

1 1 -1 -1.01

Output example 2:

(1.0+1.0i) + (-1.0-1.0i) = 0.0
(1.0+1.0i) - (-1.0-1.0i) = 2.0+2.0i
(1.0+1.0i) * (-1.0-1.0i) = -2.0i
(1.0+1.0i) / (-1.0-1.0i) = -1.0

Answer: complex operation, division operation should be careful.

#include <iostream>
#include <cmath>
using namespace std;

void print(double a, double b) {
    printf("%.1lf", a);
    if (b >= 0.0) printf("+%.1lfi", b);
    else printf("%.1lfi", b);
}

void printSample(double a, double b) {
    cout << "(";
    print(a, b);
    cout << ")";
}

void myRound(double &a) {
	a = round(a * 10.0) / 10.0;
}
void printResult(double a, double b) {
	myRound(a), myRound(b); 
    if (a == 0.0 && b == 0.0) printf("0.0");
    else if (a == 0.0) printf("%.1lfi", b);
    else if (b == 0.0) printf("%.1lf", a);
    else print(a, b);
}

int main() { 
    double a, b, c, d, ra, rb; // c1 c2
    cin >> a >> b >> c >> d; 
    // First add, subtract, multiply and divide with the original number. Only one decimal place is reserved when printing 
    char ch[4] = {'+', '-', '*', '/'};
    for (int i = 0; i < 4; ++i) {
        printSample(a, b);
        printf(" %c ", ch[i]);
        switch (ch[i]) {
            case '+': ra = a + c, rb = b + d; break;
            case '-': ra = a - c, rb = b - d; break;
            case '*': ra = a * c - b * d, rb = a * d + c * b; break;
            case '/': ra = (a * c + b * d) / (c * c + d * d), 
					  rb = (b * c - a * d) / (c * c + d * d); break; 
        }
        printSample(c, d);
        printf(" = ");
        printResult(ra, rb); // Printing of results
        cout << endl;
    }
    return 0;
}

★★ 7-37 integer is decomposed into sum of several items (20 points)

There are many ways to decompose a positive integer N into several positive integers, such as 7 = 6 + 1, 7 = 5 + 2, 7 = 5 + 1 + 1. All integer decompositions of positive integer N are obtained by programming.
Input format:

Each input contains a test case, which is a positive integer n (0 < n ≤ 30).
Output format:

Output all integer factorizations of N in ascending order. The increasing order refers to: for two decomposition sequences n 1 = {n 1, N 2,... And N 2 = {M 1, M 2,...}, if I makes n 1 = M 1, n i = M I, but n i+1 < m i+1, then n 1 sequence must be output before N 2 sequence. Each formula is added from small to large, separated by semicolons, and lines are wrapped after each output of 4 formulas.
Input example:

7

Output example:

7=1+1+1+1+1+1+1;7=1+1+1+1+1+2;7=1+1+1+1+3;7=1+1+1+2+2
7=1+1+1+4;7=1+1+2+3;7=1+1+5;7=1+2+2+2
7=1+2+4;7=1+3+3;7=1+6;7=2+2+3
7=2+5;7=3+4;7=7

Answer: get all the solutions by pruning + DFS.

#include<iostream>
#include<vector> 
using namespace std;

vector<vector<int>> vi;
int n;

void dfs(int sum, vector<int> &v) {
    if (sum == n) {
        vi.push_back(v);
        return;
    }
    for (int i = 1; i <= n; ++i) {
        if (sum + i > n) return; // Prune
        if (v.size() > 0 && v[v.size() - 1] > i) continue;
        v.push_back(i);
        dfs(sum + i, v);
        v.pop_back();
    }
}

void print(int i) { // The sequence whose subscript is i in the printing result sequence vi 
	cout << n << "=";
	int l = vi[i].size();
	for (int j = 0; j < l - 1; ++j) 
		cout << vi[i][j] << "+";
	cout << vi[i][l - 1];
}

int main() {
    cin >> n;
    vector<int> t;
    dfs(0, t);
    // Sort (vi.begin(), vi.end()); / / when DFS, the sequence has been calculated according to the order required by the title
    for (int i = 0; i < vi.size(); ++i) {
    	print(i);
    	if ((i + 1) % 4 == 0 || i == vi.size() - 1) printf("\n");
		else printf(";"); 
    }
    return 0;
}

★★ 7-38 sequence summing enhanced version (20 points)

Given A number A (1 ≤ A ≤ 9) and A non negative integer N (0 ≤ N ≤ 100000), sum the sequence S=A+AA+AAA + * AA * A (N A). For example, when A=1, N=3, S=1+11+111=123.
Input format:

Enter the number A and the non negative integer N.
Output format:

Output the value of the sum S of its N-term series.
Input example:

1 3

Output example:

123

Answer: I didn't use big integers for this question, but I got the result by regular calculation and directly assembling strings. From the lowest order, the lowest order is undoubtedly A*N. the remainder is reserved, and carry participates in the operation of the second lowest order.

#include <iostream>
#include <algorithm> 
#include <string>
using namespace std;
 
int main() {
    int a, n;
    cin >> a >> n;
    if (n == 0) {
        cout << 0;
        return 0;
    }
    string s = "";
    int r = 0, t;
    for (int i = n; i >= 1; --i) {
        t = i * a + r;
        r = t / 10;
        s += (t % 10 + '0');
    }
    while (r) {
    	t = r % 10;
		s += (t + '0');
		r /= 10;
	}
    reverse(s.begin(), s.end());
    cout << s;  
    return 0;
}

158 original articles published, 58 praised, 20000 visited+
Private letter follow

Topics: REST less Programming calculator