Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.LinkedList;
- import java.util.Queue;
- import java.util.Scanner;
- class GRAPH {
- ArrayList<Integer> GR = new ArrayList<>();
- }
- public class BridgeNum {
- public static void DFS(GRAPH[] graph, int[] used, int[] par, Queue<Integer> queue, int a) {
- used[a] = 0;
- queue.add(a);
- for(int i = 0; i < graph[a].GR.size(); i++) {
- if(used[graph[a].GR.get(i)] == 1) {
- par[graph[a].GR.get(i)] = a;
- DFS(graph, used, par, queue, graph[a].GR.get(i));
- }
- }
- }
- public static int DFS2(GRAPH[] graph, int[] comp, int[] par, Queue<Integer> queue, int component) {
- while(queue.size() > 0) {
- int a = queue.remove();
- if(comp[a] == -1) {
- VisitVertex(graph, comp, par, a, component);
- component++;
- }
- }
- return component;
- }
- public static void VisitVertex(GRAPH[] graph, int[] comp, int[] par, int a, int component) {
- comp[a] = component;
- for(int i = 0; i < graph[a].GR.size(); i++) {
- if (comp[graph[a].GR.get(i)] == -1 && par[graph[a].GR.get(i)] != a)
- VisitVertex(graph, comp, par, graph[a].GR.get(i), component);
- }
- }
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n ,m;
- n = in.nextInt();
- int[] comp = new int[n];
- int[] par = new int[n];
- int[] used = new int[n];
- for(int i = 0; i < n; i++) {
- comp[i] = -1;
- par[i] = -1;
- used[i] = 1;
- }
- GRAPH[] G = new GRAPH[n];
- for(int i = 0; i < n; i++) {
- G[i] = new GRAPH();
- }
- m = in.nextInt();
- int u, v;
- for(int i = 0; i < m; i++) {
- u = in.nextInt();
- v = in.nextInt();
- G[v].GR.add(u);
- G[u].GR.add(v);
- }
- int component = 1;
- Queue<Integer> queue = new LinkedList<Integer>();
- for(int i = 0; i < n; i++) {
- if(used[i] == 1) {
- component--;
- DFS(G, used, par, queue, i);
- }
- component = DFS2(G, comp, par, queue, component);
- }
- System.out.println(component-1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement