-
Notifications
You must be signed in to change notification settings - Fork 0
/
20209.java
123 lines (88 loc) · 2.44 KB
/
20209.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.StringTokenizer;
public class Main {
static Map<Integer, int[]> map = new HashMap<>();
static Set<String> visited = new HashSet<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
int[] seq = new int[N + 1];
st = new StringTokenizer(br.readLine());
for (int i = 1; i <= N; i++) {
seq[i] = Integer.parseInt(st.nextToken());
}
for (int i = 0; i < K; i++) {
st = new StringTokenizer(br.readLine());
int size = Integer.parseInt(st.nextToken());
int[] index = new int[size];
for (int j = 0; j < size; j++) {
index[j] = Integer.parseInt(st.nextToken());
}
map.put(i + 1, index);
}
int answer = bfs(seq);
bw.write(answer+"\n");
bw.flush();
}
public static int bfs(int[] seq) {
Queue<int[]> queue = new LinkedList<>();
visited.add(getString(seq));
queue.add(seq);
int cnt = 0;
while (!queue.isEmpty()) {
Queue<int[]> temp = new LinkedList<>(queue);
queue.clear();
while (!temp.isEmpty()) {
int[] cur = temp.poll();
if (isAllSame(cur)) {
return cnt;
}
for(Map.Entry<Integer, int[]> entry : map.entrySet()) {
int[] add = entry.getValue();
int[] index = Arrays.copyOf(cur, cur.length);
for(int i=0;i<add.length;i++) {
index[add[i]] += entry.getKey();
index[add[i]] %= 5;
}
if(visited.contains(getString(index))) {
continue;
}
visited.add(getString(index));
queue.add(index);
}
}
cnt++;
}
return -1;
}
public static String getString(int[] seq) {
String str = "";
for (int num : seq) {
str += String.valueOf(num);
}
return str;
}
public static boolean isAllSame(int[] seq) {
int std = seq[1];
for (int i = 1; i < seq.length; i++) {
if (seq[i] != std) {
return false;
}
}
return true;
}
}