日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

图论算法(五)--求解割点、割边(JAVA)

發布時間:2025/3/15 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 图论算法(五)--求解割点、割边(JAVA) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

割點:對于一個連通圖來說,如果刪除某個點之后圖不再連通,這個點就稱為割點
割點算法
時間復雜度:O(N+M)
但是下面給出的算法時間復雜度為O(N^2),這是因為下面的存儲結構都是鄰接矩陣,這樣的話用該算法就完全失去了意義,畢竟如果使用鄰接矩陣完全可以通過刪除一個點,然后進行DFS/BFS遍歷即可了。所以在實際應用中還是要使用鄰接表來保存數據,這樣時間復雜度可以達到O(N+M)
Input:
6 7
1 4
1 3
4 2
3 2
2 5
2 6
5 6

Output:
2

import java.util.Scanner; public class cutPoint {static int n, m;static int[][] e = new int[9][9];static int[] num = new int[9];static int[] low = new int[9];static int[] flag = new int[9];static int index,root;static Scanner input = new Scanner(System.in);public static void main(String[] args) {n = input.nextInt();m = input.nextInt();for (int i = 1; i <= n; i++) {for (int j = 1; j <= n; j++) {e[i][j] = 0;}}for (int i = 1; i <= m; i++) {int x = input.nextInt();int y = input.nextInt();e[x][y] = 1;e[y][x] = 1;}root = 1;dfs(1, root);for (int i = 1; i <= n; i++) {if (flag[i] == 1) {System.out.print(i + " ");}}}private static void dfs(int cur, int father) {int child = 0;index++;num[cur] = index;low[cur] = index;for (int i = 1; i <= n; i++) {if (e[cur][i] == 1) {if (num[i] == 0) {child++;dfs(i, cur);low[cur] = Math.min(low[cur], low[i]);if (cur != root && low[i] >= num[cur]) {flag[cur] = 1;}if (cur == root && child == 2) {flag[cur] = 1;}} else if (i != father){low[cur] = Math.min(low[cur], num[i]);}}}} }

割邊:對于一個連通圖來說,如果刪除某個邊之后圖不再連通,這個點就稱為割邊
割邊算法
時間復雜度:O(N+M)
同割點算法一樣,在實際應用中還是要使用鄰接表來保存數據,這樣時間復雜度可以達到O(N+M)
Input:
6 7
1 4
1 3
4 2
3 2
2 5
2 6
5 6

Output:
5-6
2-5

import java.util.Scanner; public class cutEdge {static int n, m;static int[][] e = new int[9][9];static int[] num = new int[9];static int[] low = new int[9];static int index,root;static Scanner input = new Scanner(System.in);public static void main(String[] args) {n = input.nextInt();m = input.nextInt();for (int i = 1; i <= n; i++) {for (int j = 1; j <= n; j++) {e[i][j] = 0;}}for (int i = 1; i <= m; i++) {int x = input.nextInt();int y = input.nextInt();e[x][y] = 1;e[y][x] = 1;}root = 1;dfs(1, root);}private static void dfs(int cur, int father) {index++;num[cur] = index;low[cur] = index;for (int i = 1; i <= n; i++) {if (e[cur][i] == 1) {if (num[i] == 0) {dfs(i, cur);low[cur] = Math.min(low[i], low[cur]);if (low[i] > num[cur]) {System.out.println(cur + "-" + i);}} else if (i != father) {low[cur] = Math.min(low[cur], num[i]);}}}} }

總結

以上是生活随笔為你收集整理的图论算法(五)--求解割点、割边(JAVA)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。