forked from MiYazJE/Acepta-el-reto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp307.java
98 lines (69 loc) · 2.06 KB
/
p307.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.util.*;
/**
* @author Rubén Saiz
*/
class Graph {
HashMap<Integer, LinkedList<Integer>> adyacentList;
int size;
public Graph(int size) {
this.size = size;
adyacentList = new HashMap<>();
for (int i = 0; i < this.size; i++) {
adyacentList.put(i, new LinkedList<Integer>());
}
}
public void addPair(int A, int B) {
this.adyacentList.get(A).addLast(B);
this.adyacentList.get(B).addLast(A);
}
public boolean isCyclicConntected(int s, int V, boolean visited[]) {
int parent[] = new int[V];
Arrays.fill(parent, -1);
Queue<Integer> q = new LinkedList<>();
visited[s] = true;
q.add(s);
while (!q.isEmpty()) {
int u = q.poll();
for (Integer v : this.adyacentList.get(u)) {
if (!visited[v]) {
visited[v] = true;
q.add(v);
parent[v] = u;
} else if (parent[u] != v)
return true;
}
}
return false;
}
public void clear(int to) {
for (int i = 0; i < to; i++) {
this.adyacentList.get(i).clear();
}
}
}
public class p307 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int N, V;
Graph graph = new Graph(10_001);
boolean[] visited;
boolean connected;
while (s.hasNext()) {
N = s.nextInt();
V = s.nextInt();
for (int i = 0; i < V; i++)
graph.addPair(s.nextInt(), s.nextInt());
visited = new boolean[N];
if (!graph.isCyclicConntected(0, N, visited)) {
connected = true;
for (int i = 0; i < N && connected; i++)
connected = visited[i];
System.out.println( (connected) ? "SI" : "NO" );
}
else {
System.out.println("NO");
}
graph.clear(N);
}
}
}