class059 建图、链式前向星、拓扑排序【算法】
  RPXY88prxrad 2023年12月19日 137 0


class059 建图、链式前向星、拓扑排序【算法】

class059 建图、链式前向星、拓扑排序【算法】_java

class059 建图、链式前向星、拓扑排序【算法】_java_02

code1 建图

package class059;

import java.util.ArrayList;
import java.util.Arrays;

public class Code01_CreateGraph {

	// 点的最大数量
	public static int MAXN = 11;

	// 边的最大数量
	// 只有链式前向星方式建图需要这个数量
	// 注意如果无向图的最大数量是m条边,数量要准备m*2
	// 因为一条无向边要加两条有向边
	public static int MAXM = 21;

	// 邻接矩阵方式建图
	public static int[][] graph1 = new int[MAXN][MAXN];

	// 邻接表方式建图
	// public static ArrayList<ArrayList<Integer>> graph2 = new ArrayList<>();
	public static ArrayList<ArrayList<int[]>> graph2 = new ArrayList<>();

	// 链式前向星方式建图
	public static int[] head = new int[MAXN];

	public static int[] next = new int[MAXM];

	public static int[] to = new int[MAXM];

	// 如果边有权重,那么需要这个数组
	public static int[] weight = new int[MAXM];

	public static int cnt;

	public static void build(int n) {
		// 邻接矩阵清空
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= n; j++) {
				graph1[i][j] = 0;
			}
		}
		// 邻接表清空和准备
		graph2.clear();
		// 下标需要支持1~n,所以加入n+1个列表,0下标准备但不用
		for (int i = 0; i <= n; i++) {
			graph2.add(new ArrayList<>());
		}
		// 链式前向星清空
		cnt = 1;
		Arrays.fill(head, 1, n + 1, 0);
	}

	// 链式前向星加边
	public static void addEdge(int u, int v, int w) {
		// u -> v , 边权重是w
		next[cnt] = head[u];
		to[cnt] = v;
		weight[cnt] = w;
		head[u] = cnt++;
	}

	// 三种方式建立有向图带权图
	public static void directGraph(int[][] edges) {
		// 邻接矩阵建图
		for (int[] edge : edges) {
			graph1[edge[0]][edge[1]] = edge[2];
		}
		// 邻接表建图
		for (int[] edge : edges) {
			// graph2.get(edge[0]).add(edge[1]);
			graph2.get(edge[0]).add(new int[] { edge[1], edge[2] });
		}
		// 链式前向星建图
		for (int[] edge : edges) {
			addEdge(edge[0], edge[1], edge[2]);
		}
	}

	// 三种方式建立无向图带权图
	public static void undirectGraph(int[][] edges) {
		// 邻接矩阵建图
		for (int[] edge : edges) {
			graph1[edge[0]][edge[1]] = edge[2];
			graph1[edge[1]][edge[0]] = edge[2];
		}
		// 邻接表建图
		for (int[] edge : edges) {
			// graph2.get(edge[0]).add(edge[1]);
			// graph2.get(edge[1]).add(edge[0]);
			graph2.get(edge[0]).add(new int[] { edge[1], edge[2] });
			graph2.get(edge[1]).add(new int[] { edge[0], edge[2] });
		}
		// 链式前向星建图
		for (int[] edge : edges) {
			addEdge(edge[0], edge[1], edge[2]);
			addEdge(edge[1], edge[0], edge[2]);
		}
	}

	public static void traversal(int n) {
		System.out.println("邻接矩阵遍历 :");
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= n; j++) {
				System.out.print(graph1[i][j] + " ");
			}
			System.out.println();
		}
		System.out.println("邻接表遍历 :");
		for (int i = 1; i <= n; i++) {
			System.out.print(i + "(邻居、边权) : ");
			for (int[] edge : graph2.get(i)) {
				System.out.print("(" + edge[0] + "," + edge[1] + ") ");
			}
			System.out.println();
		}
		System.out.println("链式前向星 :");
		for (int i = 1; i <= n; i++) {
			System.out.print(i + "(邻居、边权) : ");
			// 注意这个for循环,链式前向星的方式遍历
			for (int ei = head[i]; ei > 0; ei = next[ei]) {
				System.out.print("(" + to[ei] + "," + weight[ei] + ") ");
			}
			System.out.println();
		}
	}

	public static void main(String[] args) {
		// 理解了带权图的建立过程,也就理解了不带权图
		// 点的编号为1...n
		// 例子1自己画一下图,有向带权图,然后打印结果
		int n1 = 4;
		int[][] edges1 = { { 1, 3, 6 }, { 4, 3, 4 }, { 2, 4, 2 }, { 1, 2, 7 }, { 2, 3, 5 }, { 3, 1, 1 } };
		build(n1);
		directGraph(edges1);
		traversal(n1);
		System.out.println("==============================");
		// 例子2自己画一下图,无向带权图,然后打印结果
		int n2 = 5;
		int[][] edges2 = { { 3, 5, 4 }, { 4, 1, 1 }, { 3, 4, 2 }, { 5, 2, 4 }, { 2, 3, 7 }, { 1, 5, 5 }, { 4, 2, 6 } };
		build(n2);
		undirectGraph(edges2);
		traversal(n2);
	}

}

code2 210. 课程表 II

// 拓扑排序模版(Leetcode)
// 邻接表建图(动态方式)
// 课程表II
// 现在你总共有 numCourses 门课需要选,记为 0 到 numCourses - 1
// 给你一个数组 prerequisites ,其中 prerequisites[i] = [ai, bi]
// 表示在选修课程 ai 前 必须 先选修 bi
// 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示:[0,1]
// 返回你为了学完所有课程所安排的学习顺序。可能会有多个正确的顺序
// 你只要返回 任意一种 就可以了。如果不可能完成所有课程,返回 一个空数组
// 测试链接 : https://leetcode.cn/problems/course-schedule-ii/

入度删除法

package class059;

import java.util.ArrayList;

// 拓扑排序模版(Leetcode)
// 邻接表建图(动态方式)
// 课程表II
// 现在你总共有 numCourses 门课需要选,记为 0 到 numCourses - 1
// 给你一个数组 prerequisites ,其中 prerequisites[i] = [ai, bi]
// 表示在选修课程 ai 前 必须 先选修 bi
// 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示:[0,1]
// 返回你为了学完所有课程所安排的学习顺序。可能会有多个正确的顺序
// 你只要返回 任意一种 就可以了。如果不可能完成所有课程,返回 一个空数组
// 测试链接 : https://leetcode.cn/problems/course-schedule-ii/
public class Code02_TopoSortDynamicLeetcode {

	public static int[] findOrder(int numCourses, int[][] prerequisites) {
		ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
		// 0 ~ n-1
		for (int i = 0; i < numCourses; i++) {
			graph.add(new ArrayList<>());
		}
		// 入度表
		int[] indegree = new int[numCourses];
		for (int[] edge : prerequisites) {
			graph.get(edge[1]).add(edge[0]);
			indegree[edge[0]]++;
		}
		int[] queue = new int[numCourses];
		int l = 0;
		int r = 0;
		for (int i = 0; i < numCourses; i++) {
			if (indegree[i] == 0) {
				queue[r++] = i;
			}
		}
		int cnt = 0;
		while (l < r) {
			int cur = queue[l++];
			cnt++;
			for (int next : graph.get(cur)) {
				if (--indegree[next] == 0) {
					queue[r++] = next;
				}
			}
		}
		return cnt == numCourses ? queue : new int[0];
	}

}

code2 【模板】拓扑排序

// 拓扑排序模版(牛客)
// 邻接表建图(动态方式)
// 测试链接 : https://www.nowcoder.com/practice/88f7e156ca7d43a1a535f619cd3f495c
// 请同学们务必参考如下代码中关于输入、输出的处理
// 这是输入输出处理效率很高的写法
// 提交以下所有代码,把主类名改成Main,可以直接通过

package class059;

// 拓扑排序模版(牛客)
// 邻接表建图(动态方式)
// 测试链接 : https://www.nowcoder.com/practice/88f7e156ca7d43a1a535f619cd3f495c
// 请同学们务必参考如下代码中关于输入、输出的处理
// 这是输入输出处理效率很高的写法
// 提交以下所有代码,把主类名改成Main,可以直接通过

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Arrays;

public class Code02_TopoSortDynamicNowcoder {

	public static int MAXN = 200001;

	// 拓扑排序,用到队列
	public static int[] queue = new int[MAXN];

	public static int l, r;

	// 拓扑排序,入度表
	public static int[] indegree = new int[MAXN];

	// 收集拓扑排序的结果
	public static int[] ans = new int[MAXN];

	public static int n, m;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StreamTokenizer in = new StreamTokenizer(br);
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		while (in.nextToken() != StreamTokenizer.TT_EOF) {
			n = (int) in.nval;
			in.nextToken();
			m = (int) in.nval;
			// 动态建图,比赛肯定不行,但是一般大厂笔试、面试允许
			ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
			for (int i = 0; i <= n; i++) {
				graph.add(new ArrayList<>());
			}
			Arrays.fill(indegree, 0, n + 1, 0);
			for (int i = 0, from, to; i < m; i++) {
				in.nextToken();
				from = (int) in.nval;
				in.nextToken();
				to = (int) in.nval;
				graph.get(from).add(to);
				indegree[to]++;
			}
			if (!topoSort(graph)) {
				out.println(-1);
			} else {
				for (int i = 0; i < n - 1; i++) {
					out.print(ans[i] + " ");
				}
				out.println(ans[n - 1]);
			}
		}
		out.flush();
		out.close();
		br.close();
	}

	// 有拓扑排序返回true
	// 没有拓扑排序返回false
	public static boolean topoSort(ArrayList<ArrayList<Integer>> graph) {
		l = r = 0;
		for (int i = 1; i <= n; i++) {
			if (indegree[i] == 0) {
				queue[r++] = i;
			}
		}
		int fill = 0;
		while (l < r) {
			int cur = queue[l++];
			ans[fill++] = cur;
			for (int next : graph.get(cur)) {
				if (--indegree[next] == 0) {
					queue[r++] = next;
				}
			}
		}
		return fill == n;
	}

}

code2 【模板】拓扑排序

// 拓扑排序模版(牛客)
// 链式前向星建图(静态方式)
// 测试链接 : https://www.nowcoder.com/practice/88f7e156ca7d43a1a535f619cd3f495c
// 请同学们务必参考如下代码中关于输入、输出的处理
// 这是输入输出处理效率很高的写法
// 提交以下所有代码,把主类名改成Main,可以直接通过

package class059;

// 拓扑排序模版(牛客)
// 链式前向星建图(静态方式)
// 测试链接 : https://www.nowcoder.com/practice/88f7e156ca7d43a1a535f619cd3f495c
// 请同学们务必参考如下代码中关于输入、输出的处理
// 这是输入输出处理效率很高的写法
// 提交以下所有代码,把主类名改成Main,可以直接通过

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;

public class Code02_TopoSortStaticNowcoder {

	public static int MAXN = 200001;

	public static int MAXM = 200001;

	// 建图相关,链式前向星
	public static int[] head = new int[MAXN];

	public static int[] next = new int[MAXM];

	public static int[] to = new int[MAXM];

	public static int cnt;

	// 拓扑排序,用到队列
	public static int[] queue = new int[MAXN];

	public static int l, r;

	// 拓扑排序,入度表
	public static int[] indegree = new int[MAXN];

	// 收集拓扑排序的结果
	public static int[] ans = new int[MAXN];

	public static int n, m;

	public static void build(int n) {
		cnt = 1;
		Arrays.fill(head, 0, n + 1, 0);
		Arrays.fill(indegree, 0, n + 1, 0);
	}

	// 用链式前向星建图
	public static void addEdge(int f, int t) {
		next[cnt] = head[f];
		to[cnt] = t;
		head[f] = cnt++;
	}

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StreamTokenizer in = new StreamTokenizer(br);
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		while (in.nextToken() != StreamTokenizer.TT_EOF) {
			n = (int) in.nval;
			in.nextToken();
			m = (int) in.nval;
			build(n);
			for (int i = 0, from, to; i < m; i++) {
				in.nextToken();
				from = (int) in.nval;
				in.nextToken();
				to = (int) in.nval;
				addEdge(from, to);
				indegree[to]++;
			}
			if (!topoSort()) {
				out.println(-1);
			} else {
				for (int i = 0; i < n - 1; i++) {
					out.print(ans[i] + " ");
				}
				out.println(ans[n - 1]);
			}
		}
		out.flush();
		out.close();
		br.close();
	}

	public static boolean topoSort() {
		l = r = 0;
		for (int i = 1; i <= n; i++) {
			if (indegree[i] == 0) {
				queue[r++] = i;
			}
		}
		int fill = 0;
		while (l < r) {
			int cur = queue[l++];
			ans[fill++] = cur;
			// 用链式前向星的方式,遍历cur的相邻节点
			for (int ei = head[cur]; ei != 0; ei = next[ei]) {
				if (--indegree[to[ei]] == 0) {
					queue[r++] = to[ei];
				}
			}
		}
		return fill == n;
	}

}

code3 U107394 拓扑排序模板

// 字典序最小的拓扑排序
// 要求返回所有正确的拓扑排序中 字典序最小 的结果
// 建图请使用链式前向星方式,因为比赛平台用其他建图方式会卡空间
// 测试链接 : https://www.luogu.com.cn/problem/U107394
// 请同学们务必参考如下代码中关于输入、输出的处理
// 这是输入输出处理效率很高的写法
// 提交以下所有代码,把主类名改成Main,可以直接通过

code4 269.火星词典

// 火星词典
// 现有一种使用英语字母的火星语言
// 这门语言的字母顺序对你来说是未知的。
// 给你一个来自这种外星语言字典的字符串列表 words
// words 中的字符串已经 按这门新语言的字母顺序进行了排序 。
// 如果这种说法是错误的,并且给出的 words 不能对应任何字母的顺序,则返回 “”
// 否则,返回一个按新语言规则的 字典递增顺序 排序的独特字符串
// 如果有多个解决方案,则返回其中任意一个
// words中的单词一定都是小写英文字母组成的
// 测试链接 : https://leetcode.cn/problems/alien-dictionary/

题目:
269.火星词典 Plus
困难

现有一种使用英语字母的火星语言,这门语言的字母顺序对你来说是未知的。
给你一个来自这种外星语言字典的字符串列表wordswords 中的字符串已经 按这门新语言的字母顺序进行了排序

如果这种说法是错误的,并且给出的 words 不能对应任何字母的顺序,则返回"" 否则,返回一个按新语言规则的 字典递增顺序排序的独特字符串。如果有多个解决方案,则返回其中 任意一个

示例 1:
输入:words=
[“wrt”,“wrf”,“er”,“ett”,“rftt”]
输出:“wertf"
示例2:
输入:words =[“z”,“x”]
输出:“zx"
示例3:
输入:words =[“z”,“x”,“z”]
输出:"
解释:不存在合法字母顺序,因此返回

package class059;

import java.util.ArrayList;
import java.util.Arrays;

// 火星词典
// 现有一种使用英语字母的火星语言
// 这门语言的字母顺序对你来说是未知的。
// 给你一个来自这种外星语言字典的字符串列表 words
// words 中的字符串已经 按这门新语言的字母顺序进行了排序 。
// 如果这种说法是错误的,并且给出的 words 不能对应任何字母的顺序,则返回 ""
// 否则,返回一个按新语言规则的 字典递增顺序 排序的独特字符串
// 如果有多个解决方案,则返回其中任意一个
// words中的单词一定都是小写英文字母组成的
// 测试链接 : https://leetcode.cn/problems/alien-dictionary/
public class Code04_AlienDictionary {

	public static String alienOrder(String[] words) {
		// 入度表,26种字符
		int[] indegree = new int[26];
		Arrays.fill(indegree, -1);
		for (String w : words) {
			for (int i = 0; i < w.length(); i++) {
				indegree[w.charAt(i) - 'a'] = 0;
			}
		}
		// 'a' -> 0
		// 'b' -> 1
		// 'z' -> 25
		// x -> x - 'a'
		ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
		for (int i = 0; i < 26; i++) {
			graph.add(new ArrayList<>());
		}
		for (int i = 0, j, len; i < words.length - 1; i++) {
			String cur = words[i];
			String next = words[i + 1];
			j = 0;
			len = Math.min(cur.length(), next.length());
			for (; j < len; j++) {
				if (cur.charAt(j) != next.charAt(j)) {
					graph.get(cur.charAt(j) - 'a').add(next.charAt(j) - 'a');
					indegree[next.charAt(j) - 'a']++;
					break;
				}
			}
			if (j < cur.length() && j == next.length()) {
				return "";
			}
		}
		int[] queue = new int[26];
		int l = 0, r = 0;
		int kinds = 0;
		for (int i = 0; i < 26; i++) {
			if (indegree[i] != -1) {
				kinds++;
			}
			if (indegree[i] == 0) {
				queue[r++] = i;
			}
		}
		StringBuilder ans = new StringBuilder();
		while (l < r) {
			int cur = queue[l++];
			ans.append((char) (cur + 'a'));
			for (int next : graph.get(cur)) {
				if (--indegree[next] == 0) {
					queue[r++] = next;
				}
			}
		}
		return ans.length() == kinds ? ans.toString() : "";
	}

}

code5 936. 戳印序列

// 戳印序列
// 你想最终得到"abcbc",认为初始序列为"???“。印章是"abc”
// 那么可以先用印章盖出"??abc"的状态,
// 然后用印章最左字符和序列的0位置对齐,就盖出了"abcbc"
// 这个过程中,"??abc"中的a字符,被印章中的c字符覆盖了
// 每次盖章的时候,印章必须完全盖在序列内
// 给定一个字符串target是最终的目标,长度为n,认为初始序列为n个’?’
// 给定一个印章字符串stamp,目标是最终盖出target
// 但是印章的使用次数必须在10n次以内
// 返回一个数组,该数组由每个回合中被印下的最左边字母的索引组成
// 上面的例子返回[2,0],表示印章最左字符依次和序列2位置、序列0位置对齐盖下去,就得到了target
// 如果不能在10
n次内印出序列,就返回一个空数组
// 测试链接 : https://leetcode.cn/problems/stamping-the-sequence/

package class059;

import java.util.ArrayList;
import java.util.Arrays;

// 戳印序列
// 你想最终得到"abcbc",认为初始序列为"?????"。印章是"abc"
// 那么可以先用印章盖出"??abc"的状态,
// 然后用印章最左字符和序列的0位置对齐,就盖出了"abcbc"
// 这个过程中,"??abc"中的a字符,被印章中的c字符覆盖了
// 每次盖章的时候,印章必须完全盖在序列内
// 给定一个字符串target是最终的目标,长度为n,认为初始序列为n个'?'
// 给定一个印章字符串stamp,目标是最终盖出target
// 但是印章的使用次数必须在10*n次以内
// 返回一个数组,该数组由每个回合中被印下的最左边字母的索引组成
// 上面的例子返回[2,0],表示印章最左字符依次和序列2位置、序列0位置对齐盖下去,就得到了target
// 如果不能在10*n次内印出序列,就返回一个空数组
// 测试链接 : https://leetcode.cn/problems/stamping-the-sequence/
public class Code05_StampingTheSequence {

	public static int[] movesToStamp(String stamp, String target) {
		char[] s = stamp.toCharArray();
		char[] t = target.toCharArray();
		int m = s.length;
		int n = t.length;
		int[] indegree = new int[n - m + 1];
		Arrays.fill(indegree, m);
		ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
		for (int i = 0; i < n; i++) {
			graph.add(new ArrayList<>());
		}
		int[] queue = new int[n - m + 1];
		int l = 0, r = 0;
		// O(n*m)
		for (int i = 0; i <= n - m; i++) {
			// i开头....(m个)
			// i+0 i+1 i+m-1
			for (int j = 0; j < m; j++) {
				if (t[i + j] == s[j]) {
					if (--indegree[i] == 0) {
						queue[r++] = i;
					}
				} else {
					// i + j 
					// from : 错误的位置
					// to : i开头的下标
					graph.get(i + j).add(i);
				}
			}
		}
		// 同一个位置取消错误不要重复统计
		boolean[] visited = new boolean[n];
		int[] path = new int[n - m + 1];
		int size = 0;
		while (l < r) {
			int cur = queue[l++];
			path[size++] = cur;
			for (int i = 0; i < m; i++) {
				// cur : 开头位置
				// cur + 0 cur + 1 cur + 2 ... cur + m - 1
				if (!visited[cur + i]) {
					visited[cur + i] = true;
					for (int next : graph.get(cur + i)) {
						if (--indegree[next] == 0) {
							queue[r++] = next;
						}
					}
				}
			}
		}
		if (size != n - m + 1) {
			return new int[0];
		}
		// path逆序调整
		for (int i = 0, j = size - 1; i < j; i++, j--) {
			int tmp = path[i];
			path[i] = path[j];
			path[j] = tmp;
		}
		return path;
	}

}

2023-12-7 22:08:59


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月19日 0

暂无评论

推荐阅读
RPXY88prxrad