Number theory: judging prime numbers, pigeonhole theorem, drawer theory
Precautions:
Combined pruning: i < n - (k - path.size()) + 1
Add L after the number of long type
long s = 2658417853L;
Keep a few decimal places:
System.out.printf(“%.2f”, arg);
Rounding problem: For example, if you keep two decimal places, add 0.005 to the end of the number and then keep the decimal, so that there will be no truncation. .
BufferedReader and Scanner cannot be mixed
Integer converted to decimal: 1.0 * jigeSum
String is converted to an array of strings: S.toCharArray()
The range of long is 19 bits
Java XOR: ^
Chapter 2 Enumeration, Permutation and Combination
handwritten subset
import java.util.*;
import java.io.*;
public class Main {
static int[] arr = {
1,2,3,4,5,6,7};
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = arr.length;
for(int i = 1; i < (1 << n); i++) {
//i从1~2^n,每一个i代表一个集合
//内循环按为与,结果非0则输出集合元素,j是1左移次数
for(int j = 0; j < n; j++) {
if((i & (1 << j)) != 0) {
System.out.print(arr[j]+" ");
}
}
System.out.println();
}
}
}
Write the next permutation by hand:
Permutations
Combination: Use startIndex to record the starting number of each recursion. In the loop, i=startIndex
combination pruning: i < n - (k - path.size()) + 1.
Unrestricted selection of data without repeated combination: the next layer in the recursion startIndex=i
Repeat combination Unlimited selection of data: for loop cannot repeat, after sorting if(arr[i] == arr[i - 1]) continue;
Arrange directly i=0, but use an array to record whether the previous layer has been used
Ruler method
Application scenario: sliding window , [L, R], R increases as L increases
memory search
Application scenario: multiple queries,
multiple queries must be stored
Chapter 3 Recursion and Recursion
nothing
Chapter 4 Search
DFS and BFS
Chapter 5 Bisection and Union Check
binary search
Application scenario: maximizing the minimum value and minimizing the maximum value
must have monotonicity ! !
Template question: The final result takes the right
three places, which are particularly easy to remember:
1. Find whether the mid formula is +1 (this record is because the minimum < maximum, so find the minimum without adding, and find the maximum +1)
2. While loop with or without, etc. No. (Test this yourself, I really didn’t think of a good memory method)
3. Update whichever is high and left +1: This is easy to understand, whichever satisfies the condition = mid, which does not meet the condition +1
real dichotomy
Note that the end condition of the loop is that the distance between the left and right intervals is very small.
And lookup
1. Storage
2. Query
path compression: (recursive memoization)
3. Collection merging
Chapter 6 Greed
The choice must have no aftereffect, the current choice cannot affect the effect of the subsequent choice on the result
Interval Scheduling: Sort by end time, select the one that ends earlier
Interval Coverage: Sort by left endpoint, select the one that ends later
Note the familiarity with structure sorting:
Arrays.sort(goods, (Comparator<Goods>)(Goods x, Goods y) -> {
return -Double.compare(x.d, y.d);
});
Chapter 7 Dynamic Programming
Backpack
dp[i][j]: load the i-th item into a backpack with a weight of j, and the maximum value is dp[i][j] The traversal order is generally first the item and then the backpack 0-1
backpack
scrolling array Flashback to
multiple backpack scrolling arrays Positive sequence
The combination of multiple knapsack counting problems is the item first and then the knapsack (fill horizontally), and the arrangement is the knapsack first and then the item (fill vertically)
fast power
Chapter 8 Number Theory
fast power
The nature of the modulo operation: (a b) mod k = (a mod k) (b mod k) mod k
to find (b^p) mod k
First take the modulus of b to k
and decompose p into an exponent of 2, p to the right Cyclic shift and then 1 means multiplication by b
multiplication once modulo once
public static long mod(long a, long n, long k) {
// a^n mod k
a %= k;
long ans = 1; //最终结果
while(n != 0) {
if((n & 1) != 0) {
ans = (ans * a) % k;
}
a = (a * a) % k;
n = n >> 1;
}
return ans;
}
Java large number: BigInteger
greatest common divisor gcd
Roll and divide
LCM least common multiple
prime number judgment
prime number sieve
decompose prime factor
Graph Theory
Floyd's Algorithm: Find the shortest path between two adjacent points.
Judge negative circle: dp[i][i] < 0
dp[i][j] = Math.max(dp[i][j], dp[i][k]+dp[k][j])
Code issues that need attention:
- Use the adjacency matrix to save the graph, dp is the adjacency matrix
- The adjacency matrix needs to be initialized to INF
- The starting point of the graph is 1, so it is best to use 1 as the starting point of the array! !
- Don't forget that the input may have start=end! At this point the path is 0
Dijkstra's Algorithm: Find the shortest path from a point to all points
Can't handle negative weights, can't judge negative circles
SPFA: Find the shortest path from one point to all points
Judgment of negative circle: more than n rounds, the shortest path still changes
How much is the appropriate INF for the adjacency matrix initialization equal to INF?
dis[a,b] = dis[a,k] + dis[k,b]
INF = max/2
INF = -1 also works (best to use this)
Adjacency matrices cannot store multiple edges. If there are multiple edges, take the minimum value
Dijkstra: Can't handle negative weights
Java:
SPFA:
Java
to sort
import java.util.*;
import java.io.*;
public class 排序 {
public static void main(String[] args) {
Integer[] arr = {
23,1,14,56,33,7};
Comparator cmp = new myCompare();
Arrays.sort(arr, cmp);
for(Integer i : arr) {
System.out.println(i);
}
}
}
class myCompare implements Comparator<Integer> {
public int compare(Integer o1, Integer o2) {
return -Integer.compare(o1, o2);
}
}
Map<Long, Integer> map = new TreeMap<>(new Comparator<Long>() {
@Override
public int compare(Long o1, Long o2) {
return (int)(o1 - o2);
}
});
difference
When calculating the difference array, you need to add 0 in front of the original array, so as to find the first number of the score array
b[left] + value
b[right + 1] - value
Thinking questions:
1s can process 10^8 data
Java syntax
enter
Scanner input=new Scanner(System.in);
String str=input.next(); //String类型
int n=input.nextInt();//int类型
output
System.out.printf(“%d %d %d %d\n”, a, b, c, d);
Precautions
The output type should be consistent with its specified type. For example, if you want to output an integer, you cannot System.out.print(i+" ");
How to tell if a leap year
Years divisible by 4 but not by 100 or by 400
Difference: the left endpoint of the interval + value, the right endpoint of the interval - value
prefix sum and difference are reciprocal operations
The prefix sum and difference cannot be tested separately, it is only an acceleration algorithm tool
Look at the number of combinations
It is best to use a static array, defined outside the main
Use list for frequent traversal, and vector
mathematical formula for frequent get: radius, area
spfa floyd
Precautions