1、Dijkstra算法:
import javax.management.openmbean.TabularDataSupport;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import java.math.*;
public class Main
{
static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static math math_myself = new math();
static int INF = (int)1e9;
static int N = (int)2022;
static int g[][] = new int[N][N];
static int dist[] = new int[N]; // 存每个点到起点的距离
static boolean visited[] = new boolean[N]; // true表示i号点已经确定了最短距离,false表示没有确定
static int Dijkstra(int n)
{
Arrays.fill(dist,Integer.MAX_VALUE);
dist[1] = 0; // 1号点距离起点(1号点)的距离已经确定了
// n次循环,每次循环确定距离起点最短的点(有n个点所以要进行n次迭代)
for(int i = 1 ; i <= n ; i ++)
{
int t = -1; // 将t设置为-1,因为Dijkstra算法适用于不存在负权的图,t存的是当前访问的点
// 每次迭代的过程中,我们都先找到当前未确定的距离起点最短的点
for(int j = 1 ; j <= n ; j ++) // 这里的循环代表的是从1号点开始检索
{
if(!visited[j] && (t == -1 || dist[j] < dist[t])) t = j;
}
// 通过上述操作当前我们的t代表就是剩下未确定最短路的点中距离起点最短的点,与此同时,该点的最短路径也已经确定,我们将此点标记
visited[t] = true;
// 依次刚确定的点到它的相邻点的距离
for(int j = 1 ; j <= n ; j ++) dist[j] = Math.min(dist[j],dist[t] + g[t][j]);
}
if(dist[n] == Integer.MAX_VALUE) return -1;
return dist[n];
}
public static void main(String[] args) throws IOException
{
int n = 2021;
// 建立图
for(int i = 1 ; i <= n ; i ++)
{
for(int j = 1 ; j <= n ; j ++)
{
if(i == j) g[i][j] = 0;
else g[i][j] = Math.abs(i - j) > 21? INF: (int) math_myself.lcm(i, j);
}
}
pw.println(Dijkstra(2021));
pw.flush();
}
}
class rd
{
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
static String nextLine() throws IOException { return reader.readLine(); }
static String next() throws IOException
{
while(!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
static int nextInt() throws IOException { return Integer.parseInt(next()); }
static double nextDouble() throws IOException { return Double.parseDouble(next()); }
static long nextLong() throws IOException { return Long.parseLong(next()); }
static BigInteger nextBigInteger() throws IOException
{
BigInteger d = new BigInteger(rd.nextLine());
return d;
}
}
class PII
{
int x,y;
public PII(int x, int y)
{
this.x = x;
this.y = y;
}
}
class math
{
long gcd(long a,long b)
{
if(b == 0) return a;
else return gcd(b,a % b);
}
long lcm(long a,long b)
{
return a * b / gcd(a, b);
}
// 求n的所有约数
List get_factor(long n)
{
List<Long> a = new ArrayList<>();
for(long i = 1; i <= Math.sqrt(n) ; i ++)
{
if(n % i == 0)
{
a.add(i);
if(i != n / i) a.add(n / i); // 去重 // 避免一下的情况:x = 16时,i = 4 ,x / i = 4的情况,这样会加入两种情况 ^-^复杂度能减少多少是多少
}
}
// 对因子排序(升序)
Collections.sort(a);
return a;
}
}