圖論與java_算法筆記_150:圖論之雙連通及橋的應用(Java)

1 問題描述

Description

In order to get from one of the F (1 <= F <= 5,000) grazing fields (which are numbered 1..F) to another field, Bessie and the rest of the herd are forced to cross near the Tree of Rotten Apples. The cows are now tired of often being forced to take a particular path and want to build some new paths so that they will always have a choice of at least two separate routes between any pair of fields. They currently have at least one route between each pair of fields and want to have at least two. Of course, they can only travel on Official Paths when they move from one field to another.

Given a description of the current set of R (F-1 <= R <= 10,000) paths that each connect exactly two different fields, determine the minimum number of new paths (each of which connects exactly two fields) that must be built so that there are at least two separate routes between any pair of fields. Routes are considered separate if they use none of the same paths, even if they visit the same intermediate field along the way.

There might already be more than one paths between the same pair of fields, and you may also build a new path that connects the same fields as some other path.

Input

Line 1: Two space-separated integers: F and R

Lines 2..R+1: Each line contains two space-separated integers which are the fields at the endpoints of some path.

Output

Line 1: A single integer that is the number of new paths that must be built.

Sample Input

7 7

1 2

2 3

3 4

2 5

4 5

5 6

5 7

Sample Output

2

Hint

Explanation of the sample:

One visualization of the paths is:

1 2 3

+---+---+

| |

| |

6 +---+---+ 4

/ 5

/

/

7 +

Building new paths from 1 to 6 and from 4 to 7 satisfies the conditions.

1 2 3

+---+---+

: | |

: | |

6 +---+---+ 4

/ 5 :

/ :

/ :

7 + - - - -

Check some of the routes:

1 – 2: 1 –> 2 and 1 –> 6 –> 5 –> 2

1 – 4: 1 –> 2 –> 3 –> 4 and 1 –> 6 –> 5 –> 4

3 – 7: 3 –> 4 –> 7 and 3 –> 2 –> 5 –> 7

Every pair of fields is, in fact, connected by two routes.

It's possible that adding some other path will also solve the problem (like one from 6 to 7). Adding two paths, however, is the minimum.

Source

2 解決方案

具體代碼如下:

packagecom.liuzhen.practice;importjava.util.ArrayList;importjava.util.Scanner;importjava.util.Stack;public classMain {public static int n; //給定圖的頂點數

public static int count; //記錄遍歷次序

public static int[] DFN;public static int[] Low;public static int[] parent; //parent[i] = j,表示頂點i的直接父母頂點為j

public static Stackstack;public static ArrayList[] map;public static ArrayList ans; //存儲給定圖中為橋的邊

static classedge {public int a; //邊的起點

public int b; //邊的終點

public boolean used; //表示邊是否已被訪問

public edge(int a, intb) {this.a =a;this.b =b;this.used = false;

}

}

@SuppressWarnings("unchecked")public voidinit() {

count= 0;

DFN= new int[n + 1];

Low= new int[n + 1];

parent= new int[n + 1];

stack= new Stack();

map= new ArrayList[n + 1];

ans= new ArrayList();for(int i = 1;i <= n;i++) {

DFN[i]= -1;

Low[i]= -1;

parent[i]= -1;

map[i]= new ArrayList();

}

}public void TarJan(int start, intfather) {

DFN[start]= count++;

Low[start]=DFN[start];

parent[start]=father;

stack.push(start);for(int i = 0;i < map[start].size();i++) {

edge temp=map[start].get(i);if(temp.used)continue;int t =temp.b;for(int p = 0;p < map[t].size();p++) {if(map[t].get(p).b ==temp.a) {

map[t].get(p).used= true;break;

}

}

temp.used= true;int j =temp.b;if(DFN[j] == -1) {

TarJan(j, start);

Low[start]=Math.min(Low[start], Low[j]);if(Low[j] > DFN[start]) //當邊temp為割邊(或者橋)時

ans.add(temp);

}else if(j != parent[start]) { //當j不是start的直接父母節點時

Low[start] =Math.min(Low[start], DFN[j]);

}

}

}public voidgetResult() {for(int i = 1;i <= n;i++) {if(parent[i] == -1)

TarJan(i,0);

}int[] degree = new int[n + 1];for(int i = 0;i < ans.size();i++) {int a =ans.get(i).a;int b =ans.get(i).b;

degree[a]++;

degree[b]++;

}int result = 0;for(int i = 1;i <= n;i++) {if(degree[i] == 1)

result++;

}

result= (result + 1) / 2;

System.out.println(result);return;

}public static voidmain(String[] args) {

Main test= newMain();

Scanner in= newScanner(System.in);

n=in.nextInt();int m =in.nextInt();

test.init();for(int i = 0;i < m;i++) {int a =in.nextInt();int b =in.nextInt();

map[a].add(newedge(a, b));

map[b].add(newedge(b, a));

}

test.getResult();

}

}

運行結果:

7 7

1 2

2 3

3 4

2 5

4 5

5 6

5 7

2

參考資料:

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/445794.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/445794.shtml
英文地址,請注明出處:http://en.pswp.cn/news/445794.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

如何用JUnit單元測試List

問題 JUnit測試List時差強人意。 解法 引入依賴 hamcrest-library包含許多有用方法來測試List數據類型。 <dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version>&l…

java數據包解析_請教http請求數據包如何解析 重組

該樓層疑似違規已被系統折疊 隱藏此樓查看此樓下面是我捕獲到的請求報文片段dst_ip:/121.52.228.134ack:trueack_num:3064957366date:POST /messagebroker/amf HTTP/1.1Host: s16.xxhzw.game.yy.comUser-Agent: Mozilla/5.0 (Windows NT 5.1; rv:13.0) Gecko/20100101 Firefox/…

webqq java_WebQQ登錄詳解

第二次登錄請求方式:POST地址:http://d.web2.qq.com/channel/login2POST正文:r%7B%22status%22%3A%22online%22%2C%22ptwebqq%22%3A%22{0}%22%2C%22passwd_sig%22%3A%22%22%2C%22clientid%22%3A%22{1}%22%2C%22  psessionid%22%3Anull%7D&clientid{2}&psessionidnull…

LeetCode - Easy - 155. Min Stack

Topic StackDesign Description https://leetcode.com/problems/min-stack/ Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) – Push element x onto stack.pop() – Removes the element on top of the st…

java judgefilecode_VScode出現無法打開“X”: 找不到文件(file:///XXXX) 的解決辦法

如標題&#xff0c;被這個問題整了好長時間了&#xff0c;調試的時候如果有語法錯誤只能顯示相應的的行數&#xff0c;沒有辦法定位到出錯的行數上。(由于用處不是很大并且沒有找到解決辦法&#xff0c;所以就一直放著沒管23333)直到最近看到一位大佬的解決辦(重寫正則表達式)法…

LeetCode - Easy - 169. Majority Element

Topic ArrayDivide and ConquerBit Manipulation Description https://leetcode.com/problems/majority-element/ Given an array of size n, find the majority element. The majority element is the element that appears more than ? n/2 ? times. You may assume t…

java 靜態方法 異常_java空指針異常與靜態方法

從一道經典面試題說起&#xff0c;public class HaHa {public static void haha(){System.out.println("haha");}public static void main(String[] args){((HaHa)null).haha();}}打印結果 haha。這段題考查兩點知識&#xff0c;java的空指針異常和靜態方法。1&#…

java中的asList_Java中的Arrays.asList()方法

Arrays.asList()返回一個List&#xff0c;但是這種情況下&#xff0c;其底層的實現是一個final數組&#xff0c;因此不能調整其尺寸如下代碼片段&#xff1a;package chapter11.t1;import java.util.*;public class AddingGroups {public static void main(String[] args) {Lis…

java控制面板作用_Java

1. JAVA 的特性和優勢(1) Java的核心優勢 跨平臺/可移植性(2) 其他特性 安全性&#xff1b;面對對象&#xff1b;簡單性&#xff1b;高性能&#xff1b;分布式&#xff1b;多線程&#xff1b;健壯性&#xff1b;① 強大的生態系統(3) Java與C的關系 Java是C的簡化版(C—)2. JAV…

java es 數據批量導入_ElasticSearch—Java批量導入導出

網上找了很多&#xff0c;我的es是2.3.5版本&#xff0c;網上的客戶端最少都是5.x版本&#xff0c;所以沒有能用的。自己整合了一下 2.3.5版本的。pom文件&#xff1a;org.elasticsearchelasticsearch2.3.5com.alibabafastjson1.1.35org.apache.commonscommons-io1.3.2org.apac…

java原始模型模式_java設計模式--原始模型模式

簡介原始模型模式屬于對象的創建模式。通過一個原型對象來指明要創建對象的類型&#xff0c;然后用復制原型對象的方法來創建出更多同類型的對象。Java所有的類都是從java.lang.Object類繼承來的&#xff0c;Object類提供clone()方法對對象進行復制。一般調用clone()方法需要滿…

Windows的命令行窗口運行Python時,如何清屏?

問題 如標題 解法 import os os.system("cls")參考 python實現清屏

手寫文字識別java_java 手寫文字圖片識別提取 百度API

package org.fh.util;import org.json.JSONObject;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.List;import java.util.Map;/*** 說明&#xff1a;獲取文字識別token類* from&am…

LeetCode - Easy - 191. Number of 1 Bits

Topic Bit Manipulation Description https://leetcode.com/problems/number-of-1-bits/ Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight). Note: Note that in some languages such …

java并行計算同步返回_Java大文本并行計算實現過程解析

Java大文本并行計算實現過程解析簡單提高文本讀取效率&#xff0c;使用BufferedReader是個不錯的選擇。速度最快的方法是MappedByteBuffer&#xff0c;但是&#xff0c;相比BufferedReader而言&#xff0c;效果不是非常明顯。也就是說&#xff0c;后者雖然快&#xff0c;但也快…

wgs utm java,Java,將經緯度轉換為UTM

Does anyone know of a way, in Java, to convert an earth surface position from lat, lon to UTM (say in WGS84)? Im currently looking at Geotools but unfortunately the solution is not obvious.解決方案I was able to use Geotools 2.4 to get something that works…

java 指定時間轉換_Java中使用Calendar進行獲取指定時間,使用SimpleDateFormat進行格式化轉換...

java中使用Calendar獲取指定的時間public class DateTranslate {/*** 獲取指定日期的間隔月份的第一天的日期* param date* param sep* return*/public static Date getMonthFirstDay(Date date, Integer sep) {Calendar cal Calendar.getInstance();cal.setTime(getThisWeekM…

java mvc 菜鳥_【java框架】SpringMVC(1)--SpringMVC入門

1.SpringMVC框架認識Spring MVC是一個基于MVC模式的Web框架&#xff0c;SpringMVC作為Spring中的一個模塊&#xff0c;它與Spring能夠無縫集成&#xff0c;主要用于解決企業Web開發中常見的問題&#xff1a;如參數接收、文件上傳、表單驗證、國際化等等。2.SpringMVC HelloWorl…

php設置cookie 域名,php如何設置cookie對整個域名有效?

php設置cookie對整個域名有效的方法&#xff1a;由setcookie函數讓cookie對整個域名有效&#xff0c;代碼為【setcookie("cookie_test", this is cookie test, time()3600,"/",“】。php設置cookie對整個域名有效的方法&#xff1a;默認情況下的cookie僅對…

php 配置 gd2,配置PHP對gd庫的支持

搭建zabbix的時候遇到有對PHP的需求檢測&#xff0c;發現沒有對gd的支持&#xff0c;記錄下。。。GD庫是php處理圖形的擴展庫&#xff0c;它提供了一系列用來處理圖片的API&#xff0c;使用GD庫可以處理圖片&#xff0c;或者生成圖片&#xff0c;也可以給圖片加水印。1、安裝zl…