Study Notes on "Algorithm Notes"

Last updated on December 2, 2025 pm

This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.

Chapter 2 C/C++ Quick Start

2.1 Basic Data Types

2.1.2 Variable Types

When assigning an initial value greater than $2^{31}-1$ to a long long variable, you need to add LL after the initial value; otherwise, it will cause CE

long long bignum = 1234567890123456LL;

In short, if the problem requires values within $10^{9}$, use int; within $10^{18}$, use long long

Floating-point types: do not use float; just use double

char: lowercase letters have ASCII values 32 greater than uppercase letters

Character constants must be marked with single quotes to distinguish whether they are used as character variables or character constants

Escape Characters

\n 代表换行
\0 代表空字符NULL,其ASCII码为0

String Constants: A character set marked by double quotes; it can be assigned as an initial value to a character array and output using %s

You cannot assign a string constant to a character variable

char c="abcd"

is not allowed

Boolean Type

Only 0 is False; all other integers are True

2.1.3 Type Casting

(新类型名)变量名

If you assign a variable of one type to a variable of another type without writing an explicit cast, the IDE will automatically cast it

However, if a cast is needed during calculation, you cannot wait until the calculation is finished to cast

2.1.4 Symbolic Constants and const Constants

The format is

#define 标识符 常量

or

const 数据类型 变量名 = 常量;

Once the value of a constant is determined, it cannot be changed.

In addition to defining constants, define can also define any statement or fragment (macro definition). The format is as follows

#define 标识符 任何语句或者片段

For example

#include<stdio.h>
#define ADD(a,b) ((a)+(b)) //为什么要加这么多括号?是因为宏定义是直接将对应的部分替换,然后才进行编译和运行
int main(){
    int num1 =3, num2 =5;
    prints("%d", ADD(num1,num2)); //8
    return 0;
}

Therefore, try not to use macro definitions for anything other than defining constants

2.1.5 Operators

Only review bitwise operators see Oiwiki for details

2.2 Sequential Structure

scanf Format Specifiers for Common Data Type Variables

Data Type Format Specifier
int %d
long long %lld
float %f
double %lf
char %c
String (char array) %s

No need to add & when reading a string

In addition, if you want to input two numbers separated by a space such as “3 4”, the two %d can be written directly without a space

int a, b;
scanf("%d%d", &a, &b);

Reason: except for %c, scanf uses whitespace (space, tab) as the end-of-input marker for other format specifiers (such as %d)
In addition, when a character array is read using %s, spaces and newlines are used as the end-of-input markers
That is, scanf's %c format can read spaces and newlines!

printf Format Specifiers for Common Data Type Variables

Data Type Format Specifier
int %d
long long %lld
float %f
double %f
char %c
String (char array) %s

The only difference from scanf is double

Three Practical Output Formats

  1. %md
    %md can make an int variable with fewer than m digits output right-aligned in m digits, padding the high-order positions with spaces; if the variable itself exceeds m digits, it remains as is (no truncation)
#include <bits/stdc++.h>
using namespace std;   
int main()
{
    int a=123, b=1234567;
    printf("%5d\n",a);
    printf("%5d\n",b);
    return 0;
}

Output format

  123
1234567

Two spaces are padded before 123
2. %0md pads with leading 0s

#include <bits/stdc++.h>
using namespace std;   
int main()
{
    int a=123, b=1234567;
    printf("%05d\n",a);
    printf("%05d\n",b);
    return 0;
}

Output format

00123
1234567
  1. %.mf outputs with m decimal places (not equivalent to rounding)

2.2.3 Using getchar and putchar to Input/Output Characters

getchar is used to input a single character, and putchar is used to output a single character. In some situations where using the scanf function is inconvenient, getchar can be used to input characters.

#include <stdio.h>
int main(){
char cl,c2,c3;
c1 =getchar();
getchar();
c2 =getchar();
c3 = getchar();
putchar(c1);
putchar(c2);putchar(c3);
return 0
}

Input data

abcd

Output result

acd

Here, the first character 'a' is received by c1; the second character 'b' is received but not stored in any variable; the third character c is received by c2; the fourth character 'd' is received by c3. After that, three consecutive putchar calls will output c1, c2, and c3 consecutively. If you input "ab", then press Enter, then input c, then press Enter again, the output will be like this:

a
c

This is because getchar can recognize newline characters, so c2 actually stores the newline character \n; therefore, a newline appears between a and c.

2.2.4 Comments

2.2.5 typedef

You can give a complex data type an alias

#include <cstdio>
Ltypedef long long LL;//给 1ong 1ong 起个别名
int main(){
LL a=123456789012345,b=234567890123456;//直接使用 LL
printf("lld\n",a+b);
return 0;
}

2.2.6 Common math Functions

  1. fabs(double x)
    Used to take the absolute value of a double variable

  2. floor(double x) ceil(double x)

  3. pow(double r, double p)
    Returns $r^{p}$

  4. sqrt(double x)

  5. log(double x)
    Returns ln x
    In C, you cannot specify the base, so you must use the change-of-base formula.

  6. sin(double x) cso(double x) tan(double x)
    The argument must be in radians

  7. asin(double x) acos(double x) atan(double x)
    Inverse trigonometric functions

  8. round(double x)
    Rounds a double variable, and the return value is still of type double

2.3 Selection Structure

2.3.1 if Statement

2.3.3 switch Statement

Remember what break fallthrough is

2.4 Loop Structure

2.4.1 while Statement

2.4.2 do...while Statement

#include <iostream>

int main() {
    int sum = 0;
    int i = 1;

    do {
        sum += i;
        i++;
    } while (i <= 100);

    std::cout << "The sum of numbers from 1 to 100 is: " << sum << std::endl;

    return 0;
}

do...while executes the loop body once first, then checks whether the loop condition is true

2.4.3 for Statement

引用for (int x : s) is a range-based for loop syntax introduced in C++11. It...

for (int x : s) is a range-based for loop syntax introduced in C++11. Its purpose is to iterate over each element in container s, assign each element to variable x, and then process x in the loop body.


Syntax Analysis

for (int x : s) {
 // 循环体
}
  • int x: Define a variable x used to store each element in container s. The type of x should be consistent with the type of elements in container s.
  • s: An iterable container (such as std::vector, std::set, std::list, etc.).
  • :: Indicates iterating over each element in container s.
  • {}: The loop body, the operation performed on each element x.

Comparison with Traditional for Loop

Traditional for Loop

for (auto it = s.begin(); it != s.end(); ++it) {
    int x = *it;
    // 循环体
}

Range-based for Loop

for (int x : s) {
    // 循环体
}

The advantages of range-based for loops are:

  1. Concise: no need to manually manage iterators.
  2. Readable: directly expresses the intent to “iterate over each element in the container”.
  3. Safe: avoids iterator out-of-bounds or errors.

Example: Iterating over std::set

#include <iostream>
#include <set>

int main() {
    std::set<int> s = {10, 20, 30};

    for (int x : s) {
        std::cout << x << " "; // 输出 10 20 30
    }

    return 0;
}

Notes

  1. Element type matching:

    • The type of x must be consistent with the type of elements in container s. If you are unsure of the type, you can use auto:

      for (auto x : s) {
          // 循环体
      }
  2. Avoid copying:

    • If the elements in the container are complex types (such as std::string or custom classes), directly using for (auto x : s) will cause copying of elements. To avoid copying, you can use references:

      for (const auto& x : s) {
          // 循环体
      }
  3. Modifying elements:

    • If you need to modify elements in the container, you can use a non-const reference:

      for (auto& x : s) {
          x = x * 2; // 修改元素
      }

2.4.4 break and continue Statements

2.5 Arrays

2.5.1 One-Dimensional Arrays

Remember initialization; there are two ways to assign 0: assign the first element to 0, or use only a pair of braces

int a[10]={0};
int a[10]={};

Recurrence:

for(int i=1;i<10;i++){
    a[0] =1;
    a[1] =1;
    a[i+1]=a[i]+a[i-1];
} //斐波那契数列

2.5.2 Bubble Sort

for (int j = 0; j < len - 1; j++){      //长度为 n 的数组,只需要执行这样的排序循环 n-1 次
    for (int i = 0; i < len - 1 - j; i++){
            int temp = arr[i];
            if (arr[i] > arr[i + 1]){
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
    }

Don't forget the standard way to swap two numbers

2.5.3 Two-Dimensional Arrays

Initialization method

int a[5][6] = {{}}; //默认全部赋值 0

If the array size is large (around the $10^{6}$ level), it needs to be defined outside the main function

2.5.4 memset — Assign the Same Value to Every Element in an Array

The format is

memset(数组名, 值, sizeof(数组名));

It is only recommended to use memset to assign 0 or -1, because memset assigns the same value to each byte. If you want to assign other numbers, use the fill function.

2.5.5 Character Arrays

Initialization of Character Arrays

Besides assigning values one by one during assignment

char str[3] = {'a', 'b','\0'};

You can also initialize by directly assigning a string only during initialization; assigning the entire string directly like this is not allowed elsewhere in the program

char str[15] = "Good Day!";

Input and Output of Character Arrays

  1. scanf input, printf output %s treats whitespace as the end of the string
  2. getchar input, putchar output
代码CPP · 19 行
#include <bits/stdc++.h>
using namespace std;   
int main()
{
    char str[5][5];
    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            str[i][j]=getchar();
            getchar(); //这句是为了把输入中每行末尾的换行符吸收掉
        }
    }
    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            putchar(str[i][j]);
        }
        putchar('\n');
    }
    return 0;
}

This code is an example of a two-dimensional array; whatever is input is output. 3. gets input, puts output Deprecated after C11 Now, to read a line of string, you can use while c!=\n or getline

Storage Method of Character Arrays

The end is a '\0' Only char arrays need attention; be sure that the length is at least 1 more than the actual stored string length

2.5.6 string.h Header File

  1. strlen(): gets the number of characters before the first \0 in a character array

  2. strcmp(): returns the comparison result of the sizes of two strings; the comparison principle is lexicographical order

    引用In C++, lexicographical comparison of strings is performed character by...

    In C++, lexicographical comparison of strings is performed character by character based on the ASCII values of the characters. The rules of lexicographical comparison are similar to the ordering rules for words in an English dictionary. The following is a detailed explanation of lexicographical comparison of strings:


    1. Lexicographical Comparison Rules

    1. Character-by-character comparison:

      • Starting from the first character of the strings, compare the characters at corresponding positions one by one.
      • If the ASCII values of two characters are different, the string containing the character with the smaller ASCII value is smaller.
    2. Length comparison:

      • If the prefixes of two strings are exactly the same, but one string is longer than the other, the shorter string is smaller.

    2. Example Explanation

    Example 1

    • Strings "apple" and "banana":
      • Compare the first character: 'a' (ASCII 97) and 'b' (ASCII 98).
      • Because 'a' < 'b', "apple" < "banana".

    Example 2

    • Strings "apple" and "apricot":
      • The first two characters are the same ('a' and 'p').
      • Compare the third character: 'p' (ASCII 112) and 'r' (ASCII 114).
      • Because 'p' < 'r', "apple" < "apricot".

    Example 3

    • Strings "apple" and "app":
      • The first three characters are the same ('a', 'p', 'p').
      • "app" is shorter than "apple", so "app" < "apple".

    3. String Comparison in C++

    In C++, string comparison can be implemented in the following ways:

    1. Using comparison operators:

      • ==: checks whether two strings are equal.
      • !=: checks whether two strings are not equal.
      • <: checks whether the first string is less than the second string.
      • >: checks whether the first string is greater than the second string.
      • <=: checks whether the first string is less than or equal to the second string.
      • >=: checks whether the first string is greater than or equal to the second string.
    2. Example code:

      代码CPP · 18 行
      #include <iostream>
      #include <string>
      using namespace std;
                                                                                                                                                                                                
      int main() {
          string s1 = "apple";
          string s2 = "banana";
                                                                                                                                                                                                
          if (s1 < s2) {
              cout << s1 << " is less than " << s2 << endl;
          } else if (s1 > s2) {
              cout << s1 << " is greater than " << s2 << endl;
          } else {
              cout << s1 << " is equal to " << s2 << endl;
          }
                                                                                                                                                                                                
          return 0;
      }

    Output

    apple is less than banana

    4. Applications of Lexicographical Order

    Lexicographical comparison is very useful in the following scenarios:

    1. String sorting:

      • For example, sort a group of words in lexicographical order.
      • Example:
        vector<string> words = {"banana", "apple", "apricot"};
        sort(words.begin(), words.end());
        // 排序后:["apple", "apricot", "banana"]
    2. Number concatenation problem:

      • In the number concatenation problem, by comparing the lexicographical order of concatenated strings, you can find the largest concatenation result.
    3. Finding the minimum or maximum string:

      • For example, find the lexicographically smallest or largest string in a group of strings.

    5. Notes

    1. Case sensitivity:

      • Lexicographical comparison is case-sensitive. For example, 'A' (ASCII 65) and 'a' (ASCII 97) are different characters.
      • If you need to ignore case, you can first convert the strings to a uniform case.
    2. Comparison of numeric strings:

      • For numeric strings (such as "123" and "45"), lexicographical comparison may not match the comparison result of their numeric values.
      • For example, "123" < "45" (because '1' < '4'), but numerically 123 > 45.

    6. Summary

    • Lexicographical comparison of strings is performed character by character based on the ASCII values of the characters.
    • If the prefixes of two strings are the same, the shorter string is smaller.
    • In C++, you can directly use comparison operators (such as <, >) to compare the lexicographical order of strings.
    • Lexicographical comparison is very useful in scenarios such as string sorting and number concatenation problems.

    If you have other questions, feel free to continue asking!

  3. strcpy()

strcpy(字符数组1, 字符数组2);

Note: this assigns character array 2 to character array 1; the copy here also includes \0

  1. strcat()
strcat(字符数组1, 字符数组2);

Note: this appends character array 2 to the end of character array 1

2.5.7 sscanf and sprintf

Literally, sscanf can be understood as string+scanf, and sprintf can be understood as string+printf; both are under the stdio.h header file.
First, let's review scanf and printf, which can actually be written in this form:

scanf(screen, "%d", &n);
printf(screen, "%d", n);

It can be seen that scanf input actually transfers the content on screen to n in the "%d" format (i.e., from left to right).
And printf output transfers n to screen in the "%d" format (i.e., from right to left). sscanf and sprintf have the same format as above, except that screen is replaced with a character array
(suppose a char array str[100] has been defined), as shown below:

sscanf(str, "%d", &n);
sprintf(str, "%d", n);

The effect of the sscanf form above is to write the content in character array str into n in the "%d" format (still from left to right).
And the effect of the sprintf form is to write n into the character array str in the "%d" format (still from right to left). An example is as follows:

#include <bits/stdc++.h>
using namespace std;   
int main()
{
    int n=233;
    char str[100];
    sprintf(str,"%d", n);
    printf("%s\n", str);
    return 0;
}

Output result

233

The above are only some simple applications. In fact, you can perform complex formatted input and output just as with scanf and printf. For example, the following code uses sscanf to write the content in character array str into int variable n, double variable db, and char array str2 in the "%d:%lf,%s" format.

#include <bits/stdc++.h>
using namespace std;   
int main()
{
    int n;
    double db;
    char str[1000] = "2048:3.14,hello", str2[100];
    sscanf(str, "%d:%lf,%s",&n, &db, str2);
    printf("n=%d,db=%.2f,str2=%s\n",n,db,str2);
    return 0;
}

The output is

n=2048,db=3.14,str2=hello

Similarly

#include <bits/stdc++.h>
using namespace std;   
int main()
{
    int n=12;
    double db=3.1415;
    char str[1000], str2[100]="good";
    sprintf(str, "%d:%.2f,%s",n, db, str2);
    printf("str=%s\n",str);
    return 0;
}

Output result

str=12:3.14,good

2.6 Functions

2.6.1 Function Definition

  • Global variables: variables defined before all functions and valid within all program segments after their definition
  • Local variables: defined inside a function and only take effect inside the function; after the function ends, local variables are destroyed
  • Parameters inside the parentheses in a function definition are called formal parameters, abbreviated as parameters, while parameters inside the parentheses during an actual call are called actual parameters or arguments

2.6.2 More on the main Function

return 0; tells the system that the program terminated normally

2.6.3 Using Arrays as Function Parameters

When an array is used as a parameter, the length of the first dimension of the array does not need to be filled in (if it is a two-dimensional array, the length of the second dimension needs to be filled in); in an actual call, only the array name needs to be filled in.
When an array is used as a parameter, modifications to array elements inside the function are equivalent to modifications to the elements of the original array (this is different from ordinary local variables) For example

void change(int b[][5]){ //第二维要注明长度

}

An array can be passed in as a parameter, but cannot be used as a return type.

2.6.4 Nested Function Calls

2.6.5 Recursive Function Calls

Recursion is the process of a function calling itself; it will be introduced in detail in Chapter 4

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

int F(int n){
    if(n==0) return 1;
    else return F(n-1)*n;
}
int main()
{
    int n=12;
    cin>>n;
    return 0;
}

2.7 Pointers

A pointer is an int of unsigned type

2.7.2 Pointer Variables

Pointer variables are used to store pointers (or can be understood as addresses); this means treating an address as a constant, then specially defining a pointer variable to store it. Add an asterisk * after a data type to indicate that this is a pointer variable

If several pointer variables are to be defined at the same time, the asterisk only binds to the first variable name

int* p1, p2; //p1 是 int*类型的 p2 是 int 类型的

One way to assign a value to a pointer variable: the usual way to assign a value to a pointer variable is to take out the address of a variable (using the address-of operator &), and then assign it to the corresponding pointer variable:

int a;
int *p = &a;

or

int a;
int *p;
p = &a;

The address &a is assigned to p, not to *p; remember that the asterisk is part of the type

For a pointer variable, dereferencing also uses the asterisk *, as in the following code

int main(){
    int a;
    int *p=&a;
    a=233;
    printf("%d",*p); //输出 233
}

In the above code, an int variable a is first defined but not initialized. Then a pointer variable p is defined, and the address of a is assigned to p. At this point p stores the address of a. After that, a is assigned 233, which means the contents of the room at the address where a is located have been changed, but this does not affect its address. In the later output, the asterisk * is used as the key to open the room and placed before p, so that *p can obtain what is in the room, that is, the stored data.

This can be extended: since p stores an address and *p is the element stored at this address, directly assigning to * can also change the stored element

int main(){
    int a;
    int *p=&a;
    *p=233;
    printf("%d",a); //输出 233
}

Pointer variables can be added and subtracted. For an int* variable p, p+1 is the address of the next int variable after the int variable pointed to by p

2.7.3 Pointers and Arrays

The array name can be used as the first address of the array That is, if int arr[] is defined, then a==&a[0];
and a+i==&a[i], *(a+i)==a[i]; Subtracting two pointers of type int is equivalent to finding how many ints apart the two pointers are, as in the following code

int a[5];
int *p=a;
int *q=a+5;
cout<<q-p;

will output 5; this explanation also applies to pointers of other types

2.7.4 Using Pointer Variables as Function Parameters

In this case, it is regarded as passing the address of the variable into the function. If the element at this address is changed inside the function, then the original data will indeed be changed.
A classic example is using pointers as parameters to swap two numbers.

void _swap(int *a, int *b){
    int temp=*a; 
    *a=*b;
    *b=temp;
}

Classic mistake 1

void _swap(int *a, int *b){
    int *temp; 
    *temp=*a;
    *a=*b;
}

Cause of the error: the pointer temp is not initialized and is a wild pointer; it very likely points to the system working area, and the probability of an error at a random address is very high.

Solution:

void _swap(int *a, int *b){
    int x;
    int *temp=&x; 
    *temp=*a;
    *a=*b;
}

Classic mistake 2

void _swap(int *a, int *b){
    int *temp=a;
    a=b;
    b=temp;
}

Cause of the error: recall what was said earlier—function parameters are passed in a one-way, one-time manner. The “address” passed from the main function to the swap function is actually just an unsigned int; modifying the address itself in swap cannot modify the address inside the main function. The only thing that can change the data inside the main function is a modification, inside the swap function, to the data pointed to by the address. This function is actually very similar to why one cannot write a function like this

void _swap(int a, int b){
    int temp=a; 
    a=b;
    b=temp;
}

Because they are actually all just copies.

2.7.5 References

Meaning of References

A syntax unique to C++: give the original variable an alias, and operations on the reference variable are operations on the original variable A reference does not produce a copy
Method: just add an & after the parameter type of the function
Be careful to distinguish it from the & address-of operator

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

void change(int&x){
    x=2;
}
int main()
{
    int n=1;
    change(n);
    cout<<n;
}

References to Pointers

References can be used to fix Classic Mistake 2 above

void _swap(int* &p1, int* &p2){
    int *temp=p1;
    p1=p2;
    p2=temp;
}

Here, int* is effectively treated as an unsigned int type, and swapping two such integer variables requires using a reference
What is passed in is an alias of the pointer.
Constants cannot use references

引用In C++, a reference (Reference) is a special variable type that provides...

In C++, a reference (Reference) is a special variable type that provides an alias for another variable. A reference itself does not occupy extra memory space; it simply points to the memory address of another variable. Through a reference, you can directly manipulate the referenced variable without needing to access it indirectly through a pointer.

The syntax for declaring a reference is as follows:

类型 &引用名 = 变量名;
  • 类型: the type of the referenced variable.
  • 引用名: the name of the reference, used for subsequent operations.
  • 变量名: the name of the variable being referenced.

Example:

#include <iostream>

int main() {
    int a = 10;  // 定义一个整型变量 a
    int &ref = a;  // 定义一个引用 ref,它指向变量 a

    std::cout << "a = " << a << std::endl;  // 输出:a = 10
    std::cout << "ref = " << ref << std::endl;  // 输出:ref = 10

    ref = 20;  // 通过引用修改 a 的值

    std::cout << "a = " << a << std::endl;  // 输出:a = 20
    std::cout << "ref = " << ref << std::endl;  // 输出:ref = 20

    return 0;
}

Key points:

  1. Initialization: A reference must be initialized when it is declared, and once initialized, it cannot refer to another variable.

    int a = 10;
    int &ref = a;  // 正确
    int &ref2;  // 错误,引用必须初始化
  2. Alias: A reference is actually an alias of a variable; operations on the reference are operations on the original variable.

    int a = 10;
    int &ref = a;
    ref = 20;  // 等同于 a = 20;
  3. Cannot be null: A reference cannot be null; it must always refer to some valid object.

    int &ref = nullptr;  // 错误,引用不能为空
  4. Constant reference: You can declare a constant reference, in which case the reference cannot modify the referenced variable.

    int a = 10;
    const int &ref = a;  // 常量引用
    ref = 20;  // 错误,常量引用不能修改被引用的变量
  5. References as function parameters: References are often used for function parameter passing to avoid copying large objects, and they allow direct modification of the passed-in arguments.

    void increment(int &value) {
        value++;
    }
                                                                                                                                                                                                                                                                                        
    int main() {
        int a = 10;
        increment(a);
        std::cout << a << std::endl;  // 输出:11
        return 0;
    }

Summary:

References are a very powerful tool in C++, allowing you to manipulate variables in a more intuitive way and avoiding the complexity of pointers. Through a reference, you can directly modify the referenced variable without needing to access it indirectly through a pointer. References are widely used in function parameter passing, return values, and more.

2.8 Using Structs

2.8.1 Defining a Struct

An example

typedef struct
{
    char name;
    int count;
}spot;

Ways to define struct variables

typedef struct
{
    char name;
    int count;
}spot;
spot A;
spot B;
spot str[100];

or

struct spot
{
    char name;
    int count;
}A, B, str[100];

A struct cannot define an instance of itself, but it can define a pointer variable of its own type
An example

代码CPP · 40 行
#include <iostream>

// 定义一个链表节点结构体
struct Node {
 int data;           // 节点数据
 Node* next;         // 指向下一个节点的指针
};

int main() {
 // 创建链表节点
 Node* head = new Node();
 head->data = 1;
 head->next = nullptr;

 Node* second = new Node();
 second->data = 2;
 second->next = nullptr;

 Node* third = new Node();
 third->data = 3;
 third->next = nullptr;

 // 将节点连接起来
 head->next = second;
 second->next = third;

 // 遍历链表并输出数据
 Node* current = head;
 while (current != nullptr) {
     std::cout << current->data << " ";
     current = current->next;
 }

 // 释放链表内存
 delete head;
 delete second;
 delete third;

 return 0;
}

2.8.2 Accessing Elements Inside a Struct

Two methods

struct StudentInfo{
    int id;
    char name[20];
    studentInto *next;
}stu, *p;

How to access a variable

stu.id
stu.name
stu.next

To access the pointer variable p

(*p).id //先解引用为一个 struct 变量
(*p).name
(*p).next

Another way to write it

p->id
p->name
p->next

How to write an assignment

stu.id = 10086;
int getID = stu.id;

2.8.3 Initializing a Struct

Use a constructor, a function used to initialize a struct, which has the following characteristics

  1. Defined directly inside the struct
  2. Does not need a return type
  3. The function name is the same as the struct name
  4. Generated by default, with no parameters and no function body; you need to write it yourself
代码CPP · 21 行
struct StudentInfo {
    int id;
    char gender;

    //用以不初始化就定义结构体变量
    StudentInfo(){}
    // 构造函数,用于初始化结构体内部变量
    StudentInfo(int _id, char _gender) {
        id = _id;
        gender = _gender;
    }
    /* 另一种写法,使用成员初始化列表
    StudentInfo(int _id, char _gender) : id(_id), gender(_gender) {}
    */
    //只初始化 gender
    StudentInfo(char _gender){
        gender = _gender;
    }
};

StudentInfo student(12345, 'M');

As long as the number and types of parameters are not exactly the same, you can freely define any number of constructors to suit different initialization scenarios.
Note: It is precisely because the default constructor, when you have not redefined one yourself, has nothing at all, that struct variables can be defined without initialization (think about how the definition works when the constructor is not initialized?). Therefore, if you redefine a constructor yourself, you can no longer define struct variables without initialization!

2.9 Additional Material

2.9.1 cin and cout

  1. cin's input does not specify a format, and there is no need to add the address-of operator &; just write the variable name directly
    The way to read in multiple variables at once
cin>>n>>db>>c>>str;

If you want to read in an entire line, use the getline function

char str[100];
cin.getline(str,100);
引用getline is a function in the C++ standard library used to read a line of...

getline is a function in the C++ standard library used to read a line of text from an input stream (such as cin). Unlike cin's >> operator, getline can read an entire line of text containing spaces, until it encounters a newline character (\n).

Syntax

The basic syntax of the getline function is as follows:

std::getline(std::cin, string_variable);
  • std::cin: the input stream object, usually the standard input stream.
  • string_variable: a variable of type std::string, used to store the read text.

Example

The following is a simple example showing how to use the getline function with cin to read a line of text entered by the user:

#include <iostream>
#include <string>

int main() {
    std::string name;

    std::cout << "请输入你的名字:";
    std::getline(std::cin, name);

    std::cout << "你好," << name << "!" << std::endl;

    return 0;
}

Explanation

  1. Including header files:

    #include <iostream>
    #include <string>

    Include the necessary header files; <iostream> is used for input/output stream operations, and <string> is used for the std::string type.

  2. Defining a string variable:

    std::string name;

    Define a variable name of type std::string to store the text entered by the user.

  3. Prompting the user for input:

    std::cout << "请输入你的名字:";

    Use std::cout to output a prompt asking the user to enter their name.

  4. Reading user input:

    std::getline(std::cin, name);

    Use the std::getline function to read a line of text from std::cin and store it in the name variable.

  5. Outputting the result:

    std::cout << "你好," << name << "!" << std::endl;

    Use std::cout to output a greeting that includes the name entered by the user.

Notes

  • Reading an entire line of text: The getline function reads the entire line of text, including spaces and tabs, until it encounters a newline character (\n).
  • Handling the newline character: getline handles the newline character automatically and does not include it in the read text.
  • Difference from cin >>: The cin >> operator skips spaces and newline characters when reading strings, reading only the content between the first non-whitespace character and the next whitespace character.

Summary

The getline function is a very useful tool, especially when you need to read an entire line of text containing spaces. Combined with cin, you can conveniently read a line of text from user input and process it afterwards. char str[100]; cin.getline(str,100);

  1. Controlling precision with cout is a real hassle; scanf and printf are better

2.9.2 Comparison of Floating-Point Numbers

Introduce a small quantity eps to correct the floating-point errors of the computer, and then implement error-correcting code through a series of macro definitions Generally take

const double eps = 1e-8;

The core part (draw a few number lines to understand)

const double eps=1e-8;
const double PI=acos(-1.0)

#define Equ(a,b) ((fabs((a)-(b)))<(eps))
#define More(a,b) (((a)-(b))>(eps))
#define Less(a,b) (((a)-(b))<(-eps))
#define MoreEqu(a,b) (((a)-(b))>(-eps))
#define LessEqu(a,b) (((a)-(b))<(eps))

Due to precision issues, a 0 may become a very small negative number after a series of operations. In that case, performing certain operations such as sqrt will raise an error, so eps is needed to ensure the variable itself stays within its domain For example

代码CPP · 20 行
#include <iostream>
#include <cmath>

const double eps = 1e-9;

int main() {
    double x = -1e-15;

    // 确保 x 在定义域内
    if (x < 0) {
        x = eps;
    }

    // 计算平方根
    double result = std::sqrt(x);

    std::cout << "sqrt(" << x << ") = " << result << std::endl;

    return 0;
}

2.9.3 Complexity

Time Complexity

Definition: the level at which the number of basic operations an algorithm needs to execute falls
Basic operations: operations that can be executed directly, such as addition, subtraction, multiplication, and division

for(int i=0;i<n;i++){
    sum+=i;
}

The for loop executes n times, so the time complexity is O(n), i.e., linear growth

for(int i=0;i<n;i++){
    for(int j=0;j<n;j++){
        sum+=arr[i][j];
    }
}

The number of basic operations is $n^{2}$, so the time complexity is O($n^{2}$)
Similar to infinitesimals, higher-order powers will dominate lower-order powers
Evaluating time complexity: generally, an OJ system can handle roughly $10^{7}$ to $10^{8}$ operations per second, which serves as the criterion for judgment

Space Complexity

Represents the maximum amount of space an algorithm needs to consume, but usually space is sufficient while time is not, so time can be traded for space

Coding Complexity

Simply whether you feel the code is very complicated — a rather vague, qualitative concept

2.10 Black-Box Testing

It is recommended to go back and read the book directly, but one point here is worth mentioning
The scanf() function actually has a return value, which is the number of arguments passed in; when no arguments are passed in, it returns -1, and EOF can be used to represent -1

while(scanf("%d",&a)!=EOF){
    ......
}

2.11 Lambda Expressions

A lambda expression is an anonymous function that can be declared at any time in the code. In other words, lambda expressions allow you to declare a temporary function right where you need to use it, without having to define it beforehand.

[捕获列表](参数列表) -> 返回类型 { 函数体 };
  • Capture list: this allows the lambda to access external variables.
  • Parameter list: just like the parameter list of a normal function.
  • Return type: this can be omitted; the compiler will automatically deduce the return type.
  • Function body: the actual execution content of the lambda, just like a small function.

An example — suppose you need to temporarily compute the product of two numbers in your code:

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

int main(){
  int x,y;
  auto multiply=[](int a,int b)->int{
    return a*b;
  }
  cout<<multiply(x,y)<<endl;
  return 0;
}

In this code, we create a lambda expression via auto multiply = [](int a, int b) -> int { return a * b; };. This lambda function takes two parameters a and b and returns their product. We then call multiply(x, y) and output the result.

Another example: determining whether a number is even

auto isEven=[](int x)->bool{return x%2==0;}

About the capture list

The capture list determines which external variables the lambda can access, and whether they are captured by value or by reference.

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

int main(){
  int factor=2;
  auto multiplyByFactor=[factor](int x)->int{return x*factor;}
  return 0;
}

In this example, the lambda expression multiplyByFactor captures the external variable factor and uses it in its function body. The capture list [factor] allows the lambda to "remember" the value of this variable, even if the value has changed by the time the function is called.

Some Special Uses of Lambda Expressions

Storing in a Variable and Calling

#include <iostream>

int main() {
    // 将 lambda 表达式存储在变量中
    auto printMessage = []() {
        std::cout << "Hello, World!" << std::endl;
    };

    // 在后面需要的时候调用它
    printMessage(); // 输出:Hello, World!
    printMessage(); // 可以多次调用
    return 0;
}

Returning a Lambda Expression

You can write a function that returns a lambda expression for later use:

#include <iostream>

auto createMultiplier(int factor) {
    return [factor](int x) { return x * factor; };
}

int main() {
    auto doubleValue = createMultiplier(2); // 创建一个将值乘以 2 的 lambda
    auto tripleValue = createMultiplier(3); // 创建一个将值乘以 3 的 lambda

    std::cout << doubleValue(5) << std::endl; // 输出:10
    std::cout << tripleValue(5) << std::endl; // 输出:15

    return 0;
}
引用In C++ lambda expressions, [&] means capturing by reference all external...

In C++ lambda expressions, [&] means capturing by reference all external variables used in the lambda function body. This means:

  • If an external variable is used inside the lambda, that variable is captured by reference.
  • Modifications you make to these variables inside the lambda will directly affect their values outside.

Example

#include <iostream>

int main() {
    int a = 5, b = 10;
    
    // 定义一个 lambda 表达式,按引用捕获所有外部变量
    auto func = [&]() {
        a += 1;
        b += 1;
        std::cout << "Inside lambda: a = " << a << ", b = " << b << std::endl;
    };
    
    func();  // 调用 lambda 表达式
    std::cout << "Outside lambda: a = " << a << ", b = " << b << std::endl;
    
    return 0;
}

Output:

Inside lambda: a = 6, b = 11
Outside lambda: a = 6, b = 11

As shown above, since [&] captures by reference, modifications to a and b inside the lambda directly affect the external variables.

Comparison with Other Capture Modes

  • [=]: captures all external variables by value; modifications to the variables inside the lambda do not affect the external variables.
  • [a, &b]: captures variable a by value and variable b by reference. Capture modes can be mixed in this way.

In summary, [&] is a convenient capture mode, very useful when you need to use external variables inside a lambda and want to be able to modify them directly.

Example of a Recursive Lambda Expression (When the Return Type Cannot Be Determined)

#include <functional> // 需要添加此头文件

// 在 main 函数内:
std::function<void(int, int)> dfs; // 显式声明为 function 类型
dfs = [&](int now, int step) {
    if (step >= f[now]) return;
    f[now] = step;
    if (now == b) return;
    vis[now] = true;
    if (now + k[now] <= n && !vis[now + k[now]]) {
        dfs(now + k[now], step + 1); // 现在可以正确递归
    }
    if (now - k[now] >= 1 && !vis[now - k[now]]) {
        dfs(now - k[now], step + 1);
    }
    vis[now] = false;
};

Chapter 4: Getting Started (2) — Introduction to Algorithms

4.1 Sorting

4.1.1 Selection Sort

4.1.2 Insertion Sort

4.1.3 Sorting Problems and the Use of the sort Function

引用Of course! The comparison function in std::sort is used to define the so...

Of course! The comparison function in std::sort is used to define the sorting order. The comparison function must return a boolean value indicating the relative order of two elements. Specifically, the comparison function should satisfy the following conditions:

  1. Strict Weak Ordering: The comparison function must define a strict weak ordering relation, which means it must satisfy the following conditions:

    • Irreflexivity: For all x, comp(x, x) must return false.
    • Antisymmetry: If comp(x, y) returns true, then comp(y, x) must return false.
    • Transitivity: If comp(x, y) returns true and comp(y, z) returns true, then comp(x, z) must return true.
  2. Consistency: If both comp(x, y) and comp(y, x) return false, then x and y are considered equal.

Example: Comparing Integers

Suppose we have an array of integers and we want to sort it in ascending order:

代码CPP · 21 行
#include <iostream>
#include <algorithm>  // 包含 std::sort
#include <vector>     // 包含 std::vector

// 比较函数:按升序排序
bool compareAscending(int a, int b) {
    return a < b;
}

int main() {
    std::vector<int> numbers = {5, 3, 8, 1, 2};

    std::sort(numbers.begin(), numbers.end(), compareAscending);

    for (int number : numbers) {
        std::cout << number << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output:

1 2 3 5 8

Example: Comparing Strings

Suppose we have an array of strings and we want to sort them in lexicographic (alphabetical) order:

代码CPP · 22 行
#include <iostream>
#include <algorithm>  // 包含 std::sort
#include <vector>     // 包含 std::vector
#include <string>     // 包含 std::string

// 比较函数:按字典序排序
bool compareLexicographically(const std::string &a, const std::string &b) {
    return a < b;
}

int main() {
    std::vector<std::string> names = {"Alice", "Bob", "Charlie", "David", "Eve"};

    std::sort(names.begin(), names.end(), compareLexicographically);

    for (const auto &name : names) {
        std::cout << name << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output:

Alice Bob Charlie David Eve

Example: Comparing Structs

Suppose we have an array of structs containing student information and we want to sort them by age:

代码CPP · 33 行
#include <iostream>
#include <algorithm>  // 包含 std::sort
#include <vector>     // 包含 std::vector
#include <string>     // 包含 std::string

struct Student {
    std::string name;
    int age;
    float gpa;
};

// 比较函数:按年龄排序
bool compareStudentsByAge(const Student &a, const Student &b) {
    return a.age < b.age;
}

int main() {
    std::vector<Student> students = {
        {"Alice", 20, 3.8},
        {"Bob", 22, 3.5},
        {"Charlie", 21, 3.7},
        {"David", 19, 3.9},
        {"Eve", 23, 3.6}
    };

    std::sort(students.begin(), students.end(), compareStudentsByAge);

    for (const auto &student : students) {
        std::cout << "Name: " << student.name << ", Age: " << student.age << ", GPA: " << student.gpa << std::endl;
    }

    return 0;
}

Output:

Name: David, Age: 19, GPA: 3.9
Name: Alice, Age: 20, GPA: 3.8
Name: Charlie, Age: 21, GPA: 3.7
Name: Bob, Age: 22, GPA: 3.5
Name: Eve, Age: 23, GPA: 3.6

Example: Multi-Condition Comparison

Suppose we want to sort by GPA when the ages are the same, and by name when the GPAs are also the same:

代码CPP · 39 行
#include <iostream>
#include <algorithm>  // 包含 std::sort
#include <vector>     // 包含 std::vector
#include <string>     // 包含 std::string

struct Student {
    std::string name;
    int age;
    float gpa;
};

// 比较函数:按年龄、GPA、名字排序
bool compareStudents(const Student &a, const Student &b) {
    if (a.age != b.age) {
        return a.age < b.age;
    }
    if (a.gpa != b.gpa) {
        return a.gpa > b.gpa;  // 按 GPA 降序排序
    }
    return a.name < b.name;
}

int main() {
    std::vector<Student> students = {
        {"Alice", 20, 3.8},
        {"Bob", 22, 3.5},
        {"Charlie", 21, 3.7},
        {"David", 19, 3.9},
        {"Eve", 23, 3.6}
    };

    std::sort(students.begin(), students.end(), compareStudents);

    for (const auto &student : students) {
        std::cout << "Name: " << student.name << ", Age: " << student.age << ", GPA: " << student.gpa << std::endl;
    }

    return 0;
}

Output:

Name: David, Age: 19, GPA: 3.9
Name: Alice, Age: 20, GPA: 3.8
Name: Charlie, Age: 21, GPA: 3.7
Name: Bob, Age: 22, GPA: 3.5
Name: Eve, Age: 23, GPA: 3.6

Summary

The comparison function is the core part of std::sort; it determines the sorting order. The comparison function must return a boolean value indicating the relative order of two elements. By writing different comparison functions, you can implement all kinds of sorting requirements.

Sorting problems generally provide a lot of information about each individual. For convenience, this information is often all stored in a single struct.

struct Student{
	char name[10];
	char id[10];
	int score;
}stu[100100];

2. Writing the cmp Function (the strcmp function returns the result of comparing the sizes of two strings based on lexicographic order)

For example, with a sorting rule: if two students have different scores, the one with the higher score comes first; otherwise, the one whose name is lexicographically smaller comes first. You can write a cmp function like this:

bool cmp(Student a,Student b){
    if(a.score!=b.score) return a.score>b.score;
    else return strcmp(a.name,b.name)<0;
}//注意 strcmp 的返回值不一定是 1 或者 -1,与 IDE 有关

3. Implementing the Ranking

The rule is generally: individuals with different scores get different ranks, while individuals with the same score get the same rank but occupy one rank position.

For this kind of requirement, it is usually necessary to include the rank as a field in the struct when defining the struct type. Then, after the sorting is complete, there are two ways to compute the ranks:

  1. First set the rank of the first individual in the array to 1 (this individual has array index 0), then traverse the remaining individuals:

    • If the current individual's score equals the previous individual's score, then the current individual's rank = the previous individual's rank
    • Otherwise, the current individual's rank = array index + 1
    stu[0].r=1;
    for(int i=1;i<n;i++){
        if(stu[i].score==stu.[i-1].score){
            stu[i].r=stu[i-1].r;
        }
        else{
            stu[i].r=i+1;
        }
    }
  2. Sometimes you don't necessarily need to store the rank; you can just output it directly.

    int r=1;
    for(int i=0;i<n;i++){
        if(i>0&&stu[i].score!=stu[i-1].score){
            r=i+1;
        }
        //输出当前个体信息
    }

4.2 Hashing

4.2.1 Definition of Hashing and Integer Hashing

Hashing is a commonly used algorithmic idea.

For example, using a bool/int array hashTable to determine whether a number has appeared before — that is, using the input number as the array index to record properties of that number — is a good strategy of trading space for time, since the query complexity is O(1).

Below we give the definition of hashing, which can be condensed into one sentence: converting an element into an integer through a function, such that the integer can represent the element as uniquely as possible, where this conversion function is called the hash function H.

That is: if the element is key before conversion, then after conversion it becomes the integer H(key), and the resulting hash value is then recorded using an array.

For the case where key is an integer, the commonly used hash functions are:

  • Direct addressing method: H(key)=key or H(key)=a*key+b, i.e., a linear transformation

  • Middle-square method: take some of the middle digits of key² as the hash value

  • Division method: take the remainder of key divided by a number mod as the hash value, i.e., H(key)=key%mod

    This hash function can convert very large numbers into integers not exceeding mod, so they can be treated as valid array indices (note that the table length must be >= mod). Obviously, when mod is a prime, H(key) covers every number in the range [0, mod) as much as possible. Therefore, for convenience, TSize is generally taken to be a prime, and mod is set directly equal to TSize.

    However, it is easy to notice that this method may have two different numbers key1 and key2 such that H(key1)==H(key2); this situation is called a "collision".

    There are three methods below for resolving collisions; the first and second methods both compute a new hash value, and are collectively known as open addressing:

    1. Linear probing: when we obtain the hash value H(key) of key but the position with index H(key) in the table has already been occupied by some other element, we check whether the next position H(key)+1 is occupied. If not, we use that position; otherwise, we continue checking the next position (i.e., keep incrementing the hash value by 1). If the check exceeds the table length, we return to the beginning of the table and continue looping until we find a usable position, or discover that all positions in the table have been used. Obviously, this approach easily leads to clustering, i.e., several consecutive positions in the table being occupied, which reduces efficiency to some extent.

    2. Quadratic probing: in quadratic probing, in order to avoid clustering as much as possible, when the position with index H(key) in the table is occupied, the positions in the table are checked in the following order: H(key)+$1^{2}$, H(key)-$1^{2}$, H(key)+$2^{2}$, H(key)-$2^{2}$, H(key)+$3^{2}$…. If during the checking process H(key)+$k^{2}$ exceeds the table length TSize, then take H(key)+$k^{2}$ modulo the table length TSize;

      If during the checking process H(key)-$k^{2}$<0 occurs (assuming the table starts at index 0), then use ((H(key)-$k^{2}$)% TSize+ TSize)% TSize as the result (equivalent to repeatedly adding TSize to H(key)-$k^{2}$ until the first non-negative number appears). To avoid the trouble of negative numbers, you can perform only forward quadratic probing. It can be proven that if no position can be found for any k in the range [0, TSize), then no position can be found for k>TSize either.

    3. Chaining (separate chaining): unlike the two methods above, chaining does not compute a new hash value; instead, it links all keys with the same H(key) into a singly linked list (you can come back to this after studying Section 7.3). In this way, an array Link can be set up, spanning Link[0]~Link[mod], where Link[h] stores the singly linked list of keys with H(key)=h. Thus, when the hash values of multiple keys are all h, these colliding keys can be directly linked together using the singly linked list, and then this singly linked list can be traversed to find all keys with H(key)=h.

      Of course, generally speaking, you can use map from the standard template library (see Section 6.4) to directly obtain the functionality of hashing (after C++11 you can use unordered_map, which is faster), so unless you must simulate these methods or have high requirements on algorithm efficiency, you generally do not need to implement the collision-resolution methods above yourself.

4.2.2 Introduction to String Hashing

If the key is not an integer, how should the hash function be designed?

One example is: how to map the coordinates of a two-dimensional integer point P to an integer, such that the point P can be uniquely represented by that integer. Suppose the coordinates of an integer point P are (x,y), where 0<x,y<Range. Then we can define the hash function as H(P)=x*Range+y, so that for any two integer points P1 and P2 within the data range, H(P1) will never equal H(P2). Thus H(P) can uniquely represent the point P, and we can then further map it to a smaller range using the integer hashing method. The focus of this section is string hashing. String hashing refers to mapping a string S to an integer, such that the integer can represent the string S as uniquely as possible. This section only discusses converting a string into a unique integer; the advanced part is in Section 12.1.

To make the discussion easier, first assume that the strings consist only of uppercase letters A~Z. On this basis, we may treat A~Z as 0~25, which maps the 26 uppercase letters into base 26. Then, following the idea of converting base 26 to base 10, by the conclusions of base conversion, the resulting decimal number is definitely unique, thereby fulfilling the requirement of mapping a string to an integer (note: the maximum value of the converted integer is $26^{len}$-1, where len is the length of the string). The code is as follows:

int hashFunc(char s[],int len){ //hash 函数,将字符串 S 转换为整数
    int id=0;
    for(int i=0;i<len;i++){
        id=id*26+(s[i]-'A'); //将 26 进制转化为 10 进制
    }
    return id;
}

Obviously, len cannot be too long. If the string also contains lowercase letters, you can change base 26 to base 52, and it works the same way.

If digits appear, there are generally two ways to handle them: ① Following the approach for lowercase letters, increase the base to 62.

② If it is guaranteed that the string ends with a fixed number of digits, then you can convert the leading English-letter part into an integer using the approach above, and then directly append the trailing digits. For example, for the string "BCD4", composed of three characters plus one digit, you can first convert the leading "BCD" into the integer 731, and then directly append the trailing 4 to get 7314. The following code illustrates this example:

int hashFunc(char s[],int len){ //hash 函数,将字符串 S 转换为整数
    int id=0;
    for(int i=0;i<len-1;i++){
        id=id*26+(s[i]-'A'); //将 26 进制转化为 10 进制
    }
    id=id*10+(s[len]-'0');
    return id;
}

4.3 Recursion

4.3.1 Divide and Conquer

Divide and conquer, as the name suggests, means dividing the original problem into several subproblems that are smaller in scale and have the same or similar structure as the original problem, then solving these subproblems separately, and finally merging the solutions of the subproblems to obtain the solution to the original problem. In other words, the divide-and-conquer method can be divided into three steps:

  1. Divide
  2. Conquer
  3. Combine

It should be pointed out that the subproblems produced by divide and conquer should be independent of each other without overlap. If two subproblems have overlapping parts, then divide and conquer should not be used to solve the problem.

In particular, the case where the number of subproblems is 1 is called decrease and conquer.

As an algorithmic idea, divide and conquer can be implemented either recursively or non-recursively, depending on the situation.

4.3.2 Recursion

When writing a recursive function, you can assume that the system library already contains a function with the same name that implements the functionality you need; once the function is written, the logic becomes self-consistent

Recursion lies in repeatedly calling the function itself, but each time shrinking the scope of the problem until the scope is small enough that the result at the boundary can be obtained directly, and then, on the way back, computing the corresponding solutions. From this perspective, recursion is well suited to implementing the divide-and-conquer idea

When writing recursion, do not fall into endlessly analyzing the sub-processes. Analyze the boundary conditions, write what this process is supposed to handle, and then the rest is simply trusting that the sub-processes can handle your problem for you. It follows the same pattern as mathematical induction

  • Define the problem
  • Solve the base case
  • Break down the problem

There are generally two important concepts in the logic of recursion:

  1. The recursive boundary
  2. The recurrence (also called the recursive call)

Here is an example

//计算 n 的阶乘
//考虑 n! 的计算式,不难得出递归式 F(n)=nF(n-1)
//所以可以把 F(n) 变成 F(n-1),然后一直递归下去...
//什么时候是尽头呢?考虑 0!=1,不妨以 F(0)=1 作为递归边界
//即:规模减小到 n=0 的时候开始"回头"

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

int F(int n){
    if(n==0) return 1; //到达递归边界时返回
    else return n*F(n-1); //没有到达边界时使用递归式递归下去
}

Here is another example

//计算 Fibonacci 数列的第 n 项
#include<bits/stdc++.h>
using namespace std;

int F(int n){
    if(n==1||n==2) return 1; //到达递归边界时返回
    else return F(n-1)+F(n-2); //没有到达边界时使用递归式递归下去
}
//其实这就是分治法的一种应用,
//对于给定的 n 把求解 F(n) 的问题分解成求 F(n-1) 和 F(n-2) 这两个子问题,
//而 F(0)==F(1)==1 是 n 很小的时候问题的直接解决

From the two examples above, we can see that implementing a recursive function requires two things: the recursive boundary and the recurrence, where the recursive boundary is used to return the simplest, most fundamental result, and the recurrence is used to reduce the scale of the data and recurse to the next level.

Here is yet another example

代码CPP · 29 行
////按照字典序输出全排列
//可以分成若干个子问题:输出 1 开头的全排列,输出 2 开头的全排列
//...输出以 n 开头的全排列
//于是不妨设定一个数组 P 用以存放当前的排列
//再设定一个 hashTable,其中 hashTable[x]==true 表示 x 在数组 P 中

#include<bits/stdc++.h>
using namespace std;
const int maxn=11;
//P 为当前排列,hashTable 记录整数 x 是否已在 P 中
int n,P[maxn],hashTable[maxn]={false};
//当前处理排列的第 index 号位
void generateP(int index){
    if(index==n+1){//递归边界,已经处理完排列的 1~n 位
        for(int i=1;i<=n;i++){
            cout<<P[i]; //输出当前排列
        }
        cout<<endl;
        return;
    }
    for(int x=1;x<=n;x++){//枚举 1~n,试图将 x 填入 P[index] 中
        if(hashTable[x]==false){
            P[index]=x; //令 P 的第 index 位为 x,即把 x 加入当前排列
            hashTable[x]=true; //记 x 已在 P 中
            generateP(index+1); //处理排列的第 index+1 号
            hashTable[x]=false; //已处理完 P[index] 为 x 的子问题,还原状态
        }
    }
}

Finally, let's look at the n-queens problem

It refers to placing n queens on an n*n chessboard such that no two of the n queens are in the same row, the same column, or on the same diagonal, and finding the number of valid arrangements

代码CPP · 37 行
#include<bits/stdc++.h>
using namespace std;
const int maxn=11;
//每行只能放置一个皇后,每列也只能放置一个
//把 n 列皇后所在的行号依次写出,就会是 1~n 的一个排列
//只需要筛选这每个排列中合法的即可
//考虑:递归边界、递归式
//由于到达递归边界时表示生成了一个排列,
//所以需要在其内部判断是否为合法方案
//如何判断?在一个排列中两两遍历两个皇后,
//判断他们是否在一条对角线上
//如果不是就 count++
int count=0;
int n,P[maxn],hashTable[maxn]={false};
void A(int index){
    if(index==n+1){//递归边界,表示生成了一个排列(类似上一题)
        bool flag=true;
        for(int i=1;i<=n;i++){
            for(int j=i+1;j<=n;j++){
                if(abs(i-j)==abs(P[i]-P[j])){//如果在一条对角线上,斜率为±1
                    flag=false;
                    break;
                }
            }
        }
        if(flag) count++;
        return;
    }
    for(int x=1;x<=n;x++){//就是上一题全排列,因为不能在同一行同一列和全排列的数学本质相同
        if(!hashTable[x]){//这一行还没被占用
            P[index]=x;
            hashTable[x]=true;
            A(index+1);
            hashTable[x]=false;
        }
    }
}

However, this solution is in fact too brute-force, because once part of a permutation has been generated, we can already judge whether that permutation meets the requirements. If it does not, there is no need to continue recursing; simply return to the previous level. This approach is generally called backtracking

代码CPP · 28 行
#include<bits/stdc++.h>
using namespace std;
const int maxn=11;
int count=0;
int n,P[maxn],hashTable[maxn]={false};
void A(int index){
    if(index==n+1){
        count++; //能到这里的一定符合要求
        return;
    }
    for(int x=1;x<=n;x++){//第 x 行
        if(!hashTable[x]){//第 x 行还没有皇后
            bool flag=true;
            for(int pre=1;pre<index;pre++){//遍历之前的皇后
                if(abs(index-pre)==abs(P[index]-P[pre])){
                    flag=false;
                    break;
                }
            }
            if(flag){
            P[index]=x;
            hashTable[x]=true;
            A(index+1);
            hashTable[x]=false;
            }
        }
    }
}

4.4 Greedy

4.4.1 Simple Greedy

Greedy is a method for solving a class of optimization problems. It always considers the locally optimal (or better) strategy under the current state, so that the global result reaches the optimal (or a better) outcome. Generally speaking, the way to prove a greedy method is proof by contradiction: assume the strategy cannot lead to the optimal solution, and then derive a contradiction through a series of deductions

Example Problem PAT B1020 Mooncake

Problem Statement

Given the demand for mooncakes D, and given the stock and total selling price of each of n kinds of mooncakes, how should these mooncakes be sold to maximize the profit obtained, and what is the maximum profit?

Approach

Greedy strategy: always sell the mooncakes with the highest unit price to obtain the maximum profit. Therefore, for each kind of mooncake, calculate its unit price based on its stock and total selling price, and then sort all unit prices from low to high

After that, enumerate starting from the mooncakes with the highest unit price, considering two cases:

  1. If the stock of that kind of mooncake is not enough to cover the demand $\Rightarrow$ sell all of it, demand -= the stock of that kind of mooncake, profit += the total selling price of that kind of mooncake
  2. If the supply is sufficient, calculate directly

[!CAUTION] A few points to note

  1. The stock and total selling price of mooncakes can be floating-point numbers. Although the problem only states that D is an integer, for ease of calculation it is best to define them as double as well
  2. When stock > demand, you must not first set the demand to 0 and then calculate the profit, otherwise the profit for this step will be 0
  3. When stock > demand, remember to break out of the loop
Code Implementation
代码CPP · 42 行
#include<bits/stdc++.h>
using namespace std;
int n,d;

struct mooncake{
    double storage;
    double price_all;
    double price;
}cake[1010];

bool cmp(mooncake a,mooncake b){
    return a.price>b.price;
}

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

    for(int i=0;i<n;i++){
        scanf("%d",cake[i].storage);
    }
    for(int i=0;i<n;i++){
        scanf("%d",cake[i].price_all);
        cake[i].price=cake[i].price_all/cake[i].storage;
    }

    sort(cake,cake+n,cmp);

    double ans=0;

    for(int i=0;i<n;i++){
        if(cake[i].storage>=d){
            ans+=d*cake[i].price;
            break;
        }
        else{
            ans+=cake[i].price_all;
            d-=cake[i].storage;
        }
    }
    printf("%.2f",ans);
    return 0;
}

Example Problem PAT B1023 Group the Smallest Number

Problem Statement

Given several digits 0~9, they may be arranged arbitrarily on the condition that 0 is not placed first, but all of them must be used. Output the smallest number that can be formed

Analysis

First output the highest digit: choose the smallest from 1-9 and output it

After that: output the digits in the order 0-9, with the output count being their remaining occurrences

Code Implementation
代码CPP · 25 行
#include<bits/stdc++.h>
using namespace std;

int n,cnt[10],temp;

int main(){
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&temp);
        cnt[temp]++;
    }
    for(int i=1;i<=9;i++){
        if(cnt[i]!=0){
            printf("%d",i);
            cnt[i]--;
            break;
        }
    }
    for(int i=0;i<=9;i++){
        for(int j=0;j<cnt[i];j++){
            printf("%d",i);
        }
    }
    return 0;
}
引用【Luogu P4447 [AHOI2018 Junior Group] Grouping】 Problem Description Xiaok...

【Luogu P4447 [AHOI2018 Junior Group] Grouping】

Problem Description

Xiaokeke's school informatics team has a total of $n$ members, and each member has a strength value $a_i$. Now, the annual programming contest is approaching, and Xiaokeke's school has obtained several contest slots. The coach decides to divide the $n$ members of the school informatics team into several groups to participate in this contest.

However, no member is willing to team up with members whose strength differs too greatly from their own, so it is required that the strength values of the members in each group be consecutive. Meanwhile, a team does not need two members with the same strength value. For example: $[1, 2, 3, 4, 5]$ is a valid grouping scheme, because the strength values are consecutive; $[1, 2, 3, 5]$ is not a valid grouping scheme, because the strength values are not consecutive; $[0, 1, 1, 2]$ is likewise not a valid grouping scheme, because there are two members with a strength value of $1$.

If a group has too few members, it will be unable to achieve a high score due to insufficient time. So Xiaokeke wants you to provide a valid grouping scheme in which everyone is assigned to exactly one group, such that the group with the fewest members has as many members as possible. Output the maximum possible size of the smallest group.

Note: strength values may be negative, and there is no limit on the number of groups.

Input Format

The input consists of two lines:

The first line contains a positive integer $n$, denoting the number of members.
The second line contains $n$ integers, where the $i$-th integer $a_i$ denotes the strength of the $i$-th member.

Output Format

Output one line containing a positive integer, denoting the maximum possible size of the smallest group.

Sample #1

Sample Input #1

7
4 5 2 3 -4 -3 -5

Sample Output #1

3

Hints

【Sample Explanation】 Divide into $2$ groups: one group has members with strength values ${4, 5, 2, 3}$, and the other is ${-4, -3, -5}$. The smallest group has $3$ members, and it can be seen that there is no better grouping than $3$.

【Data Constraints】

For $100%$ of the data: $1\leq n\leq 100000$, $|a_i|\leq10^9$.

This problem has $10$ test points in total, numbered $1\sim10$, with the following additional guarantees for each test point:

Test Point Number Data Constraints
$1\sim2$ $n\leq 6, 1\leq a_i \leq 100$
$3\sim4$ $n\leq 1000, 1\leq a_i\leq 10^5$ and all $a_i$ are distinct
$5\sim6$ $n\leq 100000, a_i$ (all distinct)
$7\sim8$ $n\leq 100000, 1\leq a_i \leq10^5$
$9\sim 10$ $n\leq 100000, -10^9 \leq a_i \leq 10^9$

Approach: Greedy. // Greedy strategy: each time a member is added, add them to the group with the fewest members, which maximizes the size of the smallest group

代码CPP · 44 行
#include<bits/stdc++.h>
using namespace std;
using i64=long long;
const int inf=0x3f3f3f3f;

int main(){
  ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
  int n;
  cin>>n;
  vector<int> a(n);
  for(int i=0;i<n;i++){
    cin>>a[i];
  }
  sort(a.begin(),a.end());
  //贪心策略:每次加人都加在人数最少的那个队里面,这样可以最大化最小组的人数
  
  map<int,priority_queue<int,vector<int>,greater<int>>> group;
  //map 的键是这个组的实力值最大值,值是用来存储已经组建的所有符合该最大实力值的组的人数,队首的是人数最少的
  
  //遍历每个队员的实力值,进行分组
  for(int i=0;i<n;i++){
    int groupSize=0; // 当前队员加入后的组大小

    auto it=group.find(a[i]-1); //查看当前实力值减去 1 的分组(前一个实力值的组)
    if(it!=group.end()){
      if(!it->second.empty()){ //这个其实是使用队列 (优先队列也是队列) 的好习惯,先判断非空再访问
        groupSize=it->second.top();
        it->second.pop();
      }
    }
    groupSize++;
    group[a[i]].push(groupSize);
  }
  
  int minGroupSize=inf;
  for(auto& now:group){ //区别上一个循环的 it 是迭代器 (指针),这里的是 map 类型,所以访问值不需要用->
    if(!now.second.empty()){
      minGroupSize=min(minGroupSize,now.second.top());
    }
  }
  
  cout<<(minGroupSize==inf?0:minGroupSize)<<endl;
  return 0;
}

4.4.2 Interval Greedy

Introduced by the following problem:

Interval Scheduling (Non-overlapping Intervals) Problem

Given N open intervals (x, y), select as many open intervals as possible such that no two of them overlap. Output the number of intervals satisfying this condition.

For example, for the open intervals (1,3) (2,4) (3,5) (6,7), at most three intervals (1,3) (3,5) (6,7) can be selected to satisfy the problem's requirements

First consider the simplest case: if open interval $I_1$ is contained within open interval $I_2$, then choosing $I_1$ is the better choice, because choosing $I_1$ leaves more room to accommodate other open intervals

Next, sort the open intervals by their left endpoints x in descending order. Once the case of interval containment is removed, it must hold that $y_1>$$y_2 > \cdots$ $y_n$. Observing the figure, we can see that to the right of $I_1$ there must be a segment that does not overlap with any other interval; if that segment is removed, the remaining left part of $I_1$ would be contained within $I_2$, and by the previous case we know that $I_1$ should be chosen. Therefore, for this case, always choose the interval with the largest left endpoint

Code Implementation

代码CPP · 33 行
#include<bits/stdc++.h>
using namespace std;

const int max1=100;

struct interval{
    int x,y;
}iv[max1+5];

bool cmp(interval a,interval b){
    if(a.x!=b.x) return a.x>b.x;
    else return a.y<b.y;
}
int n;

int main(){
    while(scanf("%d",&n),n!=0){ //这样可以保证 n 小于等于 0 的时候不会进行
        for(int i=0;i<n;i++){
        scanf("%d%d",&iv[i].x,&iv[i].y);
        }
        sort(iv,iv+n,cmp);
        //ans 记录满足条件的区间个数,lastX 记录上一次被选中的区间的左端点
        int ans=0,lastX=iv[0].x;
        for(int i=1;i<n;i++){
            if(iv[i].y<=lastX){
                lastX=iv[i].x;
                ans++;
            }
        }
        printf("%d",ans);
    }
    return 0;
}

Regarding the way the while loop is written in the code above, let's review the comma operator

The comma operator executes the expressions on its left and right sides in order, and returns the result of the right-hand expression.

Execution process of while (scanf("%d", &n), n != 0):

  • First, execute scanf("%d", &n): read an integer from the input and store it in the variable n.
  • Then, evaluate n != 0: check whether n is not equal to 0.
  • The result of the entire comma expression is the value of n != 0 (true or false).
  • The while loop decides whether to continue iterating based on the result of n != 0

In fact, the strategy of always choosing the interval with the smallest right endpoint is also feasible

A similar problem is the interval point selection problem, which asks: given N closed intervals, what is the minimum number of points that must be chosen so that each closed interval contains at least one point

Since each step can remove half of the elements in the current interval, the time complexity is O(logN)

Requirement: a[] must be a strictly increasing (decreasing) sequence

Code Implementation

int binarysearch(int a[],int left,int right,int x){
    int mid;
    while(left<=right){ //因为 left>right 就无法形成闭区间了
        mid=(left+right)/2;
        if(a[mid]==x) return mid;
        else if(a[mid]<x){
            left=mid+1;
        }
        else{
            right=mid-1;
        }
    }
    return -1; //查找失败,返回 -1
}

The case of a strictly decreasing sequence is analogous

If the upper bound of the binary search exceeds INTMAX/2, then left+right in mid=(left+right)/2 may overflow, so the equivalent statement mid=left+(right-left)/2 is generally used instead

Let's discuss a further question: if the sequence is not strictly monotonic, how do we find the half-open interval [L,R) in which the queried element exists? If x does not exist in the sequence, L and R can also be understood as the position where x would be if it did exist in the sequence

This problem can be broken down into two subproblems (divide and conquer):

1. Find the position of the first element ≥ x in the sequence

int lower_bound(int a[],int left,int right,int x){
    int mid;
    while(left<right){ //当 left=right 的时候就是所需的下界
        mid=left+(right-left)/2;
        if(a[mid]>=x){
            right=mid;
        }
        else{
            left=mid+1;
        }
    }
    return left;
}
  1. The loop condition is left<right rather than left≤right, because the desired result is precisely the position where left=right converges
  2. The lower bound of the binary search should be 0, but should the upper bound be n-1 or n? Considering that x may not exist, and what we are computing is "the position where x would be if it existed" (i.e., the largest such position), we should start with left=0 and right=n

2. Find the position of the first element greater than x in the sequence

int upper_bound(int a[],int left,int right,int x){
    int mid;
    while(left<right){
        mid=left+(right-left)/2;
        if(a[mid]>x){
            right=mid;
        }
        else{
            left=mid+1;
        }
    }
    return left;
}

It is easy to notice that the only difference between these two functions is changing a[mid]>=x to a[mid]<x; everything else is identical

In fact, both functions solve the same problem: finding the first element in an ordered sequence that satisfies a certain condition

For the lower_bound function, what is being searched for is the position of the first element satisfying the condition "value is greater than or equal to x", while for the upper_bound function, it is the position of the first element satisfying the condition "value is greater than x". Such a "condition" must, in the sequence, first be unsatisfied and then satisfied from left to right (otherwise, take the negation of the condition)

Summary

//解决“寻找有序序列中第一个满足某条件的元素的位置”的问题的固定模板
//二分区间为左闭右闭的[left,right],初值必须能够覆盖解的所有可能取值
int solve(int left,int right){
    int mid;
    while(left<right){
        if(条件成立){ //条件成立,第一个满足条件的元素的位置<=mid
            right=mid;
        }
        else{ //条件不成立,则第一个满足条件的元素的位置>mid
            left=mid+1;
        }
    }
    return left;
}

In addition, if you want to find the position of the last element satisfying "condition C", you can first find the position of the first element satisfying "condition !C", and then subtract 1 from that element's position

Moreover, even if the binary search interval is not a closed interval, the approach still works

For example, when the binary search interval is a left-open, right-closed interval (left,right], the loop condition should be left+1<right, which means that when the loop exits, left+1=right holds, making the result obtained by the converging process unique. Since the interval is now left-open, the initial value of left should be 1 less than the minimum possible value of the solution, and the statement left=mid+1 should be changed to left=mid. The return value should also be right (after all, the closed end can be reached). The code is as follows

//解决“寻找有序序列中第一个满足某条件的元素的位置”的问题的固定模板
//二分区间为左开右闭区间 (left,right],初值必须能够覆盖解的所有可能取值
int solve(int left,int right){
    int mid;
    while(left+1<right){
        if(条件成立){ //条件成立,第一个满足条件的元素的位置<=mid
            right=mid;
        }
        else{ //条件不成立,则第一个满足条件的元素的位置>mid
            left=mid;
        }
    }
    return right;
}

How do you determine whether a query with the lower_bound or upper_bound function succeeded? You can check whether the upper bound equals n

(because what the upper_bound function computes is also the first position after the position of the element satisfying the condition)

How to Compute an Approximation of $\sqrt 2$

For $f(x)=x^2$, when $x>0$, $f(x)$ is monotonically increasing, so we can consider using binary search to approach the answer, taking precision to $10^{-5}$ as an example

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

const double eps = 1e-5; //精度为 10^{-5}
double f(double x){ //计算 f(x)
    return x*x;
}

double calsqrt(){
    double left=1,right=2,mid;
    while(right-left>eps){ //回顾之前学的高精度判断相等
        mid=left+(right-left)/2;
        if(f(mid)>2) right=mid;
        else left=mid;
    }
    return mid;
}

The Wood Stick Cutting Problem

Given N sticks of known lengths, we now want to cut them to obtain at least K sticks of equal length (the length must be an integer). What is the maximum possible length of these equal-length sticks?

It is easy to notice that the larger K is, the smaller L is. Taking this into account, we can use binary search

int F(L){
	给定长度,计算当前总段数
}

int 二分 (){
	left=1
	right=杆子最长的长度
	while(left<right){
		mid=直接算
		cnt=F(mid)
		if(cnt>=k) left=mid
		else right=mid
	}
	return mid;
}

4.5.3 Fast Power

Consider the following problem

Given three positive integers a, b, m (a<$10^9$, b<$10^6$, $1$<m<$10^9$), compute $a^{b}$%m

The following code can be used, with a time complexity of O(b)

xxxxxxxxxx typedef long long LL;LL LLpow(LL a,LL b,LL m){    LL ans=1;    for(int i=0;i<b;i++){        ans=ans*a%m; //考虑模运算的性质 (a×b)modm=[(amodm)×(bmodm)]modm    }    return ans;}cpp

Using LL instead of int in the code prevents overflow when two ints are multiplied together

Now consider a further problem

Given three positive integers a, b, m (a<$10^9$, b<$10^{18}$, $1$<m<$10^9$), compute $a^{b}$%m

For this problem, the approach above clearly will not work

Here we need to use fast power (also commonly called binary power), which is based on the idea of binary search. Fast power is based on the following facts:

  1. If b is odd, then $a^b=a*a^{b-1}$
  2. If b is even, then $a^b=a^{b/2}*a^{b/2}$

Obviously, the case where b is odd can always be converted in the next step to the case where b is even, and the case where b is even can always be converted in the next step to the case of b/2. After O(log(b)) levels of conversion, b becomes 0, and any positive integer raised to the power of 0 is 1

For example, to compute $2^{10}$:

  1. For $2^{10}$, since the exponent 10 is even, we first need to compute $2^{5}$, and then $2^{10}=2^{5}*2^{5}$
  2. For $2^{5}$, since the exponent 5 is odd, we first need to compute $2^{4}$, and then $2^5=2*2^4$
  3. For $2^4$, since the exponent 4 is even, we first need to compute $2^2$, and then $2^4=2^2*2^2$
  4. For $2^2$, since the exponent 2 is even, we first need to compute $2^1$, and then $2^2=2^1*2^1$
  5. For $2^1$, since the exponent 1 is odd, we first need to compute $2^0$, and then $2^1=2*2^0$
  6. $2^0=1$, and then we simply unwind the computation from bottom to top

This is clearly the idea of recursion, so we can obtain the recursive implementation of fast power, with a time complexity of O(logb)

typedef long long LL;
LL binaryPow(LL a,LL b,LL m){
    if(b==0) return 1;
    if(b%2==1) return a*binaryPow(a,b-1,m)%m;
    else{
        LL mul=binaryPow(a,b/2,m);
        return mul*mul%m;
    }
}

In the code above, the condition if(b%2==1) can be replaced with if(b&1), because b&1 performs a bitwise AND operation to check whether the last bit of b is 1. Therefore, when b is odd, b&1 returns 1 and the if condition holds. Writing it this way executes slightly faster

Note also that when b%2==0, you should not directly return binaryPow(a,b/2,m)*binaryPow(a,b/2,m); instead, you should compute a single binaryPow(a,b/2,m) first and then multiply. This is because the former calls the binaryPow function twice each time, causing the complexity to become O($2^{log(b)}$)=O(b). For example, when computing binaryPow(8), it becomes binaryPow(4)*binaryPow(4), and each of these two binaryPow(4) calls becomes binaryPow(2)*binaryPow(2), while each binaryPow(2) becomes binaryPow(1)*binaryPow(1), so in the end binaryPow(1) needs to be computed 8 times

In addition, depending on the specific problem, there may be two details to pay attention to:

  1. If a may be greater than m initially, then a should be taken modulo m before entering the function
  2. If m is 1, you can directly special-case the result as 0 outside the function without entering the function to compute it (since any positive integer modulo 1 is always 0)

Next, let's look at the iterative implementation of fast power (filling in a gap)

4.6 two pointers

4.6.1 What Are two pointers

two pointers is a very important idea in algorithmic programming. Let's introduce it with an example

Given an increasing sequence of positive integers and a positive integer M, find two numbers a and b at different positions in the sequence such that their sum is exactly M, and output all schemes that satisfy the condition.

For example, given the sequence {1,2,3,4,5,6} and the positive integer M=8, both $2+6=8$ and $3+5=8$ hold

The most intuitive idea for this problem is to use a double loop to enumerate a and b in the sequence and check whether their sum is M. The code implementation is as follows

for(int i=0;i<n;i++){
    for(int j=i;j<=n;j++){
        if(a[i]+a[j]==M){
            cout<<i<<j<<endl;
        }
    }
}

This has a time complexity of O($n^2$), which is too high. Let's look at the reason for the high complexity:

  1. For a fixed a[i], if the current a[j] satisfies a[i]+a[j]>M, then obviously a[i]+a[j+1]>M also holds (this is because the sequence is increasing), so there is no need to enumerate the numbers after a[j]. If this property is ignored, it leads to a large amount of useless enumeration over j
  2. For a certain a[i], if an a[j] is found such that a[i]+a[j]>M holds exactly, then for a[i+1] it must also be true that a[i+1]+a[j]>M, so the elements after a[i] also need not be enumerated

From these two points, it can be seen that the enumerations of i and j constrain each other. In fact, in this problem, two pointers will exploit the enumeration properties of an ordered sequence to effectively reduce the complexity. The algorithm proceeds as follows:

Set the initial value of index i to 0 and the initial value of index j to n-1

a[0] ··· a[i] a[i+1] ··· a[j-1] a[j] ··· a[n-1]

Then we can imagine letting only i move right (i.e., i++) and only j move left (i.e., j--), and moving i and j appropriately according to the different cases of a[i]+a[j], so that all cases can be traversed

  1. If a[i]+a[j]=M, then it is impossible to move the other index while keeping i or j fixed and still have the sum remain M, so we can only do i++ and j--
  2. If a[i]+a[j]>M, then one of them must move backward, and it can only be j that moves backward, so i stays unchanged and j--
  3. If a[i]+a[j]<M, then by the same reasoning, i++ and j stays unchanged

Repeatedly execute the three checks above until i>=j holds (this way all cases can be traversed)

The code implementation is as follows

int i=0,j=n-1;
while(i<j){
    if(a[i]+a[j]==M){
        printf("%d %d",i,j);
        i++;
        j--;
    }
    else if(a[i]+a[j]>M) j--;
    else i++;
}

Obviously the time complexity is O(n)

Here is another example

Sequence merging problem: given two increasing sequences a and b, merge them into a single increasing sequence c

Similarly, two indices i and j can be set, and the problem can be solved using a similar idea

int merge(int a[],int b[], int c[], int n, int m){
    //n 和 m 分别是数组 a 和 b 的长度
    int i=0,j=0,index=0;
    while(i<n&&j<m){
        if(a[i]<=b[j]) c[index++]=a[i++]; //相等的情况放 a 和 b 都一样
        else c[index++]=b[j++]; //把 b[j]放入序列中
    }
    while(i<n) c[index++]=a[i++]; //把 a 的剩余元素放入 c 中
    while(j<m) c[index++]=b[j++]; //把 b 的剩余元素放入 c 中
    return index; //返回序列 c 的长度
}

Summary

two pointers exploits the properties of the problem itself and of the sequence, using two indices to scan the sequence (in the same direction or in opposite directions), solving the problem with a lower complexity

4.6.2 Merge Sort

Merge sort is a sorting method based on "merging". Here we mainly introduce the most basic 2-way merge sort

Idea: group the sequence in pairs, merging the sequence into $\lceil \frac{n}{2} \rceil$ groups, sorting within each group independently, then merging these groups in pairs to generate $\lceil \frac{n}{4} \rceil$ groups, sorting within each group again, and so on, until only one group remains. The time complexity is O(nlogn)

Code implementation:

  1. Recursive implementation

    代码CPP · 25 行
    const int maxn=100;
    //将数组 a 的[l1,r1]与[l2,r2]区间合并为有序区间(此处 l2 即 r1+1)
    void merge(int a[],int l1,int r1,int l2,int r2){
        int i=l1,j=l2;
        int temp[maxn],index=0;
        while(i<=r1&&j<=r2){
            if(a[i]<=a[j]) temp[index++]=a[i++];
            else temp[index++]=a[j++];
        }
        while(i<=r1) temp[index++]=a[i++];
        while(j<=r2) temp[index++]=a[j++];
        for(int i=0;i<index;i++){
            a[l1+i]=temp[i]; //将合并之后的序列赋回给 a
        }
    }
    
    //将 a 数组当前区间[left,right]进行归并排序
    void mergeSort(int a[],int left,int right){
        if(left<right){
            int mid=left+(right-left)/2;
            mergeSort(a,left,mid); //递归,将左区间归并排序
            mergeSort(a,mid+1,right);  //递归,将右区间归并排序
            merge(a,left,mid,mid+1,right); //将左右子区间合并
        }
    }
  2. Non-recursive implementation

    The main thing to consider is that each time the sequence is grouped, the upper limit on the number of elements in a group is a power of 2. Set the initial value of the step size step to 2, then take every step elements in the array as a group and sort within it (that is, in a sub-group of length step, merge the left step/2 elements and the right step/2 elements; if the number of elements does not exceed step/2, do nothing), then set step*2 and repeat until step/2>n. The code is as follows

    void mergeSort(int a[]){
        //step 为组内元素个数,step/2 为左子区间元素个数,注意等号可以不取
        for(int step=2;step/2<n;step*=2){
            //每 step 个元素一组
            for(int i=1;i<=n;i+=step){ //对于每一组
                int mid=i+step/2-1; //元素个数为 step/2
                if(mid+1<=n){
                    merge(a,i,mid,mid+1,min(n,i+step-1));
                }
            }
        }
    }

4.6.3 Quick Sort

Quick sort has a time complexity of O(nlogn), and its implementation first requires solving a problem: for a sequence a[], adjust the positions of the elements in the sequence so that all elements to the left of a[0] (the a[0] in the original sequence, likewise below) are less than or equal to a[0], and all elements to the right are greater than a[0].

Since there are obviously many possible schemes, here is an approach implemented with two pointers, which is also the fastest method

  1. First store a[0] into temp, and define left=0, right=len-1
  2. Move right leftward until a[right]≤a[0], then move the element pointed to by a[right] to the position of left (for example, consider the first time: the first time, a[1] has been moved away, so that position can be considered empty, and the element pointed to by a[right] can be directly assigned to the position of left); afterwards, move left rightward until a[left]>a[0], then assign the element at a[left] to the position of right (because it can be considered that the previous right position was assigned to the previous left position, so that place is now empty); proceed alternately in this way
  3. Until right=left, then assign temp to this position, and it is done

Generalizing, the initial value of left is the partition point of the interval, and the element a[left] of the partition interval is called the pivot

Code implementation

int Partition(int a[],int left,int right){
    int temp=a[left];
    while(left<right){
        while(left<right&&a[right]>=temp) right--; //注意这里还要同时满足 left<right,这样才能保证外层循环结束时一定有 left=right
        a[left]=a[right];
        while(left<right&&a[left]<temp) left++;
        a[right]=a[left];
    }
    a[left]=temp;
    return left; //返回相遇的下标
}

Next, the quick sort algorithm can be implemented. Its idea is:

  1. Adjust the elements in the sequence so that, after adjustment, the leftmost element of the current sequence satisfies: all elements on its left do not exceed it, and all elements on its right are greater than it
  2. Recursively perform the adjustment in step 1 on the left side and the right side of that element, until the length of the current interval being adjusted does not exceed 1

The recursive implementation is as follows

//快速排序,left 与 right 初值为序列首尾下标
void quickSort(int a[],int left,int right){
    if(left<right){ //当前区间的长度超过 1
        //将区间 [left,right] 按照 a[left] 一分为二
        int pos=Partition(a,left,right);
        quickSort(a,left,pos-1);
        quickSort(a,pos,right);
    }
}

However, there is a flaw: it is most efficient only when the elements in the sequence are arranged fairly randomly. When the elements in the sequence are nearly sorted, the worst-case time complexity O($\mathrm{n}^2$) is reached. The main reason for this situation is that the pivot fails to divide the current interval into two sub-intervals of nearly equal length. One way to solve this problem is to choose the pivot randomly, that is, to randomly select a number from [left,right] as the pivot, which guarantees an expected time complexity of O(nlogn) for any input data

Now let's see how to generate random numbers

#include<bits/stdc++.h>
#include<time.h>
int random(int a, int b)
{
    srand((unsigned)time(NULL));
    return ((rand() % (b-a+1)) + a);
}

When b-a>RAND_MAX, you can do this:

int random(int a,int b){
    srand((unsigned)time(NULL));
    //用 rand() 生成一个在 [0,RAND_MAX] 范围内的随机数,除以 RAND_MAX 得到一个 [0,1] 之间的浮点数再乘以 b-a 再+a 即可
    return (int)(round(1.0*rand()/RAND_MAX*(b-a)+a));
}

Building on this, let's continue discussing how to write randomized quick sort

int randPartition(int a[],int left,int right){
    int p=(int)(round(1.0*rand()/RAND_MAX*(right-left))+left);
    swap(a[p],a[left]); //交换主元
    //之后一模一样
    int temp=a[left];
    while(left<right){
        while(left<right&&a[right]>=temp) right--; //注意这里还要同时满足 left<right,这样才能保证外层循环结束时一定有 left=right
        a[left]=a[right];
        while(left<right&&a[left]<temp) left++;
        a[right]=a[left];
    }
    a[left]=temp;
    return left; //返回相遇的下标
}

//quickSort 函数无需做出任何改变

4.7 Other Efficient Techniques and Algorithms

4.7.1 Lookup Table (Precomputation)

Lookup table: trading space for time. It generally refers to computing all potentially needed results in advance, so that they can be obtained directly by looking up the table later. There are several ways to do this:

  1. Compute all potentially needed results in one go within the program itself, and afterwards queries directly take these results

    This is the most common approach. For example, if a problem requires a large number of queries for the Fibonacci number F(n), each query takes O(n) time, and Q queries take O(Qn). But if all Fibonacci numbers within the given range are precomputed in advance, each query becomes O(1), and Q queries take O(Q+n), where n is the preprocessing time

  2. Compute the needed results in one or more runs in a separate program, manually paste the results into the array of the program that needs them, and then use them directly in that program

  3. For problems that seem unsolvable, first use a brute-force program to compute results for small-scale data, then look for a pattern

4.7.2 Making Good Use of Recurrence

Carefully consider whether the problem contains a recurrence relation. For example, for a class of problems involving sequences, if the value to be computed at each position of the sequence can be obtained from the results on its left and right sides, then consider whether these "results on the left and right sides" can be precomputed via recurrence, so that they need not be solved repeatedly later

【PAT A1093/B1040 Counting PATs】

The string APPAPT contains two "PAT"s, at positions: 2+4+6 and 3+4+6. Now given a string, how many PATs can be formed in total?

Input format:

One line containing a string of length at most $10^5$

Output format:

The number of PATs contained in the input. The result may be large, so output it modulo 1000000007

Approach: Direct brute force will time out; it can be analyzed as follows:

For each fixed A, the number of PATs that can be formed = (number of P's to the left of A) × (number of T's to the right of A). So the problem reduces to finding, for each A, the number of P's on its left and the number of T's on its right

A relatively fast way to obtain the number of P's to the left of each position: set up an array leftNumP, first memset it to 0, then if the character at index i is P, set leftNumP[i]=leftNumP[i]+1; otherwise leftNumP[i]=leftNumP[i]. This can be computed in O(len) time

The same applies to finding the number of T's to the right of each position, but while computing the T's, ans can also be computed at the same time. Define an int rightNumT to represent the number of T's to the right of the current position during traversal. If the current position is T, then rightNumT++; if the current position is A, then ans=(ans+leftNumP[i]*rightNumT)%MOD

4.7.3 Random Selection Algorithm

This section mainly discusses the following problem: how to find the K-th smallest number in an unordered array (assuming all numbers in the array are distinct)

If you directly use quick sort, the time complexity is O(nlogn), but there is a better random selection algorithm that achieves an expected time complexity of O(n) for any input.

Its principle is similar to the randPartition function in randomized quick sort. Analyzing this function:

After this function finishes one pass, suppose the chosen pivot is a[p]; then the number of elements on each side of the pivot is determined (assuming p is known), i.e., a[p] is the (p-left+1)-th smallest number in [left,right].

Let p-left+1=M. When K==M, the K-th smallest number is a[p].

When K<M, the K-th smallest number is on the left side of the pivot, i.e., the K-th smallest number is the K-th smallest in [left,p-1], so recurse to the left

When K>M, the K-th smallest number is on the right side of the pivot, i.e., the K-th smallest number is the (K-M)-th smallest in [p+1,right], so recurse to the right

Analysis: the algorithm can use left=right as the recursion boundary and return a[left]. The code implementation is as follows

//随机选择算法,返回 [left,right] 中第 k 小的数
int randSelect(int a[],int left,int right,int k){
    if(left==right) return a[left]; //递归边界
    int p=randPartition(a,left,right);
    int m=p-left+1;
    if(left<right&&k==m) return a[p];
    else if(left<right&&k<m) return randSelect(a,left,p-1,k);
    else if(left<right&&k>m) return randSelect(a,p+1,right,k-m); 
}

The expected time complexity of this algorithm is O(n) for any input

Below is an example application

Given a set of integers in which all integers are pairwise distinct, it needs to be split into two subsets such that the union of the two subsets is the original set and their intersection is empty. Meanwhile, under the condition that the absolute difference of the numbers of elements in the two subsets, $|n_1-n_2|$, is as small as possible, the absolute difference of the sums of their elements, $|S_1-S_2|$, should be as large as possible. Find the value of $|S_1-S_2|$

It can be divided into two cases: when n is even, clearly $n_1=n_2=\frac{n}{2}$; when n is odd, we may take $n_1=\frac{n}{2}+1,n_2=\frac{n}{2}$ (both rounded down)

To make $|S_1-S_2|$ as large as possible, obviously the original set should be sorted from smallest to largest, with the sum of the first $n_1$ elements being $S_1$ and the sum of the last $n_2$ elements being $S_2$

However, sorting the entire sequence takes O(nlogn) time; we can optimize this to O(n). Here we can consider using the random selection algorithm

We only need to use the randSelect function to find the $\frac{n}{2}$-th smallest number; the function will automatically split the two sets, and then we just let i traverse from 0 to n/2 and sum up.

4.7.4 Prefix Sums

int main(){
  vector<int> preFix(n);
  for(int i=0;i<n;++i){
    if(i==0) preFix[i]+=a[i];
    preFix[i]=preFix[i-1]+a[i];
  }
}

The C++ standard library also has a library function partial_sum

代码CPP · 18 行
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> arr = {1, 2, 3, 4, 5};
    std::vector<int> result(arr.size());  // 存储部分和的容器

    // 计算部分和并存储到 result
    std::partial_sum(arr.begin(), arr.end(), result.begin());

    // 输出结果
    for (int num : result) {
        std::cout << num << " ";
    }

    return 0;
}

Chapter 5 Beginner's Guide (3) — Mathematical Problems

5.1 Simple Mathematics

【PAT B119/A1069 The Black Hole of Numbers】

代码CPP · 39 行
#include<bits/stdc++.h>
#include<iostream>
using namespace std;

void to_array(int a[],int b){
    for(int i=0;i<4;i++){
        a[i]=b%10;
        b/=10;
    }
}

int to_number(int a[]){
    int b=0;
    for(int i=0;i<4;i++){
        b=b*10+a[i];
    }
    return b;
}

bool cmp(int a,int b){
    return a>b;
}

int main(){
    int n;
    cin>>n;
    int ans,a1,a2;
    int t[5];
    while(ans!=6174){
        to_array(t,n);
        sort(t,t+4);
        a1=to_number(t);
        sort(t,t+4,cmp);
        a2=to_number(t);
        ans=a2-a1;
        n=ans;
        printf("%04d-%04d=%04d\n",a2,a1,ans);
    }
}

5.2 Greatest Common Divisor and Least Common Multiple

5.2.1 Greatest Common Divisor

Based on the Euclidean algorithm (successive division)

gcd(a,b)=gcd(b,a%b)

The above formula can be viewed as a recurrence

There is also the recursion boundary gcd(a,0)=a

Code implementation

int gcd(int a,int b){
    if(b==0) return a;
    else return gcd(b,a%b);
}
或者
int gcd(int a,int b){
    return !b?a:gcd(b,a%b);
}

5.2.2 Least Common Multiple

First find the greatest common divisor d=gcd(a,b); then the least common multiple is $\frac{a}{d}*b$

5.3 Arithmetic Operations on Fractions

5.3.1 Representation and Simplification of Fractions

1. Representation of Fractions

struct Fraction{
    int up,down;
};

Three rules must be specified for this representation:

  1. Make down non-negative; if the fraction is negative, make up negative
  2. If the fraction is 0, set up=0, down=1
  3. The numerator and denominator are coprime

2. Simplification of Fractions

Mainly used to make the Fraction variable satisfy the three rules of fractions

Fraction reduction(Fraction result){
    if(result.down<0){ //满足第一条规定
        result.up=-result.up;
        result.down=-result.down;
    }
    if(result.up==0) result.down=1; //满足第二条规定
    else{ //满足第三条规定
        int d=gcd(abs(result.up),abs(result.down));
        result.up/=d;
        result.down/=d;
    }
    return result;
}

5.3.2 Arithmetic Operations on Fractions

1.2.3.4 Addition, Subtraction, Multiplication, and Division

They are largely similar. Just compute them by finding a common denominator the hard way, and remember to return reduction(result) at the end

5.3.3 Output of Fractions

  1. Simplify first
  2. If f.down=1, output up directly
  3. Output of mixed numbers: the integer part is r.up/r.down, the numerator part is abs(r.up)%r.down, and the denominator is r.down

Since the multiplication and division of fractions may cause the numerator or denominator to exceed the range of the int type, in general the numerator and denominator should be stored using long long

5.4 Prime Numbers

5.4.1 Primality Testing

bool isPrime(int n){
    if(n<=1) return false;
    int sqr=(int)sqrt(1.0*n); //在 n 前面乘上 1.0 使之变为浮点型
    for(int i=2;i<=sqr;i++){
        if(n%i==0) return false;
    }
    return true;
}

If n is relatively small (i.e., i^2 does not overflow the int type), it can also be written as follows

bool isPrime(int n){
    if(n<=1) return false;
    for(int i=2;i*i<=n;i++){
        if(n%i==0) return false;
    }
    return true;
}

5.4.2 Obtaining a Prime Table

The brute-force method has a complexity of O($n \sqrt n$). Below, two more efficient sieving methods are introduced.

//埃氏筛法:从 2 开始,将每个质数的倍数都标记成合数,以达到筛选素数的目的
int visit[maxn];  //maxn 是需要打的素数表(布尔数组)
void Prime(){
    memset(visit,0,sizeof(visit)); //初始化都是素数,如果是素数的话就是 1,不是素数才是 0
    for (int i = 2; i < maxn; i++) { //注意不能写成 i<=maxn
        if (!visit[i]) {         //如果 i 是素数,让 i 的所有倍数都不是素数
            for (int j = i+i; j < maxn; j += i) { 
                visit[j] = 0;
            }
        }
    }
}

The time complexity is O(nloglogn)

Principle: when we reach a number a from small to large, if a has not been sieved out by the previous steps, then a must be prime. Because if a were not prime, a would have a factor smaller than a, and a would have been sieved out in an earlier step.

代码CPP · 18 行
//欧拉筛法:在埃氏筛法的基础上,让每个合数只被它的最小质因子筛选一次,以达到不重复的目的。
bool visit[maxn+5]; //1 表示是素数,0 表示不是素数
int prime[maxn+5]; //需要打的素数表
int cnt;
void findPrime(){
    memset(visit,1,sizeof(visit));
    for(int i=2;i<maxn;i++){
        if(visit[i]){
            prime[cnt++]=i;
        }
        //遍历已知的素数来标记合数
        for(int j=0;j<cnt&&i*prime[j]<maxn;j++){
            //循环条件保证遍历的是已知的素数,以及标记的合数不超过 maxn
            visit[i*prime[j]]=0;
            if(i%prime[j]==0) break; //看下文
        }
    }
}
  • When i % prime[j] == 0, it means i is divisible by prime[j], i.e., i=k×prime[j].
  • At this point, the result of multiplying i by a larger prime (such as i * prime[j+1]) will definitely be sieved out by a multiple of prime[j]. (After the break here, as i increases, it will eventually reach a point where i is a multiple of the original i.)
  • For example, when i=4:
    • prime[j] = 2, i * prime[j] = 8.
    • Since 4 % 2 == 0, 4 * 3 = 12 will be sieved out by a multiple of 2 (i.e., 6 * 2 = 12, which can be sieved out when i=6).
    • Therefore, there is no need to continue marking 4 * 3 = 12; just break out of the loop directly.

5.5 Prime Factorization

In the end, everything comes down to a product of several distinct primes, so we might as well first build a prime table; the method for building a prime table is described above.

Since each prime factor may appear more than once, we can define a struct to store the prime factors of a number.

struct Factor{
    int x,cnt;
    //x 为质因子,cnt 为其数目
}fac[10];

Here the fac[] array stores all the prime factors of the given positive integer n; for example, for n=20=2*2*5

fac[0].x=2
fac[0].cnt=2
fac[1].x=5
fac[1].cnt=1

Since $23571113171923*29>\mathrm{INT_MAX}$, an array of size 10 for fac[] is sufficient.

We can easily notice the following property: for a composite number n, either all of its prime factors are less than or equal to $\sqrt n$, or exactly one prime factor is greater than $\sqrt n$ while all the remaining prime factors are less than or equal to $\sqrt n$.

Using this property, we can perform prime factorization on a composite number n:

  1. First, in the prime table, enumerate all primes from 2 to $\sqrt n$ and test whether they are prime factors of n.

    If so, add this factor to the fac array, then divide repeatedly, incrementing cnt each time a division is performed.

  2. If after the above operations n is still greater than 1, it means n has one and only one prime factor greater than $\sqrt n$, and that factor is the current n.

At this point, the prime factorization is complete, with a time complexity of O($\sqrt n$).

Code implementation

代码CPP · 23 行
struct Factor{
    int x,cnt=0;
}fac[10];

int main(){
    int n;
    int cnt=0;
    int prime[100];
    int temp=n; //要在外部用 n
    for(int i=2; prime[i]<=sqrt(temp);i++){
        if(n%prime[i]==0){
            fac[cnt].x=prime[i];
            while(n%prime[i]==0){
                fac[cnt].cnt++;
                n/=prime[i]; //注意这两个语句的顺序
            }
        }
    }
    if(n>1){
        fac[cnt++].x=n;
        fac[cnt].cnt=1;
    }
}

Now let's look at an example problem.

【PAT A1059】 Prime Factors

Given an integer in the int range, output its factorization into prime factors in the form of a product, in ascending order.

Sample Input

97532468

Sample Output

97532468=2^2*11*17*101*1291

Code implementation

代码CPP · 58 行
#include<bits/stdc++.h>
#include<iostream>
using namespace std;

const int maxn=100005;

struct Factor{
    int x,cnt=0;
}fac[10];


int prime[maxn],cnt;
int t[maxn]={0}; //0 表示是素数,1 表示不是素数
void findPrime(){
    for(int i=2;i<maxn;i++){
        if(!t[i]){
            prime[cnt]=i;
            cnt++;
            for(int j=i+i;j<maxn;j+=i){
                t[j]=1;
            }
        }
    }
}

int main(){ 
    int n;
    cin>>n;
    if(n==1){
        cout<<"1=1";
        return 0;
    }
    findPrime();
    int temp=n;
    int num=0;
    for(int i=0;prime[i]<=sqrt(1.0*temp);i++){
        if(n%prime[i]==0){
            fac[num].x=prime[i];
            while(n%prime[i]==0){
                fac[num].cnt++;
                n/=prime[i];
            }
            num++;
        }
    }
    if(n>1){
        fac[num].x=n;
        fac[num].cnt++;
        num++;
    }
    cout<<temp<<'=';
    for(int i=0;i<num;i++){
        if(i!=0) cout<<'*';
        if(fac[i].cnt==1) cout<<fac[i].x;
        else cout<<fac[i].x<<'^'<<fac[i].cnt; 
    }
    return 0;
}

Summary of common pitfalls:

  • For factorization within the range of INT_MAX, a prime table of size 10^5 is sufficient
  • Handle the special case n==1
  • Call findPrime() at the beginning of the main function
  • In the findPrime function, do not write i<=maxn; it should be i<maxn
  • Define a variable outside the loop to store sqrt(n)

5.6 Big Integer Arithmetic (High Precision)

代码CPP · 263 行
#include <iostream>
#include <cstring>
using namespace std;

class BigInt
{
private:
    static constexpr int N = 1000; // 位数上限
public:
    int a[N]; // 低位在前,高位在后

    // 默认构造函数,支持 int 初始化
    BigInt(int x = 0) : a{}
    {
        for (int i = 0; x; i++)
        {
            a[i] = x % 10;
            x /= 10;
        }
    }

    // 复制构造函数
    BigInt(const BigInt &b)
    {
        memcpy(a, b.a, sizeof(a));
    }

    // 赋值运算符
    BigInt &operator=(const BigInt &b)
    {
        if (this != &b)
        {
            memcpy(a, b.a, sizeof(a));
        }
        return *this;
    }

    // 加法(BigInt + BigInt)
    BigInt operator+(const BigInt &x) const
    {
        BigInt res = *this;
        res += x;
        return res;
    }

    // 加法(BigInt += BigInt)
    BigInt &operator+=(const BigInt &x)
    {
        for (int i = 0; i < N; i++)
        {
            a[i] += x.a[i];
            if (a[i] >= 10)
            {
                a[i + 1] += a[i] / 10;
                a[i] %= 10;
            }
        }
        return *this;
    }

    // 减法(BigInt - BigInt)
    BigInt operator-(const BigInt &x) const
    {
        BigInt res = *this;
        res -= x;
        return res;
    }

    // 减法(BigInt -= BigInt)
    BigInt &operator-=(const BigInt &x)
    {
        for (int i = 0; i < N; i++)
        {
            a[i] -= x.a[i];
            if (a[i] < 0)
            {
                a[i] += 10;
                a[i + 1] -= 1;
            }
        }
        return *this;
    }

    // 乘法(BigInt * int)
    BigInt operator*(int x) const
    {
        BigInt res = *this;
        res *= x;
        return res;
    }

    // 乘法(BigInt *= int)
    BigInt &operator*=(int x)
    {
        for (int i = 0; i < N; i++)
        {
            a[i] *= x;
        }
        for (int i = 0; i < N - 1; i++)
        {
            a[i + 1] += a[i] / 10;
            a[i] %= 10;
        }
        return *this;
    }

    // 乘法(BigInt * BigInt)
    BigInt operator*(const BigInt &x) const
    {
        BigInt res;
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j + i < N; j++)
            {
                res.a[i + j] += a[i] * x.a[j];
                if (res.a[i + j] >= 10)
                {
                    res.a[i + j + 1] += res.a[i + j] / 10;
                    res.a[i + j] %= 10;
                }
            }
        }
        return res;
    }

    // 取模(BigInt % int)
    int operator%(int x) const
    {
        int remainder = 0;
        for (int i = N - 1; i >= 0; i--)
        {
            remainder = (remainder * 10 + a[i]) % x;
        }
        return remainder;
    }

    // 除法(BigInt /= int)
    BigInt &operator/=(int x)
    {
        for (int i = N - 1; i >= 0; i--)
        {
            if (i)
            {
                a[i - 1] += (a[i] % x) * 10;
            }
            a[i] /= x;
        }
        return *this;
    }

    // 比较运算(BigInt == BigInt)
    bool operator==(const BigInt &x) const
    {
        for (int i = 0; i < N; i++)
        {
            if (a[i] != x.a[i])
                return false;
        }
        return true;
    }
    // 比较运算(BigInt < BigInt)
    bool operator<(const BigInt &x) const
    {
        for (int i = N - 1; i >= 0; i--)
        {
            if (a[i] < x.a[i])
                return true;
            if (a[i] > x.a[i])
                return false;
        }
        return false;
    }
    // 比较运算(BigInt > BigInt)
    bool operator>(const BigInt &x) const
    {
        return x < *this;
    }
    // 比较运算(BigInt <= BigInt)
    bool operator<=(const BigInt &x) const
    {
        return !(x < *this);
    }
    // 比较运算(BigInt >= BigInt)
    bool operator>=(const BigInt &x) const
    {
        return !(*this < x);
    }
    // 一元负号(取反运算)
    BigInt operator-() const
    {
        BigInt res = *this;
        for (int i = 0; i < N; i++)
        {
            res.a[i] = -res.a[i];
        }
        return res;
    }
    // 括号运算符(获取某个位数)
    int operator()(int index) const
    {
        if (index < 0 || index >= N)
            return -1; // 返回 -1 代表超出范围
        return a[index];
    }


    // Pre-increment (++obj)
    BigInt& operator++() 
    {
        *this += BigInt(1);
        return *this;
    }

    // Post-increment (obj++)
    BigInt operator++(int) 
    {
        BigInt temp = *this; 
        ++(*this);
        return temp;
    }

    // Pre-decrement (--obj)
    BigInt& operator--() 
    {
        *this -= BigInt(1); 
        return *this;
    }

    // Post-decrement (obj--)
    BigInt operator--(int) 
    {
        BigInt temp = *this;
        --(*this);
        return temp;
    }
    
    // 输出运算符
    friend ostream &operator<<(ostream &o, const BigInt &b)
    {
        int t = N - 1;
        while (t > 0 && b.a[t] == 0)
        {
            t--;
        }
        for (int i = t; i >= 0; i--)
        {
            o << b.a[i];
        }
        return o;
    }
    // 输入运算符
    friend istream &operator>>(istream &in, BigInt &b)
    {
        string s;
        in >> s;
        memset(b.a, 0, sizeof(b.a));
        for (int i = 0; i < s.size(); i++)
        {
            b.a[i] = s[s.size() - 1 - i] - '0';
        }
        return in;
    }
};

5.7 Extended Euclidean Algorithm

To be filled in

5.8 Combinatorial Numbers

To be filled in

Chapter 6: Introduction to the C++ Standard Template Library (STL)

6.1 Detailed Explanation of Common Uses of vector

Examples of Definition Methods

vector<int> name;
vector<char> name;
vector<vector<int> > name; //两个>>之间加上空格以防止被识别成移位操作
//这个可以理解成两个维度都可以变成的二维数组

Ways to define a vector array

vector<int> arr[100]; //这种定义方式就是一维的长度被固定成 100 了

Accessing Elements in a vector Container

Accessing by Index

Just like an ordinary array

Accessing via Iterator

An iterator can be understood as something similar to a pointer

vector<typename>::iterator it; //it 是一个 vector<typename>::iterator 型的变量

This gives us the iterator it, and we can access elements in the vector through *it. For example:

vector<int> vi;
for(inti=1;i<=5;i++){
    vi.push_back(i); //push_back(i) 在 vi 的末尾添加元素 i,即依次添加 1 2 3 4 5
}

You can access elements in the container in a way similar to using indices and pointers to access arrays

#include <bits/stdc++.h>
using namespace std;
int main(){
    vector<int> vi;
    for(int i=1;i<=5;i++){
        vi.push_back(i);
    }
    //vi.begin() 为取 vi 的首元素地址,而 it 指向这个地址
    vector<int>::iterator it=vi.begin();
    for(int i=0;i<5;i++){
        printf("%d ",*(it+i));
    }
    return 0;
}

From this we can see that vi[i]==*(vi.begin()+i)
One more note about the end() function: it returns the address after the address of the last element. As the end marker of the iterator, end() does not store any element. (Americans habitually think in terms of left-closed, right-open intervals)

#include <bits/stdc++.h>
using namespace std;
int main(){
    vector<int> vi;
    for(int i=1;i<=5;i++){
        vi.push_back(i);
    }
    //vector 的迭代器不支持 it<vi.end() 的元素,循环条件只能用 it!=vi.end()
    for(vector<int>::iterator it=vi.begin();it!=vi.end();it++){
        printf("%d ",*it);
    }
    return 0;
}

To emphasize: among STL containers, only vector and string allow the syntax of adding an integer to an iterator, such as vi.begin()+3

Analysis of Commonly Used vector Functions with Examples

push_back()

Adds an element (x) to the end of the vector, with time complexity O(1). See the example above

pop_back()

Used directly without passing arguments, to delete the last element of the vector, with time complexity O(1)

size()

Used to get the number of elements in the vector. The return value is unsigned, but %d generally works fine. Time complexity O(1)

clear()

Clears all elements in the vector, with time complexity O(N), where N is the number of elements in the vector

insert()

insert(it,x) is used to insert an element x at any iterator it of the vector, with time complexity O(N)

#include <bits/stdc++.h>
using namespace std;
int main(){
    vector<int> vi;
    for(int i=1;i<=5;i++){
        vi.push_back(i);
    }
    vi.insert(vi.begin()+2,-1);
    for(int i=0;i<vi.size();i++){
        printf("%d ",vi[i]);
    }
    return 0;
}
引用Yes, for std::vector<int> vi, vi + i == vi[i] does not hold. Analysis of...

Yes, for std::vector<int> vi, vi + i == vi[i] does not hold.

Analysis of the Reason

  1. The meaning of vi[i]:

    • vi[i] is an operator overload provided by std::vector, used to access the element at index i in the vector. Its underlying implementation is equivalent to:
      *(vi.begin() + i)
      where vi.begin() is an iterator pointing to the first element of vi, and iterators support offsetting.
  2. The meaning of vi + i:

    • vi is an object of type std::vector, not a pointer or an iterator. C++ does not allow using the addition operator directly on an object, so vi + i is illegal and will cause a compilation error.

Correct Usage

If you want to achieve an effect similar to vi[i] through a pointer or iterator, you should use vi.begin() or pointer offsetting. For example:

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

int main() {
    vector<int> vi = {10, 20, 30, 40};
    
    // 使用下标访问
    cout << vi[2] << endl;  // 输出:30

    // 使用迭代器
    auto it = vi.begin();
    cout << *(it + 2) << endl;  // 输出:30

    return 0;
}

Comparison: arr + i == arr[i] in Ordinary Arrays

For an ordinary array (such as int arr[5]), arr is a pointer to the first element of the array, so arr + i is legal and points to the address of the i-th element of the array. Meanwhile, arr[i] is actually syntactic sugar for accessing a value through pointer offsetting, essentially *(arr + i).


Conclusion

In std::vector:

  • vi[i] is a legal operation for accessing an element by index.
  • vi + i is illegal, because vi is an object rather than a pointer. If you need to perform an operation similar to vi[i], you should use an iterator or index.

erase()

There are two usages: deleting a single element, or deleting all elements within a range, both with time complexity O(N)

  1. Deleting a single element
    erase(it) deletes the element at the iterator position
#include <bits/stdc++.h>
using namespace std;
int main(){
    vector<int> vi;
    for(int i=1;i<=5;i++){
        vi.push_back(i); //1 2 3 4 5
    }
    vi.erase(vi.begin()+1); //删除 2 不是 vi.begin()+1 因为*(vi.begin())==vi[0]
    for(int i=0;i<vi.size();i++){
        printf("%d ",vi[i]);
    }
    return 0;
}
  1. Deleting all elements within a range
    erase(first,last) deletes all elements within [first,last)
    From this we can see that vi.clear() is equivalent to vi.erase(vi.begin(),vi.end())

6.2 Detailed Explanation of Common Uses of set

set, that is, a set, is a container that is automatically sorted internally and contains no duplicate elements

Definition of set

set<typename> name;

Similar to vector, or rather, the definition of most STL containers follows this pattern

Accessing Elements in a set Container

set can only be accessed through iterators

set<int>::iterator it;

STL containers other than vector and string do not support the *(it+i) access method, so you can only enumerate this way

#include <bits/stdc++.h>
using namespace std;
int main(){
    set<int> st;
    st.insert(2);
    st.insert(1);
    st.insert(3);
    st.insert(1);
    //不支持 it<st.end()
    for(set<int>::iterator it=st.begin();it!=st.end();it++){
        cout<<*it;
    } //要理解迭代器,不是针对一个对象,而是这个类中的一种数据类型
    return 0;
}

Output result

1 2 3

From this we can see that elements in a set are automatically sorted in ascending order and duplicates are automatically removed

Analysis of Commonly Used set Functions with Examples

insert()

Automatically sorts in ascending order and removes duplicates, with time complexity O(logN)

find()

find(value) returns the iterator in the set corresponding to the value value, with time complexity O(logN)

#include <bits/stdc++.h>
using namespace std;
int main(){
    set<int> st;
    st.insert(2);
    st.insert(1);
    st.insert(3);
    st.insert(1);
    set<int>::iterator it=st.find(2);
    cout<<*it<<endl; //输出 2
    return 0;
}

If the value is not found, it returns st.end(). This feature can be used together with set to implement complex hashing

erase()

    • st.erase(it) deletes a single element (the one at the corresponding iterator position), and can be used together with the find function. Time complexity is O(1)
    • st.erase(value) deletes a single element (the one whose value is value). Time complexity is O(logN)
    • Why is this possible? Because the type of value is typename, while the type of it is set::iterator
  1. Deleting all elements within a range: st.erase(first,last), where first and last are both iterators, with time complexity O(last-first)

size()

Omitted, O(1)

clear()

O(N)

6.3 Detailed Explanation of Common Uses of string

Definition of string

string str;
string str1="abcd";

Accessing Content in a string

Accessing by Index

Access a string just like accessing a character array

#include <bits/stdc++.h>
using namespace std;
int main(){
    string str="abcd";
    for(int i=0;i<str.length();i++){
        printf("%c", str[i]); //输出 abcd
    }
    return 0;
}

If you want to read in and output the entire string, you can only use cin and cout

#include <bits/stdc++.h>
using namespace std;
int main(){
    string str;
    cin>>str;
    cout<<str;
    return 0;
}

However, if you really want to use printf, you can use c_str() for the conversion

#include <bits/stdc++.h>
using namespace std;
int main(){
    string str="abcd";
    printf("%s\n", str.c_str());
    return 0;
}

Accessing via Iterator

Mainly because some functions, such as insert() and erase(), require an iterator as a parameter
Since there is no <typename> part when defining a string, you can define it directly like this

string::iterator it;

Then you can use an iterator to traverse the string

#include <bits/stdc++.h>
using namespace std;
int main(){
    string str="abcd";
    for(string::iterator it=str.begin();it!=end();it++){
        cout<<*it;
    }
    return 0;
}

The loop condition here can also be written as it<str.end(), because only vector and string support directly adding or subtracting a number from an iterator, such as str.begin()+3

Analysis of Commonly Used string Functions with Examples

operator+=

You can concatenate two strings directly

#include <bits/stdc++.h>
using namespace std;
int main(){
    string str1="abc",str2="xyz",str3;
    str3=str1+str2;
    cout<<str3; //abcxyz
}

compare operator

Two string types can be compared directly using comparison operators, based on lexicographic order

if(str1>str2){

}

length() or size()

str.length();
str.size();

Both return the length of the string and are basically the same, with time complexity O(1)

insert()

The insert() function of string has multiple forms, all with time complexity O(N)

  1. insert(pos,string), inserts the string string at position pos
    This pos position can be 0
string str1="abc",str2="opq";
str1.insert(3,str2); //往 str[3]处插入 opq,这里也可以直接写"opq"
cout<<str1<<endl; //abcopq
  1. insert(it,it2,it3), where it is the desired insertion position in the original string, and it2 and it3 are the beginning and ending iterators of the string to be inserted, indicating that [it2,it3) will be inserted at the position of it
string str1="abc",str2="opq";
str.insert(str.begin(),str2.begin,str2.end());
cout<<str1<<endl; //abcopq

erase()

Time complexity is O(N) in all cases

  1. Deleting a single element
str.erase(it);
  1. Deleting all elements within a range, two methods
    • str.erase(first,last) both are iterators
    • str.erase(pos,length) where pos is the starting position (not an iterator), and length is the number of characters to delete
    string str="abcdefg";
    str.erase(3,2); //删除 c 和 d,从第三位开始的两个 (包括第三位)
    This pos position can be 0

clear()

O(1)

substr()

substr(pos,len) returns the substring starting at position pos with length len, with time complexity O(len). Example as follows

#include <bits/stdc++.h>
using namespace std;
int main(){
    string str="Thank you for your smile.";
    cout<<str.substr(0,5)<<endl; //Thank
    cout<<str.substr(14,4)<<endl; //Your
}

This pos position can be 0

string::npos

string::npos is a constant whose value is -1, but since it is of type unsigned_int, it can also be regarded as the maximum value of the unsigned_int type. As the return value of the find function when a match fails, string::npos can be considered as -1 or 4294967295

find()

  • str.find(str2), when str2 is a substring of str, returns the position of its first occurrence in str (not an iterator); if str2 is not a substring of str, returns string::npos
  • str.find(str2,pos) matches str2 starting from position pos, with the same return value as above
    Time complexity is O(mn), where m and n are the lengths of the two strings respectively

using namespace std;
int main{
string str ="Thank you for your smile."
string str2 "you";
string str3 "me";
if (str.find (str2) string!=npos)
cout << str.fånd (str2) << endl;
if (str.find(str2, 7) String:!=npos) (
cout str.find (str2, 7) endl;
if (str. find (str3) String:!=npos)
cout << Str. find(str3) endl;
) else {
cout "I know there is no position for me." << endl;}
return O;
}

Output result

6
14
I know there is no position for me.

replace()

  • str.replace(pos,len,str2) replaces the substring of str starting at position pos with length len with str2\
  • str.replace(it1,it2,str2) replaces the substring within the iterator range [it1,it2) of str with st2
  • Time complexity is O(str.length())
#include <bits/stdc++.h>
using namespace std;
int main(){
    string str="Maybe you will turn around";
    string str2="will not";
    string str3="surely";
    cout<<str.replace(10,4,str2)<<endl;
    cout<<str.replace(str.begin(),str.begin()+5,str3);
    return 0;
}

Output

Maybe you will not turn around
surely you will not turn around

c.str()

Can convert a string into a char [], after which the sprintf and sscanf functions can be used.

sscanf(login_date.c_str(),"%d-%d",&year,&month);

PAT A1060 ARE THEY EQUAL

6.4 Detailed Explanation of Common Uses of map

map translates to mapping (actually here it can only be an injective mapping). For example, an array typename arr[] is a mapping from the int type to other types, but map can map any basic type (including STL containers) to any basic type (including STL containers), such as a mapping from string to int

Definition of map

map<typename1,typename2> mp;

The former is the type before mapping (key), and the latter is the type after mapping (value)
If it is a mapping from string to integer, you must use string instead of a char array

map<string,int> mp;

This is because a char array cannot be used as a key, so you can only use string
There are also maps like this

map<set<int>,string> mp;

Accessing Elements in a map Container

There are two ways to access a map

Accessing by Index

Just like accessing an ordinary array. For example, for a map defined as

map<char,int> mp;

you can access its corresponding int using

mp['c']

However, note that, like functions, the keys in a map are unique. For example

map<char,int> mp;
mp['c']=20;
mp['c']=30; //20被覆盖
cout<<mp['c']; //输出30

Accessing via Iterator

map<typename1,typename2>::iterator it;

Since each pair of mappings in a map has two typenames, an iterator it must be able to access both the key and the value

it->first //访问键
it->second //访问值

For example, the following example

int main(){
    map<char,int> mp;
    mp['m']=20;
    mp['r']=30;
    mp['a']=40;
    for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){
        printf("%c %d\n",it->first,it->second);
    }
    return 0;
}

Output as follows:

a 40
m 20
r 30

From this we can see that a map automatically sorts by key in ascending order (since a<m<r), which is similar to set (because its underlying principle is the same as set, both being red-black trees)

Analysis of Commonly Used map Functions with Examples

find()

find(key) returns the iterator of the mapping whose key is key, with time complexity O(logN), where N is the number of mappings in the map

map<char,int> mp;
mp['a']=1;
mp['b']=2;
map<char,int>::iterator it=mp.find('b');
printf("%c %d", it->first,it->second);

The output result is

b 2

erase() Can Be Learned by Analogy with set

  1. Deleting a single element
    • mp.erase(it), where it is the iterator of the element to be deleted, with time complexity O(1). It can be used together with the find() function
    map<char,int> mp;
    mp['a']=1;
    mp['b']=2;
    map<char,int>::iterator it=mp.find('b');
    mp.erase(it); //删除 b 2
    • mp.erase(key), where key is the key of the mapping to be deleted, with time complexity O(logN)
    map<char,int> mp;
    mp['a']=1;
    mp['b']=2;
    mp.erase('b'); //删除 b 2
  2. Deleting all elements within a range
    mp.erase(first,last), where both arguments passed in are iterators, deletes the elements within [first,last), with time complexity O(last-first)

size()

O(1), obtains the number of mapping pairs

clear()

O(N)

Common Uses

  1. Establishing a mapping between char or string and int
  2. Using map as a bool array

6.5 Detailed Explanation of Common Uses of queue

Definition of queue

queue <typename> name;

Accessing Elements in a queue Container

Since a queue is first-in-first-out, in the STL you can only access the front element via front() or the back element via back()

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

int main(){
    queue<int> q;
    for(int i=1;i<=5;i++){
        q.push(i);
    }
    cout<<q.front()<<' '<<q.back(); //输出 1 5
}

Analysis of Commonly Used queue Functions with Examples

push()

Pushes x into the queue

front() back()

Obtains the front element and the back element

pop()

Makes the front element leave the queue

int main(){
    queue<int> q;
    for(int i=1;i<=5;i++){
        q.push(i);
    }
    for(int i=1;i<=3;i++){
        q.pop(); //弹出 1 2 3
    }
    cout<<q.front()<<' '<<q.back(); //输出 4 5
}

empty()

Returns true if empty, returns false if not empty

size()

Returns the number of elements in the queue

Common Uses of queue

Breadth-first search

Note that before using front() and pop(), you need to use empty() to check whether the queue is empty

6.5+ Detailed Explanation of Common Uses of deque

Definition of deque

Similar to queue

Accessing Elements in a deque Container

Similar to queue

Common deque Functions

push_back()

Adds an element at the end

push_front()

Adds an element at the front

pop_front() and pop_back()

front() and back()

size() and clear()

6.6 Detailed Explanation of Common Uses of priority_queue

priority_queue, also known as a priority queue, is implemented using a heap at the bottom layer. In a priority queue, the front element is always the one with the highest priority in the current queue

For example, suppose the queue contains the following elements with priorities already assigned

桃子(优先级 3)
梨子(优先级 4)
苹果(优先级 1)

Then the dequeue order would be pear (priority 4) → peach (priority 3) → apple (priority 1)

Of course, you can push elements into the priority queue at any time, and the heap (the underlying data structure of the priority queue) will adjust its structure at all times, ensuring that the front element that comes out each time is the one with the highest priority

As for the priority here, it is defined by convention; in the example above, one could also define it so that a smaller number means a higher priority

Definition of priority_queue

priority_queue<typename> name;

Accessing Elements in a priority_queue Container

Unlike queue, priority_queue does not have front() and back() functions; you can only access the front element, i.e., the element with the highest priority, via the top() function

int main(){
    priority_queue<int> q;
    q.push(1);
    q.push(3);
    q.push(2);
    cout<<q.top(); //输出 3
}

Analysis of Commonly Used priority_queue Functions with Examples

push()

O(logN), where N is the current number of elements

top()

O(1)

Accesses the top element of the heap

pop()

Makes the front element leave the queue

O(logN)

int main(){
    priority_queue<int> q;
    q.push(1);
    q.push(3);
    q.push(2);
    cout<<q.top(); //输出 3
    q.pop();
    cout<<q.top(); //输出 2
}

empty()

Returns true if empty, returns false if not empty

O(1)

size()

Returns the number of elements in the priority queue

O(1)

Setting the Priority of Elements in a priority_queue

Setting the Priority for Basic Data Types

This refers to data types such as int, double, and char that can be used directly. For these, the priority queue generally assigns the highest priority to the largest number, so the front element is the largest element in the priority queue (for char type, it is the one with the largest lexicographic order).

For basic data types, the following two definitions of a priority queue are equivalent (using int as an example)

priority_queue<int> q;
priority_queue<int,vector<int>,less<int> > q; //注意最后两个>之间有空格
  • vector<int> specifies the container used to carry the underlying data structure heap; vector<typename> should be consistent with the typename mentioned earlier
  • less<int> is the comparison class for the first parameter; less<int> means that a larger number has a higher priority, while greater<int> means that a smaller number has a higher priority

Therefore, if you want the priority queue to always place the smallest element at the front, you only need to define it as follows

priority_queue<int,vector<int>,greater<int> > q; //注意最后两个>之间有空格

In fact, even for basic data types, you can use the struct-based priority setting method explained below, though the way the three parameters are written is a bit different.

Setting the Priority for Structs

Taking the fruits at the beginning of this section as an example

struct Fruit{
	string name;
	int price;
};

Now, if we want fruits with a higher price to have a higher priority, we need to overload the less-than sign "<". Overloading means redefining an existing operator, that is, you can change the function of the less-than sign. An example of how to write it is as follows

struct Fruit {
    string name;
    int price;
    friend bool operator < (fruit f1,fruit f2) {
        	return f1.price<f2.price;
	}
};

As you can see, a function has been added to the Fruit struct,

where "friend" means friend; its specific meaning will not be elaborated here

The following bool operator < (fruit f1,fruit f2) overloads the operator '<' for the fruit type

The essence of operator overloading is that for this particular type, the effect of the operator is different! So you can also define it for int, double, set, and so on

(Overloading the greater-than sign will cause a compilation error, because mathematically speaking, you only need to overload the less-than sign, i.e., f1>f2 is equivalent to checking f2<f1, and f1=f2 is equivalent to checking !(f1<f2)&&!(f2<f1))

Inside the function is return f1.price<f2.price, so after overloading, the less-than sign still functions as a less-than sign. At this point, you can directly define a priority queue of Fruit type, in which fruits with a higher price have a higher priority, as follows

priority_queue<fruit> q;

Similarly, if you want fruits with a lower price to have a higher priority, you only need to change the less-than sign in the return statement to a greater-than sign

struct Fruit {
    string name;
    int price;
    friend bool operator < (fruit f1,fruit f2) {
        	return f1.price>f2.price;
	}
};

It is not hard to notice that this overloading of the less-than sign is similar to the cmp function in sort; indeed, they look somewhat alike. Both take two variables as parameters and both return a bool, but the effects appear to be "opposite". In sorting, if you write return f1.price>f2.price, the elements are sorted from high to low, but in a priority queue, it is the fruit with the lower price that has the higher priority

The effect of this function in a priority queue is opposite to that of the cmp function in sort

You can also write it outside the struct, just like the cmp function of sort. You only need to remove friend, change the less-than sign to a pair of parentheses, write the overloaded function outside the struct, and wrap it with struct

struct cmp {
    bool operator () (fruit f1,fruit f2){
		return f1.price>f2.price; //价格小的优先级大,仍然与 sort 的相反
    }
}

In this case, use the second definition method mentioned earlier to define the priority queue

priority_queue<fruit,vector<fruit>,cmp> q;

It should be noted that even for basic data types or other STL containers (such as set), the priority can be defined this way

#include <set>
#include <iostream>
#include <functional>
using namespace std;
int main() {
    // 使用 greater 定义降序排序的 set
    set<int, greater<int>> s;
    s.insert(10);
    s.insert(5);
    s.insert(20);

    for (int x : s) {
        cout << x << " "; // 输出 20 10 5
    }
    return 0;
}

Or

代码CPP · 35 行
#include<bits/stdc++.h>

using namespace std;

struct Fruit {
    string name;
    int price;
};

// 自定义比较函数对象
struct cmp {
    bool operator()(const Fruit& f1, const Fruit& f2) const {
        return f1.price > f2.price; // 按价格从大到小排序
    }
};

int main() {
    // 创建一个 set,使用自定义比较函数对象
    set<Fruit, cmp> fruitSet;

    // 添加元素
    fruitSet.insert({"Apple", 5});
    fruitSet.insert({"Banana", 3});
    fruitSet.insert({"Orange", 8});

    // 遍历并输出
    for (const Fruit& fruit : fruitSet) {
        cout << fruit.name << " (" << fruit.price << ")\n";
        // 输出 Orange (8)
        //      Apple (5)
        //      Banana (3)
    }

    return 0;
}

Finally, it should be pointed out that if the data inside the struct is large (for example, if strings or arrays appear), it is recommended to use references to improve efficiency. In this case, you need to add const and & to the parameters of the comparison class, as shown below

friend bool operator < (const fruit &f1, const fruie &f2){
    return f1.price>f2.price;
}
bool opreator () (const fruit &f1, const fruie &f2) {
    return f1.price>f2.price;
}

Common Uses of priority_queue

It can be used to solve some greedy problems

Before using the top() function, you must check whether the priority queue is empty

6.7 Detailed Explanation of Common Uses of stack

Definition of stack

#include<stack>
stack<typename> name;

typename can be any basic data type or container

Accessing Elements in a stack Container

Since stack is itself a last-in-first-out data structure, in the STL, a stack can only access the top element via top()

int main(){
    stack<int> st;
    st.push(1);
    st.push(2);
    cout<<st.top(); //输出 2
}

Analysis of Commonly Used stack Functions with Examples

push()

O(1) push(x) pushes x onto the stack

top()

O(1) obtains the top element of the stack

pop()

O(1) pops the top element of the stack, as shown in the following example

int main(){
    stack<int> st;
    for(int i=1;i<=5;i++){
        st.push(i); //分别把 1 2 3 4 5 推入栈中
    }
    for(int i=1;i<=3;i++){
        st.pop(); //相当于推出 5 4 3
    }
    cout<<st.top(); //输出 2
    return 0;
}

empty()

Checks whether the stack is empty; returns true if empty, returns false if not empty

st.empty()

size()

Returns the number of elements in the stack, O(1)

st.size()

How to Clear a Stack

There is no built-in function for this, but you can write it like this

while(!st.empty()){
	st.pop();
}

However, a more common approach is to define a new stack, which effectively achieves clearing the stack.

Common Uses of stack

It is used to simulate some recursive processes, preventing program errors caused by the program's limit on stack memory

6.8 Detailed Explanation of Common Uses of pair

When you want to bind two elements together as a composite element but do not want to define a struct for this purpose, using pair can serve as a convenient substitute. In other words, a pair can actually be viewed as a struct with two elements inside, and the types of these two elements can be specified.

Sometimes it runs faster than a struct

Definition of pair

pair <typename1,typename2> name;

which is equivalent to

struct pair {
    tyoename1 first;
    typename2 first;
}

The way to initialize it is as follows (for example), by adding a pair of parentheses after it

pair<string,int> p("haha",5);

If you want to temporarily construct a pair in your code, there are two methods

  1. Write the type definition first, followed by two elements in parentheses

  2. Use the built-in make_pair function

    make_pair("haha",5);

Accessing Elements in a pair

A pair has only two elements, first and second, which can be accessed in the same way as an ordinary struct

pair<string,int> p("haha",5);
cout<<p.first; //输出 haha
cout<<p.second; //输出 5

Analysis of Commonly Used pair Functions with Examples

Comparison Operations

Two pair-type objects can be compared directly. The comparison rule is to use the size of first as the standard first, and only when first is equal is the size of second examined

Common Uses of pair

  1. It can be used as a substitute for a two-element struct and its constructor, saving coding time

  2. It can be used as a key-value pair for insertion into a map, for example in the following case

    #include<bits/stdc++.h>
    using namespace std;
    
    int main(){
        map<string,int> mp;
        mp.insert(make_pair("abc",123));
        mp.insert(make_pair("efg",456));
        for(auto x:mp){
            cout<<x.first<<' '<<x.second<<endl;
        }
    }

    Output

    abc 123
    efg 456

    This is because the internal implementation of map involves pair

6.9 Commonly Used Algorithm Functions

6.9.1 max(), min() and abs()

The meanings are obvious.

The parameters of max() and min() can be int or floating-point numbers; when you want to find the maximum of three numbers, you can do this:

max(x,max(y,z));

Or you can do this

max({x,y,z});

The parameter of abs() can only be an integer

6.9.2 swap()

swap(x,y) is used to swap the values of x and y

int x=1,y=2;
swap(x,y);
cout<<x<<' '<<y; //输出 2 1

6.9.3 reverse()

reverse(it1,it2) can reverse the elements between [it1, it2) pointed to by an array pointer, or the elements within the range [it1, it2) of a container's iterators

//对数组进行反转
#include<bits/stdc++.h>
using namespace std;

int main(){
    int a[5]={1,2,3,4,5};
    reverse(a,a+5); //将 a[0]~a[4]反转
    for(int i=0;i<5;i++){
        cout<<a[i]<<' '; //输出 5 4 3 2 1
    }
}

Containers also work — they must be iterators

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

int main(){
    string str="abcdefg";
    reverse(str.begin(),str.begin()+3); //对 str[0]~str[2]进行反转
    for(int i=0;i<str.length();i++){
        cout<<str[i]<<' '; //输出 cbadefg
    }
}

6.9.4 next_permutation()

next_permutation() gives the next sequence of a given sequence in the full permutation

For example, when n==3, the full permutation is

123
132
213
231
312
321

So the next sequence after 231 is 312

An example is as follows

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

int main(){
    int a[10]={1,2,3};
    //a[0]~a[2]之间的序列需要求解 next_permutation
    do{
        printf("%d%d%d\n",a[0],a[1],a[2]);
    }while(next_permutation(a,a+3));
    return 0;
}

Output result

123
132
213
231
312
321

A loop is used in the above code because next_permutation returns false when it has already reached the last sequence of the full permutation, which makes it convenient to exit the loop. And do...while is used instead of while because the sequence 1 2 3 itself also needs to be output

6.9.5 fill()

fill() can assign a certain interval of an array or container to the same value. Unlike memset, which can only assign 0 or -1, here you can assign anything

int a[5];
fill(a,a+5,233);
//a[5]={233,233,233,233,233};

6.9.6 sort()

How to Use the sort Function

sort(首元素地址(必填),尾元素地址的下一个地址,比较函数(非必填));

If no comparison function is written, the default is ascending order

How to Implement the Comparison Function cmp

Sorting Arrays of Basic Data Types

For example, to sort an array in descending order

bool cmp(int a,int b){
    return a>b; //可以理解成当 a>b 的时候把 a 放在 b 前面
}

Memory trick: if you want ascending order, use '<', because "a<b" means smaller on the left and larger on the right; if you want descending order, use '>', because "a>b" means larger on the left and smaller on the right

Sorting Arrays of Structs

For example, the following struct

struct node{
    int x,y;
}ssd[10];

If you want primary sorting by x

bool cmp(node a,node b){
    return a.x>b.x;
}

Secondary sorting

bool cmp(node a,node b){
    if(a.x!=b.x) return a.x<b.x;
    else return a.y<b.y;
}

Of course, you can also use overloaded operators

struct node{
    int a;
    int b;
    bool operator < (const node &other) const{
        return x<other.x;
    }
}
Sorting Containers

Among the STL standard containers, only vector, string, and deque can be used with sort

//以 vector 为例
bool cmp(int a,int b){
    return a>b; //降序
}
int main(){
    vector<int> vi;
    vi.push_back(2);
    vi.push_back(3);
    vi.push_back(1;
   	sort(vi.begin(),vi.end(),cmp); //3 2 1
}
//以 string 为例
string str[3]={"aa","bbbb","ccc"};
sort(str,str+3); //按照字典序
//或者按照长度排序
bool cmp(string s1,string s2){
    return s1.length()<s2.length(); 
}

6.9.7 lower_bound() and upper_bound()

These two functions need to be used on a sorted array or container; their implementation was already discussed in Section 4.5.1

lower_bound(first,last,val) is used to find the position of the first element whose value is greater than or equal to val within the range [first,last) of an array or container; if it is an array, it returns the pointer to that position; if it is a container, it returns the iterator to that position

upper_bound(first,last,val) is used to find the position of the first element whose value is greater than val within the range [first,last) of an array or container; if it is an array, it returns the pointer to that position; if it is a container, it returns the iterator to that position

If the array or container does not contain the element being searched for, both functions return the pointer or iterator to the position where the element could be inserted (i.e., the position where the element would be if it existed)

Time complexity O(log(last-first))

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

int main(){
    int a[10]={1,2,2,3,3,3,5,5,5,5};
    int* lowerPos;
    int* upperPos;
    //寻找 3
    lowerPos=lower_bound(a,a+10,3);
    upperPos=upper_bound(a,a+10,3);
    printf("%d %d",lowerPos-a,upperPos-a); //输出 3 6
    return 0;
}

As you can see, if you only want to obtain the index of the element you are looking for, you don't need to use a temporary pointer — you can simply subtract the address of the first element of the array from the return value

The Fourth Parameter of the Binary Search Functions: Comparison Function

When the compared object does not have a clear comparison type:

struct ore{
  int w,v;
  bool operator<(const ore&other)const{
    return w<other.w;
  } //一定要有重载运算符
};
Method One: Construct a Temporary Object
// 假设 Ore 已经按 w 升序排序了
    vector<ore> Ore = { {1, 10}, {3, 20}, {5, 30}, {7, 40}, {9, 50} };
    
    int mid = 6;
    // 构造一个临时的 ore 对象,w 为 mid,v 可以为任意值
    ore tmp{mid, 0};
    
    auto it = lower_bound(Ore.begin(), Ore.end(), tmp);
Method Two: Use a Custom Comparator Lambda
// 假设 Ore 已经按 w 升序排序了
    vector<ore> Ore = { {1, 10}, {3, 20}, {5, 30}, {7, 40}, {9, 50} };
    
    int mid = 6;
    auto it = lower_bound(Ore.begin(), Ore.end(), mid, [](const ore &o, int value) {
        return o.w < value;
    });

Here a lambda is passed as the comparator, where the lambda is defined as: given an ore o and an int value, it returns true if o.w < value.

In this way, lower_bound() will find the first element satisfying !(o.w < mid) (i.e., o.w >= mid).

6.9.8 accumulate()

This function can help you compute the accumulated sum of all elements in a range, and you can also specify an initial value and a custom operation.

#include <iostream>
#include <vector>
#include <numeric>  // 别忘了包含这个头文件
using namespace std;

int main() {
    vector<int> nums = {1, 2, 3, 4, 5};
    int sum = accumulate(nums.begin(), nums.end(), 0);

    cout << "累积和是:" << sum << endl; //15

    return 0;
}

In this example, we used accumulate to compute the sum of all elements in an integer vector nums. The third parameter 0 is the initial value of the accumulation, meaning the sum starts from 0. In the end, the variable sum holds the accumulated sum of all elements.

6.9.10 unique()

It helps us remove adjacent duplicate elements and returns the end position of the new range.

代码CPP · 18 行
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> nums = {1, 2, 2, 3, 4, 4, 5};
    auto it = unique(nums.begin(), nums.end());
    nums.erase(it, nums.end());

    cout << "去重后的元素是:";
    for(int num : nums) {
        cout << num << " ";
    }
    cout << endl;
	//去重后的元素是:1 2 3 4 5 
    return 0;
}

unique moves adjacent duplicate elements to the end of the vector and then returns a new iterator it. Next, we use erase to remove these duplicate elements, finally obtaining a vector without adjacent duplicate elements.

6.9.11 find()

The find function helps you find the first element equal to a specified value within a range, and returns an iterator pointing to that element. Here is how it is used:

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

int main() {
    vector<int> nums = {10, 20, 30, 40, 50};
    auto it = find(nums.begin(), nums.end(), 30);

    if(it != nums.end()) {
        cout << "找到目标元素:" << *it << endl;
    } else {
        cout << "未找到目标元素。" << endl;
    }

    return 0;
}

In this example, the find function finds the element 30 in the vector nums and returns an iterator pointing to it. If the target element cannot be found, find returns the end iterator.

6.9.12 count()

The count function helps you count how many times a specified value appears within a range.

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

int main() {
    vector<int> nums = {1, 2, 2, 3, 4, 2, 5};
    int count_of_2 = count(nums.begin(), nums.end(), 2);

    cout << "数字2出现的次数是:" << count_of_2 << endl;

    return 0;
}

In this example, the count function computes the number of times the number 2 appears in the vector nums and stores the result in the variable count_of_2.

6.9.13 partition()

The partition function divides the elements in a range into two parts according to a specified condition, so that the elements satisfying the condition are placed in the first half.

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

int main() {
    vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    partition(nums.begin(), nums.end(), [](int x){ return x % 2 == 0; });

    cout << "分区后的结果是:";
    for(int num : nums) {
        cout << num << " ";
    }
    cout << endl;
	//分区后的结果是:8 2 6 4 5 3 7 1 9 
    return 0;
}

Here, we use partition to place all the even numbers in the vector nums at the front and the odd numbers at the back. This partitioning operation uses a lambda expression to determine whether an element satisfies the condition.

6.9.14 nth_element()

nth_element() is an algorithm function in the C++ standard library, located in the <algorithm> header file. Its main purpose is to partially sort the elements in a container so that the n-th smallest element is placed at the n-th position of the container (counting from zero). In addition, the function guarantees that all elements before that position are not greater than that element, and all elements after it are not smaller than that element, but it does not sort the entire container.

Usage:

nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last);
  • first: the starting iterator of the container, pointing to the first element to be processed.
  • nth: an iterator pointing to the position of the desired "n"-th smallest element (i.e., the position where you want the n-th smallest element to be placed).
  • last: the ending iterator of the container.
代码CPP · 23 行
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    // 示例数据
    std::vector<int> vec = {1,2,3,9,4,5,8,6,10};

    // 求第 4 小的元素 (index 3),即在排序后的数组中的第 4 个位置
    std::nth_element(vec.begin(), vec.begin() + 3, vec.end());

    // 输出第 4 小的元素和数组
    std::cout << "The 4th smallest element: " << vec[3] << std::endl;

    // 输出部分排序后的数组
    std::cout << "Array after nth_element: ";
    for (int num : vec) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output:

The 4th smallest element: 4
Array after nth_element: 2 1 3 4 9 5 8 6 10

Note that nth_element does not perform a complete sort of the array.

6.9.15 is_sorted()

Checks whether the elements in a range are already sorted. By default, it returns true if the elements are in ascending or descending order, and false otherwise; of course, you can also pass in your own comparison function.

bool is_sorted(InputIterator first, InputIterator last, Compare comp);

6.9.16 merge()

Used to merge two already sorted ranges into a new sorted range.

std::vector<int> v1 = {1, 3, 5};
std::vector<int> v2 = {2, 4, 6};
std::vector<int> result(6);
    
std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), result.begin());

This is essentially this piece of code:

int merge(int a[],int b[], int c[], int n, int m){
    //n 和 m 分别是数组 a 和 b 的长度
    int i=0,j=0,index=0;
    while(i<n&&j<m){
        if(a[i]<=b[j]) c[index++]=a[i++]; //相等的情况放 a 和 b 都一样
        else c[index++]=b[j++]; //把 b[j]放入序列中
    }
    while(i<n) c[index++]=a[i++]; //把 a 的剩余元素放入 c 中
    while(j<m) c[index++]=b[j++]; //把 b 的剩余元素放入 c 中
    return index; //返回序列 c 的长度
}

6.10 Using unordered_set

Very similar to set, except that its elements are not ordered internally

引用Usage of Hash Sets A hash set (Hash Set) is an unordered collection, mai...

Usage of Hash Sets

A hash set (Hash Set) is an unordered collection, mainly used for fast lookup, insertion, and deletion operations. Its core characteristics are:

  • Elements are unique: the set cannot contain duplicate elements.
  • Operations have a time complexity of O(1)O(1) (on average).
  • In C++, hash sets are implemented by std::unordered_set.

Common Functions

The following are common operations of std::unordered_set:

1. Inserting Elements

unordered_set<int> s;
s.insert(10);  // 插入元素 10
s.insert(20);  // 插入元素 20

2. Finding Elements

if (s.find(10) != s.end()) {
    cout << "10 在集合中" << endl;
}

3. Deleting Elements

s.erase(10);  // 删除元素 10

4. Clearing the Set

s.clear();  // 清空集合

5. Getting the Size of the Set

cout << "集合大小:" << s.size() << endl;

6. Checking Whether the Set Is Empty

if (s.empty()) {
    cout << "集合为空" << endl;
}

7. Traversing the Set

Since unordered_set is unordered, the order during traversal may differ from the insertion order.

for (int x : s) {
    cout << x << " ";
}

8. Checking Whether an Element Exists

Use the count function, which returns 0 or 1.

if (s.count(10)) {
    cout << "10 在集合中" << endl;
}

Example Analysis

Example 1: Checking Whether an Array Contains Duplicate Elements

代码CPP · 32 行
#include <iostream>
#include <unordered_set>
using namespace std;

int main() {
    int n;
    cout << "请输入数组长度:";
    cin >> n;

    unordered_set<int> s;
    bool hasDuplicate = false;
    cout << "请输入数组元素:" << endl;
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;

        // 如果集合中已经有该元素,则有重复
        if (s.find(x) != s.end()) {
            hasDuplicate = true;
            break;
        }
        s.insert(x);  // 否则插入集合
    }

    if (hasDuplicate) {
        cout << "数组中有重复的元素!" << endl;
    } else {
        cout << "数组中没有重复的元素。" << endl;
    }

    return 0;
}

Sample Run:

Input 1:

Please enter the length of the array: 5
Please enter the array elements:
1 2 3 4 5

Output 1:

The array does not contain duplicate elements.

Input 2:

Please enter the length of the array: 5
Please enter the array elements:
1 2 3 2 5

Output 2:

The array contains duplicate elements!

Example 2: Counting the Number of Distinct Characters in a String

代码CPP · 18 行
#include <iostream>
#include <unordered_set>
using namespace std;

int main() {
    string str;
    cout << "请输入一个字符串:";
    cin >> str;

    unordered_set<char> s;  // 使用哈希集合存储字符
    for (char c : str) {
        s.insert(c);  // 每个字符插入集合
    }

    cout << "不重复字符的个数:" << s.size() << endl;

    return 0;
}

Sample Run:

Input:

Please enter a string: hello

Output:

Number of distinct characters: 4

Example 3: Quickly Finding a Target Pair

Given an array, determine whether there exist two numbers whose sum equals a target value.

代码CPP · 28 行
#include <iostream>
#include <unordered_set>
using namespace std;

bool hasPairWithSum(int arr[], int n, int target) {
    unordered_set<int> s;  // 哈希集合存储访问过的元素
    for (int i = 0; i < n; i++) {
        int complement = target - arr[i];
        if (s.find(complement) != s.end()) {
            return true;  // 找到和为目标值的两个数
        }
        s.insert(arr[i]);  // 否则插入集合
    }
    return false;
}

int main() {
    int arr[] = {1, 4, 6, 8, 10};
    int target = 14;

    if (hasPairWithSum(arr, 5, target)) {
        cout << "存在和为 " << target << " 的两个数!" << endl;
    } else {
        cout << "不存在和为 " << target << " 的两个数!" << endl;
    }

    return 0;
}

Sample Run:

Input array:

[1, 4, 6, 8, 10], target = 14

Output:

There exist two numbers whose sum is 14!

Summary

  • Advantages: unordered_set is well suited for lookups and deduplication, with highly efficient operations (average O(1)O(1)).
  • Disadvantages: due to its unordered nature, you cannot directly obtain an ordered result. If you need an ordered set, you can use std::set (implemented based on a red-black tree, with operations of complexity O(log⁡n)O(\log n)).

6.11 Using list

引用std::list is a container in the C++ Standard Template Library (STL) that...

std::list is a container in the C++ Standard Template Library (STL) that implements a doubly linked list. Unlike vectors (std::vector), std::list is very useful in the following scenarios:

  • Efficient insertion and deletion: In a linked list, you can perform insertion and deletion operations at any position with constant time complexity (O(1)), without the potentially large amount of data shifting that std::vector may involve.
  • No random access support: Since the underlying structure is a linked list, std::list does not support subscript access (e.g., list[i]); you can only traverse it sequentially via iterators.

Below are some commonly used std::list operations, along with example code:


1. Creation and Initialization

代码CPP · 19 行
#include <iostream>
#include <list>
using namespace std;

int main() {
    // 创建一个空的 list,元素类型为 int
    list<int> myList;

    // 使用初始化列表创建 list
    list<int> numbers = {10, 20, 30, 40};

    // 输出 numbers 中的元素
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

2. Inserting Elements

  • Insert at the end: use push_back()
  • Insert at the beginning: use push_front()
  • Insert at any position: use insert(). The insert(it, val) member function is used to insert an element into the list. it is an iterator of the list, and val is the value to be inserted. After insertion, val is located at the position immediately before the one pointed to by it. The return value is an iterator indicating the position where val was inserted.
代码CPP · 26 行
#include <iostream>
#include <list>
using namespace std;

int main() {
    list<int> myList;

    // 在末尾插入元素
    myList.push_back(10);
    myList.push_back(20);

    // 在开头插入元素
    myList.push_front(5);

    // 通过迭代器在第二个位置插入元素 15
    auto it = myList.begin();
    ++it; // 指向原来的第一个元素后面的位置
    myList.insert(it, 15);

    // 输出 list 中的元素
    for (int num : myList) {
        cout << num << " ";
    }
    cout << endl;
    return 0;
}

3. Deleting Elements

  • Delete the first element: use pop_front()
  • Delete the last element: use pop_back()
  • Delete an element at a specified position: use erase(), passing in the corresponding iterator
  • The remove(it) member function is used to delete the node pointed to by a given iterator. Note that after deletion, it becomes invalid; unless you reassign it, any operation on it will cause an error!
  • Clear all elements: use clear()
代码CPP · 22 行
#include <iostream>
#include <list>
using namespace std;

int main() {
    list<int> myList = {5, 10, 15, 20};

    // 删除第一个元素
    myList.pop_front();

    // 删除最后一个元素
    myList.pop_back();

    // 删除中间的元素(例如,删除当前 list 中的第一个元素)
    auto it = myList.begin();
    myList.erase(it);

    // 此时 list 为空,或者可以再次添加元素
    myList.clear(); // 清空所有元素

    return 0;
}

4. Traversal and Access

Since std::list does not support random access (you cannot access elements by subscript), you must use iterators or a range-based for loop to traverse it:

代码CPP · 21 行
#include <iostream>
#include <list>
using namespace std;

int main() {
    list<int> myList = {10, 20, 30, 40};

    // 使用范围 for 循环遍历
    for (int num : myList) {
        cout << num << " ";
    }
    cout << endl;

    // 使用迭代器遍历
    for (auto it = myList.begin(); it != myList.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;

    return 0;
}

5. Common Algorithm Member Functions

  • sort(): sorts the list
  • reverse(): reverses the elements in the list
  • unique(): removes consecutive duplicate elements
  • merge(): merges two sorted std::lists
代码CPP · 39 行
#include <iostream>
#include <list>
using namespace std;

int main() {
    list<int> myList = {30, 10, 20, 20, 40};

    // 排序
    myList.sort();  // 排序后:10, 20, 20, 30, 40

    // 移除连续重复的元素
    myList.unique(); // 结果:10, 20, 30, 40

    // 反转链表
    myList.reverse(); // 结果:40, 30, 20, 10

    // 输出结果
    for (int num : myList) {
        cout << num << " ";
    }
    cout << endl;

    // 合并两个已排序的 list
    list<int> list1 = {1, 3, 5};
    list<int> list2 = {2, 4, 6};

    // 确保两个 list 都已经排序
    list1.sort();
    list2.sort();
    list1.merge(list2);  // list1 合并了 list2,且 list2 变为空

    // 输出合并后的 list1
    for (int num : list1) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

6. Notes

  • Iterator invalidation: When performing insertion or deletion operations on a std::list, other iterators generally do not become invalid (unlike std::vector), but the iterator corresponding to a deleted element becomes invalid.
  • Memory usage: Since each node of a linked list requires extra pointers to store information about the preceding and following nodes, memory usage may be slightly higher than for containers with contiguous storage (such as std::vector).
  • No random access support: If you need frequent random access (for example, directly accessing the n-th element), it is recommended to use std::vector or std::deque.

In summary, std::list provides the ability to quickly insert and delete at any position, making it suitable for scenarios where data is frequently modified. However, when random access and high space efficiency are needed

, you should consider other containers.

6.12 Using multiset

Definition of multiset

multiset is a set container that can store multiple identical elements. In other words, if you have a bunch of duplicate numbers, such as 3, 5, 5, 5, 7, you can use a multiset to manage them properly. Unlike set, which does not allow duplicate elements, multiset warmly welcomes the addition of duplicate elements.

You can create one using uniformly initialized elements

int main() {
    multiset<int> numbers = {3, 5, 5, 7, 3, 9};

    // 基于范围的 for 循环遍历 multiset
    for (int num : numbers) {
        cout << num << " ";
    }

    return 0;
}

Note that a multiset automatically arranges its elements in ascending order.

For custom types, you need to overload the less-than operator

Accessing Elements in a multiset

Use iterators

Analysis of Common multiset Functions

insert()

Omitted

erase()

The erase method is used to delete elements. But be careful! If you pass in a value directly, all elements equal to that value will be deleted. If you only want to delete a specific element, it is best to first find its iterator and then use that iterator to delete it.

int main() {
    multiset<int> numbers = {3, 5, 5, 7};

    // 删除所有的 5
    numbers.erase(5);

    // 打印当前的 multiset
    for (int num : numbers) {
        cout << num << " ";
    }

    return 0;
}

If you only want to delete the first 5

auto it = numbers.find(5);  // 找到第一个 5
if (it != numbers.end()) {
    numbers.erase(it);  // 只删除找到的第一个 5
}

size()

Omitted

clear()

Omitted

empty()

Omitted

lower_bound()

Omitted different from the one in algorithm

upper_bound()

Omitted different from the one in algorithm

Chapter 7 Advanced Topics (1) — Data Structures (Part 1)

7.1 Applications of Stacks

A stack is a last-in-first-out (LIFO) data structure.

You can think of a stack as a box whose length and width are just enough for one book to be put in or taken out. Each time, you can place a book on the very top of the box, or take out the book on the very top of the box.

The top pointer: a marker that always points to the topmost element of the stack. When the stack is implemented with an array, the top pointer is an int variable (array indices start from 0), usually denoted as TOP; when the stack is implemented with a linked list, it is an int* pointer. When the stack contains no elements (i.e., the stack is empty), TOP is set to -1.

Below, an array st[] is used to implement the stack, and the int variable TOP represents the index of the top element. Several commonly used operations are demonstrated:

Clearing (clear)

The clear operation sets TOP = -1, indicating that the stack contains no elements.

void clear(){
	TOP=-1;
}

Getting the number of elements in the stack (size)

Since array indices start from 0, the number of elements is TOP+1.

int size(){
    return TOP+1;
}

Checking emptiness (empty)

bool empty(){
    if(TOP==-1) return true;
    else return false;
}

Push (push)

void push(int x){
	st[++TOP]=x; //先把 TOP+1,再把 x 存入 TOP 指向的位置
}

Pop (pop)

void pop(){
	TOP--;
}

Getting the top element (top)

int top(){
	return st[TOP];
}

It is important to note that the pop and top operations can only be used when the stack is non-empty, so you must use the empty() function to check before performing them.

In fact, using the STL stack container is simpler.

Note that the STL does not provide a built-in function for clearing a stack; you can do it like this:

while(!st.empty()){
	st.pop();
}

However, a more common approach is to define a new stack, which effectively achieves clearing the stack.

Now let's look at a problem:

引用【codeup 1918】Simple Calculator Read in a non-negative integer arithmetic...

【codeup 1918】Simple Calculator

Read in a non-negative integer arithmetic expression containing only + - x /, and compute the value of the expression.

Input format:

A string of length no more than 100, in which the operators and operands consist only of +, −, ∗, /, and integers (no less than 1 and no greater than 9), with operators and operands separated by spaces. The data guarantees that the expression is always valid, and all results in the computation process will not exceed 10^9.

Output format:

Output one line, the value of the expression, accurate to two decimal places.

Sample input

3 + 4 * 5

Output

23.00

引用1. Infix Expression The infix expression is the most common form of math...

1. Infix Expression

The infix expression is the most common form of mathematical expression in our daily lives. Its characteristic is that the operator is located between two operands. For example:

  • 3 + 4
  • (5 - 2) * 6
  • 2 + 3 * 4

Characteristics

  • Operators are located between operands.
  • Parentheses are needed to clarify the order of operations.
  • Easy for humans to understand and write, but relatively complex for computers to process.

Example

  • The infix expression 2 + 3 * 4 must be evaluated according to operator precedence: first compute 3 * 4, then compute 2 + 12, giving the result 14.

2. Postfix Expression (also known as Reverse Polish Notation)

A postfix expression is a form of expression that does not require parentheses; its characteristic is that the operator is located after the operands. For example:

  • 3 4 +
  • 5 2 - 6 *
  • 2 3 4 * +

Characteristics

  • Operators are located after the operands.
  • No parentheses are needed; the order of operations is determined entirely by the positions of the operators.
  • Very convenient for computers to process, and suitable for evaluation using a stack.

Example

  • The evaluation process of the postfix expression 2 3 4 * +:
    1. Encounter 3 4 *, compute 3 * 4 = 12.
    2. The expression becomes 2 12 +.
    3. Compute 2 + 12 = 14, giving the result 14.

3. Converting an Infix Expression to a Postfix Expression

Converting an infix expression to a postfix expression is a common task in computer science, usually implemented using a stack. Here are the conversion steps:

Conversion Rules

  1. Initialize an empty stack and an empty output list.
  2. Scan the infix expression from left to right.
  3. If an operand is encountered, add it directly to the output list.
  4. If a left parenthesis ( is encountered, push it onto the stack.
  5. If a right parenthesis ) is encountered, pop the operators from the stack and add them to the output list until a left parenthesis ( is encountered. The left parenthesis is popped but not added to the output list.
  6. If an operator is encountered:
    • Pop all operators on the stack whose precedence is higher than or equal to the current operator, and add them to the output list.
    • Push the current operator onto the stack.
  7. After scanning is finished, pop the remaining operators from the stack one by one and add them to the output list.

Example

Converting the infix expression 2 + 3 * 4 to a postfix expression:

  1. Output list: 2
  2. Stack: +
  3. Output list: 2 3
  4. Stack: + *
  5. Output list: 2 3 4
  6. Stack: + * (scanning finished; pop all operators from the stack)
  7. Output list: 2 3 4 * +

7.2 Applications of Queues

A queue is a first-in-first-out (FIFO) data structure, which is different from a stack.

An example to understand it: queuing for food in the cafeteria — those who enter the line first get their food first and leave the queue, i.e., first in, first out.

Generally, a front pointer is needed to point to the position before the front element of the queue, and a rear pointer is used to point to the rear element of the queue.

Similar to a stack, when a queue is implemented with an array, the front and rear pointers are int variables (indices start from 0); when implemented with a linked list, they are int* pointers.

Below, an array q[] is used to implement the queue, where the int variable front stores the index before the front element, and rear stores the index of the rear element (indices start from 0). Common operations are demonstrated below:

Clearing (clear)

The initial state is front=-1, rear=-1.

void clear(){
    front=rear=-1;
}

Getting the number of elements in the queue (size)

in size(){
    return rear-front;
}

Checking emptiness (empty)

bool empty(){
    if(front==rear) return true;
    else return false;
}

Enqueue (push)

Since rear points to the rear element of the queue, when an element is enqueued, rear must first be incremented by 1, and then the element is stored at the position rear points to.

void push(){
    q[++rear]=x;
}

Dequeue (pop)

This can be implemented by incrementing the front pointer by 1.

void pop(){
	front++;
}

Getting the front element (get_front)

Since front points to the position before the front element, front+1 is the position of the front element.

int get_front(){
    return q[front+1];
}

Getting the rear element (get_rear)

int get_rear(){
	return q[rear];
}

Similar to a stack, these operations can only be used when the queue is non-empty, so you must check first.

Also, it is better to use the STL more often.

7.3 Linked List Processing

7.3.1 The Concept of Linked Lists

Linear list: a commonly used data structure.

  • Sequential list: can be simply understood as an "array"
  • Linked list

When an array is defined in the normal way, the computer takes a contiguous block of memory addresses to store the array of the given length; whereas a linked list consists of several nodes (each node represents an element), and the storage locations of the nodes in memory are usually not contiguous. In addition, two nodes of a linked list are generally connected by a pointer pointing from one node to another, so a linked list node generally consists of two parts: the data field and the pointer field:

struct node {
    typename data; //数据域
    node* next; //指针域
}

Generally, the data field stores the data to be stored, and the pointer field points to the address of the next node. This produces a chain structure linked by pointers starting from a certain node, i.e., a linked list.

It can be divided into two categories:

  • Linked lists with a head node
  • Linked lists without a head node

The head node is generally called head; its data field data does not store any content, while its pointer field next points to the first node whose data field has content (this node is generally directly called the first node). Here we uniformly adopt the style with a head node. The next pointer of the last node points to NULL, indicating the end of the linked list.

7.3.2 Using the malloc Function or the new Operator to Allocate Memory Space for Linked List Nodes

The malloc Function

A function in C under the stdlib.h header file used for dynamic memory allocation; its return type is a pointer of the same variable type as requested.

typename* p=(typename*)malloc(sizeof(typename));

Taking the allocation of an int variable and a node struct variable as an example:

int *p=(int*)malloc(sizeof(int));
node* p=(node*)malloc(sizeof(node));

The logic of this code is: the size of the memory space to be allocated (i.e., sizeof(node)) is passed as the parameter to the malloc function, at which point the malloc function requests a block of memory of size sizeof(node) and returns a pointer to that block. However, at this point the pointer's type is undetermined (void*), so it needs to be cast to node*. In this way, the right-hand side of the equals sign yields a node* pointer, which is then assigned via the assignment operator to the node* pointer variable p. This successfully allocates a block of memory the size of a node type, i.e., a node struct variable, which is accessed through the pointer p.

The new Operator

new is an operator in C++ used to request dynamic memory; its return type is the same as that of the malloc function. Its basic usage is as follows:

tyoename* p=new typename;

Likewise, taking the allocation of an int variable and a node variable as an example:

int *p=new int;
node* p=new node;

Memory Leaks

This refers to memory space allocated by malloc and new not being released after use, causing it to occupy that memory space until the program ends. Therefore, after using memory allocated by malloc and new, it must be released.

The free Function

The free function corresponds to the malloc function and is likewise under stdlib.h.

//在 free 的参数中填写需要释放的内存空间的指针变量即可
free(p);

The effects of the free function:

  1. Release the memory space pointed to by the pointer variable p.
  2. Set the pointer variable p to point to the null address NULL.

Note that malloc and free must appear in pairs, otherwise it is easy to crash.

The delete Operator

Corresponds to the new operator; its usage and effect are the same as free.

delete(p);

The delete and new operators must appear in pairs.

7.3.3 Basic Operations on Linked Lists

Creating a Linked List

Now we can use malloc and new to obtain several scattered nodes; we only need to string them together, which just requires making each node's next pointer point to the address of the next node.

1. The Role of the -> Operator

The -> operator is used to access members of an object through a pointer. Its effect is equivalent to:

  1. Dereferencing the pointer (*ptr).
  2. Accessing the member of the object ((*ptr).member).

In other words, ptr->member is equivalent to (*ptr).member.


2. Usage Scenarios

The -> operator is typically used in the following scenarios:

  1. Accessing members of dynamically allocated objects:
    • When an object is dynamically allocated via new, what is returned is a pointer, in which case -> must be used to access members.
  2. Accessing members through pointers to structs or classes:
    • When an instance of a struct or class is referenced through a pointer, use -> to access its members.
  3. Accessing members of smart pointers:
    • For smart pointers (such as std::unique_ptr or std::shared_ptr), use -> to access members.
代码CPP · 38 行
#include<bits/stdc++.h>
using namespace std;

struct node {
    int data;
    node* next;
};

node *create(int a[],int len){
    node *p,*pre,*head; //当前结点 前驱结点 头结点
    head=new node; //创建头结点
    head->next=NULL; //初始化,让头结点指向 NULL
    //pre=new node; //创建前驱结点
    //上面一行不需要,因为前驱结点(pre)一开始就应该指向头结点,并不需要为 pre 创建一个新的结点,因为 pre 只需要作为指向头结点的指针
    pre=head; //最开始前驱结点就是头结点
    for(int i=0;i<len;++i){
        p=new node; //创建结点 即前驱结点的后继结点
        p->data=a[i]; //读入结点数据域 也可以 scanf
        p->next=NULL; //先初始化
        pre->next=p; //前驱结点的指针域(指向前驱结点的后继结点)设为当前新建结点的地址,把前后两个结点连接起来
        //必须要理解这里的 pre 和 p 都是指针,本质是地址
        //所以比如 i=0 的情况下,原本是 head->NULL 的,现在是 head->1 了,因为修改了 pre 就等同于修改了 head,因为 pre 和 head 的地址相同
        pre=p; //把 pre 作为 p,作为下一个结点的前驱结点
        //其实是把 pre 的地址换个地方,现在 pre 的地址是上面那一通操作生成的 p 的地址
    }
    return head; //返回头结点指针
}

int main(){
    int a[5]={1,2,3,4,5};
    node* L=create(a,5);
    L=L->next; //从第一个结点开始有数据域
    while(L!=NULL){
        printf("%d",L->data);
        L=L->next;
    } //输出 1 2 3 4 5
    return 0;
}
引用Lines 17 and 18: Passing Pointers pre->next = p; // 将前驱节点的指针域(next)指向新节点...

Lines 17 and 18: Passing Pointers

pre->next = p;  // 将前驱节点的指针域(next)指向新节点 p
pre = p;         // 将 pre 指向当前节点 p,作为下一个节点的前驱

The purpose of these two lines of code is to update the linking relationships between the nodes in the linked list. Let's explain them one by one:

  • pre->next = p;

    :

    • This line of code makes the next pointer of the previous node (i.e., the node pointed to by pre) point to the newly created node p.
    • For example, suppose the linked list currently has nodes A and B, with pre pointing to node A and p pointing to the newly created node B. What you need to do is make A->next point to B, that is, connect the linked list from A to B.
  • pre = p;

    :

    • The purpose of this line of code is to update what the predecessor node pre points to.
    • It updates pre to the current node p, that is, makes pre point to B.
    • In the next iteration of the loop, pre will be B, at which point it will act as the previous node in the update of the next pointer.

In other words, pre->next = p; is responsible for establishing the linking relationship for the new node, while pre = p; updates pre to the current node p, preparing for the creation of a new node in the next round.

Searching for Elements

Starting from the first node, repeatedly check whether the data field of the current node equals x; if it does, increment cnt. In this way, at the end, the value of cnt is the number of occurrences of element x in the list.

int search(node *head,int x){
    int cnt=0;
    node *p=head->next; //从第一个节点开始
    while(p!=NULL){
        if(p->data==x) cnt++;
        p=p->next;
    }
    return cnt;
}

Inserting Elements

"Insert element 4 at position 3" means that after the insertion is complete, the element at position 3 is 4, which means making room for the element originally at the third position (inserting between positions 2 and 3).

Suppose the original list is 6 7 8 9 10.

After inserting 4 at the third position, 7 points to 4, and 4 points to 8; implement the code following this idea.

//将 x 插入以 head 为头结点的链表的第 pos 个位置上
void insert(node *head,int pos,int x){
    node* p=head;
    for(int i=0;i<pos-1;i++){
        p=p->next; //pos-1 是为了插入位置的前一个结点,这里相当于移动 p 的指针
    }
    node *q=new node;
    q->data=x; //这个时候 q 还是野指针
    q->next=p->next;
    p->next=q;
}

This code can be written directly into the code in the "Creating a Linked List" section for use; simply pass the head pointer L returned by the create function as the first argument.

The order must be: first point the new node's pointer field next to its successor node, and only then point the pointer of the node containing the previous element to the address of the new node.

Deleting Elements

For a linked list, deleting elements means deleting all nodes in the list whose value equals a given number x. The operation proceeds as follows:

  1. Use the pointer variable p to enumerate the nodes, with the pointer variable pre serving the predecessor of the node pointed to by p.
  2. When the data field of the node pointed to by p is exactly x, perform the following three operations:
    1. Make the pointer field of the node pointed to by pre point to the successor of the node pointed to by p.
    2. Free the memory space of the node pointed to by p.
    3. Make p point to the successor of the node pointed to by pre.

The code implementation is as follows:

//删除以 head 为头结点的链表中所有数据域为 x 的结点
void del(node* head,int x){
    node *p=head->next; //p 从第一个结点开始枚举
    node *pre=head; //pre 始终保存 p 的前驱结点的指针
    while(p!=NULL){
        if(p->data==x){ //数据域恰好为 x,说明要删除该结点
            pre->next=p->next;
            delete(p);
            p=pre->next;
        }
        else{ //数据域不是 x,把 pre 和 p 都往后移一位
            pre=p;
            p=p->next;
        }
    }
}

This code can be written directly into the code in the "Creating a Linked List" section for use; simply pass the head pointer L returned by the create function as the first argument.

Finally, let's summarize these templates:

代码CPP · 59 行
#include<bits/stdc++.h>
using namespace std;
struct node {
    int data;
    node* next;
};

node *create(int a[],int len){
    node *p,*pre,*head;
    head=new node;
    head->next=NULL;
    pre=head;
    for(int i=0;i<len;i++){
        p=new node;
        p->next=NULL;
        p->data-a[i];
        pre->next=p;
        pre=p;
    }
    return head;
}
int search(node *head,int x){
    int cnt=0;
    node *p=head->next; //从第一个节点开始
    while(p!=NULL){
        if(p->data==x) cnt++;
        p=p->next;
    }
    return cnt;
}

//将 x 插入以 head 为头结点的链表的第 pos 个位置上
void insert(node *head,int pos,int x){
    node* p=head;
    for(int i=0;i<pos-1;i++){
        p=p->next; //pos-1 是为了插入位置的前一个结点,这里相当于移动 p 的指针
    }
    node *q=new node;
    q->data=x; //这个时候 q 还是野指针
    q->next=p->next;
    p->next=q;
}

//删除以 head 为头结点的链表中所有数据域为 x 的结点
void del(node* head,int x){
    node *p=head->next; //p 从第一个结点开始枚举
    node *pre=head; //pre 始终保存 p 的前驱结点的指针
    while(p!=NULL){
        if(p->data==x){ //数据域恰好为 x,说明要删除该结点
            pre->next=p->next;
            delete(p);
            p=pre->next;
        }
        else{ //数据域不是 x,把 pre 和 p 都往后移一位
            pre=p;
            p=p->next;
        }
    }
}

7.3.4 Static Linked Lists

For some problems, the addresses of nodes are relatively small integers, so there is no need to build a dynamic linked list; a simple static linked list should be used instead.

The implementation principle is hashing: by creating an array of structs and letting the array index directly represent the address of a node, accessing an element in the array directly accesses the node. Since access is very convenient, no head node is needed.

struct Node{
    typename data; //数据域
    int next; //指针域
}node[size]; //注意数组名和结构体名不要相同

next=-1 means there is no successor node

【PAT A1032】 Sharing

Given the starting addresses of two linked lists and the addresses, data, and next addresses of several nodes, find the address of the first shared node of the two linked lists. If the two lists have no shared node, output -1.

Note: Using map can easily cause Time Limit Exceeded.

代码CPP · 34 行
#include<bits/stdc++.h>
using namespace std;

const int maxn=100010;
struct Node{
    char data;
    int next;
    bool flag; //数据是否在第一条链表里面出现
    Node(){
        flag=false;
        next=-1;
    }
}node[maxn];

int main(){
    int s1,s2,n; //s1 s2 分别表示两条链表的首地址
    scanf("%d%d%d",&s1,&s2,&n);
    char data;
    int address,next;
    for(int i=0;i<n;i++){
        scanf("%d %c %d",&address,&data,&next);
        node[address].data=data;
        node[address].next=next;
    }
    int p;
    for(int p=s1;p!=-1;p=node[p].next){
        node[p].flag=true;
    }
    for(int p=s2;p!=-1;p=node[p].next){
        if(node[p].flag) break;
    }
    if(p!=-1) printf("%05d",p);
    else printf("-1");
}

This is a relatively simple problem that a static linked list can solve. For slightly more complicated problems, here is a general approach:

  1. Define the static linked list

    struct Node{
        typename data; //数据域
        int next; //指针域
        XXX; //结点的某个性质,不同的题目会有不同的设置
    }node[100010];

    For example, you can set whether a node is a node on the linked list.

  2. At the beginning of the program, initialize the static linked list. Generally, you need to initialize the XXX defined in the struct to a value that cannot be reached under normal circumstances (generally it should be smaller than all reachable values).

  3. The problem will generally give the address of the first node of a linked list, so we can traverse to obtain the entire linked list based on this address. At the same time, note that this step is also when you mark the property XXX and count the number of valid nodes.

  4. Since a static linked list uses hashing, the array indices will not be contiguous, and in many cases the nodes given by the problem are not all valid nodes (i.e., there may be nodes not on the linked list). To access the valid nodes in a controllable way, you generally need to sort the array, moving the valid nodes to the left end of the array, so that you can access them using the cnt obtained in step 3.

    Since the valid nodes need to be moved to the front, you can use the XXX defined earlier to help. In step 2, XXX needs to be initialized to a value smaller than the XXX of normal nodes, and since the XXX of invalid nodes is not modified in step 3, it will definitely be smaller than the XXX of valid nodes. Therefore, you can use a specific cmp function so that when either of the two node parameters of cmp is an invalid node, they are sorted in descending order by XXX, which moves all valid nodes to the left end of the array.

    bool cmp(Node a,Node b){
    	if(a.XXX==-1||b.XXX==-1){ //至少一个结点是无效结点 把它放在数组后面
            	return a.XXX>b.XXX;
        }
        else{
            //第二级排序
        }
    }
  5. After step 4, all valid nodes are located at the left end of the array and have been sorted in node order; what to do next depends on the problem.

【PAT A1052】 Linked List Sorting

Given the addresses address, data fields data, and pointer fields next of N nodes, and then the starting address of the linked list, output the nodes on this linked list in descending order of their data values. (The input format is the same as the output format.)

代码CPP · 40 行
//给出 N 个结点的地址 address、数据域 data 以及指针域 next,然后给出链表的首地址,要求把这个链表上的结点按 data 值从大到小输出。(输入格式与输出格式相同)
#include<bits/stdc++.h>
using namespace std;
const int maxn=100010;
struct Node{
    int address;
    int data;
    int next=-1;
    bool flag=false;
}node[maxn];
bool cmp(Node a,Node b){
    if(!a.flag||!b.flag) return a.flag>b.flag;
    else return a.data<b.data;
}
int main(){
    int headAddress,n;
    scanf("%d%d",&n,&headAddress);
    int address,data,next;
    for(int i=0;i<n;i++){
        scanf("%d%d%d",&address,&data,&next);
        node[address].address=address;
        node[address].data=data;
        node[address].next=next;
    }
    int p,cnt=0;
    for(int p=headAddress;p!=-1;p=node[p].next){
        node[p].flag=true;
        cnt++;
    }
    if(!cnt) printf("0 -1");
    else{
        sort(node,node+maxn,cmp);
        printf("%d %05d\n",cnt,node[0].address);
        for(int i=0;i<cnt;i++){
            if(i!=cnt-1) printf("%05d %d %05d\n",node[i].address,node[i].data,node[i+1].address);
            //这里一定要注意第三项不要写成 node[i].next,因为 sort 完了,我们要打印的顺序并不是按照链表链接的顺序
            else printf("%05d %d -1",node[i].address,node[i].data);
        }
    }
}

Chapter 8 Advanced Topics (2) — Search

8.1 Depth-First Search (DFS)

A search method that enumerates all complete paths to traverse all possible cases.

DFS can be implemented with a stack, but recursion is simpler.

Think of the recursive step as a fork in the road, and the recursive boundary as a dead end.

There are n items, where the weight of each item is w[i] and its value is c[i]. Now you need to select several items to put into a knapsack with capacity V, such that under the premise that the total weight of the selected items does not exceed V, the total value of the items in the knapsack is maximized. Find the maximum value (1<=n<=20).

Analysis:

Dead end: the total weight of the items exceeds V.

Fork in the road: choosing a different item each time.

代码CPP · 34 行
#include<bits/stdc++.h>
using namespace std;

const int maxn=25;

int n,v,maxValue,w[maxn],c[maxn];

void dfs(int idx,int sumW,int sumC){
    //死胡同
    if(idx==n){ //已经完成对 n 件物品的选择
        if(sumW<=v&&sumC>maxValue){
            maxValue=sumC;
        }
        return;
    }
    //岔路口
    dfs(idx+1,sumW,sumC); //不选第 idx 件物品
    //如果不选第 idx 件物品无法做到最大的话
    dfs(idx+1,sumW+w[idx],sumC+c[idx]); //选第 idx 件物品(0 起计)
    //因为数组下标 0 起计,w[idx] 其实就是已经选了 idx+1 件
}

int main(){
    cin>>n>>v;
    for(int i=0;i<n;i++){
        cin>>w[i];
    }
    for(int i=0;i<n;i++){
        cin>>c[i];
    }
    dfs(0,0,0); //初始时第 0 件物品,总重量和总价值均为 0
    cout<<maxValue;
    return 0;
}

Since each item has two choices, the time complexity is O($2^n$), but it can be slightly optimized to make it more efficient.

In the code above, the maximum value is only updated after the choices for all n items have been determined, but in fact this ignores the property that the knapsack capacity must not exceed V. In other words, the check on sumW can be moved into the "fork in the road": only enter the fork when sumW<=V. The modification is as follows:

void dfs(int idx,int sumW,int sumC){
    if(idx==n) return; //已经完成了对 n 件物品的选择
    //岔道口
    dfs(idx+1,sumW,sumC); //不选第 idx 件物品
    //只有加入第 idx 件物品后未超过容量 v 才能继续
    if(sumW+w[idx]<=v){
        if(sumC+c[idx]>maxValue) maxValue=sumC+c[idx];
    }
    dfs(idx+1,sumW+w[idx],sumC+c[idx]); //选第 idx 件物品
}

This optimizes the time complexity.

This method of saving DFS computation by using the constraints of the problem is called pruning.

In fact, the following gives a solution to a class of DFS problems: given a sequence, enumerate all subsequences (not necessarily contiguous) of this sequence.

Given n integers (possibly negative), choose exactly k of them such that the sum of these k numbers equals a given number x; if there are multiple solutions, choose the one with the largest sum of squares.

void dfs(int idx,int nowK,int sum,int sumSqu){
    if(nowK==k&&sum==x){
        if(sumSqu>maxSumSqu){
            maxSumSqu=sumSqu;
            ans=temp;
        }
        return;
    }
    //已经处理完n个数,或者超过k个数,或者和超过x,返回
    if(idx==n||nowK>k||sum>x) return;
    //选idx号数
    temp.push_back(a[idx]);
    dfs(idx+1,nowK+1,sum+a[idx],sumSqu+a[idx]*a[idx]);
    temp.pop_back();
    //不选
    dfs(idx+1,nowK,sum,sumSqu);
}

Some Pruning Techniques for DFS

First, here is a DFS template:

int ans = 最坏情况, now;  // now 为当前答案
这个模板要求在调用dfs之前先将起点标记,防止回溯出现环路。
void dfs(传入数值) {
  if (到达目的地) ans = 从当前解与已有解中选最优;
  for (遍历所有可能性)
    if (可行) {
      进行操作;
      dfs(缩小规模);
      撤回操作;
    }
}

Here ans can be a record of the solution, so choosing the best between the current solution and the existing solution becomes outputting the solution.

代码CPP · 19 行
int g[MAXN];  // 定义记忆化数组
int ans = 最坏情况, now;

void dfs f(传入数值) {
  if (g[规模] != 无效数值) return;  // 或记录解,视情况而定
  if (到达目的地) ans = 从当前解与已有解中选最优;  // 输出解,视情况而定
  for (遍历所有可能性)
    if (可行) {
      进行操作;
      dfs(缩小规模);
      撤回操作;
    }
}

int main() {
  // ...
  memset(g, 无效数值, sizeof(g));  // 初始化记忆化数组
  // ...
}

Optimality Pruning

int ans = 最坏情况, now;

void dfs(传入数值) {
  if (now比ans的答案还要差) return;
  if (到达目的地) ans = 从当前解与已有解中选最优;
  for (遍历所有可能性)
    if (可行) {
      进行操作;
      dfs(缩小规模);
      撤回操作;
    }
}

Feasibility Pruning

int ans = 最坏情况, now;

void dfs(传入数值) {
  if (当前解已不可用) return;
  if (到达目的地) ans = 从当前解与已有解中选最优;
  for (遍历所有可能性)
    if (可行) {
      进行操作;
      dfs(缩小规模);
      撤回操作;
    }
}

8.2 Breadth-First Search (BFS)

Breadth is the first keyword. When reaching a fork, always first visit all the nodes that can be directly reached from that fork, and then, in the order in which those nodes were visited, visit all the nodes that each of them can directly reach.

The algorithm relies on a queue for implementation.

void BFS(int s){ //s 为起点
    queue<int> q;
    q.push(s);
    while(!q.empty()){
        取出队首元素top;
        访问队首元素top; //访问可以是任何事情,例如输出
        将队首元素出队; 
        将top的下一层结点中未曾入队的结点全部入队,并设置为已入队;
        //并标记它们的层号为 now++,同时设置这些结点已入队
    }
}

Example problem

Given an m*n matrix whose elements are 0 or 1. A position (x,y) is said to be adjacent to the four positions above, below, left, and right of it. If there are several (one counts as several) 1s in the matrix that are adjacent (they do not need to be pairwise adjacent), then these 1s are said to form a "block". Find the number of blocks in the given matrix.

Using the idea of BFS: enumerate the element at each position; if it is 0, skip it; if it is 1, use BFS to check the 4 elements adjacent to that position (provided they are not out of bounds), and determine whether they are 1; if a checked element is 1, continue checking until the entire block of 1s has been visited. To avoid backtracking, you can define a bool array inq (short for "in queue") to record whether each position has already been enqueued during the BFS.

For the current position (x,y), you can set up two increment arrays to access the 4 adjacent positions.

int X[]={0,0,1,-1};
int Y[]={1,-1,0,0};

These correspond to (x,y+1) (x,y-1) (x+1,y) (x-1,y) respectively.

This way, you can use a for loop to enumerate the 4 directions to determine the 4 positions adjacent to the current coordinates (nowX,nowY)

for(int i=0;i<4;i++){
    newX=nowX+X[i];
    newY=nowY+Y[i];
}

The BFS code implementation for this problem is as follows

代码CPP · 53 行
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=105;
struct node{
    int x,y; //存放位置
}Node;
int n,m; //矩阵大小
int matrix[maxn][maxn]; //01 矩阵
bool inq[maxn][maxn]; //记录是否入过队
int X[4]={0,0,1,-1},Y[4]={1,-1,0,0}; //坐标增量数组
bool judge(int x,int y){
    if(x>m||x<1||y>n||y<1||inq[x][y]||matrix[x][y]==0) return false;
    //只要出界||入过队||在该点不为 1,就不访问
    return true;
}
//访问位置 (x,y) 所在的块,设置一个块内的 1 的 inq 为 true
void bfs(int x,int y){
    queue<node> q;
    Node.x=x;Node.y=y;
    q.push(Node);
    while(!q.empty()){
        node top=q.front(); //取队首元素 top
        q.pop();
        for(int i=0;i<4;i++){ //得到相邻位置
            int newX=top.x+X[i],newY=top.y+Y[i];
            if(judge(newX,newY)){ //如果这个新位置是符合要求的,需要访问
                Node.x=newX;Node.y=newY;
                q.push(Node); //入队
                inq[newX][newY]=true; //已经入过队
            }
        }
    }
}
int main(){
    cin>>m>>n;
    for(int i=1;i<=m;i++){
        for(int j=1;j<=n;j++){
            cin>>matrix[i][j];
        }
    }
    int ans=0; //记录答案(块数
    for(int i=1;i<=m;i++){
        for(int j=1;j<=n;j++){
            if(matrix[i][j]==1&&!inq[i][j]){ //如果这个位置是 1 而且没有被访问过
                ans++; //块数++
                bfs(i,j);
            }
        }
    }
    cout<<ans;
}

Of course, DFS can also be used to implement it

代码CPP · 42 行
#include<iostream>
#include<algorithm>
using namespace std;
/*dfs 的思路:
从输入的点开始搜索,如果碰到 0 了就 return
否则走岔路口:往四个方向走*/
const int maxn=105;
int m,n,matrix[maxn][maxn];
int X[4]={0,0,1,-1},Y[4]={1,-1,0,0}; //坐标增量数组
bool visited[maxn][maxn];//记录是否查询过
bool judge(int x,int y){
    if(x<1||x>m||y<1||y>n||visited[x][y]||!matrix[x][y]) return false;
    //只要出界||入过队||在该点不为 1,就不访问
    return true;
}
//搜索一个块内,并标记为 true
void dfs(int x,int y){
    if(!judge(x,y)) return;
    visited[x][y]=true;
    for(int i=0;i<4;i++){
        int newX=x+X[i],newY=y+Y[i];
        dfs(newX,newY);
    }
}
int main(){
    cin>>n>>m;
    for(int i=1;i<=m;i++){
        for(int j=1;j<=n;j++){
            cin>>matrix[i][j];
        }
    }
    int ans=0; //记录答案(块数
    for(int i=1;i<=m;i++){
        for(int j=1;j<=n;j++){
            if(matrix[i][j]&&!visited[i][j]){ //如果这个位置是 1 而且没有被访问过
                dfs(i,j);
                ans++;
            }
        }
    }
    cout<<ans;
}

Next, let's look at another example problem

Given a maze of size n*m, where * represents walls that cannot be passed through, '.' represents open ground, S denotes the starting point, and T denotes the ending point. During movement, if the current position is (x,y) (with indices starting from 0), you can only move to open ground in the four positions above, below, left, and right each time. Find the minimum number of steps from the starting point S to the ending point T.

Since what is sought is the minimum number of steps, and BFS traverses level by level, you can start counting the levels of traversal from S; the level at which the ending point T is reached is the minimum number of steps from the starting point S to the ending point T.

代码CPP · 47 行
#include<bits/stdc++.h>
using namespace std;
const int maxn=105;
int n,m;
int X[4]={0,0,-1,1},Y[4]={1,-1,0,0}; //增量数组
char maze[maxn][maxn]; //迷宫
bool inq[maxn][maxn]={false}; //是否已入过队
struct node{
    int x,y;
    int step; //从起点 S 到该位置的最少步数(即层数)
}S,T,Node; ///起点、终点、临时结点
//判断这个路径是否可行
bool judge(int x,int y){
    if(x<0||x>=n||y<0||y>=m||maze[x][y]=='*'||inq[x][y]) return false;
    return true;
}
//找到一条最短的路径
int bfs(){
    queue<node> q;
    q.push(S);
    while(!q.empty()){
        node top=q.front();
        q.pop();
        if(top.x==T.x&&top.y==T.y) return top.step;
        for(int i=0;i<4;i++){
            int newX=top.x+X[i],newY=top.y+Y[i];
            if(judge(newX,newY)){
                Node.x=newX,Node.y=newY;
                Node.step=top.step+1;
                q.push(Node);
                inq[newX][newY]=true;
            }
        }
    }
    return -1; //无法到达的时候返回 -1
}
int main(){
    cin>>n>>m;
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            cin>>maze[i][j];
        }
    }
    cin>>S.x>>S.y>>T.x>>T.y;
    S.step=0; //初始化
    cout<<bfs();
}

Here, if you want to change it to "output the shortest path"

代码CPP · 51 行
#include<bits/stdc++.h>
using namespace std;
const int maxn=105;
struct node{
    int x,y;
    vector<pair<int,int> > path;
}S,T,Node; //起点、终点、临时结点
int n,m,maze[maxn][maxn],X[4]={0,0,-1,1},Y[4]={1,-1,0,0};
bool inq[maxn][maxn]={false};//是否已入过队
//判断这个路径是否可行
bool judge(int x,int y){
    if(x<1||x>n||y<1||y>m||maze[x][y]||inq[x][y]) return false;
    return true;
}
void bfs(){
    queue<node> q;
    q.push(S);
    inq[S.x][S.y]=true; //起点入队
    while(!q.empty()){
        node top=q.front();
        q.pop();
        if(top.x==T.x&&top.y==T.y){ //到达终点
            for(const auto& x:top.path){
                cout<<x.first<<' '<<x.second<<endl;
            }
            return;
        }
        for(int i=0;i<4;i++){
            int nowX=top.x+X[i],nowY=top.y+Y[i]; //得到相邻的点
            if(judge(nowX,nowY)){ //如果可以走
                Node.x=nowX,Node.y=nowY;
                Node.path=top.path; //复制之前的路径
                Node.path.push_back({Node.x,Node.y}); //加上现在的路径
                q.push(Node); //入队
                inq[Node.x][Node.y]=true;
            }
        }
    }
}
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            cin>>maze[i][j];
        }
    }
    S.x=1,S.y=1,S.path.push_back({1,1});
    T.x=n,T.y=m;
    bfs();
    return 0;
}

The meaning of the inq array set up in BFS is whether a node has already been enqueued, not whether a node has already been visited.

The difference: if it is set to indicate whether a node has already been visited, it is possible that while a node is in the queue (but has not yet been visited), it can be reached by other nodes and thus be enqueued again, causing many nodes to be enqueued repeatedly.

Since enqueueing an element is essentially creating a copy of it inside the queue, modifying the corresponding container will not modify the other element.

Therefore, when you need to modify the elements in the queue rather than merely access them, it is best for the queue to store not the elements themselves but their indices.

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

struct node{
    int data;
}a[10];
int main(){
    queue<int> q;
    for(int i=1;i<=3;i++){
        a[i].data=i;
        q.push(i); //这里存放的是下标
    }
    a[q.front()].data=100;
    cout<<a[1].data; //输出 100
}

Chapter 9: Advanced Topics (3) — Data Structures (Part 2)

9.1 Trees and Binary Trees

9.1.1 Definition and Properties of Trees

In data structures, the branching points of branches, the leaves, and the root of a tree are abstracted as nodes (node), where the tree root is abstracted as the root node (root), and a tree can have at most one root node; the leaves are abstracted as leaf nodes (leaf), and leaf nodes do not extend any new nodes; the trunk and branches are uniformly abstracted as edges (edge), and each edge is used only to connect two nodes (one at each endpoint).

In data structures, the root node is generally placed at the very top (opposite to real trees), and then several edges extend downward to reach child nodes (thus forming subtrees downward), and the child nodes in turn extend edges downward and connect some nodes, until reaching the leaf nodes.

Below are several fairly practical concepts and properties of trees, among which 1 and 5 are often used to create boundary test data:

  1. A tree can have no nodes; this case is called an empty tree.
  2. The level of a tree is counted starting from the root node, i.e., the root node is the first level, the root node of the root node's subtree is the second level, and so on.
  3. The width of a binary tree usually refers to the maximum number of nodes at the same level.
  4. Since an edge connects two nodes and there are no cycles in a tree, for a tree with n nodes, the number of edges must be n-1; conversely, any structure that is connected and satisfies edge count = vertex count - 1 must be a tree.
  5. A leaf node is defined as a node with degree 0, so when a tree has only one node (i.e., only the root node), the root node also counts as a leaf node.
  6. The depth of a node refers to the depth value obtained by counting layer by layer from top to bottom starting from the root node (depth 1) down to that node; the height of a node refers to the height value obtained by counting layer by layer from bottom to top starting from the bottommost leaf node (height 1) up to that node. The depth of a tree is the maximum depth of the nodes in the tree, and the height of a tree is the maximum height of the nodes in the tree. For a tree, depth == height, but for a specific node this is not necessarily the case.
  7. Multiple trees combined together are called a forest (forest).

9.1.2 Recursive Definition of Binary Trees

The recursive definition of a binary tree is given directly:

  1. Either the binary tree has no root node and is an empty tree;
  2. Or the binary tree consists of a root node, a left subtree, and a right subtree, and both the left subtree and the right subtree are binary trees.

Recursive definition: defining something in terms of itself (for example, the Fibonacci sequence F(n)=F(n-1)+F(n-2) is a recursive definition, using elements of the sequence itself to define the sequence itself).

Or, in a family, a grandfather is the father's father, and a great-grandfather is the father's father's father; in this way, all males in the direct bloodline can be defined using the definition of "father."

Now let's analyze the recursive boundary and recursive formula of the recursive definition of a binary tree:

  • Recursive boundary: if the current node is empty, the recursion has reached the boundary of the tree.
  • Recursive formula: the two subtrees connected by a node are both binary trees.

Several special kinds of binary trees are introduced:

  1. Full binary tree: the number of nodes at every level reaches the maximum number of nodes that level can hold.
  2. Complete binary tree: except for the bottommost level, the number of nodes at every level reaches the maximum number of nodes that level can hold, and the bottommost level contains only several consecutive nodes from left to right, with all nodes to the right of these consecutive nodes absent.

Understanding several tree concepts from the perspective of binary trees:

  1. Level: if a binary tree is viewed as a family tree, then the level is the generation.
  2. Child node, parent node, sibling node, ancestor node, descendant node: the root node of a node's subtree is called the child node of that node, and the node itself is called the parent node of that child node; nodes with the same parent as a given node are called its sibling nodes (nodes at the same level but with different parents are called cousin nodes). If there exists a path from node X to node Y going from top to bottom, then X is an ancestor node of Y, and Y is a descendant node of X. A node is its own ancestor node and also its own descendant node.

9.1.3 Storage Structure and Basic Operations of Binary Trees

1. Storage Structure of Binary Trees

A linked list is used for the definition; the difference is that since each node of a binary tree has two outgoing edges, the pointer fields also become two. If a subtree is an empty tree, then it points to NULL; this kind of linked list is also called a binary linked list.

struct node{
    typename data; //数据域
    node* lchild; //指向左子树根节点的指针
    node* rchild; //指向右子树根节点的指针
}

Since the root node does not exist before the binary tree is built, the address is generally set to NULL.

node *root=NULL;

If you need to create a new node (for example, when inserting a node into a binary tree), you can use this function:

node* newNode(int v){
    node *Node=new node;
    Node->data=v; //结点的数据/权值为 v
    Node->lchild=Node->rchild=NULL; //初始状态下没有左右孩子
    return Node;
}

2. Searching and Modifying Binary Tree Nodes

Search: given a data field value, find all nodes in the binary tree whose data field equals the given value.

Modification: on the basis of the search, modify their data fields to the given value.

void search(node* root,int x,int newData){
    if(root==NULL) return;
    if(root->data==x) root->data=newData;
    //往左右子树递归查找
    search(root->lchild,x,newData);
    search(root->rchild,x,newData);
}

3. Inserting Binary Tree Nodes

You can think of it this way: the position where the search fails is exactly the position where the node should be inserted.

//insert 函数将在二叉树中插入一个数据域为 x 的新结点
//注意根结点 root 要使用引用
void insert(node* &root,int x){
    if(root==NULL){ //查找失败:插入位置:递归边界
        root=newNode(x);
        return;
    }
    if(由二叉树的性质,x应该插在左子树){
        insert(root->lchild,x);
    }
    else{
        insert(root->rchild,x);
    }
}

Why must root be passed by reference? This is because in the insert function, the newly created node is assigned to root. If a reference is not used, this statement cannot take effect on the original variable (i.e., the root->lchild and root->rchild of the upper level), and thus the new node cannot be attached to the binary tree. Therefore, the insert function must use a reference.

Method for determining whether a reference is needed: if the function needs to create new nodes, i.e., it modifies the structure of the binary tree, then a reference is needed; if it only modifies the contents of existing nodes or merely traverses the tree, then a reference is not needed.

As for cases where you might not be able to tell, you might as well try the difference between using and not using a reference before making a choice.

After creating a new node, be sure to set the new node's left and right pointer fields to NULL, indicating that this new node temporarily has no left or right subtrees.

4. Creating a Binary Tree

Creating a binary tree is essentially the process of inserting nodes into the binary tree, and the data fields of the nodes to be inserted are generally given by the problem. Usually, the data to be inserted is stored in an array and then inserted one by one, finally returning the pointer root that points to the root node.

//二叉树的建立
node* Create(int data[],int len){
    node* root=NULL;
    for(int i=0;i<len;i++){
        insert(root,data[i]);
    }
    return root;
}

5. Illustration of the Binary Tree Storage Structure

root==NULL means the node's address is NULL, i.e., the node does not exist.

Whereas *root==NULL is incorrect, because it means the space pointed to by root is empty, but it cannot indicate whether the address is empty.

6. Storage Structure of Complete Binary Trees

For complete binary trees, there is a more convenient storage method. Suppose nodes are numbered starting from 1, from top to bottom and from left to right:

For any node in a complete binary tree (let its number be x), the number of its left child must be 2x, and the number of its right child must be 2x+1.

Therefore, you can create an array of size $2^k$ to store the information of all nodes, where k is the maximum height of the complete binary tree, and position 1 stores the root node (not starting from 0).

Moreover, the order in which elements are stored in this array is exactly the level-order traversal sequence of the complete binary tree. The criterion for determining whether a node is a leaf node is: the number of the node's left child (why the left child? Because a complete binary tree allows the right side to be completely empty), which is root*2, is greater than the total number of nodes; the criterion for determining whether a node is an empty node is that the node's index is greater than the total number of nodes n.

9.2 Traversal of Binary Trees

It refers to visiting all nodes of a binary tree in a certain order.

A binary tree can be divided into 3 parts: the root node, the left subtree, and the right subtree, and then it can be traversed recursively.

For each of the first three traversals, the left subtree is always traversed before the right subtree, and the terms "preorder, inorder, and postorder" all refer to the position of the root node in the traversal.

9.2.1 Preorder Traversal

1. Implementation of Preorder Traversal

First visit the root node root, then visit the left subtree and the right subtree. The order is root -> left -> right.

Consider the recursive formula: the order is root -> left -> right.

Recursive boundary: reaching a dead end, i.e., the subtree being an empty tree.

void preorder(node *root){
	if(root==NULL) return;
	//访问根结点 root,例如将其数据域输出
	cout<<root->data;
	//访问左子树
	preorder(root->lchild);
	//访问右子树
	preorder(root->lchild);
}

2. Properties of the Preorder Traversal Sequence

Since preorder traversal visits the root node first, for the preorder traversal sequence of a binary tree, the first element of the sequence must be the root node.

9.2.2 Inorder Traversal

1. Implementation of Inorder Traversal

Left subtree -> root node -> right subtree

void inorder(node *root){
	if(root==NULL) return;
	//访问左子树
	inorder(root->lchild);
	cout<<root->data; //把根结点的访问放在左右子树之间
	inorder(root->rchild);
}

2. Properties of the Inorder Traversal Sequence

As long as the root node is known, the left and right subtrees can be distinguished by the position of the root node in the inorder traversal sequence.

9.2.3 Postorder Traversal

1. Implementation of Postorder Traversal

Left subtree -> right subtree -> root node

void postorder(node* root){
	if(root==NULL) return;
	postorder(root->lchild);
	postorder(root->rchild);
	cout<<root->data;
}

2. Properties of the Postorder Traversal Sequence

The last element of the sequence must be the root node.

Whether it is a preorder traversal sequence or a postorder traversal sequence, the inorder traversal sequence must be known in order to uniquely determine a tree.

This is because only through the inorder traversal sequence can the left and right subtrees be separated using the root node, thereby recursively generating a binary tree.

Of course, this method can only be used if it is guaranteed that all elements are pairwise distinct.

9.2.4 Level-Order Traversal

Traverse level by level from the root node downward, and for nodes on the same level, traverse them from left to right. This is quite similar to BFS. The basic idea is as follows:

  1. Add the root node to queue q
  2. Take out the node at the front of the queue and visit it
  3. If the node has a left child, enqueue the left child
  4. If the node has a right child, enqueue the right child
  5. Return to step 2 until the queue is empty
void LayerOrder(node *root){
	queue<node*> q; //注意队列里面是存放地址
	q.push(root);
	while(!q.empty()){
		node* top=q.front();
		q.pop();
		//(访问队首元素)
		if(top->lchild!=NULL) q.push(top->lchild);
		if(top->rchild!=NULL) q.push(top->rchild);
	}
}

It can be observed that the elements in the queue are node* rather than node. This is because, as mentioned earlier, a queue only stores copies of elements; if you want to modify the original elements, you should store addresses, i.e., variables of type node*.

In addition, in many cases the problem requires calculating the level of each node. In this case, a layer variable needs to be added to the definition of the binary tree node.

代码CPP · 23 行
struct node{
    int data,layer;
    node* lchild;
    node* rchild;
};
void LayerOrder(node *root){
    queue<node*> q;
    root->layer=0; //设置根结点的层号为 0
    q.push(root);
    while(!q.empty()){
        node* top=q.front();
        q.pop();
        //访问队首元素
        if(top->lchild!=NULL){
            top->lchild->layer=top->layer+1;
            q.push(top->lchild);
        }
        if(top->rchild!=NULL){
            top->rchild->layer=top->layer+1;
            q.push(top->rchild);
        }
    }
}

Finally, let's solve an important problem: given the preorder traversal sequence and inorder traversal sequence of a binary tree, reconstruct the binary tree.

Suppose the preorder sequence is known to be $pre_1、pre_2、\cdots、pre_n$, and the inorder sequence is $in_1、in_2、\cdots、in_n$. Then $pre_1$ is the root node of the current binary tree.

Furthermore, from the inorder sequence, we know that the root node of the current binary tree divides the inorder sequence into the left subtree and the right subtree. Therefore, we need to find $in_k=pre_1$ in the inorder sequence, which locates the root node in the inorder sequence. It is easy to see that the number of nodes in the left subtree is numLeft=k-1, so the preorder sequence interval of the left subtree is [2,k], and the inorder sequence interval is [1,k-1]; the preorder sequence interval of the right subtree is [k+1,n], and the inorder sequence interval is [k+1,n]. Thus, we only need to recursively build the binary tree for the left subtree and the right subtree.

In fact, if in the current recursive process the interval of the preorder sequence is [preL,preR] and the interval of the inorder sequence is [inL,inR], then the number of nodes in the left subtree is numLeft=k-inL. In this case, the preorder sequence interval of the left subtree is [preL+1,preL+numLeft], and the inorder sequence interval of the left subtree is [inL,k-1]; the preorder sequence interval of the right subtree is [preL+numLeft+1,preR], and the inorder sequence interval is [k+1,inR].

The recursive boundary is when the length of the preorder sequence is less than 0, meaning the current binary tree does not exist.

代码CPP · 19 行
int pre[],in[]; //先序序列和中序序列
//当前先序序列区间为 [preL,preR],中序序列区间为 [inL,inR],返回根结点地址]
node* create(int preL,int preR,int inL,int inR){
    if(preL>preR) return NULL;
    node* root=new node;
    root->data=pre[preL];
    int k;
    for(k=inL;k<=inR;k++){ //这里循环变量可以不使用 i
        if(in[k]==root->data) break; //在中序序列中找到根结点
    }
    int numLeft=k-inL;
    //左子树的结点个数为 numLeft=k-inL,左子树的先序序列区间就是 [preL+1,preL+numLeft],左子树的中序序列区间是 [inL,k-1];
    //右子树的先序序列区间是 [preL+numLeft+1,preR],中序序列区间是 [k+1,inR]
    //返回左子树的根结点地址,赋值给 root 的左指针
    root->lchiild=create(preL+1,preL+numLeft,inL,k-1);
    //返回右子树的根结点地址,赋值给 root 的右指针
    root->rchild=create(preL+numLeft+1,preR,k+1,inR);
    return root; //返回根结点地址
}

If a static implementation is used:

代码CPP · 22 行
struct node{
    char data;
    int lchild;
    int rchild;
}Node[30];
int idx=0	;
//Node[0] 为根结点

int create(int preL,int preR,int inL,int inR){
    if(preL>preR) return -1;
    int cur=idx++;
    Node[cur].data=pre[preL];
    int k;
    for(k=inL;k<=inR;k++){
        if(in[k]==pre[preL]) break;
    }
    int numLeft=k-inL;
    
    Node[cur].lchild=create(preL+1,preL+numLeft,inL,k-1);
    Node[cur].rchild=create(preL+numLeft+1,preR,k+1,inR);
    return cur;
}

Conclusion: The inorder sequence can be paired with any one of the preorder sequence, postorder sequence, or level-order sequence to construct a unique binary tree, whereas any pairing among the latter three cannot.

【PAT A1020】 Tree Traversals

Given the postorder traversal sequence and inorder traversal sequence of a binary tree, find the level-order traversal sequence of this binary tree.

Consider first reconstructing the binary tree using the postorder traversal sequence and the inorder traversal sequence, and then performing a level-order traversal on the binary tree.

代码CPP · 46 行
#include<bits/stdc++.h>
using namespace std;
const int maxn=35;
struct node{
    int data;
    node *lchild,*rchild;
};
int n,in[maxn],post[maxn];
//中序序列的开始和结尾,后序序列的开始和结尾
//返回构建出的二叉树的根结点
node *create(int inL,int inR,int postL,int postR){
    if(postL>postR) return NULL;
    //初始化根结点
    node* root=new node;
    root->data=post[postR];
    //先找到根节点所在的位置
    int k;
    for(k=inL;k<=inR;k++){
        if(in[k]==post[postR]) break;
    }
    int numLeft=k-inL; //左子树的结点个数
    //左子树:中序序列区间为 [inL,k-1] 后序序列区间为 [postL,postL+numLeft-1]
    root->lchild=create(inL,k-1,postL,postL+numLeft-1);
    //右子树:中序序列区间为 [k+1,inR] 后序序列区间为 [postL+numLeft,postR-1]
    root->rchild=create(k+1,inR,postL+numLeft,postR-1);
    return root;
}
//对二叉树进行层序遍历
void layerOrder(node *root){
    queue<node*> q;
    q.push(root);
    while(!q.empty()){
        node *top=q.front();
        q.pop();
        cout<<top->data<<' ';
        if(top->lchild!=NULL) q.push(top->lchild);
        if(top->rchild!=NULL) q.push(top->rchild);
    }
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++) cin>>post[i];
    for(int i=1;i<=n;i++) cin>>in[i];
    node *root=create(1,n,1,n);
    layerOrder(root);
}

9.2.5 Static Implementation of Binary Trees

struct node{
    typename data;
    int lchild;
    int rchild;
}Node[maxn];
int idx=0;
int newNode(int v){
    Node[idx].data=v;
    Node[idx].lchild=-1; // 以 -1 表示空
    Node[idx].rchild=-1;
    return idx++;
}

And so on. In short, it is just making things static.

Note that, same as the level-order traversal of a non-static binary tree, the level-order traversal of a statically implemented binary tree should define the queue as queue<int> q, where int is the index, rather than queue<node> q.

9.3 Traversal of Trees

A tree in the general sense, i.e., a tree where the number of child nodes is unlimited and the child nodes have no particular order.

9.3.1 Static Representation of Trees

Let the pointer field store the addresses of all its child nodes (or open a separate array to store the addresses of all child nodes).

The static representation is as follows:

struct node{
    typename data; //数据域
    vector<int> child; //指针域,存放所有子结点的下标
}Node[maxn];

Similar to the static implementation of binary trees, when a new node needs to be created, simply take an index from the array in order.

int idx=0;
int newNode(int v){
    Node[idx].data=v;
    Node[idx].child.clear(); //清空子结点
    return idx++; //返回结点下标并令 idx 自增
}

However, in general, when problems involve trees that are not binary trees, the nodes are given numbers, usually 0 to n-1, so the newNode function is not needed.

9.3.2 Preorder (Root-First) Traversal of Trees

That is, first visit the root node, then visit all subtrees.

void preOrder(int root){
    //访问当前结点,比如输出
    for(const auto&x:Node[root].child){
	preOrder(x); //递归访问结点 root 的所有子结点
    }
}

In the code for the root-first traversal of a tree, although the recursive boundary is not explicitly written, the recursive boundary does in fact exist. The recursive boundary is determined by the structure of the tree. Specifically, when the traversal reaches a leaf node, that node has no child nodes, so the for loop is never entered, and the recursive calls naturally terminate.

9.3.3 Level-Order Traversal of Trees

代码CPP · 21 行
struct node{
    int layer;
    int data;
    vector<int> child;
}Node[maxn];
void layerOrder(int root){
    queue<int> q; //记得 queue 里面存放的是指针/下标
    Node[root].layer=0;
    q.push(root);
    while(!q.empty()){
        int top=q.front();
        q.pop();
        cout<<Node[top].data;
        for(const auto&x:Node[top].child){
            if(x!=-1){
                Node[x].layer=Node[top].layer+1;
                q.push(x);
            }
        }
    }
}

9.3.4 Understanding DFS and BFS from Tree Traversals

1. DFS and Root-First Traversal

For any valid DFS solving process, it can be drawn in the form of a tree, where dead ends are equivalent to leaf nodes in the tree, and forks are equivalent to non-leaf nodes in the tree. Moreover, the DFS traversal process of this tree is exactly the process of the root-first traversal of the tree.

2. BFS and Level-Order Traversal

For any valid BFS solving process, it can likewise be drawn in the form of a tree.

[PAT A1053] Path of Equal Weight

Given a tree and the weight of each node, find all paths from the root node to leaf nodes such that the sum of the weights of the nodes on each path equals a given constant S. If there are multiple such paths, output them in non-increasing order of the paths. The size of a path refers to a lexicographic-like ordering (a1->a2->....an)

代码CPP · 51 行
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn=105;
int n,m,S; //树的结点数,非叶子结点个数(边数),给定权
int id,k,child;
//记录路径 (记录的是结点的编号),有更高权值的路径应优先输出,而读入时已经对权值排好了序,因此 dfs 的时候总是会优先访问权值更大的进行输出
vector<int> path;
struct node{
    int data;
    int layer;
    vector<int> child;
}Node[maxn];
bool cmp(int a,int b){
    return Node[a].data>Node[b].data;
}
void dfs(int idx,int sum){ //idx 是目前访问的结点编号,sum 是目前的权值和
    if(sum>S) return; //剪枝
    if(sum==S){
        if(Node[idx].child.empty()){ //如果这个时候是叶子结点才输出,否则直接 return
            for(const auto&x:path) printf("%d ",Node[x].data);
            printf("\n");
        }
        return;
    }
    for(const auto&x:Node[idx].child){//枚举所有孩子结点
        //选择这个孩子结点
        path.push_back(x); //将结点 child 加到路径 path 末尾 
        dfs(x,sum+Node[x].data); //递归进入下一层
        //不选择这个孩子结点,回溯
        path.pop_back();
    }
}
int main(){
    scanf("%d%d%d",&n,&m,&S);
    for(int i=0;i<n;i++){
        scanf("%d",&Node[i].data);
    }
    for(int i=0;i<m;i++){
        scanf("%d%d",&id,&k);
        for(int i=0;i<k;i++){
            scanf("%d",&child);
            Node[id].child.push_back(child); 
        }
        //输出的时候按照路径的权值输出,先把孩子的权值排好序
        sort(Node[id].child.begin(),Node[id].child.end(),cmp);
    }
    path.push_back(0); //插入根结点
    dfs(0,Node[0].data);
}

9.4 Binary Search Tree (BST)

9.4.1 Definition of a Binary Search Tree

  • Either it is an empty tree
  • If the left subtree is not empty, then the values of all nodes in the left subtree are less than or equal to the value of its root node
  • If the right subtree is not empty, then the values of all nodes in the right subtree are greater than the value of its root node
  • The left and right subtrees are also binary search trees, respectively

In fact, there are two ways to define it; another one is

  • If the left subtree is not empty, then the values of all nodes in the left subtree are less than the value of its root node
  • If the right subtree is not empty, then the values of all nodes in the right subtree are greater than the value of its root node
  • There are no nodes with equal weights

In this case, add a cnt variable inside the node to record the number of occurrences of that weight.

9.4.2 Basic Operations of a Binary Search Tree

代码CPP · 19 行
struct node{
    int v;
    int lchild,rchild;
    int siz; //(两子树 + 自己本身) 的大小(结点数之和)
}bst[maxn];

int search(int v,int idx){
    if(idx==0) return 0; //查找失败
    
    if(v==bst[idx].v){
        return idx;
    }
    else if(v<bst[idx].v){
        search(v,bst[idx].lchild);
    }
    else{
        search(v,bst[idx].rchild);
    }
}

Note: the static implementation is used uniformly

2. Insertion

代码CPP · 25 行
void insert(int v,int idx){ //v 表示权值,idx 表示当前的结点编号
    bst[idx].siz++;
    if(v>bst[idx].v){ //说明 v 应该插入到右子树
        if(bst[idx].rchild!=0){
            insert(v,bst[idx].rchild);
        }
        else{ //不存在右孩子
            cnt++;
            bst[cnt].v=v;
            bst[cnt].siz=1;
            bst[idx].rchild=cnt;
        }
    }
    else{
        if(bst[idx].lchild!=0){
            insert(v,bst[idx].lchild);
        }
        else{
            cnt++;
            bst[cnt].v=v;
            bst[cnt].siz=1;
            bst[idx].lchild=cnt;
        }
    }
}

3. Deletion

There are three cases for deleting a node in a binary search tree (BST):

  1. The target node is a leaf node: simply delete it directly.
  2. The target node has only one child node: replace it with its only child node.
  3. The target node has two child nodes: find its predecessor (the maximum value in the left subtree) or successor (the minimum value in the right subtree) to replace it, then recursively delete that predecessor or successor node.

First, here are the functions for finding the predecessor and successor

代码CPP · 29 行
int findPre(int v){
    int idx=1; //从根结点开始搜索
    int ans=-inf;
    while(idx){
        if(bst[idx].v<v){
            ans=bst[idx].v;
            idx=bst[idx].rchild;
        }
        else{
            idx=bst[idx].lchild;
        }
    }
    return ans;
}

int findPost(int v){
    int idx=1;
    int ans=inf;
    while(idx){
        if(bst[idx].v>v){
            ans=bst[idx].v;
            idx=bst[idx].lchild;
        }
        else{
            idx=bst[idx].rchild;
        }
    }
    return ans;
}

Then, here is the deletion function

代码CPP · 35 行
void remove(int &idx, int v) {
    if (idx == 0) return; // 树为空,直接返回

    if (v < bst[idx].v) {
        // 目标值在左子树
        remove(bst[idx].lchild, v);
    } else if (v > bst[idx].v) {
        // 目标值在右子树
        remove(bst[idx].rchild, v);
    } else {
        // 找到目标节点
        if (bst[idx].lchild == 0 && bst[idx].rchild == 0) {
            // 情况 1:叶子节点,直接删除
            idx = 0;
        } else if (bst[idx].lchild == 0) {
            // 情况 2:只有右子树
            idx = bst[idx].rchild;
        } else if (bst[idx].rchild == 0) {
            // 情况 2:只有左子树
            idx = bst[idx].lchild;
        } else {
            // 情况 3:有两个子节点
            int preIdx = bst[idx].lchild;
            while (bst[preIdx].rchild) { // 找前驱
                preIdx = bst[preIdx].rchild;
            }
            bst[idx].v = bst[preIdx].v; // 用前驱值替换
            remove(bst[idx].lchild, bst[preIdx].v); // 递归删除前驱
        }
    }

    if (idx != 0) { // 维护子树大小信息
        bst[idx].siz = 1 + bst[bst[idx].lchild].siz + bst[bst[idx].rchild].siz;
    }
}

9.4.3 Properties of Binary Search Trees

9.5 Balanced Binary Tree (AVL Tree)

9.5.1 Definition of a Balanced Binary Tree

9.5.2 Basic Operations of a Balanced Binary Tree

9.6 Union-Find Set

9.6.1 Definition of a Union-Find Set

A union-find set is a data structure for maintaining sets.

"Union", "find", and "set" are taken from merge, find, and set, respectively.

A union-find set supports the following two operations:

  1. Union: merge two sets
  2. Find: determine whether two elements are in the same set

Implementation:

int father[N];

Here father[i] denotes the parent node of element i, and the parent node itself is also an element in the set. For example, father[1]=2 means that the parent node of element 1 is element 2, and the set an element belongs to is represented by this parent-child relationship. In addition, if father[i]==i, it means that element i is the root node of the set. However, for the same set there is only one root node, and it is used as the identifier of the set it belongs to.

9.6.2 Basic Operations of a Union-Find Set

1. Initialization

At the beginning, each element is an independent set, so you only need to set father[i]=i for all elements, or set father[i]=-1

2. Find

Since it is stipulated that there is only one root node in the same set, the find operation is the process of finding the root node of a given node. It can be implemented either iteratively or recursively; in both cases the idea is to repeatedly look for the parent node until the root node is found.

int findFather(int x){
    while(x!=father[x]){
        x=father[x];
    }
    return x;
}

int findFather(int x){
    if(x==father[x]) return x;
    else return findFather(father[x]);
}

3. Union

Union means merging two sets into one set. In problems, two elements are generally given, and you are asked to merge the sets that these two elements belong to. The concrete implementation is to first determine whether the two elements belong to the same set; only when the two elements belong to different sets should they be merged, and the merging process is generally to point the parent of the root node of one set to the root node of the other set. The idea is as follows:

  1. For the two given elements a and b, first determine whether they belong to the same set; simply call the find function to check whether their root nodes are the same.
  2. Merge the two sets: in step 1, the root nodes faA and faB of the two elements have already been obtained, so you only need to point the parent node of one to the other node. For example, setting father[faA]=faB or the other way around both work.
void Union(int a,int b){
    int faA=findFather(a);
    int faB=findFather(b);
    if(faA!=faB){
        father[faA]=faB;
    }
}

9.6.3 Path Compression

The functions mentioned above have not been optimized. Now consider an extreme case: if the problem gives a large number of elements that form a chain, then the find function will be very inefficient. The following is an optimization idea.

Since our findFather() function is only meant to find the root node, we can completely point the parent of all nodes along the path of the current query node to the root node, so that during the search there is no need to keep backtracking to find the parent, and the time complexity drops to $O(1)$.

The conversion steps can be summarized as follows:

  1. Obtain the root node r of x using the original method
  2. Walk through the process of finding the root node again starting from x, changing the parent of all nodes along the path to the root node r.
int findFather(int x){
    int a=x; //由于 x 在下面的 while 循环会变成根结点,先存一下原来的 x
    while(x!=father[x]){
        x=father[x];
    }
    //到这里 x 存放的是根结点,下面把路径上所有结点的 father 都改成根结点。
    while(a!=father[a]){
        int z=a;
        a=father[a];
        father[z]=x;
    }
    return x;
}

There is also a recursive version

int findFather(int x){
    return x==father[x] ? x : father[x]=findFather(father[x]);
}

Below is a simple problem that uses a union-find set

Example Problem: Good Friends

引用Problem Description There is a strange space called the "Digital World",...

Problem Description

There is a strange space called the "Digital World", in which live many Digimon, some of whom may be good friends. Moreover, the Digital World has two unwritten rules:

First, Digimon A and Digimon B being good friends is equivalent to Digimon B and Digimon A being good friends.

Second, if Digimon A and Digimon C are good friends, and Digimon B and Digimon C are also good friends, then A and B are also good friends. Now, given the information about all good-friend relationships among these Digimon, the question is: into how many groups can these Digimon be divided, such that any two Digimon in the same group are good friends, and any Digimon in different groups are not good friends.

Input Format

The first line of the input contains two positive integers n (n<=100) and m (m<=100), representing the number of Digimon and the number of good-friend groups respectively, where the Digimon are numbered 1~n. The next m lines each contain two positive integers a and b, indicating that Digimon a and Digimon b are good friends.

Sample Input

4 2
1 4
2 3

Sample Output

2

This problem is a union-find model. The "groups" in the problem can be viewed as sets, and the good-friend relationships given in the problem can be viewed as edges between two nodes. Then, when inputting these good-friend relationships, the union operation of the union-find set can be performed on them at the same time.

To find the number of sets, the following rule is needed: for the same set, there is only one root node, and it is used as the identifier of the set it belongs to. Therefore, open a bool flag[n] to record whether each node serves as the root node of some set. In this way, after processing the input data, you can traverse all elements, set the flag of the root node of the set each element belongs to to true, and finally accumulate the elements in flag. The code is as follows

代码CPP · 49 行
#include<bits/stdc++.h>
using namespace std;

const int maxn=110;
int father[maxn];
bool flag[maxn];

int findFather(int x){
    int a=x;
    while(x!=father[x]){
        x=father[x];
    }
    while(a!=father[a]){
        int z=a;
        a=father[a];
        father[z]=x;
    }
    return x;
}
void Union(int a,int b){
    int faA=father[a];
    int faB=father[b];
    if(faA!=faB){
        father[faA]=faB;
    }
    return;
}

int main(){
    int n,m,a,b;
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        father[i]=i;
        //flag[i]=false; 全局变量默认是 false
    }
    for(int i=0;i<m;i++){
        cin>>a>>b;
        Union(a,b);
    }
    for(int i=1;i<=n;i++){
        flag[findFather(i)]=true;
    }
    int ans=0;
    for(int i=1;i<=n;i++){
        ans+=(int)flag[i];
    }
    cout<<ans;
    return 0;
}

9.7 Heap

9.7.1 Definition and Basic Operations of a Heap

9.7.2 Heap Sort

9.8 Huffman Tree

9.8.1 Huffman Tree

9.8.2 Huffman Coding

Chapter 10 Advanced Topics (4) — Graph Algorithms

A graph consists of vertices and edges. Graphs are divided into directed graphs and undirected graphs.

The degree of a vertex: the number of edges connected to that vertex.

For a directed graph: the number of outgoing edges of a vertex is called the out-degree, and the number of incoming edges is called the in-degree.

The weights of vertices and edges are called vertex weights and edge weights, respectively.

10.2 Storage of Graphs

10.2.1 Adjacency Matrix

Suppose the vertices of graph G(V,E) are numbered from 0 to n-1; then the two dimensions of the two-dimensional array G[n][n] can be used to represent the vertex labels of the graph.

If G[i][j]==1 -> there is an edge between vertices i and j; if it is 0, there is no edge. In addition, if there is an edge weight, let G[i][j] store the edge weight, and for non-existent edges, set the edge weight to 0, -1, or inf.

For an undirected graph, the adjacency matrix is a symmetric matrix.

To prevent MLE, the adjacency matrix is only suitable for problems where the number of vertices is not too large (<=1000).

10.2.2 Adjacency List

Suppose the vertices of graph G(V,E) are numbered from 0 to n-1, and each vertex may have several outgoing edges. If all the outgoing edges of the same vertex are placed in one list, then n vertices will have n lists (vertices with no outgoing edges correspond to empty lists). These n lists are called the adjacency list of graph G, denoted Adj[n], where Adj[i] stores the list composed of all outgoing edges of vertex i.

Here we use a vector to implement the adjacency list.

struct Node{
  int v; //边的终点编号
  int w; //边权
  Node(int _v,int _w):v(_v),w(_w){};
}
vector<Node> Adj[n];

Then, if we want to add a directed edge from vertex 1 to vertex 3 with edge weight 4, we can do it like this:

Adj[1].emplace_back(3,4);

If you want to add an undirected edge, you can design a function like this

// 添加无向边 (u, v, w)
void addEdge(int u, int v, int w) {
    Adj[u].emplace_back(v, w);  // 在 u 的邻接表中添加边 (u, v, w)
    Adj[v].emplace_back(u, w);  // 在 v 的邻接表中添加边 (v, u, w)
}

In this way, when adding an undirected edge, not only is (v, w) added to Adj[u], but (u, w) is also added to Adj[v], ensuring the bidirectional property of the graph.

10.3 Traversal of Graphs

10.3.1 Traversing a Graph Using Depth-First Search (DFS)

First, two concepts are introduced:

  1. Connected Component: In an undirected graph, if two vertices can reach each other (possibly indirectly through some path), then the two vertices are said to be connected. If any two vertices of graph G(V,E) are connected, then graph G is called a connected graph; otherwise, it is called a non-connected graph, and its maximal connected subgraphs are called connected components.
  2. Strongly Connected Component: In a directed graph, if two vertices can each reach the other through a directed path, the two vertices are said to be strongly connected. If any two vertices of graph G(V,E) are strongly connected, then graph G is called a strongly connected graph; otherwise, it is called a non-strongly-connected graph, and its maximal strongly connected subgraphs are called strongly connected components.

For convenience of description, connected components and strongly connected components are collectively referred to below as connected blocks.

Therefore, traversing the entire graph means traversing all connected blocks. The basic idea of DFS traversal of a graph is to mark visited vertices as visited, so that when this vertex is encountered again in a subsequent recursion, it is not processed again, until all vertices of the entire graph have been marked as visited.

Below is pseudocode for DFS

DFS(u){ //访问顶点 u
vis[u]=true;
    for(从u出发能到达的所有顶点v){
        if(!vis[v]) DFS(v);
    }
    DFSTraveG{ //遍历图 G
        for(G的所有顶点u){
            if(!vis[u]) DFS(u); //访问 u 所在的连通块
    }
}

Based on this code, the code for the adjacency matrix and adjacency list can be substituted in to obtain the following templates:

代码CPP · 25 行
//邻接矩阵版本
cosnt int maxv=1000; //最大顶点数
const int inf=0x3f3f3f3f;

int n,G[maxv][maxv];
bool vis[maxv]={false};

void dfs(int u,int depth){
    vis[u]=true;
    //如果需要对 u 进行一些操作可以在这里进行
    //下面对所有从 u 出发能到达的分支顶点进行枚举
    for(int v=0;v<n;v++){
        if(!vis[v]&&G[u][v]!=inf){
            dfs(v,depth+1); //访问 v,深度++
        }
    }
}

void DFSTrave(){ //遍历图 G
    for(int u=0;u<n;u++){
        if(!vis[u]){
            dfs(u+1);
        }
    }
}
代码CPP · 22 行
//邻接表版本
cosnt int maxv=1000; //最大顶点数
const int inf=0x3f3f3f3f;

vector<int> Adj[maxv];
int n; //顶点数
bool vis[maxv]={false};

void dfs(int u,int depth){
    vis[u]=true;
    //如果要对 u 进行一些操作可以在这里
    for(int i=0;i<(int)Adj[u].size();i++){
        int v=Adj[u][i];
        if(!vis[v]) dfs(v,depth+1);
    }
}

void DFSTrave(){
    for(int u=0;u<n;u++){
        if(!vis[u]) dfs(u,1);
    }
}

【PAT A1034】 Head of a Gang

代码CPP · 69 行
#include<bits/stdc++.h>
using namespace std;

const int maxn=2010;
const int inf=0x3f3f3f3f;
int G[maxn][maxn];
int weight[maxn];
bool vis[maxn];
map<string,int> stringToInt;
map<int,string> intToString;
map<string,int> Gang;
int n,k;
int numPerson;

int change(string s){
    if(stringToInt.find(s)!=stringToInt.end()){
        return stringToInt[s];
    }
    else{
        stringToInt[s]=numPerson;
        intToString[numPerson]=s;
        return numPerson++;
    }
}

void dfs(int now,int &head,int &numMember,int &totalValue){
    vis[now]=true;
    numMember++;
    if(weight[now]>weight[head]) head=now;
    for(int v=0;v<numPerson;v++){
        if(!vis[v]&&G[now][v]!=0){
            totalValue+=G[now][v];
            dfs(v,head,numMember,totalValue);
        }
    }
}

void dfstrave(){
    for(int i=0;i<numPerson;i++){
        if(!vis[i]){
            int head=i,numMember=0,totalValue=0;
            dfs(i,head,numMember,totalValue);
            if(numMember>2&&totalValue>k){
                Gang[intToString[head]]=numMember;
            }
        }
    }
}

int main(){
    cin>>n>>k;
    for(int i=0;i<n;i++){
        string s1,s2;
        int w;
        cin>>s1>>s2>>w;
        int id1=change(s1);
        int id2=change(s2);
        weight[id1]+=w;
        weight[id2]+=w;
        G[id1][id2]+=w;
        G[id2][id1]+=w;
    }
    dfstrave();
    cout<<Gang.size()<<"\n";
    for(auto &[x,y]:Gang){
        cout<<x<<" "<<y<<"\n";
    }
    return 0;
}

10.3.2 Traversing a Graph Using Breadth-First Search (BFS)

代码CPP · 28 行
//邻接矩阵版本
int n;
int G[maxv][maxv];
bool inq[maxv];

void bfs(int u){ //遍历顶点 u 所在的连通块
    queue<int> q;
    q.push(u);
    inq[u]=true;
    while(!q.empty()){
        int top=q.front();
        q.pop();
        for(int v=0;v<n;v++){
            if(!inq[v]&&G[top][v]!=0){
                q.push(v);
                inq[v]=true;
            }
        }
    }
}

void bfsTrave(){
    for(int i=0;i<n;i++){
        if(!inq[i]){
            bfs(i);
        }
    }
}
代码CPP · 28 行
//邻接表版本
vector<int> Adj[maxv];
int n;
bool inq[maxv];

void bfs(int u){
    queue<int> q;
    q.push(u);
    inq[u]=true;
    while(!q.empty()){
        int top=q.front();
        q.pop();
        for(int v:Adj[top]){
            if(!inq[v]){
                q.push(v);
                inq[v]=true;
            }
        }
    }
}

void bfsTrave(){
    for(int i=0;i<n;i++){
        if(!inq[i]){
            bfs(i);
        }
    }
}

If you need to record the level of each node, you can use a struct

代码CPP · 26 行
//邻接表版本
struct node{
    int v;
    int layer;
}Node;
vector<node> Adj[maxv];
int n;
bool inq[maxv];

void bfs(int s){ //s 为起始顶点编号
    queue<node> q;
    Node.v=s;Node.layer=0;
    q.push(Node);
    inq[Node.v]=true;
    while(!q.empty()){
        node top=q.front();
        q.pop();
        for(node next:Adj[top.v]){
            next.layer=top.layer+1;
            if(!inq[next.v]){
                q.push(next);
                inq[next.v]=true;
            }
        }
    }
}

10.4 Shortest Path

This is a very classic problem: given a graph G(V,E), find a path from the starting point to the destination such that the sum of the weights of all edges traversed along this path is minimized.

10.4.1 Dijkstra's Algorithm

10.4.2 Bellman-Ford Algorithm and SPFA Algorithm

10.4.3 Floyd's Algorithm

10.5 Minimum Spanning Tree

10.5.1 Minimum Spanning Tree and Its Properties

10.5.2 Prim's Algorithm

10.5.3 Kruskal's Algorithm

10.6 Topological Sort

代码CPP · 44 行
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr); cout.tie(nullptr);
    
    int n,m;
    cin>>n>>m;
    vector<vector<int>> g(n+1);
    vector<int> ind(n+1,0);
    vector<int> outd(n+1,0);
    for(int i=0;i<m;i++){
        int a,b;
        cin>>a>>b;
        g[a].push_back(b);
        ind[b]++;
        outd[a]++;
    }

    queue<int> q;
    for(int i=1;i<=n;i++){
        if(ind[i]==0){
            q.push(i);
        }
    }
	int num=0;
    while(!q.empty()){
        int u=q.front();
        q.pop();
        for(int v:g[u]){
            ind[v]--;
            if(ind[v]==0){
                q.push(v);
            }
        }
        num++;
    }
	//num==m 则为 DAG,反之
    return 0;
}

10.6.1 Directed Acyclic Graph

10.6.2 Topological Sort

10.7 Critical Path

10.7.1 AOV Networks and AOE Networks

10.7.2 Longest Path

10.7.3 Critical Path

Chapter 11 Advanced Topics (5) — Dynamic Programming

11.1 Recursive and Iterative Approaches to Dynamic Programming

11.1.1 What Is Dynamic Programming

It is an algorithmic idea used to solve a class of optimization problems. Simply put, dynamic programming breaks a complex problem down into several subproblems, and obtains the optimal solution to the original problem by combining the optimal solutions of the subproblems. Dynamic programming records the solution of every subproblem it has already solved.

In general, dynamic programming can be implemented using either an iterative or a recursive approach, where the recursive approach is also known as memoized search.

11.1.2 The Recursive Approach to Dynamic Programming

Using memoized search to compute the Fibonacci sequence

int dp[maxn];
int F(int n){
    if(n<=1) return 1;
    if(dp[n]) return dp[n]; //已经计算过,直接返回结果
    else{
        dp[n]=F(n-1)+F(n-2);
        return dp[n];
    }
}

This leads to a concept: if a problem can be decomposed into several subproblems, and these subproblems recur repeatedly, then the problem is said to have overlapping subproblems.

Therefore, a problem must have overlapping subproblems in order to be solved with dynamic programming.

11.1.3 The Iterative Approach to Dynamic Programming

The Number Tower Problem

Arrange some numbers into the shape of a tower, where the i-th layer contains i numbers. Now you must walk from the first layer to the n-th layer, and at each step you can only move to one of the two connected numbers in the next layer. The question is: what is the maximum possible sum obtained by adding up all the numbers along the path?

According to the problem description, use a two-dimensional array f to store the j-th number in the i-th layer. If we try to enumerate all paths, the time complexity is $O(2^n)$, which is unacceptable, because paths would be visited repeatedly. The solution is to record the maximum value that all paths from a number to the bottom layer can produce, and then simply look it up directly when that number is visited. Let dp[i][j] denote the maximum sum obtainable among all paths starting from the j-th number in the i-th row and reaching the bottom layer. Once this array is defined, dp[1][1] is the final answer we want; now let's compute it.

Notice a detail: to compute dp[1][1], we must first compute its two subproblems dp[2][1] and dp[2][2], that is, we make a decision — whether to go to f[2][1] or f[2][2]. Thus dp[1][1] can be written as $$

\mathrm{dp}[1][1]=max(\mathrm{dp[2][1],dp[2][2]})+\mathrm{f[1][1]} $$ From this we can generalize the following: to compute d[i][j], we must first compute its two subproblems d[i+1][j] and d[i+1][j+1], that is, we make a decision, and thus we have $$ \mathrm{dp}[i][j]=max(\mathrm{dp[i+1][j],dp[i+1][j+1]})+\mathrm{f[i][j]} $$ Call d[i][j] the state of the problem, and call the formula above the state transition equation, which transitions each state to d[i+1][j] and d[i+1][j+1]. Note that the state d[i][j] depends only on the states of layer i+1 and is unrelated to the states of other layers, so a state at layer i can always be derived from the two substates at layer i+1. Also note that the recursive boundary should be that the dp values of the last layer of the number tower always equal the elements themselves, i.e., dp[n][j]==f[n][j]. Call this directly determinable part the boundary, and the iterative approach to dynamic programming always starts from this boundary and spreads through the entire dp array via the state transition equation.

In this way, we can start from the dp values at each position of the bottom layer and keep computing upward, finally obtaining dp[1][1], which is the answer we need. The code implementation is as follows

代码CPP · 33 行
#include<bits/stdc++.h>
using namespace std;
const int maxn=1000;
int n,f[maxn][maxn],dp[maxn][maxn];

//状态转移方程的递归实现,调用时从初始状态调用
int P(int i,int j){
    if(dp[i][j]) return dp[i][j]; //记忆化存储
    if(i==n) return dp[i][j]=f[i][j];
    return dp[i][j]=max(P(i+1,j),P(i+1,j+1))+f[i][j];
}

int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=i;j++){
            cin>>f[i][j];
        }
    }
    //边界条件
    for(int i=1;i<=n;i++){
        dp[n][i]=f[n][i];
    }
    //从 n-1 层往上不断计算 dp[i][j]
    for(int i=n-1;i>=1;i--){
        for(int j=1;j<=i;j++){
            //状态转移方程
            dp[i][j]=max(dp[i+1][j],dp[i+1][j+1])+f[i][j];
        }
    }
    cout<<dp[1][1]<<endl;
    return 0;
}

Recursion can also achieve a similar effect

The iterative approach computes bottom-up, i.e., starting from the boundary and continuously solving upward until the target problem is solved

Whereas the recursive approach is top-down, starting from the target problem and decomposing it into combinations of subproblems until the boundary is reached

From the problem above, we can further introduce a concept: if the optimal solution to a problem can be constructed from the optimal solutions of its subproblems, then the problem is said to have optimal substructure. Optimal substructure guarantees that the optimal solution to the original problem in a dynamic programming problem can be derived from the optimal solutions of the subproblems, so a problem must have optimal substructure in order to be solved with dynamic programming.

It should be pointed out that a problem must have both overlapping subproblems and optimal substructure in order to be solved with dynamic programming. Note the distinction between the two concepts:

  1. Divide and conquer vs. dynamic programming. The subproblems produced by divide and conquer do not overlap, whereas the problems solved by dynamic programming have overlapping subproblems. Divide and conquer does not necessarily solve optimization problems, while dynamic programming always solves optimization problems.
  2. Greedy vs. dynamic programming. Both require that the original problem have optimal substructure. Greedy is similar to top-down, but instead of waiting for the subproblems to be solved before choosing which one to use, it chooses a strategy to directly solve a subproblem. Dynamic programming, on the other hand, always starts from the boundary.

11.2 Maximum Continuous Subsequence Sum

Given a sequence of numbers $A_1,A_2, \cdots A_n$, find i,j (1≤i≤j≤n) such that $A_i+\cdots A_j$ is maximized, and output this maximum sum.

Sample

-2 11 -4 13 -5 -2

If done by brute force, enumerating i and j takes $\mathrm{O(n^2)}$ complexity, and computing a[i]+...+a[j] takes O(n) complexity, so the total complexity is $\mathrm{O(n^3)}$. If we use the prefix sum approach, letting s[i]=a[0]+a[1]+...+a[i], then a[i]+...+a[j]=s[j]-s[i-1] makes the computation time O(1), but the total complexity is still $\mathrm{O(n^2)}$, which is unacceptable.

Below we introduce the dynamic programming approach, with complexity O(n).

  1. Let dp[i] denote the maximum sum of a continuous sequence ending with a[i] (here it is required that a[i] must be the end of the continuous sequence).

    By setting up such a dp array, all we need to do is find the maximum value among dp[0] to dp[n-1] (because which element serves as the end is unknown). Next, we need to figure out how to compute the dp array

  2. Consider the following: since dp[i] must be a continuous sequence ending with a[i], there are only two cases

    1. The continuous sequence with the maximum sum has only one element, i.e., it both starts and ends with a[i]
    2. The continuous sequence with the maximum sum has multiple elements, i.e., it starts at some position p (p<i) and ends at a[i].

    In the first case, the maximum sum is a[i] itself.

    In the second case, the maximum sum is dp[i-1]+a[i], i.e., a[p]+...+a[i-1]+a[i]=dp[i-1]=a[i] (forcibly splitting the cases of i and i-1 apart to obtain the idea for the state equation)

    Since there are only these two cases, we obtain the state transition equation $$ \mathrm{dp[i]}=max (\mathrm{a[i],dp[i-1]+a[i]}) $$ This formula depends only on i and the elements before i, and the boundary is dp[0]=a[0], so enumerating i solves the problem.

No Aftereffect Property

The no aftereffect property of a state means: the current state records historical information, and once the current state is determined, it will not change again; future decisions can only be made on the basis of one or several existing states, and historical information can only influence future decisions through the existing states.

For problems solvable by dynamic programming, there are always many ways to design states, but not all states have the no aftereffect property, so it is necessary to design a state with the no aftereffect property and a corresponding state transition equation.

Designing the state and the state transition equation is the core of dynamic programming.

11.3 Longest Non-Decreasing Subsequence (LIS)

In a sequence of numbers, find the longest subsequence (which need not be contiguous) such that this sequence is non-decreasing.

Brute force: each element has two cases, taken or not taken; judge each case until the enumeration is complete, with time complexity $\mathrm{O(2^n)}$. Below we introduce the dynamic programming approach.

Let dp[i] denote the length of the longest non-decreasing subsequence ending with a[i] (just like the maximum continuous subsequence sum problem, ending with a[i] is a mandatory requirement). Then for a[i] there are two possibilities:

  1. If there exists an element a[j] before a[i] (j<i) such that a[j]≤a[i] and dp[j]+1>dp[i] (i.e., appending a[i] after the LIS ending with a[j] yields a longer LIS than the current one ending with a[i]), then append a[i] after the LIS ending with a[j], forming a longer non-decreasing subsequence (let dp[i]=dp[j]+1)
  2. If all elements before a[i] are greater than a[i], then a[i] can only form an LIS of length 1 by itself

The length of the LIS ending with a[i] is the maximum length that can be formed among cases 1 and 2.

From this we write the state transition equation $$ \mathrm{dp[i]}=max(\mathrm{1,dp[j]+1}) \ (j=1,2,\cdots.i-1&&a[j]<a[i]) \ 边界 dp[i]=1(先假设每个元素自成一个子序列) $$ An example code implementation

int ans=-1; //记录最大的 dp[i]
for(int i=1;i<=n;i++){
    dp[i]=1; //先假设每个元素自成一个子序列
    for(int j=1;j<i;j++){
        if(a[i]>=a[j]&&(dp[j]+1>dp[i])){
		dp[i]=dp[j]+1; //状态转移方程用以更新 dp[i]
            //也可以是 dp[i]=max(dp[i],dp[j]+1); 上面那个判断去掉
        }
    }
    ans=max(ans,dp[i]);
}

11.4 Longest Common Subsequence (LCS)

Given two strings (or number sequences) a and b, find a string such that its length is the length of the longest common part of A and B (the subsequence need not be contiguous)

Sample:

The longest common subsequence of "sadstory" and "adminsorry" is "adsory", with length 6.

Let dp[i][j] denote the length of the LCS before position i of string a and position j of string b (indices start from 1); for example, dp[4][5] denotes the LCS length of "sads" and "admin". Then, depending on the situation of a[i] and b[j], there are two decisions.

  1. If a[i]==b[j], then the LCS of string a and string b increases by one, i.e., dp[i][j]=dp[i-1][j-1]+1
  2. If a[i]!=b[j], then the LCS before position i of string a and position j of string b cannot be extended, so dp[i][j] will inherit the larger of dp[i-1][j] and dp[i][j-1], i.e., dp[i][j]=max{dp[i-1][j],dp[i][j-1]} (because they are not equal, stepping back one position from this position does not affect the length, but which dimension to step back in requires case analysis, i.e., taking a max)

From this we obtain the state transition equation $$ \mathrm{dp[i][j]}= \begin{cases} \mathrm{dp[i-1][j-1]+1,a[i]==b[j]} \ max(\mathrm{dp[i-1][j],dp[i][j-1]}), \mathrm{a[i]!=b[j]} \end{cases} \ 边界:\mathrm{dp[i][0]=dp[j][0]=0} \ \mathrm{i 和 j 从 1 遍历到各自字符串的长度} $$

11.5 Longest Palindromic Substring

Given a string s, find the length of the longest palindromic substring of s.

Example:

The longest palindromic substring of "PATZJUJZTACCBCC" is "ATZJUJZTA", with length 9

Dynamic programming approach, time complexity $\mathrm{O(n^2)}$

Let bool dp[i][j] denote whether the substring represented by s[i] through s[j] is a palindromic substring. Then, depending on whether s[i] equals s[j], the answer can be divided into two cases:

  1. If s[i]==s[j], then as long as s[i+1] through s[j-1] is a palindromic substring, s[i] through s[j] is a palindromic substring; otherwise it is not.
  2. If s[i]!=s[j], then s[i] through s[j] is definitely not a palindromic substring.

From this we can write the state transition equation $$ \mathrm{dp[i][j]=} \begin{cases} \mathrm{dp[i+1][j-1] ,s[i]==s[j]} \ \mathrm{false, s[i]!=s[j]} \end{cases} \ \mathrm{边界 dp[i][i]=1, dp[i][i+1]=(s[i]==s[i+1]?true:false)} $$ However, a direct double loop cannot guarantee that dp[i+1][j-1] has been computed, and thus dp[i+1][j-1] cannot be computed. The solution is as follows:

Following the principle that the recursive approach starts from the boundary: consider enumerating by the length of the substring and the starting position of the substring, i.e., first enumerate the substring length L, then enumerate the left endpoint i, so that the right endpoint i+L-1 can also be obtained directly.

11.6 Longest Path in a DAG

11.7 The Knapsack Problem

11.7.1 Multi-Stage Dynamic Programming Problems

The characteristic of this class of problems is: they can be described as several ordered stages, and the state of each stage depends only on the state of the previous stage. Simply start from the first problem and, following the order of the stages, solve the computation of the states in each stage, and the solution to the states in the last stage can be obtained.

11.7.2 The 0-1 Knapsack Problem

There are n items, where the weight of each item is w[i] and its value is c[i]. Now there is a knapsack with capacity V. The question is how to select items to put into the knapsack so that the total value of the items in the knapsack is maximized. Each item can be used at most once.

The dfs approach has a time complexity of $O(2^n)$, which is clearly not feasible; using dynamic programming gives $O(nV)$.

Let dp[i][v] denote the maximum value that can be obtained by packing the first i items (1≤i≤n, 0≤v≤V) into a knapsack of capacity v exactly ("exactly" means filling the capacity v exactly).

Consider the choice strategy for the i-th item; there are two cases:

  1. Do not put the i-th item in; then the problem reduces to dp[i-1][v]
  2. Put the i-th item in; then the problem reduces to the maximum value obtainable by packing the first i-1 items exactly into a knapsack of capacity v-w[i], i.e., dp[i-1][v-w[i]]+c[i]

Thus we have $$ \mathrm{dp[i][v]}=max{\mathrm{dp[i-1][v],dp[i-1][v-w[i]]+c[i]}} \ 1≤i≤n,w[i]≤v≤V $$ The above is the state transition equation. Note also that dp[i][v] only depends on the previous state dp[i-1][], so we can enumerate i from 1 to n and v from 0 to V, and by the boundary dp[0][v]=0*(the value of 0 items is of course 0)*, the entire dp array can be computed by recurrence. Since dp[i][v] represents the case of being exactly v, we need to enumerate dp[n][v] and take its maximum value.

The code is as follows

int ans=0;
for(int i=0;i<n;i++){
    for(int v=w[i];v<=V;v++){
        dp[i][v]=max(dp[i-1][v],dp[i-1][v-w[i]]+c[i]);

    }
}
for(int v=1;v<=V;v++){
    ans=max(ans,dp[n][v]);
}
cout<<ans;

Both the time complexity and space complexity are $O(nV)$, but the space complexity can be further optimized.

Notice that each time dp[i][v] is computed, only the data to the left of dp[i-1][v] is needed (i.e., the data from 0 to v), and when computing dp[i+1][], the data in the dp[i-1][] part is no longer useful. So we can open a one-dimensional array dp[v], with the enumeration direction i from 1 to n and v from V to 0 (in reverse order!), and the state transition equation becomes $$ \mathrm{dp[v]}=max{\mathrm{dp[v],dp[v-w[i]]+c[i]}} \ 1≤i≤n,w[i]≤v≤V $$ This is equivalent to overwriting dp[i-1][v] each time dp[i][v] is computed, in order to save space

for(int i=0;i<n;i++){
    for(int v=V;v>=w[i];v--){
        dp[v]=max(dp[v],dp[v-w[i]+c[i]]);
    }
}
cout<<dp[V];

Remember that when using a one-dimensional array for storage, the enumeration of v must be in reverse order!

For problems that can be divided into stages, we can always try to use the stage as one dimension of the state, which makes it easier for us to obtain states that satisfy the no-aftereffect property. If the currently designed state does not satisfy the no-aftereffect property, consider raising the dimensionality of the state, adding one or several dimensions to represent the corresponding information.

11.7.3 The Complete Knapsack Problem

There are n kinds of items, where the weight of each item is w[i] and its value is c[i]. Now there is a knapsack with capacity V. The question is how to select items to put into the knapsack so that the total value of the items in the knapsack is maximized. Each item is available in unlimited quantity.

Similarly, let dp[i][v] denote the maximum value that can be obtained by packing the first i items (1≤i≤n, 0≤v≤V) into a knapsack of capacity v exactly ("exactly" means filling the capacity v exactly).

For the i-th item:

  1. If we do not put the i-th item in, then dp[i][v]=dp[i-1][v]
  2. If we put the i-th item in, we transition to the state dp[i][v-w[i]]+c[i]; this is because each item can be placed any number of times, so after putting in the i-th item, we can still put in the i-th item again

The state transition equation is $$ \mathrm{dp[i][v]}=max{\mathrm{dp[i-1][v],dp[i][v-w[i]]+c[i]}} \ 1≤i≤n,w[i]≤v≤V \ 边界\ d[0][v]=0 $$ It can also be rewritten in one-dimensional form $$ \mathrm{dp[v]}=max{\mathrm{dp[v],dp[v-w[i]]+c[i]}} \ 1≤i≤n,w[i]≤v≤V \ 边界\ d[v]=0 $$ This is exactly the same as the 0-1 knapsack problem, with the only difference being that here v must be enumerated in the forward direction

Because dp[i][v] can directly overwrite dp[i-1][v]

11.8 Summary

The models covered so far are listed as follows:

  1. Maximum continuous subsequence sum

    Let dp[i] denote the maximum sum of a continuous sequence ending with a[i].

  2. Longest non-decreasing subsequence (LIS)

    Let dp[i] denote the length of the longest non-decreasing subsequence ending with a[i]

  3. Longest common subsequence (LCS)

    Let dp[i][j] denote the length of the LCS before position i of string a and position j of string b

  4. Longest palindromic substring

    Let bool dp[i][j] denote whether the substring represented by s[i] through s[j] is a palindromic substring

  5. Number tower DP

    Let dp[i][j] denote the maximum sum obtainable along all paths starting from the j-th number in the i-th row and reaching the bottom layer

  6. Longest path in a DAG

    Let dp[i] denote the length of the longest path obtainable starting from vertex i

  7. 0-1 knapsack

    Let dp[i][v] denote the maximum value obtainable by packing the first i items exactly into a knapsack of capacity v

  8. Complete knapsack

    Let dp[i][v] denote the maximum value obtainable by packing the first i items exactly into a knapsack of capacity v

Special note: In general, a "subsequence" need not be contiguous, while a "substring" must be contiguous.

When a problem involves a sequence or string (denoted a), consider designing the state in one of the following two forms, and then consider the state transition equation based on the characteristics of the endpoints.

  1. Let dp[i] denote the xxx ending (or starting) with a[i]
  2. Let dp[i][j] denote the xxx of the interval from a[i] to a[j]

In both cases, xxx is the description of the original problem.

When the problem in a question involves several dimensions, analyze how many dimensions are needed to represent the states in the problem, and then for each dimension adopt one of the following descriptions:

  1. Exactly i
  2. The first i

After the meaning of each dimension has been set, the meaning of the dp array can be set as "let the dp array denote the XXX that is exactly i (or the first i), exactly j (or the first j)......", where xxx is the description of the original problem. Next, consider the state transition equation based on the characteristics of the endpoints.


Study Notes on "Algorithm Notes"
https://blog.wendain.ing/en/posts/algorithm-note/
Author
wendaining
Posted on
November 2, 2024
Updated on
December 2, 2025
Licensed under