Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class MaxComponent{
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n = in.nextInt(); // вершины
- int m = in.nextInt(); // ребра
- Graph g1 = new Graph(n);
- for (int i = 0; i < m; i++) {
- g1.addEdge(in.nextInt(), in.nextInt());
- }
- g1.findComps();
- System.out.println(g1);
- }
- private static class Graph{
- private int V;
- private Vector<Integer> adj[];
- private boolean[] used;
- private Vector<Integer> comp;
- private Vector<Integer> maxComp;
- public Graph(int v){
- V = v;
- adj = new Vector[V];
- used = new boolean[V];
- comp = new Vector<>();
- maxComp = new Vector<>();
- for (int i = 0; i < v; i++) {
- adj[i] = new Vector<>();
- }
- }
- public void addEdge(int u, int v){
- adj[u].add(v);
- //adj[v].add(u);
- }
- public void findComps(){
- for (int i = 0; i < V; i++) {
- used[i] = false;
- }
- for (int i = 0; i < V; i++) {
- if (!used[i]){
- comp.removeAllElements();
- DFS(i);
- if (comp.size() > maxComp.size()) {
- maxComp.removeAllElements();
- maxComp.addAll(comp);
- }
- }
- }
- }
- public void DFS(int v){
- used[v] = true;
- comp.add(v);
- for (int i = 0; i < adj[v].size(); i++) {
- int to = adj[v].get(i);
- if (!used[to]) DFS(to);
- }
- }
- public String toString(){
- StringBuilder res = new StringBuilder("graph {");
- for (int i = 0; i < V; i++) {
- res.append("\n ").append(i);
- if (maxComp.contains(i)) res.append(" [color = red]");
- }
- for (int i = 0; i < adj.length; i++) {
- if (!adj[i].isEmpty())
- for (int j = 0; j < adj[i].size(); j++) {
- res.append("\n ").append(i).append(" -- ").append(adj[i].get(j));
- if (maxComp.contains(i)) res.append(" [color = red]");
- }
- }
- res.append("\n}");
- return res.toString();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement