File tree Expand file tree Collapse file tree 1 file changed +76
-0
lines changed
Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.io.* ;
3+ import java.util.* ;
4+
5+ public class Main {
6+
7+ static List<Integer > [] graph;
8+ static boolean [] visited;
9+ static boolean isgraph;
10+
11+ public static void main (String [] args ) throws Exception {
12+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
13+ StringBuilder sb = new StringBuilder ();
14+
15+ int T = Integer . parseInt(br. readLine());
16+
17+ for (int t= 0 ;t< T ;t++ ) {
18+ StringTokenizer st;
19+ int N = Integer . parseInt(br. readLine());
20+ int M = Integer . parseInt(br. readLine());
21+
22+ graph = new ArrayList [N + 1 ];
23+ visited = new boolean [N + 1 ];
24+ isgraph = false ;
25+
26+ for (int i = 1 ; i <= N ; i++ ) {
27+ graph[i] = new ArrayList<> ();
28+ }
29+
30+ for (int i = 0 ; i < M ; i++ ) {
31+ st = new StringTokenizer (br. readLine());
32+ int a = Integer . parseInt(st. nextToken());
33+ int b = Integer . parseInt(st. nextToken());
34+
35+ graph[a]. add(b);
36+ graph[b]. add(a);
37+ }
38+
39+ if (M != N - 1 ) {
40+ sb. append(" graph\n " );
41+ continue ;
42+ }
43+
44+ dfs(1 , - 1 );
45+
46+ boolean connected = true ;
47+ for (int i = 1 ; i <= N ; i++ ) {
48+ if (! visited[i]) {
49+ connected = false ;
50+ break ;
51+ }
52+ }
53+
54+ if (isgraph || ! connected) {
55+ sb. append(" graph\n " );
56+ } else {
57+ sb. append(" tree\n " );
58+ }
59+ }
60+
61+ System . out. print(sb);
62+ }
63+
64+ static void dfs (int cur , int parent ) {
65+ visited[cur] = true ;
66+
67+ for (int next : graph[cur]) {
68+ if (! visited[next]) {
69+ dfs(next, cur);
70+ } else if (next != parent) {
71+ isgraph = true ;
72+ }
73+ }
74+ }
75+ }
76+ ```
You can’t perform that action at this time.
0 commit comments