id
stringlengths
22
25
content
stringlengths
327
628k
max_stars_repo_path
stringlengths
49
49
condefects-java_data_401
// "static void main" must be defined in a public class. import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] inDegree = new int[n + 1]; for(int i = 0; i < m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); inDegree[b]++; } // System.out.println(Arrays.toString(inDegree)); int ans = -1; for(int i = 1; i < n; i++) { if(inDegree[i] == 0) { if(ans == -1) { ans = i; }else { ans = -1; break; } } } System.out.println(ans); } } // "static void main" must be defined in a public class. import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] inDegree = new int[n + 1]; for(int i = 0; i < m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); inDegree[b]++; } // System.out.println(Arrays.toString(inDegree)); int ans = -1; for(int i = 1; i <= n; i++) { if(inDegree[i] == 0) { if(ans == -1) { ans = i; }else { ans = -1; break; } } } System.out.println(ans); } }
ConDefects/ConDefects/Code/abc313_b/Java/44406546
condefects-java_data_402
import com.sun.source.tree.Tree; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static int maxDist = 0; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); Set<Integer> set = new HashSet<>(); for (int i = 1; i < n; i++) { set.add(i); } for (int i = 0; i < m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); set.remove(b); } if (set.size() != 1) { System.out.println(-1); } else { System.out.println(set.iterator().next()); } // // } } import com.sun.source.tree.Tree; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static int maxDist = 0; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); Set<Integer> set = new HashSet<>(); for (int i = 1; i <= n; i++) { set.add(i); } for (int i = 0; i < m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); set.remove(b); } if (set.size() != 1) { System.out.println(-1); } else { System.out.println(set.iterator().next()); } // // } }
ConDefects/ConDefects/Code/abc313_b/Java/46002395
condefects-java_data_403
import java.util.*; public class Main { public static final int MOD998 = 998244353; public static final int MOD100 = 1000000007; public static void main(String[] args) throws Exception { ContestScanner sc = new ContestScanner(); ContestPrinter cp = new ContestPrinter(); int N = sc.nextInt(); long[][] poly = sc.nextLongMatrix(N, 2); int M = sc.nextInt(); long[][] shift = sc.nextLongMatrix(M, 2); int Q = sc.nextInt(); long[][] query = sc.nextLongMatrix(Q, 2); long[][] edge = new long[N][2]; for (int n = 0; n < N - 1; n++) { edge[n][0] = poly[n + 1][0] - poly[n][0]; edge[n][1] = poly[n + 1][1] - poly[n][1]; } long[] maxvalue = new long[N]; Arrays.fill(maxvalue, Long.MIN_VALUE); for (long[] sh : shift) { for (int n = 0; n < N; n++) { maxvalue[n] = Math.max(maxvalue[n], -((long) poly[n][0] + sh[0]) * edge[n][1] + ((long) poly[n][1] + sh[1]) * edge[n][0]); } } for (long[] q : query) { boolean ok = true; for (int n = 0; n < N; n++) { if (-(long) q[0] * edge[n][1] + (long) q[1] * edge[n][0] < maxvalue[n]) { ok = false; } } cp.println(ok ? "Yes" : "No"); } cp.close(); } ////////////////// // My Library // ////////////////// public static class SlopeTrick { private PriorityQueue<Long> lq = new PriorityQueue<>(Comparator.reverseOrder()); private PriorityQueue<Long> rq = new PriorityQueue<>(); private long lshift = 0; private long rshift = 0; private long min = 0; public long getMin() { return min; } public long get(long x) { long val = min; for (long l : lq) { if (l - x > 0) { val += l - x; } } for (long r : rq) { if (x - r > 0) { val += x - r; } } return val; } public long getMinPosLeft() { return lq.isEmpty() ? Long.MIN_VALUE : lq.peek() + lshift; } public long getMinPosRight() { return rq.isEmpty() ? Long.MAX_VALUE : rq.peek() + rshift; } public void addConst(long a) { min += a; } public void addSlopeRight(long a) { if (!lq.isEmpty() && lq.peek() + lshift > a) { min += lq.peek() + lshift - a; lq.add(a - lshift); rq.add(lq.poll() + lshift - rshift); } else { rq.add(a - rshift); } } public void addSlopeLeft(long a) { if (!rq.isEmpty() && rq.peek() < a) { min += a - rq.peek() - rshift; rq.add(a - rshift); lq.add(rq.poll() + rshift - lshift); } else { lq.add(a - lshift); } } public void addAbs(long a) { addSlopeLeft(a); addSlopeRight(a); } public void shift(long a) { lshift += a; rshift += a; } public void slideLeft(long a) { lshift += a; } public void slideRight(long a) { rshift += a; } public void clearLeft() { lq.clear(); } public void clearRight() { rq.clear(); } public void clearMin() { min = 0; } } public static int zeroOneBFS(int[][][] weighted_graph, int start, int goal) { int[] dist = new int[weighted_graph.length]; Arrays.fill(dist, Integer.MAX_VALUE); dist[start] = 0; LinkedList<Integer> queue = new LinkedList<>(); queue.add(start); while (!queue.isEmpty()) { int now = queue.poll(); if (now == goal) { return dist[goal]; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; if (info[1] == 0) { queue.addFirst(info[0]); } else { queue.addLast(info[0]); } } } } return -1; } public static int[] zeroOneBFSAll(int[][][] weighted_graph, int start) { int[] dist = new int[weighted_graph.length]; Arrays.fill(dist, Integer.MAX_VALUE); dist[start] = 0; LinkedList<Integer> queue = new LinkedList<>(); queue.add(start); while (!queue.isEmpty()) { int now = queue.poll(); for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; if (info[1] == 0) { queue.addFirst(info[0]); } else { queue.addLast(info[0]); } } } } return dist; } public static long dijkstra(int[][][] weighted_graph, int start, int goal) { long[] dist = new long[weighted_graph.length]; Arrays.fill(dist, 0, dist.length, Long.MAX_VALUE); dist[start] = 0; PriorityQueue<Pair<Integer, Long>> unsettled = new PriorityQueue<>((u, v) -> (int) (u.cdr - v.cdr)); unsettled.offer(new Pair<Integer, Long>(start, 0L)); while (!unsettled.isEmpty()) { Pair<Integer, Long> pair = unsettled.poll(); int now = pair.car; if (now == goal) { return dist[goal]; } if (dist[now] < pair.cdr) { continue; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; unsettled.offer(new Pair<Integer, Long>(info[0], dist[info[0]])); } } } return -1; } public static long[] dijkstraAll(int[][][] weighted_graph, int start) { long[] dist = new long[weighted_graph.length]; Arrays.fill(dist, 0, dist.length, Long.MAX_VALUE); dist[start] = 0; PriorityQueue<Pair<Integer, Long>> unsettled = new PriorityQueue<>((u, v) -> (int) (u.cdr - v.cdr)); unsettled.offer(new Pair<Integer, Long>(start, 0L)); while (!unsettled.isEmpty()) { Pair<Integer, Long> pair = unsettled.poll(); int now = pair.car; if (dist[now] < pair.cdr) { continue; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; unsettled.offer(new Pair<Integer, Long>(info[0], dist[info[0]])); } } } return dist; } public static long countLatticePoint(int[] p1, int[] p2, boolean include_end) { long difx = p2[0] - p1[0]; long dify = p2[1] - p1[1]; if (difx == 0 && dify == 0) { return include_end ? 1 : 0; } if (difx == 0 || dify == 0) { return Math.abs(difx + dify) + (include_end ? 1 : -1); } return MathLib.gcd(difx, dify) + (include_end ? 1 : -1); } public static long countLatticePoint(long[] p1, long[] p2, boolean include_end) { long difx = p2[0] - p1[0]; long dify = p2[1] - p1[1]; if (difx == 0 && dify == 0) { return include_end ? 1 : 0; } if (difx == 0 || dify == 0) { return Math.abs(difx + dify) + (include_end ? 1 : -1); } return MathLib.gcd(difx, dify) + (include_end ? 1 : -1); } // Don't contain same points! public static long countLatticePoint(int[] p1, int[] p2, int[] p3, boolean include_edge) { int[][] arr = new int[][] { p1, p2, p3 }; Arrays.sort(arr, Comparator.comparingInt(p -> ((int[]) p)[0]).thenComparingInt(p -> ((int[]) p)[1])); if ((p2[0] - p1[0]) * (long) (p3[1] - p2[1]) == (p2[1] - p1[1]) * (long) (p3[0] - p2[0])) { return countLatticePoint(arr[0], arr[2], true) - (include_edge ? 0 : 3); } long b = countLatticePoint(p1, p2, true) + countLatticePoint(p2, p3, true) + countLatticePoint(p3, p1, true) - 3; long i = (getAreaTriangle(p1, p2, p3) - b) / 2 + 1; return include_edge ? i + b : i; } public static long getAreaTriangle(int[] p1, int[] p2, int[] p3) { int x1 = p2[0] - p1[0]; int x2 = p3[0] - p2[0]; int y1 = p2[1] - p1[1]; int y2 = p3[1] - p2[1]; return Math.abs((long) x1 * y2 - (long) x2 * y1); } // Don't contain same points! public static long countLatticePointConvex(int[][] points, boolean include_edge) { if (points.length == 1) { return include_edge ? 1 : 0; } if (points.length == 2) { return countLatticePoint(points[0], points[1], include_edge); } long s = 0; for (int n = 1; n < points.length - 1; n++) { s += getAreaTriangle(points[0], points[n], points[n + 1]); } long b = countLatticePoint(points[points.length - 1], points[0], true) - points.length; for (int n = 0; n < points.length - 1; n++) { b += countLatticePoint(points[n], points[n + 1], true); } long i = (s - b) / 2 + 1; return include_edge ? i + b : i; } public static class RationalAngle implements Comparable<RationalAngle> { public long x; public long y; public static boolean include_pi_to_minus = true; public RationalAngle(long x, long y) { if (x == 0) { this.x = x; if (y == 0) { throw new UnsupportedOperationException("Angle to (0, 0) is invalid."); } else { this.y = y > 0 ? 1 : -1; } } else if (y == 0) { this.x = x > 0 ? 1 : -1; this.y = 0; } else { long gcd = MathLib.gcd(x, y); this.x = x / gcd; this.y = y / gcd; } } public RationalAngle copy() { return new RationalAngle(x, y); } public RationalAngle add(RationalAngle a) { RationalAngle res = copy(); res.addArg(a); return res; } public void addArg(RationalAngle a) { long nx = x * a.x - y * a.y; long ny = y * a.x + x * a.y; x = nx; y = ny; } public RationalAngle sub(RationalAngle a) { RationalAngle res = copy(); res.subArg(a); return res; } public void subArg(RationalAngle a) { long nx = x * a.x + y * a.y; long ny = y * a.x - x * a.y; x = nx; y = ny; } public boolean equals(RationalAngle a) { return x == a.x && y == a.y; } public boolean parallel(RationalAngle a) { return x == a.x && y == a.y || x == -a.x && y == -a.y; } public int rotDirection(RationalAngle trg) { if (parallel(trg)) { return 0; } else if (trg.sub(this).y > 0) { return 1; } else { return -1; } } public RationalAngle minus() { return new RationalAngle(x, -y); } public RationalAngle rev() { return new RationalAngle(-x, -y); } public double toRadian() { return Math.atan2(y, x); } private int toQuad() { if (x == 0) { if (y > 0) { return 2; } else { return -2; } } else if (x > 0) { if (y == 0) { return 0; } else if (y > 0) { return 1; } else { return -1; } } else { if (y == 0) { return include_pi_to_minus ? -4 : 4; } else if (y > 0) { return 3; } else { return -3; } } } @Override public int compareTo(RationalAngle ra) { if (ra == null) { throw new NullPointerException(); } int me = toQuad(); int you = ra.toQuad(); if (me > you) { return 1; } else if (me < you) { return -1; } long sub = sub(ra).y; if (sub == 0) { return 0; } else if (sub > 0) { return 1; } else { return -1; } } } public static class Pair<A, B> { public final A car; public final B cdr; public Pair(A car_, B cdr_) { car = car_; cdr = cdr_; } private static boolean eq(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } private static int hc(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair<?, ?> rhs = (Pair<?, ?>) o; return eq(car, rhs.car) && eq(cdr, rhs.cdr); } @Override public int hashCode() { return hc(car) ^ hc(cdr); } } public static class Tuple1<A> extends Pair<A, Object> { public Tuple1(A a) { super(a, null); } } public static class Tuple2<A, B> extends Pair<A, Tuple1<B>> { public Tuple2(A a, B b) { super(a, new Tuple1<>(b)); } } public static class Tuple3<A, B, C> extends Pair<A, Tuple2<B, C>> { public Tuple3(A a, B b, C c) { super(a, new Tuple2<>(b, c)); } } public static class Tuple4<A, B, C, D> extends Pair<A, Tuple3<B, C, D>> { public Tuple4(A a, B b, C c, D d) { super(a, new Tuple3<>(b, c, d)); } } public static class Tuple5<A, B, C, D, E> extends Pair<A, Tuple4<B, C, D, E>> { public Tuple5(A a, B b, C c, D d, E e) { super(a, new Tuple4<>(b, c, d, e)); } } public static class PriorityQueueLogTime<T> { private PriorityQueue<T> queue; private Multiset<T> total; private int size = 0; public PriorityQueueLogTime() { queue = new PriorityQueue<>(); total = new Multiset<>(); } public PriorityQueueLogTime(Comparator<T> c) { queue = new PriorityQueue<>(c); total = new Multiset<>(); } public void clear() { queue.clear(); total.clear(); size = 0; } public boolean contains(T e) { return total.count(e) > 0; } public boolean isEmpty() { return size == 0; } public boolean offer(T e) { total.addOne(e); size++; return queue.offer(e); } public T peek() { if (total.isEmpty()) { return null; } simplify(); return queue.peek(); } public T poll() { if (total.isEmpty()) { return null; } simplify(); size--; T res = queue.poll(); total.removeOne(res); return res; } public void remove(T e) { total.removeOne(e); size--; } public int size() { return size; } private void simplify() { while (total.count(queue.peek()) == 0) { queue.poll(); } } } static int[][] scanGraphOneIndexed(ContestScanner sc, int node, int edge, boolean undirected) { int[][] arr = sc.nextIntArrayMulti(edge, 2); for (int n = 0; n < edge; n++) { arr[0][n]--; arr[1][n]--; } return GraphBuilder.makeGraph(node, edge, arr[0], arr[1], undirected); } static int[][][] scanWeightedGraphOneIndexed(ContestScanner sc, int node, int edge, boolean undirected) { int[][] arr = sc.nextIntArrayMulti(edge, 3); for (int n = 0; n < edge; n++) { arr[0][n]--; arr[1][n]--; } return GraphBuilder.makeGraphWithWeight(node, edge, arr[0], arr[1], arr[2], undirected); } static class EdgeData { private int capacity; private int[] from, to, weight; private int p = 0; private boolean weighted; public EdgeData(boolean weighted) { this(weighted, 500000); } public EdgeData(boolean weighted, int initial_capacity) { capacity = initial_capacity; from = new int[capacity]; to = new int[capacity]; weight = new int[capacity]; this.weighted = weighted; } public void addEdge(int u, int v) { if (weighted) { System.err.println("The graph is weighted!"); return; } if (p == capacity) { int[] newfrom = new int[capacity * 2]; int[] newto = new int[capacity * 2]; System.arraycopy(from, 0, newfrom, 0, capacity); System.arraycopy(to, 0, newto, 0, capacity); capacity *= 2; from = newfrom; to = newto; } from[p] = u; to[p] = v; p++; } public void addEdge(int u, int v, int w) { if (!weighted) { System.err.println("The graph is NOT weighted!"); return; } if (p == capacity) { int[] newfrom = new int[capacity * 2]; int[] newto = new int[capacity * 2]; int[] newweight = new int[capacity * 2]; System.arraycopy(from, 0, newfrom, 0, capacity); System.arraycopy(to, 0, newto, 0, capacity); System.arraycopy(weight, 0, newweight, 0, capacity); capacity *= 2; from = newfrom; to = newto; weight = newweight; } from[p] = u; to[p] = v; weight[p] = w; p++; } public int[] getFrom() { int[] result = new int[p]; System.arraycopy(from, 0, result, 0, p); return result; } public int[] getTo() { int[] result = new int[p]; System.arraycopy(to, 0, result, 0, p); return result; } public int[] getWeight() { int[] result = new int[p]; System.arraycopy(weight, 0, result, 0, p); return result; } public int size() { return p; } } //////////////////////////////// // Atcoder Library for Java // //////////////////////////////// static class MathLib { private static long safe_mod(long x, long m) { x %= m; if (x < 0) x += m; return x; } private static long[] inv_gcd(long a, long b) { a = safe_mod(a, b); if (a == 0) return new long[] { b, 0 }; long s = b, t = a; long m0 = 0, m1 = 1; while (t > 0) { long u = s / t; s -= t * u; m0 -= m1 * u; long tmp = s; s = t; t = tmp; tmp = m0; m0 = m1; m1 = tmp; } if (m0 < 0) m0 += b / s; return new long[] { s, m0 }; } public static long gcd(long a, long b) { a = java.lang.Math.abs(a); b = java.lang.Math.abs(b); return inv_gcd(a, b)[0]; } public static long lcm(long a, long b) { a = java.lang.Math.abs(a); b = java.lang.Math.abs(b); return a / gcd(a, b) * b; } public static long pow_mod(long x, long n, int m) { assert n >= 0; assert m >= 1; if (m == 1) return 0L; x = safe_mod(x, m); long ans = 1L; while (n > 0) { if ((n & 1) == 1) ans = (ans * x) % m; x = (x * x) % m; n >>>= 1; } return ans; } public static long[] crt(long[] r, long[] m) { assert (r.length == m.length); int n = r.length; long r0 = 0, m0 = 1; for (int i = 0; i < n; i++) { assert (1 <= m[i]); long r1 = safe_mod(r[i], m[i]), m1 = m[i]; if (m0 < m1) { long tmp = r0; r0 = r1; r1 = tmp; tmp = m0; m0 = m1; m1 = tmp; } if (m0 % m1 == 0) { if (r0 % m1 != r1) return new long[] { 0, 0 }; continue; } long[] ig = inv_gcd(m0, m1); long g = ig[0], im = ig[1]; long u1 = m1 / g; if ((r1 - r0) % g != 0) return new long[] { 0, 0 }; long x = (r1 - r0) / g % u1 * im % u1; r0 += x * m0; m0 *= u1; if (r0 < 0) r0 += m0; // System.err.printf("%d %d\n", r0, m0); } return new long[] { r0, m0 }; } public static long floor_sum(long n, long m, long a, long b) { long ans = 0; if (a >= m) { ans += (n - 1) * n * (a / m) / 2; a %= m; } if (b >= m) { ans += n * (b / m); b %= m; } long y_max = (a * n + b) / m; long x_max = y_max * m - b; if (y_max == 0) return ans; ans += (n - (x_max + a - 1) / a) * y_max; ans += floor_sum(y_max, a, m, (a - x_max % a) % a); return ans; } public static java.util.ArrayList<Long> divisors(long n) { java.util.ArrayList<Long> divisors = new ArrayList<>(); java.util.ArrayList<Long> large = new ArrayList<>(); for (long i = 1; i * i <= n; i++) if (n % i == 0) { divisors.add(i); if (i * i < n) large.add(n / i); } for (int p = large.size() - 1; p >= 0; p--) { divisors.add(large.get(p)); } return divisors; } } static class Multiset<T> extends java.util.TreeMap<T, Long> { public Multiset() { super(); } public Multiset(java.util.List<T> list) { super(); for (T e : list) this.addOne(e); } public long count(Object elm) { return getOrDefault(elm, 0L); } public void add(T elm, long amount) { if (!this.containsKey(elm)) put(elm, amount); else replace(elm, get(elm) + amount); if (this.count(elm) == 0) this.remove(elm); } public void addOne(T elm) { this.add(elm, 1); } public void removeOne(T elm) { this.add(elm, -1); } public void removeAll(T elm) { this.add(elm, -this.count(elm)); } public static <T> Multiset<T> merge(Multiset<T> a, Multiset<T> b) { Multiset<T> c = new Multiset<>(); for (T x : a.keySet()) c.add(x, a.count(x)); for (T y : b.keySet()) c.add(y, b.count(y)); return c; } } static class GraphBuilder { public static int[][] makeGraph(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, boolean undirected) { int[][] graph = new int[NumberOfNodes][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = to[i]; if (undirected) graph[to[i]][--outdegree[to[i]]] = from[i]; } return graph; } public static int[][][] makeGraphWithWeight(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, int[] weight, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], weight[i] }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], weight[i] }; } return graph; } public static int[][][] makeGraphWithEdgeInfo(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], i, 0 }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], i, 1 }; } return graph; } public static int[][][] makeGraphWithWeightAndEdgeInfo(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, int[] weight, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], weight[i], i, 0 }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], weight[i], i, 1 }; } return graph; } } static class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } java.util.ArrayList<java.util.ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new java.util.ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(java.util.ArrayList::isEmpty); return result; } } static class ModIntFactory { private final ModArithmetic ma; private final int mod; private final boolean usesMontgomery; private final ModArithmetic.ModArithmeticMontgomery maMontgomery; private ArrayList<Integer> factorial; private ArrayList<Integer> factorial_inversion; public ModIntFactory(int mod) { this.ma = ModArithmetic.of(mod); this.usesMontgomery = ma instanceof ModArithmetic.ModArithmeticMontgomery; this.maMontgomery = usesMontgomery ? (ModArithmetic.ModArithmeticMontgomery) ma : null; this.mod = mod; this.factorial = new ArrayList<>(); this.factorial_inversion = new ArrayList<>(); } public ModInt create(long value) { if ((value %= mod) < 0) value += mod; if (usesMontgomery) { return new ModInt(maMontgomery.generate(value)); } else { return new ModInt((int) value); } } private void prepareFactorial(int max) { factorial.ensureCapacity(max + 1); if (factorial.size() == 0) factorial.add(1); for (int i = factorial.size(); i <= max; i++) { factorial.add(ma.mul(factorial.get(i - 1), i)); } } public ModInt factorial(int i) { prepareFactorial(i); return create(factorial.get(i)); } public ModInt permutation(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); if (factorial_inversion.size() > n) { return create(ma.mul(factorial.get(n), factorial_inversion.get(n - r))); } return create(ma.div(factorial.get(n), factorial.get(n - r))); } public ModInt combination(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); if (factorial_inversion.size() > n) { return create( ma.mul(factorial.get(n), ma.mul(factorial_inversion.get(n - r), factorial_inversion.get(r)))); } return create(ma.div(factorial.get(n), ma.mul(factorial.get(r), factorial.get(n - r)))); } public void prepareFactorialInv(int max) { prepareFactorial(max); factorial_inversion.ensureCapacity(max + 1); for (int i = factorial_inversion.size(); i <= max; i++) { factorial_inversion.add(ma.inv(factorial.get(i))); } } public int getMod() { return mod; } public class ModInt { private int value; private ModInt(int value) { this.value = value; } public int mod() { return mod; } public int value() { if (ma instanceof ModArithmetic.ModArithmeticMontgomery) { return ((ModArithmetic.ModArithmeticMontgomery) ma).reduce(value); } return value; } public ModInt add(ModInt mi) { return new ModInt(ma.add(value, mi.value)); } public ModInt add(ModInt mi1, ModInt mi2) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt add(ModInt mi1, ModInt... mis) { ModInt mi = add(mi1); for (ModInt m : mis) mi.addAsg(m); return mi; } public ModInt add(long mi) { return new ModInt(ma.add(value, ma.remainder(mi))); } public ModInt sub(ModInt mi) { return new ModInt(ma.sub(value, mi.value)); } public ModInt sub(long mi) { return new ModInt(ma.sub(value, ma.remainder(mi))); } public ModInt mul(ModInt mi) { return new ModInt(ma.mul(value, mi.value)); } public ModInt mul(ModInt mi1, ModInt mi2) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mul(ModInt mi1, ModInt... mis) { ModInt mi = mul(mi1); for (ModInt m : mis) mi.mulAsg(m); return mi; } public ModInt mul(long mi) { return new ModInt(ma.mul(value, ma.remainder(mi))); } public ModInt div(ModInt mi) { return new ModInt(ma.div(value, mi.value)); } public ModInt div(long mi) { return new ModInt(ma.div(value, ma.remainder(mi))); } public ModInt inv() { return new ModInt(ma.inv(value)); } public ModInt pow(long b) { return new ModInt(ma.pow(value, b)); } public ModInt addAsg(ModInt mi) { this.value = ma.add(value, mi.value); return this; } public ModInt addAsg(ModInt mi1, ModInt mi2) { return addAsg(mi1).addAsg(mi2); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return addAsg(mi1).addAsg(mi2).addAsg(mi3); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return addAsg(mi1).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt addAsg(ModInt... mis) { for (ModInt m : mis) addAsg(m); return this; } public ModInt addAsg(long mi) { this.value = ma.add(value, ma.remainder(mi)); return this; } public ModInt subAsg(ModInt mi) { this.value = ma.sub(value, mi.value); return this; } public ModInt subAsg(long mi) { this.value = ma.sub(value, ma.remainder(mi)); return this; } public ModInt mulAsg(ModInt mi) { this.value = ma.mul(value, mi.value); return this; } public ModInt mulAsg(ModInt mi1, ModInt mi2) { return mulAsg(mi1).mulAsg(mi2); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mulAsg(ModInt... mis) { for (ModInt m : mis) mulAsg(m); return this; } public ModInt mulAsg(long mi) { this.value = ma.mul(value, ma.remainder(mi)); return this; } public ModInt divAsg(ModInt mi) { this.value = ma.div(value, mi.value); return this; } public ModInt divAsg(long mi) { this.value = ma.div(value, ma.remainder(mi)); return this; } @Override public String toString() { return String.valueOf(value()); } @Override public boolean equals(Object o) { if (o instanceof ModInt) { ModInt mi = (ModInt) o; return mod() == mi.mod() && value() == mi.value(); } return false; } @Override public int hashCode() { return (1 * 37 + mod()) * 37 + value(); } } private static abstract class ModArithmetic { abstract int mod(); abstract int remainder(long value); abstract int add(int a, int b); abstract int sub(int a, int b); abstract int mul(int a, int b); int div(int a, int b) { return mul(a, inv(b)); } int inv(int a) { int b = mod(); if (b == 1) return 0; long u = 1, v = 0; while (b >= 1) { int t = a / b; a -= t * b; int tmp1 = a; a = b; b = tmp1; u -= t * v; long tmp2 = u; u = v; v = tmp2; } if (a != 1) { throw new ArithmeticException("divide by zero"); } return remainder(u); } int pow(int a, long b) { if (b < 0) throw new ArithmeticException("negative power"); int r = 1; int x = a; while (b > 0) { if ((b & 1) == 1) r = mul(r, x); x = mul(x, x); b >>= 1; } return r; } static ModArithmetic of(int mod) { if (mod <= 0) { throw new IllegalArgumentException(); } else if (mod == 1) { return new ModArithmetic1(); } else if (mod == 2) { return new ModArithmetic2(); } else if (mod == 998244353) { return new ModArithmetic998244353(); } else if (mod == 1000000007) { return new ModArithmetic1000000007(); } else if ((mod & 1) == 1) { return new ModArithmeticMontgomery(mod); } else { return new ModArithmeticBarrett(mod); } } private static final class ModArithmetic1 extends ModArithmetic { int mod() { return 1; } int remainder(long value) { return 0; } int add(int a, int b) { return 0; } int sub(int a, int b) { return 0; } int mul(int a, int b) { return 0; } int pow(int a, long b) { return 0; } } private static final class ModArithmetic2 extends ModArithmetic { int mod() { return 2; } int remainder(long value) { return (int) (value & 1); } int add(int a, int b) { return a ^ b; } int sub(int a, int b) { return a ^ b; } int mul(int a, int b) { return a & b; } } private static final class ModArithmetic998244353 extends ModArithmetic { private final int mod = 998244353; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmetic1000000007 extends ModArithmetic { private final int mod = 1000000007; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmeticMontgomery extends ModArithmeticDynamic { private final long negInv; private final long r2; private ModArithmeticMontgomery(int mod) { super(mod); long inv = 0; long s = 1, t = 0; for (int i = 0; i < 32; i++) { if ((t & 1) == 0) { t += mod; inv += s; } t >>= 1; s <<= 1; } long r = (1l << 32) % mod; this.negInv = inv; this.r2 = (r * r) % mod; } private int generate(long x) { return reduce(x * r2); } private int reduce(long x) { x = (x + ((x * negInv) & 0xffff_ffffl) * mod) >>> 32; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return generate((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } @Override int inv(int a) { return super.inv(reduce(a)); } @Override int pow(int a, long b) { return generate(super.pow(a, b)); } } private static final class ModArithmeticBarrett extends ModArithmeticDynamic { private static final long mask = 0xffff_ffffl; private final long mh; private final long ml; private ModArithmeticBarrett(int mod) { super(mod); /** * m = floor(2^64/mod) 2^64 = p*mod + q, 2^32 = a*mod + b => (a*mod + b)^2 = * p*mod + q => p = mod*a^2 + 2ab + floor(b^2/mod) */ long a = (1l << 32) / mod; long b = (1l << 32) % mod; long m = a * a * mod + 2 * a * b + (b * b) / mod; mh = m >>> 32; ml = m & mask; } private int reduce(long x) { long z = (x & mask) * ml; z = (x & mask) * mh + (x >>> 32) * ml + (z >>> 32); z = (x >>> 32) * mh + (z >>> 32); x -= z * mod; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } } private static class ModArithmeticDynamic extends ModArithmetic { final int mod; ModArithmeticDynamic(int mod) { this.mod = mod; } int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int sum = a + b; return sum >= mod ? sum - mod : sum; } int sub(int a, int b) { int sum = a - b; return sum < 0 ? sum + mod : sum; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } } } static class Convolution { /** * Find a primitive root. * * @param m A prime number. * @return Primitive root. */ private static int primitiveRoot(int m) { if (m == 2) return 1; if (m == 167772161) return 3; if (m == 469762049) return 3; if (m == 754974721) return 11; if (m == 998244353) return 3; int[] divs = new int[20]; divs[0] = 2; int cnt = 1; int x = (m - 1) / 2; while (x % 2 == 0) x /= 2; for (int i = 3; (long) (i) * i <= x; i += 2) { if (x % i == 0) { divs[cnt++] = i; while (x % i == 0) { x /= i; } } } if (x > 1) { divs[cnt++] = x; } for (int g = 2;; g++) { boolean ok = true; for (int i = 0; i < cnt; i++) { if (pow(g, (m - 1) / divs[i], m) == 1) { ok = false; break; } } if (ok) return g; } } /** * Power. * * @param x Parameter x. * @param n Parameter n. * @param m Mod. * @return n-th power of x mod m. */ private static long pow(long x, long n, int m) { if (m == 1) return 0; long r = 1; long y = x % m; while (n > 0) { if ((n & 1) != 0) r = (r * y) % m; y = (y * y) % m; n >>= 1; } return r; } /** * Ceil of power 2. * * @param n Value. * @return Ceil of power 2. */ private static int ceilPow2(int n) { int x = 0; while ((1L << x) < n) x++; return x; } /** * Garner's algorithm. * * @param c Mod convolution results. * @param mods Mods. * @return Result. */ private static long garner(long[] c, int[] mods) { int n = c.length + 1; long[] cnst = new long[n]; long[] coef = new long[n]; java.util.Arrays.fill(coef, 1); for (int i = 0; i < n - 1; i++) { int m1 = mods[i]; long v = (c[i] - cnst[i] + m1) % m1; v = v * pow(coef[i], m1 - 2, m1) % m1; for (int j = i + 1; j < n; j++) { long m2 = mods[j]; cnst[j] = (cnst[j] + coef[j] * v) % m2; coef[j] = (coef[j] * m1) % m2; } } return cnst[n - 1]; } /** * Pre-calculation for NTT. * * @param mod NTT Prime. * @param g Primitive root of mod. * @return Pre-calculation table. */ private static long[] sumE(int mod, int g) { long[] sum_e = new long[30]; long[] es = new long[30]; long[] ies = new long[30]; int cnt2 = Integer.numberOfTrailingZeros(mod - 1); long e = pow(g, (mod - 1) >> cnt2, mod); long ie = pow(e, mod - 2, mod); for (int i = cnt2; i >= 2; i--) { es[i - 2] = e; ies[i - 2] = ie; e = e * e % mod; ie = ie * ie % mod; } long now = 1; for (int i = 0; i < cnt2 - 2; i++) { sum_e[i] = es[i] * now % mod; now = now * ies[i] % mod; } return sum_e; } /** * Pre-calculation for inverse NTT. * * @param mod Mod. * @param g Primitive root of mod. * @return Pre-calculation table. */ private static long[] sumIE(int mod, int g) { long[] sum_ie = new long[30]; long[] es = new long[30]; long[] ies = new long[30]; int cnt2 = Integer.numberOfTrailingZeros(mod - 1); long e = pow(g, (mod - 1) >> cnt2, mod); long ie = pow(e, mod - 2, mod); for (int i = cnt2; i >= 2; i--) { es[i - 2] = e; ies[i - 2] = ie; e = e * e % mod; ie = ie * ie % mod; } long now = 1; for (int i = 0; i < cnt2 - 2; i++) { sum_ie[i] = ies[i] * now % mod; now = now * es[i] % mod; } return sum_ie; } /** * Inverse NTT. * * @param a Target array. * @param sumIE Pre-calculation table. * @param mod NTT Prime. */ private static void butterflyInv(long[] a, long[] sumIE, int mod) { int n = a.length; int h = ceilPow2(n); for (int ph = h; ph >= 1; ph--) { int w = 1 << (ph - 1), p = 1 << (h - ph); long inow = 1; for (int s = 0; s < w; s++) { int offset = s << (h - ph + 1); for (int i = 0; i < p; i++) { long l = a[i + offset]; long r = a[i + offset + p]; a[i + offset] = (l + r) % mod; a[i + offset + p] = (mod + l - r) * inow % mod; } int x = Integer.numberOfTrailingZeros(~s); inow = inow * sumIE[x] % mod; } } } /** * Inverse NTT. * * @param a Target array. * @param sumE Pre-calculation table. * @param mod NTT Prime. */ private static void butterfly(long[] a, long[] sumE, int mod) { int n = a.length; int h = ceilPow2(n); for (int ph = 1; ph <= h; ph++) { int w = 1 << (ph - 1), p = 1 << (h - ph); long now = 1; for (int s = 0; s < w; s++) { int offset = s << (h - ph + 1); for (int i = 0; i < p; i++) { long l = a[i + offset]; long r = a[i + offset + p] * now % mod; a[i + offset] = (l + r) % mod; a[i + offset + p] = (l - r + mod) % mod; } int x = Integer.numberOfTrailingZeros(~s); now = now * sumE[x] % mod; } } } /** * Convolution. * * @param a Target array 1. * @param b Target array 2. * @param mod NTT Prime. * @return Answer. */ public static long[] convolution(long[] a, long[] b, int mod) { int n = a.length; int m = b.length; if (n == 0 || m == 0) return new long[0]; int z = 1 << ceilPow2(n + m - 1); { long[] na = new long[z]; long[] nb = new long[z]; System.arraycopy(a, 0, na, 0, n); System.arraycopy(b, 0, nb, 0, m); a = na; b = nb; } int g = primitiveRoot(mod); long[] sume = sumE(mod, g); long[] sumie = sumIE(mod, g); butterfly(a, sume, mod); butterfly(b, sume, mod); for (int i = 0; i < z; i++) { a[i] = a[i] * b[i] % mod; } butterflyInv(a, sumie, mod); a = java.util.Arrays.copyOf(a, n + m - 1); long iz = pow(z, mod - 2, mod); for (int i = 0; i < n + m - 1; i++) a[i] = a[i] * iz % mod; return a; } /** * Convolution. * * @param a Target array 1. * @param b Target array 2. * @param mod Any mod. * @return Answer. */ public static long[] convolutionLL(long[] a, long[] b, int mod) { int n = a.length; int m = b.length; if (n == 0 || m == 0) return new long[0]; int mod1 = 754974721; int mod2 = 167772161; int mod3 = 469762049; long[] c1 = convolution(a, b, mod1); long[] c2 = convolution(a, b, mod2); long[] c3 = convolution(a, b, mod3); int retSize = c1.length; long[] ret = new long[retSize]; int[] mods = { mod1, mod2, mod3, mod }; for (int i = 0; i < retSize; ++i) { ret[i] = garner(new long[] { c1[i], c2[i], c3[i] }, mods); } return ret; } /** * Convolution by ModInt. * * @param a Target array 1. * @param b Target array 2. * @return Answer. */ public static java.util.List<ModIntFactory.ModInt> convolution(java.util.List<ModIntFactory.ModInt> a, java.util.List<ModIntFactory.ModInt> b) { int mod = a.get(0).mod(); long[] va = a.stream().mapToLong(ModIntFactory.ModInt::value).toArray(); long[] vb = b.stream().mapToLong(ModIntFactory.ModInt::value).toArray(); long[] c = convolutionLL(va, vb, mod); ModIntFactory factory = new ModIntFactory(mod); return java.util.Arrays.stream(c).mapToObj(factory::create).collect(java.util.stream.Collectors.toList()); } /** * Naive convolution. (Complexity is O(N^2)!!) * * @param a Target array 1. * @param b Target array 2. * @param mod Mod. * @return Answer. */ public static long[] convolutionNaive(long[] a, long[] b, int mod) { int n = a.length; int m = b.length; int k = n + m - 1; long[] ret = new long[k]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ret[i + j] += a[i] * b[j] % mod; ret[i + j] %= mod; } } return ret; } } static class SCC { static class Edge { int from, to; public Edge(int from, int to) { this.from = from; this.to = to; } } final int n; int m; final java.util.ArrayList<Edge> unorderedEdges; final int[] start; final int[] ids; boolean hasBuilt = false; public SCC(int n) { this.n = n; this.unorderedEdges = new java.util.ArrayList<>(); this.start = new int[n + 1]; this.ids = new int[n]; } public void addEdge(int from, int to) { rangeCheck(from); rangeCheck(to); unorderedEdges.add(new Edge(from, to)); start[from + 1]++; this.m++; } public int id(int i) { if (!hasBuilt) { throw new UnsupportedOperationException("Graph hasn't been built."); } rangeCheck(i); return ids[i]; } public int[][] build() { for (int i = 1; i <= n; i++) { start[i] += start[i - 1]; } Edge[] orderedEdges = new Edge[m]; int[] count = new int[n + 1]; System.arraycopy(start, 0, count, 0, n + 1); for (Edge e : unorderedEdges) { orderedEdges[count[e.from]++] = e; } int nowOrd = 0; int groupNum = 0; int k = 0; // parent int[] par = new int[n]; int[] vis = new int[n]; int[] low = new int[n]; int[] ord = new int[n]; java.util.Arrays.fill(ord, -1); // u = lower32(stack[i]) : visiting vertex // j = upper32(stack[i]) : jth child long[] stack = new long[n]; // size of stack int ptr = 0; // non-recursional DFS for (int i = 0; i < n; i++) { if (ord[i] >= 0) continue; par[i] = -1; // vertex i, 0th child. stack[ptr++] = 0l << 32 | i; // stack is not empty while (ptr > 0) { // last element long p = stack[--ptr]; // vertex int u = (int) (p & 0xffff_ffffl); // jth child int j = (int) (p >>> 32); if (j == 0) { // first visit low[u] = ord[u] = nowOrd++; vis[k++] = u; } if (start[u] + j < count[u]) { // there are more children // jth child int to = orderedEdges[start[u] + j].to; // incr children counter stack[ptr++] += 1l << 32; if (ord[to] == -1) { // new vertex stack[ptr++] = 0l << 32 | to; par[to] = u; } else { // backward edge low[u] = Math.min(low[u], ord[to]); } } else { // no more children (leaving) while (j-- > 0) { int to = orderedEdges[start[u] + j].to; // update lowlink if (par[to] == u) low[u] = Math.min(low[u], low[to]); } if (low[u] == ord[u]) { // root of a component while (true) { // gathering verticies int v = vis[--k]; ord[v] = n; ids[v] = groupNum; if (v == u) break; } groupNum++; // incr the number of components } } } } for (int i = 0; i < n; i++) { ids[i] = groupNum - 1 - ids[i]; } int[] counts = new int[groupNum]; for (int x : ids) counts[x]++; int[][] groups = new int[groupNum][]; for (int i = 0; i < groupNum; i++) { groups[i] = new int[counts[i]]; } for (int i = 0; i < n; i++) { int cmp = ids[i]; groups[cmp][--counts[cmp]] = i; } hasBuilt = true; return groups; } private void rangeCheck(int i) { if (i < 0 || i >= n) { throw new IndexOutOfBoundsException(String.format("Index %d out of bounds for length %d", i, n)); } } } static class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in) { this.in = in; } public ContestScanner() { this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit)); } n = n * 10 + digit; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = this.nextInt(); return array; } public int[][] nextIntArrayMulti(int length, int width) { int[][] arrays = new int[width][length]; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) arrays[j][i] = this.nextInt(); } return arrays; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width) { long[][] mat = new long[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width) { int[][] mat = new int[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width) { double[][] mat = new double[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width) { char[][] mat = new char[height][width]; for (int h = 0; h < height; h++) { String s = this.next(); for (int w = 0; w < width; w++) { mat[h][w] = s.charAt(w); } } return mat; } } static class ContestPrinter extends java.io.PrintWriter { public ContestPrinter(java.io.PrintStream stream) { super(stream); } public ContestPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n - 1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n - 1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } } static class Permutation implements java.util.Iterator<int[]>, Iterable<int[]> { private int[] next; public Permutation(int n) { next = java.util.stream.IntStream.range(0, n).toArray(); } @Override public boolean hasNext() { return next != null; } @Override public int[] next() { int[] r = next.clone(); next = nextPermutation(next); return r; } @Override public java.util.Iterator<int[]> iterator() { return this; } public static int[] nextPermutation(int[] a) { if (a == null || a.length < 2) return null; int p = 0; for (int i = a.length - 2; i >= 0; i--) { if (a[i] >= a[i + 1]) continue; p = i; break; } int q = 0; for (int i = a.length - 1; i > p; i--) { if (a[i] <= a[p]) continue; q = i; break; } if (p == 0 && q == 0) return null; int temp = a[p]; a[p] = a[q]; a[q] = temp; int l = p, r = a.length; while (++l < --r) { temp = a[l]; a[l] = a[r]; a[r] = temp; } return a; } } static class SegTree<S> { final int MAX; final int N; final java.util.function.BinaryOperator<S> op; final S E; final S[] data; @SuppressWarnings("unchecked") public SegTree(int n, java.util.function.BinaryOperator<S> op, S e) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.E = e; this.op = op; this.data = (S[]) new Object[N << 1]; java.util.Arrays.fill(data, E); } public SegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e) { this(dat.length, op, e); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, data, N, l); for (int i = N - 1; i > 0; i--) { data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]); } } public void set(int p, S x) { exclusiveRangeCheck(p); data[p += N] = x; p >>= 1; while (p > 0) { data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]); p >>= 1; } } public S get(int p) { exclusiveRangeCheck(p); return data[p + N]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException(String.format("Invalid range: [%d, %d)", l, r)); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); S sumLeft = E; S sumRight = E; l += N; r += N; while (l < r) { if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]); if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight); l >>= 1; r >>= 1; } return op.apply(sumLeft, sumRight); } public S allProd() { return data[1]; } public int maxRight(int l, java.util.function.Predicate<S> f) { inclusiveRangeCheck(l); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!f.test(op.apply(sum, data[l]))) { while (l < N) { l = l << 1; if (f.test(op.apply(sum, data[l]))) { sum = op.apply(sum, data[l]); l++; } } return l - N; } sum = op.apply(sum, data[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> f) { inclusiveRangeCheck(r); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!f.test(op.apply(data[r], sum))) { while (r < N) { r = r << 1 | 1; if (f.test(op.apply(data[r], sum))) { sum = op.apply(data[r], sum); r--; } } return r + 1 - N; } sum = op.apply(data[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d).", p, 0, MAX)); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d].", p, 0, MAX)); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } public String toDetailedString() { return toDetailedString(1, 0); } private String toDetailedString(int k, int sp) { if (k >= N) return indent(sp) + data[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent); s += "\n"; s += indent(sp) + data[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n-- > 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(data[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } static class LazySegTree<S, F> { final int MAX; final int N; final int Log; final java.util.function.BinaryOperator<S> Op; final S E; final java.util.function.BiFunction<F, S, S> Mapping; final java.util.function.BinaryOperator<F> Composition; final F Id; final S[] Dat; final F[] Laz; @SuppressWarnings("unchecked") public LazySegTree(int n, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.Log = Integer.numberOfTrailingZeros(N); this.Op = op; this.E = e; this.Mapping = mapping; this.Composition = composition; this.Id = id; this.Dat = (S[]) new Object[N << 1]; this.Laz = (F[]) new Object[N]; java.util.Arrays.fill(Dat, E); java.util.Arrays.fill(Laz, Id); } public LazySegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this(dat.length, op, e, mapping, composition, id); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, Dat, N, l); for (int i = N - 1; i > 0; i--) { Dat[i] = Op.apply(Dat[i << 1 | 0], Dat[i << 1 | 1]); } } private void push(int k) { if (Laz[k] == Id) return; int lk = k << 1 | 0, rk = k << 1 | 1; Dat[lk] = Mapping.apply(Laz[k], Dat[lk]); Dat[rk] = Mapping.apply(Laz[k], Dat[rk]); if (lk < N) Laz[lk] = Composition.apply(Laz[k], Laz[lk]); if (rk < N) Laz[rk] = Composition.apply(Laz[k], Laz[rk]); Laz[k] = Id; } private void pushTo(int k) { for (int i = Log; i > 0; i--) push(k >> i); } private void pushTo(int lk, int rk) { for (int i = Log; i > 0; i--) { if (((lk >> i) << i) != lk) push(lk >> i); if (((rk >> i) << i) != rk) push(rk >> i); } } private void updateFrom(int k) { k >>= 1; while (k > 0) { Dat[k] = Op.apply(Dat[k << 1 | 0], Dat[k << 1 | 1]); k >>= 1; } } private void updateFrom(int lk, int rk) { for (int i = 1; i <= Log; i++) { if (((lk >> i) << i) != lk) { int lki = lk >> i; Dat[lki] = Op.apply(Dat[lki << 1 | 0], Dat[lki << 1 | 1]); } if (((rk >> i) << i) != rk) { int rki = (rk - 1) >> i; Dat[rki] = Op.apply(Dat[rki << 1 | 0], Dat[rki << 1 | 1]); } } } public void set(int p, S x) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = x; updateFrom(p); } public S get(int p) { exclusiveRangeCheck(p); p += N; pushTo(p); return Dat[p]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException(String.format("Invalid range: [%d, %d)", l, r)); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return E; l += N; r += N; pushTo(l, r); S sumLeft = E, sumRight = E; while (l < r) { if ((l & 1) == 1) sumLeft = Op.apply(sumLeft, Dat[l++]); if ((r & 1) == 1) sumRight = Op.apply(Dat[--r], sumRight); l >>= 1; r >>= 1; } return Op.apply(sumLeft, sumRight); } public S allProd() { return Dat[1]; } public void apply(int p, F f) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = Mapping.apply(f, Dat[p]); updateFrom(p); } public void apply(int l, int r, F f) { if (l > r) { throw new IllegalArgumentException(String.format("Invalid range: [%d, %d)", l, r)); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return; l += N; r += N; pushTo(l, r); for (int l2 = l, r2 = r; l2 < r2;) { if ((l2 & 1) == 1) { Dat[l2] = Mapping.apply(f, Dat[l2]); if (l2 < N) Laz[l2] = Composition.apply(f, Laz[l2]); l2++; } if ((r2 & 1) == 1) { r2--; Dat[r2] = Mapping.apply(f, Dat[r2]); if (r2 < N) Laz[r2] = Composition.apply(f, Laz[r2]); } l2 >>= 1; r2 >>= 1; } updateFrom(l, r); } public int maxRight(int l, java.util.function.Predicate<S> g) { inclusiveRangeCheck(l); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; pushTo(l); S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!g.test(Op.apply(sum, Dat[l]))) { while (l < N) { push(l); l = l << 1; if (g.test(Op.apply(sum, Dat[l]))) { sum = Op.apply(sum, Dat[l]); l++; } } return l - N; } sum = Op.apply(sum, Dat[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> g) { inclusiveRangeCheck(r); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; pushTo(r - 1); S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!g.test(Op.apply(Dat[r], sum))) { while (r < N) { push(r); r = r << 1 | 1; if (g.test(Op.apply(Dat[r], sum))) { sum = Op.apply(Dat[r], sum); r--; } } return r + 1 - N; } sum = Op.apply(Dat[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException(String.format("Index %d is not in [%d, %d).", p, 0, MAX)); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException(String.format("Index %d is not in [%d, %d].", p, 0, MAX)); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } private S[] simulatePushAll() { S[] simDat = java.util.Arrays.copyOf(Dat, 2 * N); F[] simLaz = java.util.Arrays.copyOf(Laz, 2 * N); for (int k = 1; k < N; k++) { if (simLaz[k] == Id) continue; int lk = k << 1 | 0, rk = k << 1 | 1; simDat[lk] = Mapping.apply(simLaz[k], simDat[lk]); simDat[rk] = Mapping.apply(simLaz[k], simDat[rk]); if (lk < N) simLaz[lk] = Composition.apply(simLaz[k], simLaz[lk]); if (rk < N) simLaz[rk] = Composition.apply(simLaz[k], simLaz[rk]); simLaz[k] = Id; } return simDat; } public String toDetailedString() { return toDetailedString(1, 0, simulatePushAll()); } private String toDetailedString(int k, int sp, S[] dat) { if (k >= N) return indent(sp) + dat[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent, dat); s += "\n"; s += indent(sp) + dat[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent, dat); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n-- > 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { S[] dat = simulatePushAll(); StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(dat[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } static class MaxFlow { private static final class InternalCapEdge { final int to; final int rev; long cap; InternalCapEdge(int to, int rev, long cap) { this.to = to; this.rev = rev; this.cap = cap; } } public static final class CapEdge { public final int from, to; public final long cap, flow; CapEdge(int from, int to, long cap, long flow) { this.from = from; this.to = to; this.cap = cap; this.flow = flow; } @Override public boolean equals(Object o) { if (o instanceof CapEdge) { CapEdge e = (CapEdge) o; return from == e.from && to == e.to && cap == e.cap && flow == e.flow; } return false; } } private static final class IntPair { final int first, second; IntPair(int first, int second) { this.first = first; this.second = second; } } static final long INF = Long.MAX_VALUE; private final int n; private final java.util.ArrayList<IntPair> pos; private final java.util.ArrayList<InternalCapEdge>[] g; @SuppressWarnings("unchecked") public MaxFlow(int n) { this.n = n; this.pos = new java.util.ArrayList<>(); this.g = new java.util.ArrayList[n]; for (int i = 0; i < n; i++) { this.g[i] = new java.util.ArrayList<>(); } } public int addEdge(int from, int to, long cap) { rangeCheck(from, 0, n); rangeCheck(to, 0, n); nonNegativeCheck(cap, "Capacity"); int m = pos.size(); pos.add(new IntPair(from, g[from].size())); int fromId = g[from].size(); int toId = g[to].size(); if (from == to) toId++; g[from].add(new InternalCapEdge(to, toId, cap)); g[to].add(new InternalCapEdge(from, fromId, 0L)); return m; } private InternalCapEdge getInternalEdge(int i) { return g[pos.get(i).first].get(pos.get(i).second); } private InternalCapEdge getInternalEdgeReversed(InternalCapEdge e) { return g[e.to].get(e.rev); } public CapEdge getEdge(int i) { int m = pos.size(); rangeCheck(i, 0, m); InternalCapEdge e = getInternalEdge(i); InternalCapEdge re = getInternalEdgeReversed(e); return new CapEdge(re.to, e.to, e.cap + re.cap, re.cap); } public CapEdge[] getEdges() { CapEdge[] res = new CapEdge[pos.size()]; java.util.Arrays.setAll(res, this::getEdge); return res; } public void changeEdge(int i, long newCap, long newFlow) { int m = pos.size(); rangeCheck(i, 0, m); nonNegativeCheck(newCap, "Capacity"); if (newFlow > newCap) { throw new IllegalArgumentException( String.format("Flow %d is greater than the capacity %d.", newCap, newFlow)); } InternalCapEdge e = getInternalEdge(i); InternalCapEdge re = getInternalEdgeReversed(e); e.cap = newCap - newFlow; re.cap = newFlow; } public long maxFlow(int s, int t) { return flow(s, t, INF); } public long flow(int s, int t, long flowLimit) { rangeCheck(s, 0, n); rangeCheck(t, 0, n); long flow = 0L; int[] level = new int[n]; int[] que = new int[n]; int[] iter = new int[n]; while (flow < flowLimit) { bfs(s, t, level, que); if (level[t] < 0) break; java.util.Arrays.fill(iter, 0); while (flow < flowLimit) { long d = dfs(t, s, flowLimit - flow, iter, level); if (d == 0) break; flow += d; } } return flow; } private void bfs(int s, int t, int[] level, int[] que) { java.util.Arrays.fill(level, -1); int hd = 0, tl = 0; que[tl++] = s; level[s] = 0; while (hd < tl) { int u = que[hd++]; for (InternalCapEdge e : g[u]) { int v = e.to; if (e.cap == 0 || level[v] >= 0) continue; level[v] = level[u] + 1; if (v == t) return; que[tl++] = v; } } } private long dfs(int cur, int s, long flowLimit, int[] iter, int[] level) { if (cur == s) return flowLimit; long res = 0; int curLevel = level[cur]; for (int itMax = g[cur].size(); iter[cur] < itMax; iter[cur]++) { int i = iter[cur]; InternalCapEdge e = g[cur].get(i); InternalCapEdge re = getInternalEdgeReversed(e); if (curLevel <= level[e.to] || re.cap == 0) continue; long d = dfs(e.to, s, Math.min(flowLimit - res, re.cap), iter, level); if (d <= 0) continue; e.cap += d; re.cap -= d; res += d; if (res == flowLimit) break; } return res; } public boolean[] minCut(int s) { rangeCheck(s, 0, n); boolean[] visited = new boolean[n]; int[] stack = new int[n]; int ptr = 0; stack[ptr++] = s; visited[s] = true; while (ptr > 0) { int u = stack[--ptr]; for (InternalCapEdge e : g[u]) { int v = e.to; if (e.cap > 0 && !visited[v]) { visited[v] = true; stack[ptr++] = v; } } } return visited; } private void rangeCheck(int i, int minInclusive, int maxExclusive) { if (i < 0 || i >= maxExclusive) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, maxExclusive)); } } private void nonNegativeCheck(long cap, String attribute) { if (cap < 0) { throw new IllegalArgumentException(String.format("%s %d is negative.", attribute, cap)); } } } static class StringAlgorithm { private static int[] saNaive(int[] s) { int n = s.length; int[] sa = new int[n]; for (int i = 0; i < n; i++) { sa[i] = i; } insertionsortUsingComparator(sa, (l, r) -> { while (l < n && r < n) { if (s[l] != s[r]) return s[l] - s[r]; l++; r++; } return -(l - r); }); return sa; } public static int[] saDoubling(int[] s) { int n = s.length; int[] sa = new int[n]; for (int i = 0; i < n; i++) { sa[i] = i; } int[] rnk = java.util.Arrays.copyOf(s, n); int[] tmp = new int[n]; for (int k = 1; k < n; k *= 2) { final int _k = k; final int[] _rnk = rnk; java.util.function.IntBinaryOperator cmp = (x, y) -> { if (_rnk[x] != _rnk[y]) return _rnk[x] - _rnk[y]; int rx = x + _k < n ? _rnk[x + _k] : -1; int ry = y + _k < n ? _rnk[y + _k] : -1; return rx - ry; }; mergesortUsingComparator(sa, cmp); tmp[sa[0]] = 0; for (int i = 1; i < n; i++) { tmp[sa[i]] = tmp[sa[i - 1]] + (cmp.applyAsInt(sa[i - 1], sa[i]) < 0 ? 1 : 0); } int[] buf = tmp; tmp = rnk; rnk = buf; } return sa; } private static void insertionsortUsingComparator(int[] a, java.util.function.IntBinaryOperator comparator) { final int n = a.length; for (int i = 1; i < n; i++) { final int tmp = a[i]; if (comparator.applyAsInt(a[i - 1], tmp) > 0) { int j = i; do { a[j] = a[j - 1]; j--; } while (j > 0 && comparator.applyAsInt(a[j - 1], tmp) > 0); a[j] = tmp; } } } private static void mergesortUsingComparator(int[] a, java.util.function.IntBinaryOperator comparator) { final int n = a.length; final int[] work = new int[n]; for (int block = 1; block <= n; block <<= 1) { final int block2 = block << 1; for (int l = 0, max = n - block; l < max; l += block2) { int m = l + block; int r = Math.min(l + block2, n); System.arraycopy(a, l, work, 0, block); for (int i = l, wi = 0, ti = m;; i++) { if (ti == r) { System.arraycopy(work, wi, a, i, block - wi); break; } if (comparator.applyAsInt(work[wi], a[ti]) > 0) { a[i] = a[ti++]; } else { a[i] = work[wi++]; if (wi == block) break; } } } } } private static final int THRESHOLD_NAIVE = 50; // private static final int THRESHOLD_DOUBLING = 0; private static int[] sais(int[] s, int upper) { int n = s.length; if (n == 0) return new int[0]; if (n == 1) return new int[] { 0 }; if (n == 2) { if (s[0] < s[1]) { return new int[] { 0, 1 }; } else { return new int[] { 1, 0 }; } } if (n < THRESHOLD_NAIVE) { return saNaive(s); } // if (n < THRESHOLD_DOUBLING) { // return saDoubling(s); // } int[] sa = new int[n]; boolean[] ls = new boolean[n]; for (int i = n - 2; i >= 0; i--) { ls[i] = s[i] == s[i + 1] ? ls[i + 1] : s[i] < s[i + 1]; } int[] sumL = new int[upper + 1]; int[] sumS = new int[upper + 1]; for (int i = 0; i < n; i++) { if (ls[i]) { sumL[s[i] + 1]++; } else { sumS[s[i]]++; } } for (int i = 0; i <= upper; i++) { sumS[i] += sumL[i]; if (i < upper) sumL[i + 1] += sumS[i]; } java.util.function.Consumer<int[]> induce = lms -> { java.util.Arrays.fill(sa, -1); int[] buf = new int[upper + 1]; System.arraycopy(sumS, 0, buf, 0, upper + 1); for (int d : lms) { if (d == n) continue; sa[buf[s[d]]++] = d; } System.arraycopy(sumL, 0, buf, 0, upper + 1); sa[buf[s[n - 1]]++] = n - 1; for (int i = 0; i < n; i++) { int v = sa[i]; if (v >= 1 && !ls[v - 1]) { sa[buf[s[v - 1]]++] = v - 1; } } System.arraycopy(sumL, 0, buf, 0, upper + 1); for (int i = n - 1; i >= 0; i--) { int v = sa[i]; if (v >= 1 && ls[v - 1]) { sa[--buf[s[v - 1] + 1]] = v - 1; } } }; int[] lmsMap = new int[n + 1]; java.util.Arrays.fill(lmsMap, -1); int m = 0; for (int i = 1; i < n; i++) { if (!ls[i - 1] && ls[i]) { lmsMap[i] = m++; } } int[] lms = new int[m]; { int p = 0; for (int i = 1; i < n; i++) { if (!ls[i - 1] && ls[i]) { lms[p++] = i; } } } induce.accept(lms); if (m > 0) { int[] sortedLms = new int[m]; { int p = 0; for (int v : sa) { if (lmsMap[v] != -1) { sortedLms[p++] = v; } } } int[] recS = new int[m]; int recUpper = 0; recS[lmsMap[sortedLms[0]]] = 0; for (int i = 1; i < m; i++) { int l = sortedLms[i - 1], r = sortedLms[i]; int endL = (lmsMap[l] + 1 < m) ? lms[lmsMap[l] + 1] : n; int endR = (lmsMap[r] + 1 < m) ? lms[lmsMap[r] + 1] : n; boolean same = true; if (endL - l != endR - r) { same = false; } else { while (l < endL && s[l] == s[r]) { l++; r++; } if (l == n || s[l] != s[r]) same = false; } if (!same) { recUpper++; } recS[lmsMap[sortedLms[i]]] = recUpper; } int[] recSA = sais(recS, recUpper); for (int i = 0; i < m; i++) { sortedLms[i] = lms[recSA[i]]; } induce.accept(sortedLms); } return sa; } public static int[] suffixArray(int[] s, int upper) { assert (0 <= upper); for (int d : s) { assert (0 <= d && d <= upper); } return sais(s, upper); } public static int[] suffixArray(int[] s) { int n = s.length; int[] vals = Arrays.copyOf(s, n); java.util.Arrays.sort(vals); int p = 1; for (int i = 1; i < n; i++) { if (vals[i] != vals[i - 1]) { vals[p++] = vals[i]; } } int[] s2 = new int[n]; for (int i = 0; i < n; i++) { s2[i] = java.util.Arrays.binarySearch(vals, 0, p, s[i]); } return sais(s2, p); } public static int[] suffixArray(char[] s) { int n = s.length; int[] s2 = new int[n]; for (int i = 0; i < n; i++) { s2[i] = s[i]; } return sais(s2, 255); } public static int[] suffixArray(java.lang.String s) { return suffixArray(s.toCharArray()); } public static int[] lcpArray(int[] s, int[] sa) { int n = s.length; assert (n >= 1); int[] rnk = new int[n]; for (int i = 0; i < n; i++) { rnk[sa[i]] = i; } int[] lcp = new int[n - 1]; int h = 0; for (int i = 0; i < n; i++) { if (h > 0) h--; if (rnk[i] == 0) { continue; } int j = sa[rnk[i] - 1]; for (; j + h < n && i + h < n; h++) { if (s[j + h] != s[i + h]) break; } lcp[rnk[i] - 1] = h; } return lcp; } public static int[] lcpArray(char[] s, int[] sa) { int n = s.length; int[] s2 = new int[n]; for (int i = 0; i < n; i++) { s2[i] = s[i]; } return lcpArray(s2, sa); } public static int[] lcpArray(java.lang.String s, int[] sa) { return lcpArray(s.toCharArray(), sa); } public static int[] zAlgorithm(int[] s) { int n = s.length; if (n == 0) return new int[0]; int[] z = new int[n]; for (int i = 1, j = 0; i < n; i++) { int k = j + z[j] <= i ? 0 : Math.min(j + z[j] - i, z[i - j]); while (i + k < n && s[k] == s[i + k]) k++; z[i] = k; if (j + z[j] < i + z[i]) j = i; } z[0] = n; return z; } public static int[] zAlgorithm(char[] s) { int n = s.length; if (n == 0) return new int[0]; int[] z = new int[n]; for (int i = 1, j = 0; i < n; i++) { int k = j + z[j] <= i ? 0 : Math.min(j + z[j] - i, z[i - j]); while (i + k < n && s[k] == s[i + k]) k++; z[i] = k; if (j + z[j] < i + z[i]) j = i; } z[0] = n; return z; } public static int[] zAlgorithm(String s) { return zAlgorithm(s.toCharArray()); } } } import java.util.*; public class Main { public static final int MOD998 = 998244353; public static final int MOD100 = 1000000007; public static void main(String[] args) throws Exception { ContestScanner sc = new ContestScanner(); ContestPrinter cp = new ContestPrinter(); int N = sc.nextInt(); long[][] poly = sc.nextLongMatrix(N, 2); int M = sc.nextInt(); long[][] shift = sc.nextLongMatrix(M, 2); int Q = sc.nextInt(); long[][] query = sc.nextLongMatrix(Q, 2); long[][] edge = new long[N][2]; for (int n = 0; n < N - 1; n++) { edge[n][0] = poly[n + 1][0] - poly[n][0]; edge[n][1] = poly[n + 1][1] - poly[n][1]; } edge[N - 1][0] = poly[0][0] - poly[N - 1][0]; edge[N - 1][1] = poly[0][1] - poly[N - 1][1]; long[] maxvalue = new long[N]; Arrays.fill(maxvalue, Long.MIN_VALUE); for (long[] sh : shift) { for (int n = 0; n < N; n++) { maxvalue[n] = Math.max(maxvalue[n], -((long) poly[n][0] + sh[0]) * edge[n][1] + ((long) poly[n][1] + sh[1]) * edge[n][0]); } } for (long[] q : query) { boolean ok = true; for (int n = 0; n < N; n++) { if (-(long) q[0] * edge[n][1] + (long) q[1] * edge[n][0] < maxvalue[n]) { ok = false; } } cp.println(ok ? "Yes" : "No"); } cp.close(); } ////////////////// // My Library // ////////////////// public static class SlopeTrick { private PriorityQueue<Long> lq = new PriorityQueue<>(Comparator.reverseOrder()); private PriorityQueue<Long> rq = new PriorityQueue<>(); private long lshift = 0; private long rshift = 0; private long min = 0; public long getMin() { return min; } public long get(long x) { long val = min; for (long l : lq) { if (l - x > 0) { val += l - x; } } for (long r : rq) { if (x - r > 0) { val += x - r; } } return val; } public long getMinPosLeft() { return lq.isEmpty() ? Long.MIN_VALUE : lq.peek() + lshift; } public long getMinPosRight() { return rq.isEmpty() ? Long.MAX_VALUE : rq.peek() + rshift; } public void addConst(long a) { min += a; } public void addSlopeRight(long a) { if (!lq.isEmpty() && lq.peek() + lshift > a) { min += lq.peek() + lshift - a; lq.add(a - lshift); rq.add(lq.poll() + lshift - rshift); } else { rq.add(a - rshift); } } public void addSlopeLeft(long a) { if (!rq.isEmpty() && rq.peek() < a) { min += a - rq.peek() - rshift; rq.add(a - rshift); lq.add(rq.poll() + rshift - lshift); } else { lq.add(a - lshift); } } public void addAbs(long a) { addSlopeLeft(a); addSlopeRight(a); } public void shift(long a) { lshift += a; rshift += a; } public void slideLeft(long a) { lshift += a; } public void slideRight(long a) { rshift += a; } public void clearLeft() { lq.clear(); } public void clearRight() { rq.clear(); } public void clearMin() { min = 0; } } public static int zeroOneBFS(int[][][] weighted_graph, int start, int goal) { int[] dist = new int[weighted_graph.length]; Arrays.fill(dist, Integer.MAX_VALUE); dist[start] = 0; LinkedList<Integer> queue = new LinkedList<>(); queue.add(start); while (!queue.isEmpty()) { int now = queue.poll(); if (now == goal) { return dist[goal]; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; if (info[1] == 0) { queue.addFirst(info[0]); } else { queue.addLast(info[0]); } } } } return -1; } public static int[] zeroOneBFSAll(int[][][] weighted_graph, int start) { int[] dist = new int[weighted_graph.length]; Arrays.fill(dist, Integer.MAX_VALUE); dist[start] = 0; LinkedList<Integer> queue = new LinkedList<>(); queue.add(start); while (!queue.isEmpty()) { int now = queue.poll(); for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; if (info[1] == 0) { queue.addFirst(info[0]); } else { queue.addLast(info[0]); } } } } return dist; } public static long dijkstra(int[][][] weighted_graph, int start, int goal) { long[] dist = new long[weighted_graph.length]; Arrays.fill(dist, 0, dist.length, Long.MAX_VALUE); dist[start] = 0; PriorityQueue<Pair<Integer, Long>> unsettled = new PriorityQueue<>((u, v) -> (int) (u.cdr - v.cdr)); unsettled.offer(new Pair<Integer, Long>(start, 0L)); while (!unsettled.isEmpty()) { Pair<Integer, Long> pair = unsettled.poll(); int now = pair.car; if (now == goal) { return dist[goal]; } if (dist[now] < pair.cdr) { continue; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; unsettled.offer(new Pair<Integer, Long>(info[0], dist[info[0]])); } } } return -1; } public static long[] dijkstraAll(int[][][] weighted_graph, int start) { long[] dist = new long[weighted_graph.length]; Arrays.fill(dist, 0, dist.length, Long.MAX_VALUE); dist[start] = 0; PriorityQueue<Pair<Integer, Long>> unsettled = new PriorityQueue<>((u, v) -> (int) (u.cdr - v.cdr)); unsettled.offer(new Pair<Integer, Long>(start, 0L)); while (!unsettled.isEmpty()) { Pair<Integer, Long> pair = unsettled.poll(); int now = pair.car; if (dist[now] < pair.cdr) { continue; } for (int[] info : weighted_graph[now]) { if (dist[info[0]] > dist[now] + info[1]) { dist[info[0]] = dist[now] + info[1]; unsettled.offer(new Pair<Integer, Long>(info[0], dist[info[0]])); } } } return dist; } public static long countLatticePoint(int[] p1, int[] p2, boolean include_end) { long difx = p2[0] - p1[0]; long dify = p2[1] - p1[1]; if (difx == 0 && dify == 0) { return include_end ? 1 : 0; } if (difx == 0 || dify == 0) { return Math.abs(difx + dify) + (include_end ? 1 : -1); } return MathLib.gcd(difx, dify) + (include_end ? 1 : -1); } public static long countLatticePoint(long[] p1, long[] p2, boolean include_end) { long difx = p2[0] - p1[0]; long dify = p2[1] - p1[1]; if (difx == 0 && dify == 0) { return include_end ? 1 : 0; } if (difx == 0 || dify == 0) { return Math.abs(difx + dify) + (include_end ? 1 : -1); } return MathLib.gcd(difx, dify) + (include_end ? 1 : -1); } // Don't contain same points! public static long countLatticePoint(int[] p1, int[] p2, int[] p3, boolean include_edge) { int[][] arr = new int[][] { p1, p2, p3 }; Arrays.sort(arr, Comparator.comparingInt(p -> ((int[]) p)[0]).thenComparingInt(p -> ((int[]) p)[1])); if ((p2[0] - p1[0]) * (long) (p3[1] - p2[1]) == (p2[1] - p1[1]) * (long) (p3[0] - p2[0])) { return countLatticePoint(arr[0], arr[2], true) - (include_edge ? 0 : 3); } long b = countLatticePoint(p1, p2, true) + countLatticePoint(p2, p3, true) + countLatticePoint(p3, p1, true) - 3; long i = (getAreaTriangle(p1, p2, p3) - b) / 2 + 1; return include_edge ? i + b : i; } public static long getAreaTriangle(int[] p1, int[] p2, int[] p3) { int x1 = p2[0] - p1[0]; int x2 = p3[0] - p2[0]; int y1 = p2[1] - p1[1]; int y2 = p3[1] - p2[1]; return Math.abs((long) x1 * y2 - (long) x2 * y1); } // Don't contain same points! public static long countLatticePointConvex(int[][] points, boolean include_edge) { if (points.length == 1) { return include_edge ? 1 : 0; } if (points.length == 2) { return countLatticePoint(points[0], points[1], include_edge); } long s = 0; for (int n = 1; n < points.length - 1; n++) { s += getAreaTriangle(points[0], points[n], points[n + 1]); } long b = countLatticePoint(points[points.length - 1], points[0], true) - points.length; for (int n = 0; n < points.length - 1; n++) { b += countLatticePoint(points[n], points[n + 1], true); } long i = (s - b) / 2 + 1; return include_edge ? i + b : i; } public static class RationalAngle implements Comparable<RationalAngle> { public long x; public long y; public static boolean include_pi_to_minus = true; public RationalAngle(long x, long y) { if (x == 0) { this.x = x; if (y == 0) { throw new UnsupportedOperationException("Angle to (0, 0) is invalid."); } else { this.y = y > 0 ? 1 : -1; } } else if (y == 0) { this.x = x > 0 ? 1 : -1; this.y = 0; } else { long gcd = MathLib.gcd(x, y); this.x = x / gcd; this.y = y / gcd; } } public RationalAngle copy() { return new RationalAngle(x, y); } public RationalAngle add(RationalAngle a) { RationalAngle res = copy(); res.addArg(a); return res; } public void addArg(RationalAngle a) { long nx = x * a.x - y * a.y; long ny = y * a.x + x * a.y; x = nx; y = ny; } public RationalAngle sub(RationalAngle a) { RationalAngle res = copy(); res.subArg(a); return res; } public void subArg(RationalAngle a) { long nx = x * a.x + y * a.y; long ny = y * a.x - x * a.y; x = nx; y = ny; } public boolean equals(RationalAngle a) { return x == a.x && y == a.y; } public boolean parallel(RationalAngle a) { return x == a.x && y == a.y || x == -a.x && y == -a.y; } public int rotDirection(RationalAngle trg) { if (parallel(trg)) { return 0; } else if (trg.sub(this).y > 0) { return 1; } else { return -1; } } public RationalAngle minus() { return new RationalAngle(x, -y); } public RationalAngle rev() { return new RationalAngle(-x, -y); } public double toRadian() { return Math.atan2(y, x); } private int toQuad() { if (x == 0) { if (y > 0) { return 2; } else { return -2; } } else if (x > 0) { if (y == 0) { return 0; } else if (y > 0) { return 1; } else { return -1; } } else { if (y == 0) { return include_pi_to_minus ? -4 : 4; } else if (y > 0) { return 3; } else { return -3; } } } @Override public int compareTo(RationalAngle ra) { if (ra == null) { throw new NullPointerException(); } int me = toQuad(); int you = ra.toQuad(); if (me > you) { return 1; } else if (me < you) { return -1; } long sub = sub(ra).y; if (sub == 0) { return 0; } else if (sub > 0) { return 1; } else { return -1; } } } public static class Pair<A, B> { public final A car; public final B cdr; public Pair(A car_, B cdr_) { car = car_; cdr = cdr_; } private static boolean eq(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } private static int hc(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair<?, ?> rhs = (Pair<?, ?>) o; return eq(car, rhs.car) && eq(cdr, rhs.cdr); } @Override public int hashCode() { return hc(car) ^ hc(cdr); } } public static class Tuple1<A> extends Pair<A, Object> { public Tuple1(A a) { super(a, null); } } public static class Tuple2<A, B> extends Pair<A, Tuple1<B>> { public Tuple2(A a, B b) { super(a, new Tuple1<>(b)); } } public static class Tuple3<A, B, C> extends Pair<A, Tuple2<B, C>> { public Tuple3(A a, B b, C c) { super(a, new Tuple2<>(b, c)); } } public static class Tuple4<A, B, C, D> extends Pair<A, Tuple3<B, C, D>> { public Tuple4(A a, B b, C c, D d) { super(a, new Tuple3<>(b, c, d)); } } public static class Tuple5<A, B, C, D, E> extends Pair<A, Tuple4<B, C, D, E>> { public Tuple5(A a, B b, C c, D d, E e) { super(a, new Tuple4<>(b, c, d, e)); } } public static class PriorityQueueLogTime<T> { private PriorityQueue<T> queue; private Multiset<T> total; private int size = 0; public PriorityQueueLogTime() { queue = new PriorityQueue<>(); total = new Multiset<>(); } public PriorityQueueLogTime(Comparator<T> c) { queue = new PriorityQueue<>(c); total = new Multiset<>(); } public void clear() { queue.clear(); total.clear(); size = 0; } public boolean contains(T e) { return total.count(e) > 0; } public boolean isEmpty() { return size == 0; } public boolean offer(T e) { total.addOne(e); size++; return queue.offer(e); } public T peek() { if (total.isEmpty()) { return null; } simplify(); return queue.peek(); } public T poll() { if (total.isEmpty()) { return null; } simplify(); size--; T res = queue.poll(); total.removeOne(res); return res; } public void remove(T e) { total.removeOne(e); size--; } public int size() { return size; } private void simplify() { while (total.count(queue.peek()) == 0) { queue.poll(); } } } static int[][] scanGraphOneIndexed(ContestScanner sc, int node, int edge, boolean undirected) { int[][] arr = sc.nextIntArrayMulti(edge, 2); for (int n = 0; n < edge; n++) { arr[0][n]--; arr[1][n]--; } return GraphBuilder.makeGraph(node, edge, arr[0], arr[1], undirected); } static int[][][] scanWeightedGraphOneIndexed(ContestScanner sc, int node, int edge, boolean undirected) { int[][] arr = sc.nextIntArrayMulti(edge, 3); for (int n = 0; n < edge; n++) { arr[0][n]--; arr[1][n]--; } return GraphBuilder.makeGraphWithWeight(node, edge, arr[0], arr[1], arr[2], undirected); } static class EdgeData { private int capacity; private int[] from, to, weight; private int p = 0; private boolean weighted; public EdgeData(boolean weighted) { this(weighted, 500000); } public EdgeData(boolean weighted, int initial_capacity) { capacity = initial_capacity; from = new int[capacity]; to = new int[capacity]; weight = new int[capacity]; this.weighted = weighted; } public void addEdge(int u, int v) { if (weighted) { System.err.println("The graph is weighted!"); return; } if (p == capacity) { int[] newfrom = new int[capacity * 2]; int[] newto = new int[capacity * 2]; System.arraycopy(from, 0, newfrom, 0, capacity); System.arraycopy(to, 0, newto, 0, capacity); capacity *= 2; from = newfrom; to = newto; } from[p] = u; to[p] = v; p++; } public void addEdge(int u, int v, int w) { if (!weighted) { System.err.println("The graph is NOT weighted!"); return; } if (p == capacity) { int[] newfrom = new int[capacity * 2]; int[] newto = new int[capacity * 2]; int[] newweight = new int[capacity * 2]; System.arraycopy(from, 0, newfrom, 0, capacity); System.arraycopy(to, 0, newto, 0, capacity); System.arraycopy(weight, 0, newweight, 0, capacity); capacity *= 2; from = newfrom; to = newto; weight = newweight; } from[p] = u; to[p] = v; weight[p] = w; p++; } public int[] getFrom() { int[] result = new int[p]; System.arraycopy(from, 0, result, 0, p); return result; } public int[] getTo() { int[] result = new int[p]; System.arraycopy(to, 0, result, 0, p); return result; } public int[] getWeight() { int[] result = new int[p]; System.arraycopy(weight, 0, result, 0, p); return result; } public int size() { return p; } } //////////////////////////////// // Atcoder Library for Java // //////////////////////////////// static class MathLib { private static long safe_mod(long x, long m) { x %= m; if (x < 0) x += m; return x; } private static long[] inv_gcd(long a, long b) { a = safe_mod(a, b); if (a == 0) return new long[] { b, 0 }; long s = b, t = a; long m0 = 0, m1 = 1; while (t > 0) { long u = s / t; s -= t * u; m0 -= m1 * u; long tmp = s; s = t; t = tmp; tmp = m0; m0 = m1; m1 = tmp; } if (m0 < 0) m0 += b / s; return new long[] { s, m0 }; } public static long gcd(long a, long b) { a = java.lang.Math.abs(a); b = java.lang.Math.abs(b); return inv_gcd(a, b)[0]; } public static long lcm(long a, long b) { a = java.lang.Math.abs(a); b = java.lang.Math.abs(b); return a / gcd(a, b) * b; } public static long pow_mod(long x, long n, int m) { assert n >= 0; assert m >= 1; if (m == 1) return 0L; x = safe_mod(x, m); long ans = 1L; while (n > 0) { if ((n & 1) == 1) ans = (ans * x) % m; x = (x * x) % m; n >>>= 1; } return ans; } public static long[] crt(long[] r, long[] m) { assert (r.length == m.length); int n = r.length; long r0 = 0, m0 = 1; for (int i = 0; i < n; i++) { assert (1 <= m[i]); long r1 = safe_mod(r[i], m[i]), m1 = m[i]; if (m0 < m1) { long tmp = r0; r0 = r1; r1 = tmp; tmp = m0; m0 = m1; m1 = tmp; } if (m0 % m1 == 0) { if (r0 % m1 != r1) return new long[] { 0, 0 }; continue; } long[] ig = inv_gcd(m0, m1); long g = ig[0], im = ig[1]; long u1 = m1 / g; if ((r1 - r0) % g != 0) return new long[] { 0, 0 }; long x = (r1 - r0) / g % u1 * im % u1; r0 += x * m0; m0 *= u1; if (r0 < 0) r0 += m0; // System.err.printf("%d %d\n", r0, m0); } return new long[] { r0, m0 }; } public static long floor_sum(long n, long m, long a, long b) { long ans = 0; if (a >= m) { ans += (n - 1) * n * (a / m) / 2; a %= m; } if (b >= m) { ans += n * (b / m); b %= m; } long y_max = (a * n + b) / m; long x_max = y_max * m - b; if (y_max == 0) return ans; ans += (n - (x_max + a - 1) / a) * y_max; ans += floor_sum(y_max, a, m, (a - x_max % a) % a); return ans; } public static java.util.ArrayList<Long> divisors(long n) { java.util.ArrayList<Long> divisors = new ArrayList<>(); java.util.ArrayList<Long> large = new ArrayList<>(); for (long i = 1; i * i <= n; i++) if (n % i == 0) { divisors.add(i); if (i * i < n) large.add(n / i); } for (int p = large.size() - 1; p >= 0; p--) { divisors.add(large.get(p)); } return divisors; } } static class Multiset<T> extends java.util.TreeMap<T, Long> { public Multiset() { super(); } public Multiset(java.util.List<T> list) { super(); for (T e : list) this.addOne(e); } public long count(Object elm) { return getOrDefault(elm, 0L); } public void add(T elm, long amount) { if (!this.containsKey(elm)) put(elm, amount); else replace(elm, get(elm) + amount); if (this.count(elm) == 0) this.remove(elm); } public void addOne(T elm) { this.add(elm, 1); } public void removeOne(T elm) { this.add(elm, -1); } public void removeAll(T elm) { this.add(elm, -this.count(elm)); } public static <T> Multiset<T> merge(Multiset<T> a, Multiset<T> b) { Multiset<T> c = new Multiset<>(); for (T x : a.keySet()) c.add(x, a.count(x)); for (T y : b.keySet()) c.add(y, b.count(y)); return c; } } static class GraphBuilder { public static int[][] makeGraph(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, boolean undirected) { int[][] graph = new int[NumberOfNodes][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = to[i]; if (undirected) graph[to[i]][--outdegree[to[i]]] = from[i]; } return graph; } public static int[][][] makeGraphWithWeight(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, int[] weight, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], weight[i] }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], weight[i] }; } return graph; } public static int[][][] makeGraphWithEdgeInfo(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], i, 0 }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], i, 1 }; } return graph; } public static int[][][] makeGraphWithWeightAndEdgeInfo(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to, int[] weight, boolean undirected) { int[][][] graph = new int[NumberOfNodes][][]; int[] outdegree = new int[NumberOfNodes]; for (int i = 0; i < NumberOfEdges; i++) { outdegree[from[i]]++; if (undirected) outdegree[to[i]]++; } for (int i = 0; i < NumberOfNodes; i++) graph[i] = new int[outdegree[i]][]; for (int i = 0; i < NumberOfEdges; i++) { graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], weight[i], i, 0 }; if (undirected) graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], weight[i], i, 1 }; } return graph; } } static class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } java.util.ArrayList<java.util.ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new java.util.ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(java.util.ArrayList::isEmpty); return result; } } static class ModIntFactory { private final ModArithmetic ma; private final int mod; private final boolean usesMontgomery; private final ModArithmetic.ModArithmeticMontgomery maMontgomery; private ArrayList<Integer> factorial; private ArrayList<Integer> factorial_inversion; public ModIntFactory(int mod) { this.ma = ModArithmetic.of(mod); this.usesMontgomery = ma instanceof ModArithmetic.ModArithmeticMontgomery; this.maMontgomery = usesMontgomery ? (ModArithmetic.ModArithmeticMontgomery) ma : null; this.mod = mod; this.factorial = new ArrayList<>(); this.factorial_inversion = new ArrayList<>(); } public ModInt create(long value) { if ((value %= mod) < 0) value += mod; if (usesMontgomery) { return new ModInt(maMontgomery.generate(value)); } else { return new ModInt((int) value); } } private void prepareFactorial(int max) { factorial.ensureCapacity(max + 1); if (factorial.size() == 0) factorial.add(1); for (int i = factorial.size(); i <= max; i++) { factorial.add(ma.mul(factorial.get(i - 1), i)); } } public ModInt factorial(int i) { prepareFactorial(i); return create(factorial.get(i)); } public ModInt permutation(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); if (factorial_inversion.size() > n) { return create(ma.mul(factorial.get(n), factorial_inversion.get(n - r))); } return create(ma.div(factorial.get(n), factorial.get(n - r))); } public ModInt combination(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); if (factorial_inversion.size() > n) { return create( ma.mul(factorial.get(n), ma.mul(factorial_inversion.get(n - r), factorial_inversion.get(r)))); } return create(ma.div(factorial.get(n), ma.mul(factorial.get(r), factorial.get(n - r)))); } public void prepareFactorialInv(int max) { prepareFactorial(max); factorial_inversion.ensureCapacity(max + 1); for (int i = factorial_inversion.size(); i <= max; i++) { factorial_inversion.add(ma.inv(factorial.get(i))); } } public int getMod() { return mod; } public class ModInt { private int value; private ModInt(int value) { this.value = value; } public int mod() { return mod; } public int value() { if (ma instanceof ModArithmetic.ModArithmeticMontgomery) { return ((ModArithmetic.ModArithmeticMontgomery) ma).reduce(value); } return value; } public ModInt add(ModInt mi) { return new ModInt(ma.add(value, mi.value)); } public ModInt add(ModInt mi1, ModInt mi2) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt add(ModInt mi1, ModInt... mis) { ModInt mi = add(mi1); for (ModInt m : mis) mi.addAsg(m); return mi; } public ModInt add(long mi) { return new ModInt(ma.add(value, ma.remainder(mi))); } public ModInt sub(ModInt mi) { return new ModInt(ma.sub(value, mi.value)); } public ModInt sub(long mi) { return new ModInt(ma.sub(value, ma.remainder(mi))); } public ModInt mul(ModInt mi) { return new ModInt(ma.mul(value, mi.value)); } public ModInt mul(ModInt mi1, ModInt mi2) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mul(ModInt mi1, ModInt... mis) { ModInt mi = mul(mi1); for (ModInt m : mis) mi.mulAsg(m); return mi; } public ModInt mul(long mi) { return new ModInt(ma.mul(value, ma.remainder(mi))); } public ModInt div(ModInt mi) { return new ModInt(ma.div(value, mi.value)); } public ModInt div(long mi) { return new ModInt(ma.div(value, ma.remainder(mi))); } public ModInt inv() { return new ModInt(ma.inv(value)); } public ModInt pow(long b) { return new ModInt(ma.pow(value, b)); } public ModInt addAsg(ModInt mi) { this.value = ma.add(value, mi.value); return this; } public ModInt addAsg(ModInt mi1, ModInt mi2) { return addAsg(mi1).addAsg(mi2); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return addAsg(mi1).addAsg(mi2).addAsg(mi3); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return addAsg(mi1).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt addAsg(ModInt... mis) { for (ModInt m : mis) addAsg(m); return this; } public ModInt addAsg(long mi) { this.value = ma.add(value, ma.remainder(mi)); return this; } public ModInt subAsg(ModInt mi) { this.value = ma.sub(value, mi.value); return this; } public ModInt subAsg(long mi) { this.value = ma.sub(value, ma.remainder(mi)); return this; } public ModInt mulAsg(ModInt mi) { this.value = ma.mul(value, mi.value); return this; } public ModInt mulAsg(ModInt mi1, ModInt mi2) { return mulAsg(mi1).mulAsg(mi2); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mulAsg(ModInt... mis) { for (ModInt m : mis) mulAsg(m); return this; } public ModInt mulAsg(long mi) { this.value = ma.mul(value, ma.remainder(mi)); return this; } public ModInt divAsg(ModInt mi) { this.value = ma.div(value, mi.value); return this; } public ModInt divAsg(long mi) { this.value = ma.div(value, ma.remainder(mi)); return this; } @Override public String toString() { return String.valueOf(value()); } @Override public boolean equals(Object o) { if (o instanceof ModInt) { ModInt mi = (ModInt) o; return mod() == mi.mod() && value() == mi.value(); } return false; } @Override public int hashCode() { return (1 * 37 + mod()) * 37 + value(); } } private static abstract class ModArithmetic { abstract int mod(); abstract int remainder(long value); abstract int add(int a, int b); abstract int sub(int a, int b); abstract int mul(int a, int b); int div(int a, int b) { return mul(a, inv(b)); } int inv(int a) { int b = mod(); if (b == 1) return 0; long u = 1, v = 0; while (b >= 1) { int t = a / b; a -= t * b; int tmp1 = a; a = b; b = tmp1; u -= t * v; long tmp2 = u; u = v; v = tmp2; } if (a != 1) { throw new ArithmeticException("divide by zero"); } return remainder(u); } int pow(int a, long b) { if (b < 0) throw new ArithmeticException("negative power"); int r = 1; int x = a; while (b > 0) { if ((b & 1) == 1) r = mul(r, x); x = mul(x, x); b >>= 1; } return r; } static ModArithmetic of(int mod) { if (mod <= 0) { throw new IllegalArgumentException(); } else if (mod == 1) { return new ModArithmetic1(); } else if (mod == 2) { return new ModArithmetic2(); } else if (mod == 998244353) { return new ModArithmetic998244353(); } else if (mod == 1000000007) { return new ModArithmetic1000000007(); } else if ((mod & 1) == 1) { return new ModArithmeticMontgomery(mod); } else { return new ModArithmeticBarrett(mod); } } private static final class ModArithmetic1 extends ModArithmetic { int mod() { return 1; } int remainder(long value) { return 0; } int add(int a, int b) { return 0; } int sub(int a, int b) { return 0; } int mul(int a, int b) { return 0; } int pow(int a, long b) { return 0; } } private static final class ModArithmetic2 extends ModArithmetic { int mod() { return 2; } int remainder(long value) { return (int) (value & 1); } int add(int a, int b) { return a ^ b; } int sub(int a, int b) { return a ^ b; } int mul(int a, int b) { return a & b; } } private static final class ModArithmetic998244353 extends ModArithmetic { private final int mod = 998244353; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmetic1000000007 extends ModArithmetic { private final int mod = 1000000007; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmeticMontgomery extends ModArithmeticDynamic { private final long negInv; private final long r2; private ModArithmeticMontgomery(int mod) { super(mod); long inv = 0; long s = 1, t = 0; for (int i = 0; i < 32; i++) { if ((t & 1) == 0) { t += mod; inv += s; } t >>= 1; s <<= 1; } long r = (1l << 32) % mod; this.negInv = inv; this.r2 = (r * r) % mod; } private int generate(long x) { return reduce(x * r2); } private int reduce(long x) { x = (x + ((x * negInv) & 0xffff_ffffl) * mod) >>> 32; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return generate((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } @Override int inv(int a) { return super.inv(reduce(a)); } @Override int pow(int a, long b) { return generate(super.pow(a, b)); } } private static final class ModArithmeticBarrett extends ModArithmeticDynamic { private static final long mask = 0xffff_ffffl; private final long mh; private final long ml; private ModArithmeticBarrett(int mod) { super(mod); /** * m = floor(2^64/mod) 2^64 = p*mod + q, 2^32 = a*mod + b => (a*mod + b)^2 = * p*mod + q => p = mod*a^2 + 2ab + floor(b^2/mod) */ long a = (1l << 32) / mod; long b = (1l << 32) % mod; long m = a * a * mod + 2 * a * b + (b * b) / mod; mh = m >>> 32; ml = m & mask; } private int reduce(long x) { long z = (x & mask) * ml; z = (x & mask) * mh + (x >>> 32) * ml + (z >>> 32); z = (x >>> 32) * mh + (z >>> 32); x -= z * mod; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } } private static class ModArithmeticDynamic extends ModArithmetic { final int mod; ModArithmeticDynamic(int mod) { this.mod = mod; } int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int sum = a + b; return sum >= mod ? sum - mod : sum; } int sub(int a, int b) { int sum = a - b; return sum < 0 ? sum + mod : sum; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } } } static class Convolution { /** * Find a primitive root. * * @param m A prime number. * @return Primitive root. */ private static int primitiveRoot(int m) { if (m == 2) return 1; if (m == 167772161) return 3; if (m == 469762049) return 3; if (m == 754974721) return 11; if (m == 998244353) return 3; int[] divs = new int[20]; divs[0] = 2; int cnt = 1; int x = (m - 1) / 2; while (x % 2 == 0) x /= 2; for (int i = 3; (long) (i) * i <= x; i += 2) { if (x % i == 0) { divs[cnt++] = i; while (x % i == 0) { x /= i; } } } if (x > 1) { divs[cnt++] = x; } for (int g = 2;; g++) { boolean ok = true; for (int i = 0; i < cnt; i++) { if (pow(g, (m - 1) / divs[i], m) == 1) { ok = false; break; } } if (ok) return g; } } /** * Power. * * @param x Parameter x. * @param n Parameter n. * @param m Mod. * @return n-th power of x mod m. */ private static long pow(long x, long n, int m) { if (m == 1) return 0; long r = 1; long y = x % m; while (n > 0) { if ((n & 1) != 0) r = (r * y) % m; y = (y * y) % m; n >>= 1; } return r; } /** * Ceil of power 2. * * @param n Value. * @return Ceil of power 2. */ private static int ceilPow2(int n) { int x = 0; while ((1L << x) < n) x++; return x; } /** * Garner's algorithm. * * @param c Mod convolution results. * @param mods Mods. * @return Result. */ private static long garner(long[] c, int[] mods) { int n = c.length + 1; long[] cnst = new long[n]; long[] coef = new long[n]; java.util.Arrays.fill(coef, 1); for (int i = 0; i < n - 1; i++) { int m1 = mods[i]; long v = (c[i] - cnst[i] + m1) % m1; v = v * pow(coef[i], m1 - 2, m1) % m1; for (int j = i + 1; j < n; j++) { long m2 = mods[j]; cnst[j] = (cnst[j] + coef[j] * v) % m2; coef[j] = (coef[j] * m1) % m2; } } return cnst[n - 1]; } /** * Pre-calculation for NTT. * * @param mod NTT Prime. * @param g Primitive root of mod. * @return Pre-calculation table. */ private static long[] sumE(int mod, int g) { long[] sum_e = new long[30]; long[] es = new long[30]; long[] ies = new long[30]; int cnt2 = Integer.numberOfTrailingZeros(mod - 1); long e = pow(g, (mod - 1) >> cnt2, mod); long ie = pow(e, mod - 2, mod); for (int i = cnt2; i >= 2; i--) { es[i - 2] = e; ies[i - 2] = ie; e = e * e % mod; ie = ie * ie % mod; } long now = 1; for (int i = 0; i < cnt2 - 2; i++) { sum_e[i] = es[i] * now % mod; now = now * ies[i] % mod; } return sum_e; } /** * Pre-calculation for inverse NTT. * * @param mod Mod. * @param g Primitive root of mod. * @return Pre-calculation table. */ private static long[] sumIE(int mod, int g) { long[] sum_ie = new long[30]; long[] es = new long[30]; long[] ies = new long[30]; int cnt2 = Integer.numberOfTrailingZeros(mod - 1); long e = pow(g, (mod - 1) >> cnt2, mod); long ie = pow(e, mod - 2, mod); for (int i = cnt2; i >= 2; i--) { es[i - 2] = e; ies[i - 2] = ie; e = e * e % mod; ie = ie * ie % mod; } long now = 1; for (int i = 0; i < cnt2 - 2; i++) { sum_ie[i] = ies[i] * now % mod; now = now * es[i] % mod; } return sum_ie; } /** * Inverse NTT. * * @param a Target array. * @param sumIE Pre-calculation table. * @param mod NTT Prime. */ private static void butterflyInv(long[] a, long[] sumIE, int mod) { int n = a.length; int h = ceilPow2(n); for (int ph = h; ph >= 1; ph--) { int w = 1 << (ph - 1), p = 1 << (h - ph); long inow = 1; for (int s = 0; s < w; s++) { int offset = s << (h - ph + 1); for (int i = 0; i < p; i++) { long l = a[i + offset]; long r = a[i + offset + p]; a[i + offset] = (l + r) % mod; a[i + offset + p] = (mod + l - r) * inow % mod; } int x = Integer.numberOfTrailingZeros(~s); inow = inow * sumIE[x] % mod; } } } /** * Inverse NTT. * * @param a Target array. * @param sumE Pre-calculation table. * @param mod NTT Prime. */ private static void butterfly(long[] a, long[] sumE, int mod) { int n = a.length; int h = ceilPow2(n); for (int ph = 1; ph <= h; ph++) { int w = 1 << (ph - 1), p = 1 << (h - ph); long now = 1; for (int s = 0; s < w; s++) { int offset = s << (h - ph + 1); for (int i = 0; i < p; i++) { long l = a[i + offset]; long r = a[i + offset + p] * now % mod; a[i + offset] = (l + r) % mod; a[i + offset + p] = (l - r + mod) % mod; } int x = Integer.numberOfTrailingZeros(~s); now = now * sumE[x] % mod; } } } /** * Convolution. * * @param a Target array 1. * @param b Target array 2. * @param mod NTT Prime. * @return Answer. */ public static long[] convolution(long[] a, long[] b, int mod) { int n = a.length; int m = b.length; if (n == 0 || m == 0) return new long[0]; int z = 1 << ceilPow2(n + m - 1); { long[] na = new long[z]; long[] nb = new long[z]; System.arraycopy(a, 0, na, 0, n); System.arraycopy(b, 0, nb, 0, m); a = na; b = nb; } int g = primitiveRoot(mod); long[] sume = sumE(mod, g); long[] sumie = sumIE(mod, g); butterfly(a, sume, mod); butterfly(b, sume, mod); for (int i = 0; i < z; i++) { a[i] = a[i] * b[i] % mod; } butterflyInv(a, sumie, mod); a = java.util.Arrays.copyOf(a, n + m - 1); long iz = pow(z, mod - 2, mod); for (int i = 0; i < n + m - 1; i++) a[i] = a[i] * iz % mod; return a; } /** * Convolution. * * @param a Target array 1. * @param b Target array 2. * @param mod Any mod. * @return Answer. */ public static long[] convolutionLL(long[] a, long[] b, int mod) { int n = a.length; int m = b.length; if (n == 0 || m == 0) return new long[0]; int mod1 = 754974721; int mod2 = 167772161; int mod3 = 469762049; long[] c1 = convolution(a, b, mod1); long[] c2 = convolution(a, b, mod2); long[] c3 = convolution(a, b, mod3); int retSize = c1.length; long[] ret = new long[retSize]; int[] mods = { mod1, mod2, mod3, mod }; for (int i = 0; i < retSize; ++i) { ret[i] = garner(new long[] { c1[i], c2[i], c3[i] }, mods); } return ret; } /** * Convolution by ModInt. * * @param a Target array 1. * @param b Target array 2. * @return Answer. */ public static java.util.List<ModIntFactory.ModInt> convolution(java.util.List<ModIntFactory.ModInt> a, java.util.List<ModIntFactory.ModInt> b) { int mod = a.get(0).mod(); long[] va = a.stream().mapToLong(ModIntFactory.ModInt::value).toArray(); long[] vb = b.stream().mapToLong(ModIntFactory.ModInt::value).toArray(); long[] c = convolutionLL(va, vb, mod); ModIntFactory factory = new ModIntFactory(mod); return java.util.Arrays.stream(c).mapToObj(factory::create).collect(java.util.stream.Collectors.toList()); } /** * Naive convolution. (Complexity is O(N^2)!!) * * @param a Target array 1. * @param b Target array 2. * @param mod Mod. * @return Answer. */ public static long[] convolutionNaive(long[] a, long[] b, int mod) { int n = a.length; int m = b.length; int k = n + m - 1; long[] ret = new long[k]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ret[i + j] += a[i] * b[j] % mod; ret[i + j] %= mod; } } return ret; } } static class SCC { static class Edge { int from, to; public Edge(int from, int to) { this.from = from; this.to = to; } } final int n; int m; final java.util.ArrayList<Edge> unorderedEdges; final int[] start; final int[] ids; boolean hasBuilt = false; public SCC(int n) { this.n = n; this.unorderedEdges = new java.util.ArrayList<>(); this.start = new int[n + 1]; this.ids = new int[n]; } public void addEdge(int from, int to) { rangeCheck(from); rangeCheck(to); unorderedEdges.add(new Edge(from, to)); start[from + 1]++; this.m++; } public int id(int i) { if (!hasBuilt) { throw new UnsupportedOperationException("Graph hasn't been built."); } rangeCheck(i); return ids[i]; } public int[][] build() { for (int i = 1; i <= n; i++) { start[i] += start[i - 1]; } Edge[] orderedEdges = new Edge[m]; int[] count = new int[n + 1]; System.arraycopy(start, 0, count, 0, n + 1); for (Edge e : unorderedEdges) { orderedEdges[count[e.from]++] = e; } int nowOrd = 0; int groupNum = 0; int k = 0; // parent int[] par = new int[n]; int[] vis = new int[n]; int[] low = new int[n]; int[] ord = new int[n]; java.util.Arrays.fill(ord, -1); // u = lower32(stack[i]) : visiting vertex // j = upper32(stack[i]) : jth child long[] stack = new long[n]; // size of stack int ptr = 0; // non-recursional DFS for (int i = 0; i < n; i++) { if (ord[i] >= 0) continue; par[i] = -1; // vertex i, 0th child. stack[ptr++] = 0l << 32 | i; // stack is not empty while (ptr > 0) { // last element long p = stack[--ptr]; // vertex int u = (int) (p & 0xffff_ffffl); // jth child int j = (int) (p >>> 32); if (j == 0) { // first visit low[u] = ord[u] = nowOrd++; vis[k++] = u; } if (start[u] + j < count[u]) { // there are more children // jth child int to = orderedEdges[start[u] + j].to; // incr children counter stack[ptr++] += 1l << 32; if (ord[to] == -1) { // new vertex stack[ptr++] = 0l << 32 | to; par[to] = u; } else { // backward edge low[u] = Math.min(low[u], ord[to]); } } else { // no more children (leaving) while (j-- > 0) { int to = orderedEdges[start[u] + j].to; // update lowlink if (par[to] == u) low[u] = Math.min(low[u], low[to]); } if (low[u] == ord[u]) { // root of a component while (true) { // gathering verticies int v = vis[--k]; ord[v] = n; ids[v] = groupNum; if (v == u) break; } groupNum++; // incr the number of components } } } } for (int i = 0; i < n; i++) { ids[i] = groupNum - 1 - ids[i]; } int[] counts = new int[groupNum]; for (int x : ids) counts[x]++; int[][] groups = new int[groupNum][]; for (int i = 0; i < groupNum; i++) { groups[i] = new int[counts[i]]; } for (int i = 0; i < n; i++) { int cmp = ids[i]; groups[cmp][--counts[cmp]] = i; } hasBuilt = true; return groups; } private void rangeCheck(int i) { if (i < 0 || i >= n) { throw new IndexOutOfBoundsException(String.format("Index %d out of bounds for length %d", i, n)); } } } static class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in) { this.in = in; } public ContestScanner() { this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit)); } n = n * 10 + digit; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = this.nextInt(); return array; } public int[][] nextIntArrayMulti(int length, int width) { int[][] arrays = new int[width][length]; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) arrays[j][i] = this.nextInt(); } return arrays; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width) { long[][] mat = new long[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width) { int[][] mat = new int[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width) { double[][] mat = new double[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width) { char[][] mat = new char[height][width]; for (int h = 0; h < height; h++) { String s = this.next(); for (int w = 0; w < width; w++) { mat[h][w] = s.charAt(w); } } return mat; } } static class ContestPrinter extends java.io.PrintWriter { public ContestPrinter(java.io.PrintStream stream) { super(stream); } public ContestPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n - 1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n - 1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } } static class Permutation implements java.util.Iterator<int[]>, Iterable<int[]> { private int[] next; public Permutation(int n) { next = java.util.stream.IntStream.range(0, n).toArray(); } @Override public boolean hasNext() { return next != null; } @Override public int[] next() { int[] r = next.clone(); next = nextPermutation(next); return r; } @Override public java.util.Iterator<int[]> iterator() { return this; } public static int[] nextPermutation(int[] a) { if (a == null || a.length < 2) return null; int p = 0; for (int i = a.length - 2; i >= 0; i--) { if (a[i] >= a[i + 1]) continue; p = i; break; } int q = 0; for (int i = a.length - 1; i > p; i--) { if (a[i] <= a[p]) continue; q = i; break; } if (p == 0 && q == 0) return null; int temp = a[p]; a[p] = a[q]; a[q] = temp; int l = p, r = a.length; while (++l < --r) { temp = a[l]; a[l] = a[r]; a[r] = temp; } return a; } } static class SegTree<S> { final int MAX; final int N; final java.util.function.BinaryOperator<S> op; final S E; final S[] data; @SuppressWarnings("unchecked") public SegTree(int n, java.util.function.BinaryOperator<S> op, S e) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.E = e; this.op = op; this.data = (S[]) new Object[N << 1]; java.util.Arrays.fill(data, E); } public SegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e) { this(dat.length, op, e); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, data, N, l); for (int i = N - 1; i > 0; i--) { data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]); } } public void set(int p, S x) { exclusiveRangeCheck(p); data[p += N] = x; p >>= 1; while (p > 0) { data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]); p >>= 1; } } public S get(int p) { exclusiveRangeCheck(p); return data[p + N]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException(String.format("Invalid range: [%d, %d)", l, r)); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); S sumLeft = E; S sumRight = E; l += N; r += N; while (l < r) { if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]); if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight); l >>= 1; r >>= 1; } return op.apply(sumLeft, sumRight); } public S allProd() { return data[1]; } public int maxRight(int l, java.util.function.Predicate<S> f) { inclusiveRangeCheck(l); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!f.test(op.apply(sum, data[l]))) { while (l < N) { l = l << 1; if (f.test(op.apply(sum, data[l]))) { sum = op.apply(sum, data[l]); l++; } } return l - N; } sum = op.apply(sum, data[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> f) { inclusiveRangeCheck(r); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!f.test(op.apply(data[r], sum))) { while (r < N) { r = r << 1 | 1; if (f.test(op.apply(data[r], sum))) { sum = op.apply(data[r], sum); r--; } } return r + 1 - N; } sum = op.apply(data[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d).", p, 0, MAX)); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d].", p, 0, MAX)); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } public String toDetailedString() { return toDetailedString(1, 0); } private String toDetailedString(int k, int sp) { if (k >= N) return indent(sp) + data[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent); s += "\n"; s += indent(sp) + data[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n-- > 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(data[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } static class LazySegTree<S, F> { final int MAX; final int N; final int Log; final java.util.function.BinaryOperator<S> Op; final S E; final java.util.function.BiFunction<F, S, S> Mapping; final java.util.function.BinaryOperator<F> Composition; final F Id; final S[] Dat; final F[] Laz; @SuppressWarnings("unchecked") public LazySegTree(int n, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.Log = Integer.numberOfTrailingZeros(N); this.Op = op; this.E = e; this.Mapping = mapping; this.Composition = composition; this.Id = id; this.Dat = (S[]) new Object[N << 1]; this.Laz = (F[]) new Object[N]; java.util.Arrays.fill(Dat, E); java.util.Arrays.fill(Laz, Id); } public LazySegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this(dat.length, op, e, mapping, composition, id); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, Dat, N, l); for (int i = N - 1; i > 0; i--) { Dat[i] = Op.apply(Dat[i << 1 | 0], Dat[i << 1 | 1]); } } private void push(int k) { if (Laz[k] == Id) return; int lk = k << 1 | 0, rk = k << 1 | 1; Dat[lk] = Mapping.apply(Laz[k], Dat[lk]); Dat[rk] = Mapping.apply(Laz[k], Dat[rk]); if (lk < N) Laz[lk] = Composition.apply(Laz[k], Laz[lk]); if (rk < N) Laz[rk] = Composition.apply(Laz[k], Laz[rk]); Laz[k] = Id; } private void pushTo(int k) { for (int i = Log; i > 0; i--) push(k >> i); } private void pushTo(int lk, int rk) { for (int i = Log; i > 0; i--) { if (((lk >> i) << i) != lk) push(lk >> i); if (((rk >> i) << i) != rk) push(rk >> i); } } private void updateFrom(int k) { k >>= 1; while (k > 0) { Dat[k] = Op.apply(Dat[k << 1 | 0], Dat[k << 1 | 1]); k >>= 1; } } private void updateFrom(int lk, int rk) { for (int i = 1; i <= Log; i++) { if (((lk >> i) << i) != lk) { int lki = lk >> i; Dat[lki] = Op.apply(Dat[lki << 1 | 0], Dat[lki << 1 | 1]); } if (((rk >> i) << i) != rk) { int rki = (rk - 1) >> i; Dat[rki] = Op.apply(Dat[rki << 1 | 0], Dat[rki << 1 | 1]); } } } public void set(int p, S x) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = x; updateFrom(p); } public S get(int p) { exclusiveRangeCheck(p); p += N; pushTo(p); return Dat[p]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException(String.format("Invalid range: [%d, %d)", l, r)); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return E; l += N; r += N; pushTo(l, r); S sumLeft = E, sumRight = E; while (l < r) { if ((l & 1) == 1) sumLeft = Op.apply(sumLeft, Dat[l++]); if ((r & 1) == 1) sumRight = Op.apply(Dat[--r], sumRight); l >>= 1; r >>= 1; } return Op.apply(sumLeft, sumRight); } public S allProd() { return Dat[1]; } public void apply(int p, F f) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = Mapping.apply(f, Dat[p]); updateFrom(p); } public void apply(int l, int r, F f) { if (l > r) { throw new IllegalArgumentException(String.format("Invalid range: [%d, %d)", l, r)); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return; l += N; r += N; pushTo(l, r); for (int l2 = l, r2 = r; l2 < r2;) { if ((l2 & 1) == 1) { Dat[l2] = Mapping.apply(f, Dat[l2]); if (l2 < N) Laz[l2] = Composition.apply(f, Laz[l2]); l2++; } if ((r2 & 1) == 1) { r2--; Dat[r2] = Mapping.apply(f, Dat[r2]); if (r2 < N) Laz[r2] = Composition.apply(f, Laz[r2]); } l2 >>= 1; r2 >>= 1; } updateFrom(l, r); } public int maxRight(int l, java.util.function.Predicate<S> g) { inclusiveRangeCheck(l); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; pushTo(l); S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!g.test(Op.apply(sum, Dat[l]))) { while (l < N) { push(l); l = l << 1; if (g.test(Op.apply(sum, Dat[l]))) { sum = Op.apply(sum, Dat[l]); l++; } } return l - N; } sum = Op.apply(sum, Dat[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> g) { inclusiveRangeCheck(r); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; pushTo(r - 1); S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!g.test(Op.apply(Dat[r], sum))) { while (r < N) { push(r); r = r << 1 | 1; if (g.test(Op.apply(Dat[r], sum))) { sum = Op.apply(Dat[r], sum); r--; } } return r + 1 - N; } sum = Op.apply(Dat[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException(String.format("Index %d is not in [%d, %d).", p, 0, MAX)); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException(String.format("Index %d is not in [%d, %d].", p, 0, MAX)); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } private S[] simulatePushAll() { S[] simDat = java.util.Arrays.copyOf(Dat, 2 * N); F[] simLaz = java.util.Arrays.copyOf(Laz, 2 * N); for (int k = 1; k < N; k++) { if (simLaz[k] == Id) continue; int lk = k << 1 | 0, rk = k << 1 | 1; simDat[lk] = Mapping.apply(simLaz[k], simDat[lk]); simDat[rk] = Mapping.apply(simLaz[k], simDat[rk]); if (lk < N) simLaz[lk] = Composition.apply(simLaz[k], simLaz[lk]); if (rk < N) simLaz[rk] = Composition.apply(simLaz[k], simLaz[rk]); simLaz[k] = Id; } return simDat; } public String toDetailedString() { return toDetailedString(1, 0, simulatePushAll()); } private String toDetailedString(int k, int sp, S[] dat) { if (k >= N) return indent(sp) + dat[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent, dat); s += "\n"; s += indent(sp) + dat[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent, dat); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n-- > 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { S[] dat = simulatePushAll(); StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(dat[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } static class MaxFlow { private static final class InternalCapEdge { final int to; final int rev; long cap; InternalCapEdge(int to, int rev, long cap) { this.to = to; this.rev = rev; this.cap = cap; } } public static final class CapEdge { public final int from, to; public final long cap, flow; CapEdge(int from, int to, long cap, long flow) { this.from = from; this.to = to; this.cap = cap; this.flow = flow; } @Override public boolean equals(Object o) { if (o instanceof CapEdge) { CapEdge e = (CapEdge) o; return from == e.from && to == e.to && cap == e.cap && flow == e.flow; } return false; } } private static final class IntPair { final int first, second; IntPair(int first, int second) { this.first = first; this.second = second; } } static final long INF = Long.MAX_VALUE; private final int n; private final java.util.ArrayList<IntPair> pos; private final java.util.ArrayList<InternalCapEdge>[] g; @SuppressWarnings("unchecked") public MaxFlow(int n) { this.n = n; this.pos = new java.util.ArrayList<>(); this.g = new java.util.ArrayList[n]; for (int i = 0; i < n; i++) { this.g[i] = new java.util.ArrayList<>(); } } public int addEdge(int from, int to, long cap) { rangeCheck(from, 0, n); rangeCheck(to, 0, n); nonNegativeCheck(cap, "Capacity"); int m = pos.size(); pos.add(new IntPair(from, g[from].size())); int fromId = g[from].size(); int toId = g[to].size(); if (from == to) toId++; g[from].add(new InternalCapEdge(to, toId, cap)); g[to].add(new InternalCapEdge(from, fromId, 0L)); return m; } private InternalCapEdge getInternalEdge(int i) { return g[pos.get(i).first].get(pos.get(i).second); } private InternalCapEdge getInternalEdgeReversed(InternalCapEdge e) { return g[e.to].get(e.rev); } public CapEdge getEdge(int i) { int m = pos.size(); rangeCheck(i, 0, m); InternalCapEdge e = getInternalEdge(i); InternalCapEdge re = getInternalEdgeReversed(e); return new CapEdge(re.to, e.to, e.cap + re.cap, re.cap); } public CapEdge[] getEdges() { CapEdge[] res = new CapEdge[pos.size()]; java.util.Arrays.setAll(res, this::getEdge); return res; } public void changeEdge(int i, long newCap, long newFlow) { int m = pos.size(); rangeCheck(i, 0, m); nonNegativeCheck(newCap, "Capacity"); if (newFlow > newCap) { throw new IllegalArgumentException( String.format("Flow %d is greater than the capacity %d.", newCap, newFlow)); } InternalCapEdge e = getInternalEdge(i); InternalCapEdge re = getInternalEdgeReversed(e); e.cap = newCap - newFlow; re.cap = newFlow; } public long maxFlow(int s, int t) { return flow(s, t, INF); } public long flow(int s, int t, long flowLimit) { rangeCheck(s, 0, n); rangeCheck(t, 0, n); long flow = 0L; int[] level = new int[n]; int[] que = new int[n]; int[] iter = new int[n]; while (flow < flowLimit) { bfs(s, t, level, que); if (level[t] < 0) break; java.util.Arrays.fill(iter, 0); while (flow < flowLimit) { long d = dfs(t, s, flowLimit - flow, iter, level); if (d == 0) break; flow += d; } } return flow; } private void bfs(int s, int t, int[] level, int[] que) { java.util.Arrays.fill(level, -1); int hd = 0, tl = 0; que[tl++] = s; level[s] = 0; while (hd < tl) { int u = que[hd++]; for (InternalCapEdge e : g[u]) { int v = e.to; if (e.cap == 0 || level[v] >= 0) continue; level[v] = level[u] + 1; if (v == t) return; que[tl++] = v; } } } private long dfs(int cur, int s, long flowLimit, int[] iter, int[] level) { if (cur == s) return flowLimit; long res = 0; int curLevel = level[cur]; for (int itMax = g[cur].size(); iter[cur] < itMax; iter[cur]++) { int i = iter[cur]; InternalCapEdge e = g[cur].get(i); InternalCapEdge re = getInternalEdgeReversed(e); if (curLevel <= level[e.to] || re.cap == 0) continue; long d = dfs(e.to, s, Math.min(flowLimit - res, re.cap), iter, level); if (d <= 0) continue; e.cap += d; re.cap -= d; res += d; if (res == flowLimit) break; } return res; } public boolean[] minCut(int s) { rangeCheck(s, 0, n); boolean[] visited = new boolean[n]; int[] stack = new int[n]; int ptr = 0; stack[ptr++] = s; visited[s] = true; while (ptr > 0) { int u = stack[--ptr]; for (InternalCapEdge e : g[u]) { int v = e.to; if (e.cap > 0 && !visited[v]) { visited[v] = true; stack[ptr++] = v; } } } return visited; } private void rangeCheck(int i, int minInclusive, int maxExclusive) { if (i < 0 || i >= maxExclusive) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, maxExclusive)); } } private void nonNegativeCheck(long cap, String attribute) { if (cap < 0) { throw new IllegalArgumentException(String.format("%s %d is negative.", attribute, cap)); } } } static class StringAlgorithm { private static int[] saNaive(int[] s) { int n = s.length; int[] sa = new int[n]; for (int i = 0; i < n; i++) { sa[i] = i; } insertionsortUsingComparator(sa, (l, r) -> { while (l < n && r < n) { if (s[l] != s[r]) return s[l] - s[r]; l++; r++; } return -(l - r); }); return sa; } public static int[] saDoubling(int[] s) { int n = s.length; int[] sa = new int[n]; for (int i = 0; i < n; i++) { sa[i] = i; } int[] rnk = java.util.Arrays.copyOf(s, n); int[] tmp = new int[n]; for (int k = 1; k < n; k *= 2) { final int _k = k; final int[] _rnk = rnk; java.util.function.IntBinaryOperator cmp = (x, y) -> { if (_rnk[x] != _rnk[y]) return _rnk[x] - _rnk[y]; int rx = x + _k < n ? _rnk[x + _k] : -1; int ry = y + _k < n ? _rnk[y + _k] : -1; return rx - ry; }; mergesortUsingComparator(sa, cmp); tmp[sa[0]] = 0; for (int i = 1; i < n; i++) { tmp[sa[i]] = tmp[sa[i - 1]] + (cmp.applyAsInt(sa[i - 1], sa[i]) < 0 ? 1 : 0); } int[] buf = tmp; tmp = rnk; rnk = buf; } return sa; } private static void insertionsortUsingComparator(int[] a, java.util.function.IntBinaryOperator comparator) { final int n = a.length; for (int i = 1; i < n; i++) { final int tmp = a[i]; if (comparator.applyAsInt(a[i - 1], tmp) > 0) { int j = i; do { a[j] = a[j - 1]; j--; } while (j > 0 && comparator.applyAsInt(a[j - 1], tmp) > 0); a[j] = tmp; } } } private static void mergesortUsingComparator(int[] a, java.util.function.IntBinaryOperator comparator) { final int n = a.length; final int[] work = new int[n]; for (int block = 1; block <= n; block <<= 1) { final int block2 = block << 1; for (int l = 0, max = n - block; l < max; l += block2) { int m = l + block; int r = Math.min(l + block2, n); System.arraycopy(a, l, work, 0, block); for (int i = l, wi = 0, ti = m;; i++) { if (ti == r) { System.arraycopy(work, wi, a, i, block - wi); break; } if (comparator.applyAsInt(work[wi], a[ti]) > 0) { a[i] = a[ti++]; } else { a[i] = work[wi++]; if (wi == block) break; } } } } } private static final int THRESHOLD_NAIVE = 50; // private static final int THRESHOLD_DOUBLING = 0; private static int[] sais(int[] s, int upper) { int n = s.length; if (n == 0) return new int[0]; if (n == 1) return new int[] { 0 }; if (n == 2) { if (s[0] < s[1]) { return new int[] { 0, 1 }; } else { return new int[] { 1, 0 }; } } if (n < THRESHOLD_NAIVE) { return saNaive(s); } // if (n < THRESHOLD_DOUBLING) { // return saDoubling(s); // } int[] sa = new int[n]; boolean[] ls = new boolean[n]; for (int i = n - 2; i >= 0; i--) { ls[i] = s[i] == s[i + 1] ? ls[i + 1] : s[i] < s[i + 1]; } int[] sumL = new int[upper + 1]; int[] sumS = new int[upper + 1]; for (int i = 0; i < n; i++) { if (ls[i]) { sumL[s[i] + 1]++; } else { sumS[s[i]]++; } } for (int i = 0; i <= upper; i++) { sumS[i] += sumL[i]; if (i < upper) sumL[i + 1] += sumS[i]; } java.util.function.Consumer<int[]> induce = lms -> { java.util.Arrays.fill(sa, -1); int[] buf = new int[upper + 1]; System.arraycopy(sumS, 0, buf, 0, upper + 1); for (int d : lms) { if (d == n) continue; sa[buf[s[d]]++] = d; } System.arraycopy(sumL, 0, buf, 0, upper + 1); sa[buf[s[n - 1]]++] = n - 1; for (int i = 0; i < n; i++) { int v = sa[i]; if (v >= 1 && !ls[v - 1]) { sa[buf[s[v - 1]]++] = v - 1; } } System.arraycopy(sumL, 0, buf, 0, upper + 1); for (int i = n - 1; i >= 0; i--) { int v = sa[i]; if (v >= 1 && ls[v - 1]) { sa[--buf[s[v - 1] + 1]] = v - 1; } } }; int[] lmsMap = new int[n + 1]; java.util.Arrays.fill(lmsMap, -1); int m = 0; for (int i = 1; i < n; i++) { if (!ls[i - 1] && ls[i]) { lmsMap[i] = m++; } } int[] lms = new int[m]; { int p = 0; for (int i = 1; i < n; i++) { if (!ls[i - 1] && ls[i]) { lms[p++] = i; } } } induce.accept(lms); if (m > 0) { int[] sortedLms = new int[m]; { int p = 0; for (int v : sa) { if (lmsMap[v] != -1) { sortedLms[p++] = v; } } } int[] recS = new int[m]; int recUpper = 0; recS[lmsMap[sortedLms[0]]] = 0; for (int i = 1; i < m; i++) { int l = sortedLms[i - 1], r = sortedLms[i]; int endL = (lmsMap[l] + 1 < m) ? lms[lmsMap[l] + 1] : n; int endR = (lmsMap[r] + 1 < m) ? lms[lmsMap[r] + 1] : n; boolean same = true; if (endL - l != endR - r) { same = false; } else { while (l < endL && s[l] == s[r]) { l++; r++; } if (l == n || s[l] != s[r]) same = false; } if (!same) { recUpper++; } recS[lmsMap[sortedLms[i]]] = recUpper; } int[] recSA = sais(recS, recUpper); for (int i = 0; i < m; i++) { sortedLms[i] = lms[recSA[i]]; } induce.accept(sortedLms); } return sa; } public static int[] suffixArray(int[] s, int upper) { assert (0 <= upper); for (int d : s) { assert (0 <= d && d <= upper); } return sais(s, upper); } public static int[] suffixArray(int[] s) { int n = s.length; int[] vals = Arrays.copyOf(s, n); java.util.Arrays.sort(vals); int p = 1; for (int i = 1; i < n; i++) { if (vals[i] != vals[i - 1]) { vals[p++] = vals[i]; } } int[] s2 = new int[n]; for (int i = 0; i < n; i++) { s2[i] = java.util.Arrays.binarySearch(vals, 0, p, s[i]); } return sais(s2, p); } public static int[] suffixArray(char[] s) { int n = s.length; int[] s2 = new int[n]; for (int i = 0; i < n; i++) { s2[i] = s[i]; } return sais(s2, 255); } public static int[] suffixArray(java.lang.String s) { return suffixArray(s.toCharArray()); } public static int[] lcpArray(int[] s, int[] sa) { int n = s.length; assert (n >= 1); int[] rnk = new int[n]; for (int i = 0; i < n; i++) { rnk[sa[i]] = i; } int[] lcp = new int[n - 1]; int h = 0; for (int i = 0; i < n; i++) { if (h > 0) h--; if (rnk[i] == 0) { continue; } int j = sa[rnk[i] - 1]; for (; j + h < n && i + h < n; h++) { if (s[j + h] != s[i + h]) break; } lcp[rnk[i] - 1] = h; } return lcp; } public static int[] lcpArray(char[] s, int[] sa) { int n = s.length; int[] s2 = new int[n]; for (int i = 0; i < n; i++) { s2[i] = s[i]; } return lcpArray(s2, sa); } public static int[] lcpArray(java.lang.String s, int[] sa) { return lcpArray(s.toCharArray(), sa); } public static int[] zAlgorithm(int[] s) { int n = s.length; if (n == 0) return new int[0]; int[] z = new int[n]; for (int i = 1, j = 0; i < n; i++) { int k = j + z[j] <= i ? 0 : Math.min(j + z[j] - i, z[i - j]); while (i + k < n && s[k] == s[i + k]) k++; z[i] = k; if (j + z[j] < i + z[i]) j = i; } z[0] = n; return z; } public static int[] zAlgorithm(char[] s) { int n = s.length; if (n == 0) return new int[0]; int[] z = new int[n]; for (int i = 1, j = 0; i < n; i++) { int k = j + z[j] <= i ? 0 : Math.min(j + z[j] - i, z[i - j]); while (i + k < n && s[k] == s[i + k]) k++; z[i] = k; if (j + z[j] < i + z[i]) j = i; } z[0] = n; return z; } public static int[] zAlgorithm(String s) { return zAlgorithm(s.toCharArray()); } } }
ConDefects/ConDefects/Code/abc251_g/Java/31687680
condefects-java_data_404
import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class Main { public static long qpow(int x, int n, int MOD) { if (n == 0) return 1; long res = qpow(x, n / 2, MOD); return n % 2 == 0 ? res * res % MOD : res * res % MOD * x % MOD; } static class Pair { long x; long y; public Pair(long x, long y) { this.x = x; this.y = y; } } static class Triplet { long x; long y; long idx; public Triplet(long x, long y, long idx) { this.x = x; this.y = y; this.idx = idx; } } static void make(int[] parent) { for (int i = 0; i < parent.length; i++) { parent[i] = i; } } static int find(int v, int[] parent) { if (v == parent[v]) return v; return parent[v] = find(parent[v], parent); } static boolean union(int a, int b, int[] parent, int[] freq) { a = find(a, parent); b = find(b, parent); if (a == b) return freq[b] % 2 == 0; freq[a] += freq[b]; parent[b] = a; return true; } static boolean strenbs(Pair a[], Pair b) { // x is the target value or key boolean ok = false; int l = 0, r = a.length - 1; while (l <= r) { int m = (l + r) / 2; if (a[m].x > b.x) { r = m - 1; if (a[m].y < b.y) return true; } else l = m + 1; } return false; } static int dfs(int u, int p, ArrayList<ArrayList<Integer>> adj, boolean[] vis) { vis[u] = true; int c = 0; for (int v : adj.get(u)) { if (vis[v] == true) continue; c += 1 + dfs(v, u, adj, vis); } return c; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = 1; StringBuilder str = new StringBuilder(); for (int xx = 0; xx < t; xx++) { int n = sc.nextInt(); int m = sc.nextInt(); ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); for (int i = 0; i < m; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; adj.get(a).add(b); adj.get(b).add(a); } boolean[] vis = new boolean[n]; long ans = 0; for (int i = 0; i < n; i++) { if (vis[i] == true) continue; int k = dfs(i, -1, adj, vis); ans += (k * (k + 1)) / 2; // System.out.println(k + " " + ans); } str.append(ans - m); } System.out.println(str); sc.close(); } } import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class Main { public static long qpow(int x, int n, int MOD) { if (n == 0) return 1; long res = qpow(x, n / 2, MOD); return n % 2 == 0 ? res * res % MOD : res * res % MOD * x % MOD; } static class Pair { long x; long y; public Pair(long x, long y) { this.x = x; this.y = y; } } static class Triplet { long x; long y; long idx; public Triplet(long x, long y, long idx) { this.x = x; this.y = y; this.idx = idx; } } static void make(int[] parent) { for (int i = 0; i < parent.length; i++) { parent[i] = i; } } static int find(int v, int[] parent) { if (v == parent[v]) return v; return parent[v] = find(parent[v], parent); } static boolean union(int a, int b, int[] parent, int[] freq) { a = find(a, parent); b = find(b, parent); if (a == b) return freq[b] % 2 == 0; freq[a] += freq[b]; parent[b] = a; return true; } static boolean strenbs(Pair a[], Pair b) { // x is the target value or key boolean ok = false; int l = 0, r = a.length - 1; while (l <= r) { int m = (l + r) / 2; if (a[m].x > b.x) { r = m - 1; if (a[m].y < b.y) return true; } else l = m + 1; } return false; } static int dfs(int u, int p, ArrayList<ArrayList<Integer>> adj, boolean[] vis) { vis[u] = true; int c = 0; for (int v : adj.get(u)) { if (vis[v] == true) continue; c += 1 + dfs(v, u, adj, vis); } return c; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = 1; StringBuilder str = new StringBuilder(); for (int xx = 0; xx < t; xx++) { int n = sc.nextInt(); int m = sc.nextInt(); ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); for (int i = 0; i < m; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; adj.get(a).add(b); adj.get(b).add(a); } boolean[] vis = new boolean[n]; long ans = 0; for (int i = 0; i < n; i++) { if (vis[i] == true) continue; long k = dfs(i, -1, adj, vis); ans += (k * (k + 1)) / 2; // System.out.println(k + " " + ans); } str.append(ans - m); } System.out.println(str); sc.close(); } }
ConDefects/ConDefects/Code/abc350_d/Java/53748018
condefects-java_data_405
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { try(Scanner sc = new Scanner(System.in);) { int n = sc.nextInt(); int m = sc.nextInt(); UnionFind uf = new UnionFind(n); for(int i = 0; i < m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); a--; b--; uf.unite(a, b); } long ans = 0; for(int i = 0; i < n; i++) { if(uf.root(i) == i) { int s = uf.siz(i); ans += s * (s - 1) / 2; } } System.out.println(ans - m); } } } class UnionFind{ private int[] par; private int[] siz; public UnionFind(int n) { par = new int[n]; siz= new int[n]; Arrays.fill(par, -1); Arrays.fill(siz, 1); } public int root(int x) { if(par[x] == -1) return x; return par[x] = root(par[x]); } public boolean same(int x, int y) { return root(x) == root(y); } public int siz(int x) { return siz[root(x)]; } public boolean unite(int x, int y) { x = root(x); y = root(y); if(x == y) return false; if(siz[x] > siz[y]) { int tmp = x; x = y; y = tmp; } par[x] = y; siz[y] += siz[x]; return true; } } import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { try(Scanner sc = new Scanner(System.in);) { int n = sc.nextInt(); int m = sc.nextInt(); UnionFind uf = new UnionFind(n); for(int i = 0; i < m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); a--; b--; uf.unite(a, b); } long ans = 0; for(int i = 0; i < n; i++) { if(uf.root(i) == i) { long s = uf.siz(i); ans += s * (s - 1) / 2; } } System.out.println(ans - m); } } } class UnionFind{ private int[] par; private int[] siz; public UnionFind(int n) { par = new int[n]; siz= new int[n]; Arrays.fill(par, -1); Arrays.fill(siz, 1); } public int root(int x) { if(par[x] == -1) return x; return par[x] = root(par[x]); } public boolean same(int x, int y) { return root(x) == root(y); } public int siz(int x) { return siz[root(x)]; } public boolean unite(int x, int y) { x = root(x); y = root(y); if(x == y) return false; if(siz[x] > siz[y]) { int tmp = x; x = y; y = tmp; } par[x] = y; siz[y] += siz[x]; return true; } }
ConDefects/ConDefects/Code/abc350_d/Java/52731169
condefects-java_data_406
import java.util.*; // 我认为这个题是并查集的题 public class Main { public static int[] p = null; // 表示的是父亲 public static void main(String[] args) { var sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); p = new int[n + 10]; for(int i = 1; i <= n; i ++ ) { p[i] = i; // 刚开始的祖宗 都是自己自己 } long ret = 0; int mm = m; var mp = new HashMap<Integer, Long>(); var se = new TreeSet<Integer>(); while(m -- != 0 ) { int x = sc.nextInt(); int y = sc.nextInt(); // 这里理解为y加到x的节点下面 p[find(y)] = find(x); // 该不会是这里出问题了吧 } for(int i = 1; i <= n; i ++ ) { int x = p[i]; if(!mp.containsKey(x)) { mp.put(x, 0l); } long t = mp.get(x) + 1; mp.put(x, t); se.add(x); // 这里面存的是 都是祖宗 } for(int i : se) { //System.out.print("i = " + i + "\n"); //System.out.print("x = " + mp.get(i) + "\n"); long tt = mp.get(i); long t2 = mp.get(i) - 1; ret += tt * t2 / 2; //System.out.print("ret = " + ret + "\n"); } ret -= mm; System.out.print(ret); } public static int find(int x) { if(x != p[x])p[x] = find(p[x]); return p[x]; } } import java.util.*; // 我认为这个题是并查集的题 public class Main { public static int[] p = null; // 表示的是父亲 public static void main(String[] args) { var sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); p = new int[n + 10]; for(int i = 1; i <= n; i ++ ) { p[i] = i; // 刚开始的祖宗 都是自己自己 } long ret = 0; int mm = m; var mp = new HashMap<Integer, Long>(); var se = new TreeSet<Integer>(); while(m -- != 0 ) { int x = sc.nextInt(); int y = sc.nextInt(); // 这里理解为y加到x的节点下面 p[find(y)] = find(x); // 该不会是这里出问题了吧 } for(int i = 1; i <= n; i ++ ) { int x = p[find(i)]; if(!mp.containsKey(x)) { mp.put(x, 0l); } long t = mp.get(x) + 1; mp.put(x, t); se.add(x); // 这里面存的是 都是祖宗 } for(int i : se) { //System.out.print("i = " + i + "\n"); //System.out.print("x = " + mp.get(i) + "\n"); long tt = mp.get(i); long t2 = mp.get(i) - 1; ret += tt * t2 / 2; //System.out.print("ret = " + ret + "\n"); } ret -= mm; System.out.print(ret); } public static int find(int x) { if(x != p[x])p[x] = find(p[x]); return p[x]; } }
ConDefects/ConDefects/Code/abc350_d/Java/53947932
condefects-java_data_407
import java.util.*; public class Main { static Scanner s = new Scanner(System.in); static int n, m, p[], size[], a, b; public static void main(String[] args) { n = s.nextInt(); m = s.nextInt(); int k = m; p = new int[n + 1]; size = new int[n + 1]; for(int i = 1; i <= n; i++) { p[i] = i; size[i] = 1; } while(m -- >0) { a = s.nextInt(); b = s.nextInt(); if(find(a)!=find(b)) { size[find(b)] += size[find(a)]; p[find(a)] = find(b); } } long res = 0; Set<Integer> set = new HashSet<>(); for(int i = 1; i<=n; i++) { if(!set.contains(find(i))) { set.add(find(i)); int num = size[find(i)]; res += (num)*(num-1)/2; } } System.out.print(res - k); } private static int find(int x) { if(p[x] != x) p[x] = find(p[x]); return p[x]; } } import java.util.*; public class Main { static Scanner s = new Scanner(System.in); static int n, m, p[], size[], a, b; public static void main(String[] args) { n = s.nextInt(); m = s.nextInt(); int k = m; p = new int[n + 1]; size = new int[n + 1]; for(int i = 1; i <= n; i++) { p[i] = i; size[i] = 1; } while(m -- >0) { a = s.nextInt(); b = s.nextInt(); if(find(a)!=find(b)) { size[find(b)] += size[find(a)]; p[find(a)] = find(b); } } long res = 0; Set<Integer> set = new HashSet<>(); for(int i = 1; i<=n; i++) { if(!set.contains(find(i))) { set.add(find(i)); int num = size[find(i)]; res += 1l*(num)*(num-1)/2; } } System.out.print(res - k); } private static int find(int x) { if(p[x] != x) p[x] = find(p[x]); return p[x]; } }
ConDefects/ConDefects/Code/abc350_d/Java/52983262
condefects-java_data_408
import java.util.Scanner; import java.util.List; import java.util.ArrayList; public class Main { public static void main(String[] args){ ArrayList<Integer> ball = new ArrayList<Integer>(); Scanner scan = new Scanner(System.in); int number = scan.nextInt(); scan.nextLine(); String inputs = scan.nextLine(); String[] n = inputs.split(" "); ArrayList<Integer> inp = new ArrayList<Integer>(); for(int i= 0;i<n.length;i++){ inp.add(Integer.parseInt(n[i])); } ball.add(inp.get(0)); for(int k = 1; k<inp.size();k++){ int addnumber = inp.get(k); if(ball.get(ball.size()-1) != addnumber){ ball.add(addnumber); System.out.println(addnumber+"add"); }else{ while(ball.get(ball.size()-1) == addnumber){ System.out.println(addnumber+"remove"); ball.remove(ball.size()-1); addnumber= addnumber+1; if(ball.size()==0){ break; } } ball.add(addnumber); } } System.out.println(ball.size()); } } import java.util.Scanner; import java.util.List; import java.util.ArrayList; public class Main { public static void main(String[] args){ ArrayList<Integer> ball = new ArrayList<Integer>(); Scanner scan = new Scanner(System.in); int number = scan.nextInt(); scan.nextLine(); String inputs = scan.nextLine(); String[] n = inputs.split(" "); ArrayList<Integer> inp = new ArrayList<Integer>(); for(int i= 0;i<n.length;i++){ inp.add(Integer.parseInt(n[i])); } ball.add(inp.get(0)); for(int k = 1; k<inp.size();k++){ int addnumber = inp.get(k); if(ball.get(ball.size()-1) != addnumber){ ball.add(addnumber); }else{ while(ball.get(ball.size()-1) == addnumber){ ball.remove(ball.size()-1); addnumber= addnumber+1; if(ball.size()==0){ break; } } ball.add(addnumber); } } System.out.println(ball.size()); } }
ConDefects/ConDefects/Code/abc351_c/Java/53619313
condefects-java_data_409
import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; public class Main{ public static void main(String[] args){ InputStreamReader input = new InputStreamReader(System.in); BufferedReader buff = new BufferedReader(input); try { final int N = Integer.parseInt( buff.readLine()); final int N_max = 2 * N + 2; int[] ans = new int[N_max]; ans[1] = 0; String[] str = buff.readLine().split(" "); for( int i = 1 ; i <= N ; i++){ int a = Integer.parseInt(str[i-1]); ans[2*i] = ans[a] + 1; ans[2*i +1] = ans[a] + 1; } StringBuilder t = new StringBuilder(); for (int i = 1; i < N_max - 1; i++) { t.append(ans[i]); t.append("\n"); } System.out.print(t.toString()); buff.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } } import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; public class Main{ public static void main(String[] args){ InputStreamReader input = new InputStreamReader(System.in); BufferedReader buff = new BufferedReader(input); try { final int N = Integer.parseInt( buff.readLine()); final int N_max = 2 * N + 2; int[] ans = new int[N_max]; ans[1] = 0; String[] str = buff.readLine().split(" "); for( int i = 1 ; i <= N ; i++){ int a = Integer.parseInt(str[i-1]); ans[2*i] = ans[a] + 1; ans[2*i +1] = ans[a] + 1; } StringBuilder t = new StringBuilder(); for (int i = 1; i < N_max; i++) { t.append(ans[i]); t.append("\n"); } System.out.print(t.toString()); buff.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } }
ConDefects/ConDefects/Code/abc274_c/Java/46767516
condefects-java_data_410
import java.util.Scanner; public class Main { public static void main( String args[]) { Scanner scn = new Scanner( System.in); int N = scn.nextInt(); int[] days = new int[N]; int[] ans = new int[N]; for ( int i = 0; i < N; i++) { days[i] = scn.nextInt(); } for ( int j = 0; j < N - 1; j++) { if ( days[j] > days[j + 1]) { ans[j] = 1; ans[j + 1] = 1; } } StringBuilder sb = new StringBuilder(); for ( int k = 0; k < N; k++) { sb.append( ans[k] + " "); } sb.deleteCharAt( sb.length() - 1); System.out.println( sb.toString()); } } import java.util.Scanner; public class Main { public static void main( String args[]) { Scanner scn = new Scanner( System.in); int N = scn.nextInt(); int[] days = new int[N]; int[] ans = new int[N]; for ( int i = 0; i < N; i++) { days[i] = scn.nextInt(); } for ( int j = 0; j < N - 1; j++) { if ( days[j] > days[j + 1]) { ans[j] = ans[j] == 1 ? 0 : 1; ans[j + 1] = 1; } } StringBuilder sb = new StringBuilder(); for ( int k = 0; k < N; k++) { sb.append( ans[k] + " "); } sb.deleteCharAt( sb.length() - 1); System.out.println( sb.toString()); } }
ConDefects/ConDefects/Code/arc128_a/Java/34663018
condefects-java_data_411
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.NoSuchElementException; class Main implements Runnable { public static void main(String[] args) { new Main().run(); } long gcd(long a, long b) { return a==0?b:gcd(b%a,a); } public void run() { FastScanner sc = new FastScanner(); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int[] a=new int[n]; for (int i=0;i<n;++i) a[i]=sc.nextInt(); int[] ans=new int[n]; for (int i=0;i+1<n;++i) { if (a[i]<a[i+1]) { ans[i]^=1; ans[i+1]^=1; } } for (int i=0;i<n;++i) { pw.print(ans[i]+(i==n-1?"\n":" ")); } pw.close(); } void tr(Object...objects) { System.out.println(Arrays.deepToString(objects)); } } class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next());} } import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.NoSuchElementException; class Main implements Runnable { public static void main(String[] args) { new Main().run(); } long gcd(long a, long b) { return a==0?b:gcd(b%a,a); } public void run() { FastScanner sc = new FastScanner(); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int[] a=new int[n]; for (int i=0;i<n;++i) a[i]=sc.nextInt(); int[] ans=new int[n]; for (int i=0;i+1<n;++i) { if (a[i]>a[i+1]) { ans[i]^=1; ans[i+1]^=1; } } for (int i=0;i<n;++i) { pw.print(ans[i]+(i==n-1?"\n":" ")); } pw.close(); } void tr(Object...objects) { System.out.println(Arrays.deepToString(objects)); } } class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next());} }
ConDefects/ConDefects/Code/arc128_a/Java/26883391
condefects-java_data_412
import java.util.*; public class Main { public static long MOD = 1000000007; public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = sc.next(); long ans = 1; long length = 1; long div = pow(2,MOD - 2); for(int i = 0;i < n - 1;i++) { if(s.charAt(i) == s.charAt(i + 1)) { ans = (length + 1L)/2 * ans % MOD; length = 1; }else { length++; } //System.out.println(i + ":" + ans + " " + length); }ans = ans * (length + 1L) % MOD * div % MOD; System.out.println(ans); }public static long pow(long a,long b) { String bs = Long.toBinaryString(b); long[] pownum = new long[bs.length() + 1]; long ret = 1; pownum[bs.length()] = a; for(int i = bs.length() - 1;i >= 0;i--) { if(bs.charAt(i) == '1') { ret =ret * pownum[i + 1] % MOD; }pownum[i] = pownum[i + 1] * pownum[i + 1] % MOD; } return ret; } } import java.util.*; public class Main { public static long MOD = 1000000007; public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = sc.next(); long ans = 1; long length = 1; long div = pow(2,MOD - 2); for(int i = 0;i < n - 1;i++) { if(s.charAt(i) == s.charAt(i + 1)) { ans = (length + 1L)/2 * ans % MOD; length = 1; }else { length++; } //System.out.println(i + ":" + ans + " " + length); }ans = (length + 1L) /2 * ans % MOD; System.out.println(ans); }public static long pow(long a,long b) { String bs = Long.toBinaryString(b); long[] pownum = new long[bs.length() + 1]; long ret = 1; pownum[bs.length()] = a; for(int i = bs.length() - 1;i >= 0;i--) { if(bs.charAt(i) == '1') { ret =ret * pownum[i + 1] % MOD; }pownum[i] = pownum[i + 1] * pownum[i + 1] % MOD; } return ret; } }
ConDefects/ConDefects/Code/arc180_a/Java/55018310
condefects-java_data_413
import java.math.*; import java.util.*; import java.io.*; public class Main { static int t, n, m, k, p, s, e, c, h, q, g, l, r, count; static long answer = 0, mod = 1000000007, L; static long max = 0, min = Long.MAX_VALUE; static int[] parent; static boolean f = false; static boolean[][] map; static StringBuilder sb = new StringBuilder(); static String[] list; static int[] order; static int len; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; String ss; int i0, i1, i2, i3, t0, t1, t2, t3, q, ll, rr, len, pre; n = Integer.parseInt(br.readLine()); char[] c = br.readLine().toCharArray(); for(i0 = 1; i0 < n; i0+=2) if(c[i0]=='A') c[i0]++; else c[i0]--; answer = 1; pre = c[0]; t0 = 0; for(i0 = 0; i0 < n; i0++) { if(pre==c[i0]) t0++; else { answer = (answer*((t0+1)/2))%mod; t0 = 1; pre = c[i0]; } } answer = (answer*(t0+1)/2)%mod; System.out.println(answer); } static int GCD(int x, int y) { return y==0?x:GCD(y,x%y); } static double ccw(double x1, double y1, double x2, double y2, double x3, double y3) { return x1*y2+x2*y3+x3*y1-x2*y1-x3*y2-x1*y3; } static int Find(int x) { if(0==parent[x]) return x; return parent[x] = Find(parent[x]); } static void Union(int x, int y) { parent[Find(x)] = Find(y); } public static long readLong() throws Exception{ long val = 0; int c = System.in.read(); while (c <= ' ') { c = System.in.read(); } boolean flag = (c == '-'); if (flag) c = System.in.read(); do { val = 10 * val + c - 48; } while ((c = System.in.read()) >= 48 && c <= 57); if (flag) return -val; return val; } public static int readInt() throws Exception{ int val = 0; int c = System.in.read(); while (c <= ' ') { c = System.in.read(); } boolean flag = (c == '-'); if (flag) c = System.in.read(); do { val = 10 * val + c - 48; } while ((c = System.in.read()) >= 48 && c <= 57); if (flag) return -val; return val; } } import java.math.*; import java.util.*; import java.io.*; public class Main { static int t, n, m, k, p, s, e, c, h, q, g, l, r, count; static long answer = 0, mod = 1000000007, L; static long max = 0, min = Long.MAX_VALUE; static int[] parent; static boolean f = false; static boolean[][] map; static StringBuilder sb = new StringBuilder(); static String[] list; static int[] order; static int len; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; String ss; int i0, i1, i2, i3, t0, t1, t2, t3, q, ll, rr, len, pre; n = Integer.parseInt(br.readLine()); char[] c = br.readLine().toCharArray(); for(i0 = 1; i0 < n; i0+=2) if(c[i0]=='A') c[i0]++; else c[i0]--; answer = 1; pre = c[0]; t0 = 0; for(i0 = 0; i0 < n; i0++) { if(pre==c[i0]) t0++; else { answer = (answer*((t0+1)/2))%mod; t0 = 1; pre = c[i0]; } } answer = (answer*((t0+1)/2))%mod; System.out.println(answer); } static int GCD(int x, int y) { return y==0?x:GCD(y,x%y); } static double ccw(double x1, double y1, double x2, double y2, double x3, double y3) { return x1*y2+x2*y3+x3*y1-x2*y1-x3*y2-x1*y3; } static int Find(int x) { if(0==parent[x]) return x; return parent[x] = Find(parent[x]); } static void Union(int x, int y) { parent[Find(x)] = Find(y); } public static long readLong() throws Exception{ long val = 0; int c = System.in.read(); while (c <= ' ') { c = System.in.read(); } boolean flag = (c == '-'); if (flag) c = System.in.read(); do { val = 10 * val + c - 48; } while ((c = System.in.read()) >= 48 && c <= 57); if (flag) return -val; return val; } public static int readInt() throws Exception{ int val = 0; int c = System.in.read(); while (c <= ' ') { c = System.in.read(); } boolean flag = (c == '-'); if (flag) c = System.in.read(); do { val = 10 * val + c - 48; } while ((c = System.in.read()) >= 48 && c <= 57); if (flag) return -val; return val; } }
ConDefects/ConDefects/Code/arc180_a/Java/55040463
condefects-java_data_414
import java.util.*; import java.util.function.*; import java.util.stream.*; import java.io.*; class Solve extends Util { void solve() { int n = in.i(); int m = in.i(); int k = in.i(); long[] a = new long[n]; long[] b = new long[n]; for (int i = 0; i < n; i++) { a[i] = in.l(); b[i] = in.l(); } long[] c = new long[m]; long[] d = new long[m]; for (int i = 0; i < m; i++) { c[i] = in.l(); d[i] = in.l(); } double ng = 0, ok = 1; for (int i = 0; i < 100; i++) { double x = (ng + ok) / 2; double y = x / (1 - x); List<Double> p = new ArrayList<>(); for (int j = 0; j < m; j++) { p.add((double) c[j] - y * d[j]); } Collections.sort(p); long check = 0; //out.a("p: "); //for (int j = 0; j < m; j++) out.a(p.get(j) + " "); //out.an(); for (int j = 0; j < n; j++) { double q = (double) a[j] - y * b[j]; int idx = lower_bound(p, -q); //out.an("q: " + q + " idx: " + idx); check += m - idx; } if (check < k) ok = x; else ng = x; } double ans = ok * 100; out.an(ans); } } // My Library // Version: 2022.12.07 // ================================================================================================= // TODO: // * end を半開区間にする public class Main extends Util { public static void main(String[] args) { try { new Solve().solve(); } catch (Exception e) { throw e; } finally { out.flush(); } } } @FunctionalInterface interface F1<T, R> extends Function<T, R> { default R x(T t) { return apply(t); } } @FunctionalInterface interface F2<T, U, R> extends BiFunction<T, U, R> { default F1<U, R> x(T p1) { return p2 -> apply(p1, p2); } default F1<T, F1<U, R>> currying() { return p1 -> p2 -> apply(p1, p2); } default F2<U, T, R> flip() { return (p1, p2) -> apply(p2, p1); } } @FunctionalInterface interface F3<T, U, V, R> { R apply(T t, U u, V v); default F2<U, V, R> x(T p1) { return (p2, p3) -> apply(p1, p2, p3); } default F1<V, R> x(T p1, U p2) { return p3 -> apply(p1, p2, p3); } default F1<T, F1<U, F1<V, R>>> currying() { return p1 -> p2 -> p3 -> apply(p1, p2, p3); } default F3<V, U, T, R> flip() { return (p1, p2, p3) -> apply(p3, p2, p1); } } @FunctionalInterface interface F4<T, U, V, W, R> { R apply(T t, U u, V v, W w); default F3<U, V, W, R> x(T p1) { return (p2, p3, p4) -> apply(p1, p2, p3, p4); } default F2<V, W, R> x(T p1, U p2) { return (p3, p4) -> apply(p1, p2, p3, p4); } default F1<W, R> x(T p1, U p2, V p3) { return p4 -> apply(p1, p2, p3, p4); } default F1<T, F1<U, F1<V, F1<W, R>>>> currying() { return p1 -> p2 -> p3 -> p4 -> apply(p1, p2, p3, p4); } default F4<W, V, U, T, R> flip() { return (p1, p2, p3, p4) -> apply(p4, p3, p2, p1); } } @FunctionalInterface interface F5<T, U, V, W, X, R> { R apply(T t, U u, V v, W w, X x); default F4<U, V, W, X, R> x(T p1) { return (p2, p3, p4, p5) -> apply(p1, p2, p3, p4, p5); } default F3<V, W, X, R> x(T p1, U p2) { return (p3, p4, p5) -> apply(p1, p2, p3, p4, p5); } default F2<W, X, R> x(T p1, U p2, V p3) { return (p4, p5) -> apply(p1, p2, p3, p4, p5); } default F1<X, R> x(T p1, U p2, V p3, W p4) { return p5 -> apply(p1, p2, p3, p4, p5); } default F1<T, F1<U, F1<V, F1<W, F1<X, R>>>>> currying() { return p1 -> p2 -> p3 -> p4 -> p5 -> apply(p1, p2, p3, p4, p5); } default F5<X, W, V, U, T, R> flip() { return (p1, p2, p3, p4, p5) -> apply(p5, p4, p3, p2, p1); } } @FunctionalInterface interface F6<T, U, V, W, X, Y, R> { R apply(T t, U u, V v, W w, X x, Y y); default F5<U, V, W, X, Y, R> x(T p1) { return (p2, p3, p4, p5, p6) -> apply(p1, p2, p3, p4, p5, p6); } default F4<V, W, X, Y, R> x(T p1, U p2) { return (p3, p4, p5, p6) -> apply(p1, p2, p3, p4, p5, p6); } default F3<W, X, Y, R> x(T p1, U p2, V p3) { return (p4, p5, p6) -> apply(p1, p2, p3, p4, p5, p6); } default F2<X, Y, R> x(T p1, U p2, V p3, W p4) { return (p5, p6) -> apply(p1, p2, p3, p4, p5, p6); } default F1<Y, R> x(T p1, U p2, V p3, W p4, X p5) { return p6 -> apply(p1, p2, p3, p4, p5, p6); } default F1<T, F1<U, F1<V, F1<W, F1<X, F1<Y, R>>>>>> currying() { return p1 -> p2 -> p3 -> p4 -> p5 -> p6 -> apply(p1, p2, p3, p4, p5, p6); } default F6<Y, X, W, V, U, T, R> flip() { return (p1, p2, p3, p4, p5, p6) -> apply(p6, p5, p4, p3, p2, p1); } } @FunctionalInterface interface F7<T, U, V, W, X, Y, Z, R> { R apply(T t, U u, V v, W w, X x, Y y, Z z); default F6<U, V, W, X, Y, Z, R> x(T p1) { return (p2, p3, p4, p5, p6, p7) -> apply(p1, p2, p3, p4, p5, p6, p7); } default F5<V, W, X, Y, Z, R> x(T p1, U p2) { return (p3, p4, p5, p6, p7) -> apply(p1, p2, p3, p4, p5, p6, p7); } default F4<W, X, Y, Z, R> x(T p1, U p2, V p3) { return (p4, p5, p6, p7) -> apply(p1, p2, p3, p4, p5, p6, p7); } default F3<X, Y, Z, R> x(T p1, U p2, V p3, W p4) { return (p5, p6, p7) -> apply(p1, p2, p3, p4, p5, p6, p7); } default F2<Y, Z, R> x(T p1, U p2, V p3, W p4, X p5) { return (p6, p7) -> apply(p1, p2, p3, p4, p5, p6, p7); } default F1<Z, R> x(T p1, U p2, V p3, W p4, X p5, Y p6) { return p7 -> apply(p1, p2, p3, p4, p5, p6, p7); } default F1<T, F1<U, F1<V, F1<W, F1<X, F1<Y, F1<Z, R>>>>>>> currying() { return p1 -> p2 -> p3 -> p4 -> p5 -> p6 -> p7 -> apply(p1, p2, p3, p4, p5, p6, p7); } default F7<Z, Y, X, W, V, U, T, R> flip() { return (p1, p2, p3, p4, p5, p6, p7) -> apply(p7, p6, p5, p4, p3, p2, p1); } } class RLENode<T> { T val; int len; RLENode(T val, int len) { this.val = val; this.len = len; } } // FIXME: class RLE<T> { RLENode<T>[] values; public RLE(T[] target) { if (target.length == 0) { @SuppressWarnings("unchecked") RLENode<T>[] array = new RLENode[0]; values = array; return; } List<RLENode<T>> list = new ArrayList<>(); T cur = target[0]; int cnt = 1; for (int i = 1; i < target.length; i++) { if (target[i].equals(cur)) { // NOTE: 参照比較をしないように注意 cnt++; } else { list.add(new RLENode<T>(cur, cnt)); cur = target[i]; cnt = 1; } } list.add(new RLENode<T>(cur, cnt)); @SuppressWarnings("unchecked") RLENode<T>[] array = list.toArray(RLENode[]::new); values = array; } void print() { for (int i = 0; i < values.length; i++) { System.out.println(values[i].val + " " + values[i].len); } } HashMap<T, Integer> toMap() { HashMap<T, Integer> map = new HashMap<>(); for (int i = 0; i < values.length; i++) { map.put(values[i].val, values[i].len); } return map; } } class Graph { List<Integer>[] edges; int[] weights; int n; boolean sortedEdges; boolean isDirected; @SuppressWarnings("unchecked") Graph(int n, boolean isDirected, boolean sortEdges) { this.n = n; this.edges = new ArrayList[n+1]; for (int i = 1; i <= n; i++) { edges[i] = new ArrayList<Integer>(); } this.weights = new int[n+1]; this.sortedEdges = !sortEdges; this.isDirected = isDirected; } Graph(int n, boolean isDirected) { this(n, isDirected, false); } public void addEdge(int u, int v) { assert 1 <= u && u <= n; assert 1 <= v && v <= n; edges[u].add(v); if (!isDirected) edges[v].add(u); sortedEdges = false; } public void addEdge(int[] u, int[] v) { assert u != null && v != null; assert u.length == v.length; for (int i = 0; i < u.length; i++) addEdge(u[i], v[i]); } private void sortEdges() { for (int i = 1; i <= n; i++) Collections.sort(this.edges[i]); sortedEdges = true; } public List<Integer> bfs(Graph g, int s) { int[] ps = new int[this.n+1]; int[] ds = new int[this.n+1]; int[] cs = new int[this.n+1]; List<Integer> path = new ArrayList<Integer>(); Arrays.fill(ds, Integer.MAX_VALUE); ds[s] = 0; Deque<Integer> q = new ArrayDeque<Integer>(); q.add(s); cs[s] = 1; while (!q.isEmpty()) { int u = q.remove(); path.add(u); for (int v : g.edges[u]) { if (cs[v] == 0) { ps[v] = u; ds[v] = ds[u] + 1; cs[v] = 1; q.add(v); } } cs[u] = 2; } return path; } public int[] dfs(int s, int g) { int[] ds = new int[n+1]; // depth int[] fs = new int[n+1]; // first discovered int[] cs = new int[n+1]; // color (0: white, 1: gray, 2: black) int[] pi = new int[n+1]; // parent index List<Integer> path = new ArrayList<Integer>(); int time = 0; sortEdges(); dfs(ds, fs, cs, pi, path, time, s, g); int[] res = Util.toIntArray(path); Util.reverse(res); return res; } public boolean dfs(int[] ds, int[] fs, int[] cs, int[] pi, List<Integer> path, int time, int u, int g) { time++; ds[u] = time; cs[u] = 1; if (u == g) { path.add(u); return true; } for (int v : this.edges[u]) { if (pi[u] != v) { pi[v] = u; boolean res = dfs(ds, fs, cs, pi, path, time, v, g); if (res) { path.add(u); return true; } } } cs[u] = 2; time++; fs[u] = time; return false; } } // convert list, array, map, set, queue, stack class Test { public static long pow(long a, long b, long mod) { if (b == 0) return 1; if (b == 1) return a; if (b % 2 == 0) return pow(a * a % mod, b / 2, mod); return a * pow(a * a % mod, b / 2, mod) % mod; } public static void sortSome(long[] key, long[]... value) { long[][] array = new long[key.length][1+value.length]; for (int i = 0; i < key.length; i++) { array[0][i] = key[i]; for (int j = 1; j < array[i].length; j++) { array[j][i] = value[j-1][i]; } } Arrays.sort(array, Comparator.comparingLong(a -> a[0])); } public static long[] primeFact(long n, boolean allow_dup) { List<Long> list = new ArrayList<>(); int upper = (int)Math.sqrt(n) + 1; for (long i = 2; i <= upper; i++) { if (n % i != 0) continue; list.add(i); n /= i; while (n % i == 0) { if (allow_dup) list.add(i); n /= i; } } if (n != 1) list.add(n); return list.stream().mapToLong(i -> i).toArray(); } static List<long[]> permutation(long[] seed) { List<long[]> list = new ArrayList<>(); long[] perm = new long[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(list, seed, perm, used, 0); return list; } static void buildPerm(List<long[]> list, long[] seed, long[] perm, boolean[] used, int index) { if (index == seed.length) { list.add(perm.clone()); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(list, seed, perm, used, index + 1); used[i] = false; } } static void combInternal(List<int[]> res, int input[], int empty[], int start, int end, int index, int r) { if (index == r) { res.add(Arrays.copyOf(empty, r)); return; } for (int y = start; y <= end && end - y + 1 >= r - index; y++) { empty[index] = input[y]; combInternal(res, input, empty, y + 1, end, index + 1, r); } } static List<int[]> combination(int input[], int n, int r) { int empty[] = new int[r]; List<int[]> list = new ArrayList<>(); combInternal(list, input, empty, 0, n-1, 0, r); return list; } } class Util { static In in = new In(); static Out out = new Out(); public static final int N10_9 = 1000000000; public static final int N10_9_7 = 1000000007; public static final char[] abc = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; public static final char[] ABC = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; public static void sort(Object[] a) { Arrays.sort(a); } public static <T> void sort(T[] a, Comparator<? super T> c) { Arrays.sort(a, c); } public static void sort(int[] a) { Arrays.sort(a); } public static void sort(int[] a, int from, int to) { Arrays.sort(a, from, to); } public static void sort(long[] a) { Arrays.sort(a); } public static void sort(long[] a, int from, int to) { Arrays.sort(a, from, to); } public static void sort(double[] a) { Arrays.sort(a); } public static void sort(double[] a, int from, int to) { Arrays.sort(a, from, to); } public static void sort(char[] a) { Arrays.sort(a); } public static void sort(char[] a, int from, int to) { Arrays.sort(a, from, to); } public static int gcd(int a, int b) { return MyMath.gcd(a, b); } public static long gcd(long a, long b) { return MyMath.gcd(a, b); } public static int lcm(int a, int b) { return MyMath.lcm(a, b); } public static long lcm(long a, long b) { return MyMath.lcm(a, b); } public static int sum(int[] a, int start, int end) { int sum = 0; for (int i = start; i < end; i++) sum += a[i]; return sum; } public static long sum(long[] a, int start, int end) { long sum = 0; for (int i = start; i < end; i++) sum += a[i]; return sum; } public static double sum(double[] a, int start, int end) { double sum = 0; for (int i = start; i < end; i++) sum += a[i]; return sum; } public static int sum(int[] a) { return sum(a, 0, a.length); } public static long sum(long[] a) { return sum(a, 0, a.length); } public static double sum(double[] a) { return sum(a, 0, a.length); } public static int sum(int a, int ... b) { return a + sum(b); } public static long sum(long a, long ... b) { return a + sum(b); } public static double sum(double a, double ... b) { return a + sum(b); } public static int lower_bound(List<Integer> list, int target) { return ~Collections.binarySearch(list, target, (x, y) -> x.compareTo(y) >= 0 ? 1 : -1); } public static int upper_bound(List<Integer> list, int target) { return ~Collections.binarySearch(list, target, (x, y) -> x.compareTo(y) > 0 ? 1 : -1); } public static int lower_bound(List<Double> list, double target) { return ~Collections.binarySearch(list, target, (x, y) -> x.compareTo(y) >= 0 ? 1 : -1); } public static int upper_bound(List<Double> list, double target) { return ~Collections.binarySearch(list, target, (x, y) -> x.compareTo(y) > 0 ? 1 : -1); } // ビット全探索 public static boolean[][] bitAll(int n) { boolean[][] res = new boolean[1 << n][n]; for (int i = 0; i < 1 << n; i++) { for (int j = 0; j < n; j++) { res[i][j] = (i >> j & 1) == 1; } } return res; } public static boolean[][] bitAll(int n, int bitCount) { List<boolean[]> res = new ArrayList<>(); boolean[] b = new boolean[n]; for (int i = (1 << bitCount) - 1; i < 1 << n;) { assert Integer.bitCount(i) == bitCount; for (int j = 0; j < n; j++) b[j] = (i >> j & 1) == 1; res.add(b.clone()); int t = i | i - 1; i = t + 1 | (~t & -~t) - 1 >> Integer.numberOfTrailingZeros(i) + 1; } return toBooleanArrayArray(res); } public static int[][] bitAllFilter(boolean[][] use, int[] array) { int[][] res = new int[use.length][]; for (int i = 0; i < use.length; i++) { int size = 0; for (int j = 0; j < use[i].length; j++) if (use[i][j]) size++; res[i] = new int[size]; int index = 0; for (int j = 0; j < array.length; j++) if (use[i][j]) res[i][index++] = array[j]; } return res; } public static long[][] bitAllFilter(boolean[][] use, long[] array) { long[][] res = new long[use.length][]; for (int i = 0; i < use.length; i++) { int size = 0; for (int j = 0; j < use[i].length; j++) if (use[i][j]) size++; res[i] = new long[size]; int index = 0; for (int j = 0; j < array.length; j++) if (use[i][j]) res[i][index++] = array[j]; } return res; } public static double[][] bitAllFilter(boolean[][] use, double[] array) { double[][] res = new double[use.length][]; for (int i = 0; i < use.length; i++) { int size = 0; for (int j = 0; j < use[i].length; j++) if (use[i][j]) size++; res[i] = new double[size]; int index = 0; for (int j = 0; j < array.length; j++) if (use[i][j]) res[i][index++] = array[j]; } return res; } public static Object[][] bitAllFilter(boolean[][] use, Object[] array) { Object[][] res = new Object[use.length][]; for (int i = 0; i < use.length; i++) { int size = 0; for (int j = 0; j < use[i].length; j++) if (use[i][j]) size++; res[i] = new Object[size]; int index = 0; for (int j = 0; j < array.length; j++) if (use[i][j]) res[i][index++] = array[j]; } return res; } public static int[][][] bitAllFilter(boolean[][] use, int[][] array) { int[][][] res = new int[use.length][][]; for (int i = 0; i < use.length; i++) { int size = 0; for (int j = 0; j < use[i].length; j++) if (use[i][j]) size++; res[i] = new int[size][]; int index = 0; for (int j = 0; j < array.length; j++) if (use[i][j]) res[i][index++] = array[j]; } return res; } public static long[][][] bitAllFilter(boolean[][] use, long[][] array) { long[][][] res = new long[use.length][][]; for (int i = 0; i < use.length; i++) { int size = 0; for (int j = 0; j < use[i].length; j++) if (use[i][j]) size++; res[i] = new long[size][]; int index = 0; for (int j = 0; j < array.length; j++) if (use[i][j]) res[i][index++] = array[j]; } return res; } public static int[] arrayRange(int start, int end, int headspace, int tailspace) { int n = end - start + 1; int[] res = new int[n + headspace + tailspace]; int cur = start; for (int i = headspace; i < n + headspace; i++) res[i] = cur++; return res; } public static int[] arrayRange(int start, int end) { return arrayRange(start, end, 0, 0); } public static long[] arrayRange(long start, long end, int headspace, int tailspace) { long n = end - start + 1; long[] res = new long[(int)n + headspace + tailspace]; long cur = start; for (int i = headspace; i < n + headspace; i++) res[i] = cur++; return res; } public static long[] arrayRange(long start, long end) { return arrayRange(start, end, 0, 0); } public static long[] toLongArray(Collection<?> list) { return list.stream().mapToLong(i -> (long)i).toArray(); } public static int[] toIntArray(Collection<?> list) { return list.stream().mapToInt(i -> (int)i).toArray(); } public static double[] toDoubleArray(Collection<?> list) { return list.stream().mapToDouble(i -> (double)i).toArray(); } public static boolean[] toBooleanArray(Collection<?> list) { Object[] a = list.toArray(); boolean[] b = new boolean[a.length]; for (int i = 0; i < b.length; i++) { b[i] = (boolean)a[i]; } return b; } public static String[] toStringArray(Collection<?> list) { return list.stream().map(i -> i.toString()).toArray(String[]::new); } public static long[][] toLongArrayArray(Collection<?> list) { return list.toArray(long[][]::new); } public static int[][] toIntArrayArray(Collection<?> list) { return list.toArray(int[][]::new); } public static double[][] toDoubleArrayArray(Collection<?> list) { return list.toArray(double[][]::new); } public static boolean[][] toBooleanArrayArray(Collection<?> list) { return list.toArray(boolean[][]::new); } public static String[][] toStringArrayArray(Collection<?> list) { return list.toArray(String[][]::new); } public static <T> void reverse(T[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(boolean[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(int[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(long[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(double[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(float[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(byte[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(char[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static int[] distinct(int[] a) { return Arrays.stream(a).distinct().toArray(); } public static long[] distinct(long[] a) { return Arrays.stream(a).distinct().toArray(); } public static double[] distinct(double[] a) { return Arrays.stream(a).distinct().toArray(); } public static void fill(int[] a, int v) { Arrays.fill(a, v); } public static void fill(long[] a, long v) { Arrays.fill(a, v); } public static void fill(double[] a, double v) { Arrays.fill(a, v); } public static void fill(boolean[] a, boolean v) { Arrays.fill(a, v); } public static void fill(char[] a, char v) { Arrays.fill(a, v); } public static void fill(int[][] a, int v) { for (int[] i : a) fill(i, v); } public static void fill(long[][] a, long v) { for (long[] i : a) fill(i, v); } public static void fill(double[][] a, double v) { for (double[] i : a) fill(i, v); } public static void fill(boolean[][] a, boolean v) { for (boolean[] i : a) fill(i, v); } public static void fill(char[][] a, char v) { for (char[] i : a) fill(i, v); } public static void fill(int[][][] a, int v) { for (int[][] i : a) fill(i, v); } public static void fill(long[][][] a, long v) { for (long[][] i : a) fill(i, v); } public static void fill(double[][][] a, double v) { for (double[][] i : a) fill(i, v); } public static void fill(boolean[][][] a, boolean v) { for (boolean[][] i : a) fill(i, v); } public static void fill(char[][][] a, char v) { for (char[][] i : a) fill(i, v); } public static void fill(int[][][][] a, int v) { for (int[][][] i : a) fill(i, v); } public static void fill(long[][][][] a, long v) { for (long[][][] i : a) fill(i, v); } public static void fill(double[][][][] a, double v) { for (double[][][] i : a) fill(i, v); } public static void fill(boolean[][][][] a, boolean v) { for (boolean[][][] i : a) fill(i, v); } public static void fill(char[][][][] a, char v) { for (char[][][] i : a) fill(i, v); } // NOTE: These methods require Java 16 or higher. public static List<Long> arrayToList(long[] array) { return Arrays.stream(array).boxed().collect(Collectors.toList()); //return Arrays.stream(array).boxed().toList(); } public static List<Integer> arrayToList(int[] array) { return Arrays.stream(array).boxed().collect(Collectors.toList()); //return Arrays.stream(array).boxed().toList(); } public static List<Double> arrayToList(double[] array) { return Arrays.stream(array).boxed().collect(Collectors.toList()); //return Arrays.stream(array).boxed().toList(); } public static List<Boolean> arrayToList(boolean[] array) { Boolean[] a = new Boolean[array.length]; for (int i = 0; i < a.length; i++) a[i] = array[i]; return Arrays.stream(a).collect(Collectors.toList()); //return Arrays.stream(a).toList(); } public static List<Character> arrayToList(char[] array) { return Arrays.stream(arrayBoxed(array)).collect(Collectors.toList()); } public static <T> List<T> arrayToList(T[] array) { return Arrays.stream(array).collect(Collectors.toList()); //return Arrays.stream(array).toList(); } public static Long[] arrayBoxed(long[] array) { return Arrays.stream(array).boxed().toArray(Long[]::new); } public static Integer[] arrayBoxed(int[] array) { return Arrays.stream(array).boxed().toArray(Integer[]::new); } public static Double[] arrayBoxed(double[] array) { return Arrays.stream(array).boxed().toArray(Double[]::new); } public static Boolean[] arrayBoxed(boolean[] array) { Boolean[] a = new Boolean[array.length]; for (int i = 0; i < array.length; i++) { a[i] = array[i]; } return a; } public static Character[] arrayBoxed(char[] array) { Character[] a = new Character[array.length]; for (int i = 0; i < array.length; i++) { a[i] = array[i]; } return a; } public static long[] arrayUnboxed(Long[] array) { return Arrays.stream(array).mapToLong(i -> i).toArray(); } public static int[] arrayUnboxed(Integer[] array) { return Arrays.stream(array).mapToInt(i -> i).toArray(); } public static double[] arrayUnboxed(Double[] array) { return Arrays.stream(array).mapToDouble(i -> i).toArray(); } public static boolean[] arrayUnboxed(Boolean[] array) { boolean[] a = new boolean[array.length]; for (int i = 0; i < array.length; i++) { a[i] = array[i]; } return a; } public static char[] arrayUnboxed(Character[] array) { char[] a = new char[array.length]; for (int i = 0; i < array.length; i++) { a[i] = array[i]; } return a; } // 最大値 (int) public static int max(int a, int b) { return Math.max(a, b); } public static int max(int a, int ... nums) { return max(a, max(nums)); } public static int max(int[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = a[0]; for (int i = start; i <= end; i++) res = Math.max(res, a[i]); return res; } public static int max(int[] a, int start) { return max(a, start, a.length - 1); } public static int max(int[] a) { return max(a, 0, a.length - 1); } public static int maxIndex(int[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = start; for (int i = start; i <= end; i++) { if (a[i] > a[res]) res = i; } return res; } public static int maxIndex(int[] a, int start) { return maxIndex(a, start, a.length - 1); } public static int maxIndex(int[] a) { return maxIndex(a, 0, a.length - 1); } // 最小値 (int) public static int min(int a, int b) { return Math.min(a, b); } public static int min(int a, int ... nums) { return min(a, min(nums)); } public static int min(int[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = a[0]; for (int i = start; i <= end; i++) res = Math.min(res, a[i]); return res; } public static int min(int[] a, int start) { return min(a, start, a.length - 1); } public static int min(int[] a) { return min(a, 0, a.length - 1); } public static int minIndex(int[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = start; for (int i = start; i <= end; i++) { if (a[i] < a[res]) res = i; } return res; } public static int minIndex(int[] a, int start) { return minIndex(a, start, a.length - 1); } public static int minIndex(int[] a) { return minIndex(a, 0, a.length - 1); } // 最大値 (long) public static long max(long a, long b) { return Math.max(a, b); } public static long max(long a, long ... nums) { return max(a, max(nums)); } public static long max(long[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; long res = a[0]; for (int i = start; i <= end; i++) res = Math.max(res, a[i]); return res; } public static long max(long[] a, int start) { return max(a, start, a.length - 1); } public static long max(long[] a) { return max(a, 0, a.length - 1); } public static int maxIndex(long[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = start; for (int i = start; i <= end; i++) { if (a[i] > a[res]) res = i; } return res; } public static int maxIndex(long[] a, int start) { return maxIndex(a, start, a.length - 1); } public static int maxIndex(long[] a) { return maxIndex(a, 0, a.length - 1); } // 最小値 (long) public static long min(long a, long b) { return Math.min(a, b); } public static long min(long a, long ... nums) { return min(a, min(nums)); } public static long min(long[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; long res = a[0]; for (int i = start; i <= end; i++) res = Math.min(res, a[i]); return res; } public static long min(long[] a, int start) { return min(a, start, a.length - 1); } public static long min(long[] a) { return min(a, 0, a.length - 1); } public static int minIndex(long[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = start; for (int i = start; i <= end; i++) { if (a[i] < a[res]) res = i; } return res; } public static int minIndex(long[] a, int start) { return minIndex(a, start, a.length - 1); } public static int minIndex(long[] a) { return minIndex(a, 0, a.length - 1); } // 最大値 (double) public static double max(double a, double b) { return Math.max(a, b); } public static double max(double a, double ... nums) { return max(a, max(nums)); } public static double max(double[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; double res = a[0]; for (int i = start; i <= end; i++) res = Math.max(res, a[i]); return res; } public static double max(double[] a, int start) { return max(a, start, a.length - 1); } public static double max(double[] a) { return max(a, 0, a.length - 1); } public static int maxIndex(double[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = start; for (int i = start; i <= end; i++) { if (a[i] > a[res]) res = i; } return res; } public static int maxIndex(double[] a, int start) { return maxIndex(a, start, a.length - 1); } public static int maxIndex(double[] a) { return maxIndex(a, 0, a.length - 1); } // 最小値 (double) public static double min(double a, double b) { return Math.min(a, b); } public static double min(double a, double ... nums) { return min(a, min(nums)); } public static double min(double[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; double res = a[0]; for (int i = start; i <= end; i++) res = Math.min(res, a[i]); return res; } public static double min(double[] a, int start) { return min(a, start, a.length - 1); } public static double min(double[] a) { return min(a, 0, a.length - 1); } public static int minIndex(double[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = start; for (int i = start; i <= end; i++) { if (a[i] < a[res]) res = i; } return res; } public static int minIndex(double[] a, int start) { return minIndex(a, start, a.length - 1); } public static int minIndex(double[] a) { return minIndex(a, 0, a.length - 1); } // 絶対値 public static int abs(int a) { return Math.abs(a); } public static long abs(long a) { return Math.abs(a); } public static double abs(double a) { return Math.abs(a); } // チェビシェフ距離(チェス盤距離) public static long chebyshevDistance(long x1, long y1, long x2, long y2) { return max(abs(x1 - x2), abs(y1 - y2)); } public static int chebyshevDistance(int x1, int y1, int x2, int y2) { return max(abs(x1 - x2), abs(y1 - y2)); } // マンハッタン距離 public static long manhattanDistance(long x1, long y1, long x2, long y2) { return abs(x1 - x2) + abs(y1 - y2); } public static int manhattanDistance(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } // ユークリッド距離 public static int euclideanDistance(int x1, int y1, int x2, int y2) { return (int) Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); } public static long euclideanDistance(long x1, long y1, long x2, long y2) { return (long) Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); } // 外積 public static long cross(long ox, long oy, long ax, long ay, long bx, long by) { // 外積: |a||b|sinθ = axby - bxay return (ax - ox) * (by - oy) - (bx - ox) * (ay - oy); } public static long cross(long ax, long xy, long bx, long by) { // 外積: |a||b|sinθ = axby - bxay return cross(0, 0, ax, xy, bx, by); } // 内積 public static long dot(long ox, long oy, long ax, long ay, long bx, long by) { // 内積: |a||b|cosθ = axbx + ayby return (ax - ox) * (bx - ox) + (ay - oy) * (by - oy); } public static long dot(long ax, long xy, long bx, long by) { // 内積: |a||b|cosθ = axbx + ayby return dot(0, 0, ax, xy, bx, by); } // swap public static String swap(String s, int i, int j) { char[] cs = s.toCharArray(); char tmp = cs[i]; cs[i] = cs[j]; cs[j] = tmp; return String.valueOf(cs); } public static void swap(boolean[] a, int i, int j) { boolean tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void swap(long[] a, int i, int j) { long tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void swap(double[] a, int i, int j) { double tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void swap(float[] a, int i, int j) { float tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void swap(byte[] a, int i, int j) { byte tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void swap(char[] a, int i, int j) { char tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static <T> void swap(T[] a, int i, int j) { T tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static <T> void swap(List<T> a, int i, int j) { T tmp = a.get(i); a.set(i, a.get(j)); a.set(j, tmp); } // 間にあるかどうか public static boolean between(int a, int x, int b) { if (a > b) return between(b, x, a); return a <= x && x <= b; } public static boolean between(long a, long x, long b) { if (a > b) return between(b, x, a); return a <= x && x <= b; } public static boolean between(double a, double x, double b) { if (a > b) return between(b, x, a); return a <= x && x <= b; } public static boolean between(float a, float x, float b) { if (a > b) return between(b, x, a); return a <= x && x <= b; } public static boolean between(byte a, byte x, byte b) { if (a > b) return between(b, x, a); return a <= x && x <= b; } public static boolean between(char a, char x, char b) { if (a > b) return between(b, x, a); return a <= x && x <= b; } } class MyMath { // 最大公約数 (Greatest Common Divisor) public static long gcd(long a, long b) { if (a < b) { long tmp = a; a = b; b = tmp; } while (b != 0) { long tmp = a % b; a = b; b = tmp; } return a; } public static int gcd(int a, int b) { if (a < b) { int tmp = a; a = b; b = tmp; } while (b != 0) { int tmp = a % b; a = b; b = tmp; } return a; } // 最小公倍数 (Least Common Multiple) public static long lcm(long a, long b) { return a * b / gcd(a, b); } public static int lcm(int a, int b) { return a * b / gcd(a, b); } // 素数列挙 (Prime enumeration) public static int[] primes(int max) { return primes_base((int)Math.sqrt(max) + 1); } public static int[] primes_base(int max) { boolean[] is_prime = new boolean[max]; for (int i = 0; i < max; i++) { is_prime[i] = true; } for (int i = 2; i < max; i++) { if (is_prime[i]) { for (int j = i * 2; j < max; j += i) { is_prime[j] = false; } } } int cnt = 0; for (int i = 2; i < max; i++) { if (is_prime[i]) cnt++; } int[] primes = new int[cnt]; int index = 0; for (int i = 2; i < max && index < cnt; i++) { if (is_prime[i]) primes[index++] = i; } return primes; } // TODO: public static int[] primes_base_bit(int max) { long[] is_prime = new long[max/64+1]; for (int i = 0; i < max; i++) { is_prime[i/64] = is_prime[i/64] | (1 << (i%64)); // is_prime[i] = true } for (int i = 2; i < max; i++) { if ((is_prime[i/64] & (1 << (i%64))) != 0) { // is_prime[i] for (int j = i * 2; j < max; j += i) { is_prime[j/64] = is_prime[j/64] & (~(1 << (j%64))); // is_prime[j] = false } } } int cnt = 0; for (int i = 2; i < max; i++) { if ((is_prime[i/64] & (1 << (i%64))) != 0) cnt++; // is_prime[i] } int[] primes = new int[cnt]; int index = 0; for (int i = 2; i < max && index < cnt; i++) { if ((is_prime[i/64] & (1 << (i%64))) != 0) primes[index++] = i; // is_prime[i] } return primes; } } class In { private final InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; public In(InputStream in) { this.in = in; } public In() { this.in = System.in; } private final boolean hasNextByte() { if (ptr < buflen) return true; ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) return false; return true; } private final int readByte() { return hasNextByte() ? buffer[ptr++] : -1; } private static final boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public final boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) { ptr++; } return hasNextByte(); } public final String s() { StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public final void nextThrow(int n) { for (int i = 0; i < n; i++) this.s(); } public final void nextThrow() { this.nextThrow(1); } public final long l() { long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } assert '0' <= b && b <= '9' : "NumberFormatException"; while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else { //assert b == ' ' || b == '\n' : "NumberFormatException"; return minus ? -n : n; } b = readByte(); } } public long[] la(int n, int headspace, int tailspace) { long[] result = new long[n + headspace + tailspace]; for (int i = headspace; i < n + headspace; i++) result[i] = l(); return result; } public long[] la(int n, int headspace) { return la(n, headspace, 0); } public long[] la(int n) { return la(n, 0, 0); } // TODO: public long[][] laa(int n, int m) { long[][] result = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) result[i][j] = l(); } return result; } public final int i() { long nl = l(); assert (Integer.MIN_VALUE <= nl || nl <= Integer.MAX_VALUE) : "NumberFormatException"; return (int)nl; } public int[] ia(int n, int headspace, int tailspace) { int[] result = new int[n + headspace + tailspace]; for (int i = headspace; i < n + headspace; i++) result[i] = i(); return result; } public int[] ia(int n, int headspace) { return ia(n, headspace, 0); } public int[] ia(int n) { return ia(n, 0, 0); } // TODO: public int[][] iaa(int n, int m) { int[][] result = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) result[i][j] = i(); } return result; } public int[][] ias(int ncol, int n) { int[][] result = new int[ncol][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < ncol; j++) result[j][i] = i(); } return result; } public double d() { return Double.parseDouble(s()); } public boolean[] b(char True) { String s = this.s(); int n = s.length(); boolean[] array = new boolean[n]; for (int i = 0; i < n; i++) array[i] = s.charAt(i) == True; return array; } } class Out { PrintWriter out; Out() { this.out = new PrintWriter(System.out); } public final void as() { out.print(' '); } public final void an() { out.print('\n'); } public final <T> void a(T n) { out.print(n); } public final <T> void as(T n) { out.print(n); out.print(' '); } public final <T> void an(T n) { out.println(n); } public final void yesno(boolean b) { out.println(b ? "Yes" : "No"); } public final void aas(int[] n) { int nm = n.length-1; for (int i = 0; i < nm; i++) { out.print(n[i]); out.print(' '); } out.println(n[nm]); } public final void aan(int[] n) { int nm = n.length-1; for (int i = 0; i < nm; i++) { out.println(n[i]); } out.println(n[nm]); } public final void aas(int[][] n) { int nm = n.length; for (int i = 0; i < nm; i++) { aas(n[i]); } } public final void aas(long[] n) { int nm = n.length-1; for (int i = 0; i < nm; i++) { out.print(n[i]); out.print(' '); } out.println(n[nm]); } public final void aan(long[] n) { int nm = n.length-1; for (int i = 0; i < nm; i++) { out.println(n[i]); } out.println(n[nm]); } public final void aas(long[][] n) { int nm = n.length; for (int i = 0; i < nm; i++) { aas(n[i]); } } public final void flush() { out.flush(); } public final void flushln() { out.print('\n'); out.flush(); } } // Edge class E { int u; int v; int w; public E(int u, int v, int w) { this.u = u; this.v = v; this.w = w; } public E(int u, int v) { this(u, v, 0); } } // Union-Find class UF { int[] parent; int[] rank; int[] size; public UF(int n) { parent = new int[n+1]; rank = new int[n+1]; size = new int[n+1]; for (int i = 1; i <= n; i++) { parent[i] = i; rank[i] = 0; size[i] = 1; } } public int find(int x) { assert (0 < x && x < parent.length) : "IndexOutOfBoundsException"; if (parent[x] == x) return x; return parent[x] = find(parent[x]); } public void union(int x, int y) { assert (0 < x && x < parent.length) : "IndexOutOfBoundsException"; assert (0 < y && y < parent.length) : "IndexOutOfBoundsException"; x = find(x); y = find(y); if (x == y) return; if (rank[x] < rank[y]) { parent[x] = y; size[y] += size[x]; } else { parent[y] = x; size[x] += size[y]; if (rank[x] == rank[y]) rank[x]++; } } public boolean same(int x, int y) { assert (0 < x && x < parent.length) : "IndexOutOfBoundsException"; assert (0 < y && y < parent.length) : "IndexOutOfBoundsException"; return find(x) == find(y); } public int size(int x) { assert (0 < x && x < parent.length) : "IndexOutOfBoundsException"; return size[find(x)]; } } class MyComparator { private static Comparator<int[]> dictIntArray = null; static Comparator<int[]> dictIntArray() { if (dictIntArray == null) dictIntArray = (a, b) -> Arrays.compare(a, b); return dictIntArray; } private static Comparator<int[][]> dictIntArrayArray = null; static Comparator<int[][]> dictIntArrayArray() { if (dictIntArrayArray == null) dictIntArrayArray = (a, b) -> { for (int i = 0; i < a.length; i++) { int c = Arrays.compare(a[i], b[i]); if (c != 0) return c; } return 0; }; return dictIntArrayArray; } } import java.util.*; import java.util.function.*; import java.util.stream.*; import java.io.*; class Solve extends Util { void solve() { int n = in.i(); int m = in.i(); long k = in.l(); long[] a = new long[n]; long[] b = new long[n]; for (int i = 0; i < n; i++) { a[i] = in.l(); b[i] = in.l(); } long[] c = new long[m]; long[] d = new long[m]; for (int i = 0; i < m; i++) { c[i] = in.l(); d[i] = in.l(); } double ng = 0, ok = 1; for (int i = 0; i < 100; i++) { double x = (ng + ok) / 2; double y = x / (1 - x); List<Double> p = new ArrayList<>(); for (int j = 0; j < m; j++) { p.add((double) c[j] - y * d[j]); } Collections.sort(p); long check = 0; //out.a("p: "); //for (int j = 0; j < m; j++) out.a(p.get(j) + " "); //out.an(); for (int j = 0; j < n; j++) { double q = (double) a[j] - y * b[j]; int idx = lower_bound(p, -q); //out.an("q: " + q + " idx: " + idx); check += m - idx; } if (check < k) ok = x; else ng = x; } double ans = ok * 100; out.an(ans); } } // My Library // Version: 2022.12.07 // ================================================================================================= // TODO: // * end を半開区間にする public class Main extends Util { public static void main(String[] args) { try { new Solve().solve(); } catch (Exception e) { throw e; } finally { out.flush(); } } } @FunctionalInterface interface F1<T, R> extends Function<T, R> { default R x(T t) { return apply(t); } } @FunctionalInterface interface F2<T, U, R> extends BiFunction<T, U, R> { default F1<U, R> x(T p1) { return p2 -> apply(p1, p2); } default F1<T, F1<U, R>> currying() { return p1 -> p2 -> apply(p1, p2); } default F2<U, T, R> flip() { return (p1, p2) -> apply(p2, p1); } } @FunctionalInterface interface F3<T, U, V, R> { R apply(T t, U u, V v); default F2<U, V, R> x(T p1) { return (p2, p3) -> apply(p1, p2, p3); } default F1<V, R> x(T p1, U p2) { return p3 -> apply(p1, p2, p3); } default F1<T, F1<U, F1<V, R>>> currying() { return p1 -> p2 -> p3 -> apply(p1, p2, p3); } default F3<V, U, T, R> flip() { return (p1, p2, p3) -> apply(p3, p2, p1); } } @FunctionalInterface interface F4<T, U, V, W, R> { R apply(T t, U u, V v, W w); default F3<U, V, W, R> x(T p1) { return (p2, p3, p4) -> apply(p1, p2, p3, p4); } default F2<V, W, R> x(T p1, U p2) { return (p3, p4) -> apply(p1, p2, p3, p4); } default F1<W, R> x(T p1, U p2, V p3) { return p4 -> apply(p1, p2, p3, p4); } default F1<T, F1<U, F1<V, F1<W, R>>>> currying() { return p1 -> p2 -> p3 -> p4 -> apply(p1, p2, p3, p4); } default F4<W, V, U, T, R> flip() { return (p1, p2, p3, p4) -> apply(p4, p3, p2, p1); } } @FunctionalInterface interface F5<T, U, V, W, X, R> { R apply(T t, U u, V v, W w, X x); default F4<U, V, W, X, R> x(T p1) { return (p2, p3, p4, p5) -> apply(p1, p2, p3, p4, p5); } default F3<V, W, X, R> x(T p1, U p2) { return (p3, p4, p5) -> apply(p1, p2, p3, p4, p5); } default F2<W, X, R> x(T p1, U p2, V p3) { return (p4, p5) -> apply(p1, p2, p3, p4, p5); } default F1<X, R> x(T p1, U p2, V p3, W p4) { return p5 -> apply(p1, p2, p3, p4, p5); } default F1<T, F1<U, F1<V, F1<W, F1<X, R>>>>> currying() { return p1 -> p2 -> p3 -> p4 -> p5 -> apply(p1, p2, p3, p4, p5); } default F5<X, W, V, U, T, R> flip() { return (p1, p2, p3, p4, p5) -> apply(p5, p4, p3, p2, p1); } } @FunctionalInterface interface F6<T, U, V, W, X, Y, R> { R apply(T t, U u, V v, W w, X x, Y y); default F5<U, V, W, X, Y, R> x(T p1) { return (p2, p3, p4, p5, p6) -> apply(p1, p2, p3, p4, p5, p6); } default F4<V, W, X, Y, R> x(T p1, U p2) { return (p3, p4, p5, p6) -> apply(p1, p2, p3, p4, p5, p6); } default F3<W, X, Y, R> x(T p1, U p2, V p3) { return (p4, p5, p6) -> apply(p1, p2, p3, p4, p5, p6); } default F2<X, Y, R> x(T p1, U p2, V p3, W p4) { return (p5, p6) -> apply(p1, p2, p3, p4, p5, p6); } default F1<Y, R> x(T p1, U p2, V p3, W p4, X p5) { return p6 -> apply(p1, p2, p3, p4, p5, p6); } default F1<T, F1<U, F1<V, F1<W, F1<X, F1<Y, R>>>>>> currying() { return p1 -> p2 -> p3 -> p4 -> p5 -> p6 -> apply(p1, p2, p3, p4, p5, p6); } default F6<Y, X, W, V, U, T, R> flip() { return (p1, p2, p3, p4, p5, p6) -> apply(p6, p5, p4, p3, p2, p1); } } @FunctionalInterface interface F7<T, U, V, W, X, Y, Z, R> { R apply(T t, U u, V v, W w, X x, Y y, Z z); default F6<U, V, W, X, Y, Z, R> x(T p1) { return (p2, p3, p4, p5, p6, p7) -> apply(p1, p2, p3, p4, p5, p6, p7); } default F5<V, W, X, Y, Z, R> x(T p1, U p2) { return (p3, p4, p5, p6, p7) -> apply(p1, p2, p3, p4, p5, p6, p7); } default F4<W, X, Y, Z, R> x(T p1, U p2, V p3) { return (p4, p5, p6, p7) -> apply(p1, p2, p3, p4, p5, p6, p7); } default F3<X, Y, Z, R> x(T p1, U p2, V p3, W p4) { return (p5, p6, p7) -> apply(p1, p2, p3, p4, p5, p6, p7); } default F2<Y, Z, R> x(T p1, U p2, V p3, W p4, X p5) { return (p6, p7) -> apply(p1, p2, p3, p4, p5, p6, p7); } default F1<Z, R> x(T p1, U p2, V p3, W p4, X p5, Y p6) { return p7 -> apply(p1, p2, p3, p4, p5, p6, p7); } default F1<T, F1<U, F1<V, F1<W, F1<X, F1<Y, F1<Z, R>>>>>>> currying() { return p1 -> p2 -> p3 -> p4 -> p5 -> p6 -> p7 -> apply(p1, p2, p3, p4, p5, p6, p7); } default F7<Z, Y, X, W, V, U, T, R> flip() { return (p1, p2, p3, p4, p5, p6, p7) -> apply(p7, p6, p5, p4, p3, p2, p1); } } class RLENode<T> { T val; int len; RLENode(T val, int len) { this.val = val; this.len = len; } } // FIXME: class RLE<T> { RLENode<T>[] values; public RLE(T[] target) { if (target.length == 0) { @SuppressWarnings("unchecked") RLENode<T>[] array = new RLENode[0]; values = array; return; } List<RLENode<T>> list = new ArrayList<>(); T cur = target[0]; int cnt = 1; for (int i = 1; i < target.length; i++) { if (target[i].equals(cur)) { // NOTE: 参照比較をしないように注意 cnt++; } else { list.add(new RLENode<T>(cur, cnt)); cur = target[i]; cnt = 1; } } list.add(new RLENode<T>(cur, cnt)); @SuppressWarnings("unchecked") RLENode<T>[] array = list.toArray(RLENode[]::new); values = array; } void print() { for (int i = 0; i < values.length; i++) { System.out.println(values[i].val + " " + values[i].len); } } HashMap<T, Integer> toMap() { HashMap<T, Integer> map = new HashMap<>(); for (int i = 0; i < values.length; i++) { map.put(values[i].val, values[i].len); } return map; } } class Graph { List<Integer>[] edges; int[] weights; int n; boolean sortedEdges; boolean isDirected; @SuppressWarnings("unchecked") Graph(int n, boolean isDirected, boolean sortEdges) { this.n = n; this.edges = new ArrayList[n+1]; for (int i = 1; i <= n; i++) { edges[i] = new ArrayList<Integer>(); } this.weights = new int[n+1]; this.sortedEdges = !sortEdges; this.isDirected = isDirected; } Graph(int n, boolean isDirected) { this(n, isDirected, false); } public void addEdge(int u, int v) { assert 1 <= u && u <= n; assert 1 <= v && v <= n; edges[u].add(v); if (!isDirected) edges[v].add(u); sortedEdges = false; } public void addEdge(int[] u, int[] v) { assert u != null && v != null; assert u.length == v.length; for (int i = 0; i < u.length; i++) addEdge(u[i], v[i]); } private void sortEdges() { for (int i = 1; i <= n; i++) Collections.sort(this.edges[i]); sortedEdges = true; } public List<Integer> bfs(Graph g, int s) { int[] ps = new int[this.n+1]; int[] ds = new int[this.n+1]; int[] cs = new int[this.n+1]; List<Integer> path = new ArrayList<Integer>(); Arrays.fill(ds, Integer.MAX_VALUE); ds[s] = 0; Deque<Integer> q = new ArrayDeque<Integer>(); q.add(s); cs[s] = 1; while (!q.isEmpty()) { int u = q.remove(); path.add(u); for (int v : g.edges[u]) { if (cs[v] == 0) { ps[v] = u; ds[v] = ds[u] + 1; cs[v] = 1; q.add(v); } } cs[u] = 2; } return path; } public int[] dfs(int s, int g) { int[] ds = new int[n+1]; // depth int[] fs = new int[n+1]; // first discovered int[] cs = new int[n+1]; // color (0: white, 1: gray, 2: black) int[] pi = new int[n+1]; // parent index List<Integer> path = new ArrayList<Integer>(); int time = 0; sortEdges(); dfs(ds, fs, cs, pi, path, time, s, g); int[] res = Util.toIntArray(path); Util.reverse(res); return res; } public boolean dfs(int[] ds, int[] fs, int[] cs, int[] pi, List<Integer> path, int time, int u, int g) { time++; ds[u] = time; cs[u] = 1; if (u == g) { path.add(u); return true; } for (int v : this.edges[u]) { if (pi[u] != v) { pi[v] = u; boolean res = dfs(ds, fs, cs, pi, path, time, v, g); if (res) { path.add(u); return true; } } } cs[u] = 2; time++; fs[u] = time; return false; } } // convert list, array, map, set, queue, stack class Test { public static long pow(long a, long b, long mod) { if (b == 0) return 1; if (b == 1) return a; if (b % 2 == 0) return pow(a * a % mod, b / 2, mod); return a * pow(a * a % mod, b / 2, mod) % mod; } public static void sortSome(long[] key, long[]... value) { long[][] array = new long[key.length][1+value.length]; for (int i = 0; i < key.length; i++) { array[0][i] = key[i]; for (int j = 1; j < array[i].length; j++) { array[j][i] = value[j-1][i]; } } Arrays.sort(array, Comparator.comparingLong(a -> a[0])); } public static long[] primeFact(long n, boolean allow_dup) { List<Long> list = new ArrayList<>(); int upper = (int)Math.sqrt(n) + 1; for (long i = 2; i <= upper; i++) { if (n % i != 0) continue; list.add(i); n /= i; while (n % i == 0) { if (allow_dup) list.add(i); n /= i; } } if (n != 1) list.add(n); return list.stream().mapToLong(i -> i).toArray(); } static List<long[]> permutation(long[] seed) { List<long[]> list = new ArrayList<>(); long[] perm = new long[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(list, seed, perm, used, 0); return list; } static void buildPerm(List<long[]> list, long[] seed, long[] perm, boolean[] used, int index) { if (index == seed.length) { list.add(perm.clone()); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(list, seed, perm, used, index + 1); used[i] = false; } } static void combInternal(List<int[]> res, int input[], int empty[], int start, int end, int index, int r) { if (index == r) { res.add(Arrays.copyOf(empty, r)); return; } for (int y = start; y <= end && end - y + 1 >= r - index; y++) { empty[index] = input[y]; combInternal(res, input, empty, y + 1, end, index + 1, r); } } static List<int[]> combination(int input[], int n, int r) { int empty[] = new int[r]; List<int[]> list = new ArrayList<>(); combInternal(list, input, empty, 0, n-1, 0, r); return list; } } class Util { static In in = new In(); static Out out = new Out(); public static final int N10_9 = 1000000000; public static final int N10_9_7 = 1000000007; public static final char[] abc = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; public static final char[] ABC = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; public static void sort(Object[] a) { Arrays.sort(a); } public static <T> void sort(T[] a, Comparator<? super T> c) { Arrays.sort(a, c); } public static void sort(int[] a) { Arrays.sort(a); } public static void sort(int[] a, int from, int to) { Arrays.sort(a, from, to); } public static void sort(long[] a) { Arrays.sort(a); } public static void sort(long[] a, int from, int to) { Arrays.sort(a, from, to); } public static void sort(double[] a) { Arrays.sort(a); } public static void sort(double[] a, int from, int to) { Arrays.sort(a, from, to); } public static void sort(char[] a) { Arrays.sort(a); } public static void sort(char[] a, int from, int to) { Arrays.sort(a, from, to); } public static int gcd(int a, int b) { return MyMath.gcd(a, b); } public static long gcd(long a, long b) { return MyMath.gcd(a, b); } public static int lcm(int a, int b) { return MyMath.lcm(a, b); } public static long lcm(long a, long b) { return MyMath.lcm(a, b); } public static int sum(int[] a, int start, int end) { int sum = 0; for (int i = start; i < end; i++) sum += a[i]; return sum; } public static long sum(long[] a, int start, int end) { long sum = 0; for (int i = start; i < end; i++) sum += a[i]; return sum; } public static double sum(double[] a, int start, int end) { double sum = 0; for (int i = start; i < end; i++) sum += a[i]; return sum; } public static int sum(int[] a) { return sum(a, 0, a.length); } public static long sum(long[] a) { return sum(a, 0, a.length); } public static double sum(double[] a) { return sum(a, 0, a.length); } public static int sum(int a, int ... b) { return a + sum(b); } public static long sum(long a, long ... b) { return a + sum(b); } public static double sum(double a, double ... b) { return a + sum(b); } public static int lower_bound(List<Integer> list, int target) { return ~Collections.binarySearch(list, target, (x, y) -> x.compareTo(y) >= 0 ? 1 : -1); } public static int upper_bound(List<Integer> list, int target) { return ~Collections.binarySearch(list, target, (x, y) -> x.compareTo(y) > 0 ? 1 : -1); } public static int lower_bound(List<Double> list, double target) { return ~Collections.binarySearch(list, target, (x, y) -> x.compareTo(y) >= 0 ? 1 : -1); } public static int upper_bound(List<Double> list, double target) { return ~Collections.binarySearch(list, target, (x, y) -> x.compareTo(y) > 0 ? 1 : -1); } // ビット全探索 public static boolean[][] bitAll(int n) { boolean[][] res = new boolean[1 << n][n]; for (int i = 0; i < 1 << n; i++) { for (int j = 0; j < n; j++) { res[i][j] = (i >> j & 1) == 1; } } return res; } public static boolean[][] bitAll(int n, int bitCount) { List<boolean[]> res = new ArrayList<>(); boolean[] b = new boolean[n]; for (int i = (1 << bitCount) - 1; i < 1 << n;) { assert Integer.bitCount(i) == bitCount; for (int j = 0; j < n; j++) b[j] = (i >> j & 1) == 1; res.add(b.clone()); int t = i | i - 1; i = t + 1 | (~t & -~t) - 1 >> Integer.numberOfTrailingZeros(i) + 1; } return toBooleanArrayArray(res); } public static int[][] bitAllFilter(boolean[][] use, int[] array) { int[][] res = new int[use.length][]; for (int i = 0; i < use.length; i++) { int size = 0; for (int j = 0; j < use[i].length; j++) if (use[i][j]) size++; res[i] = new int[size]; int index = 0; for (int j = 0; j < array.length; j++) if (use[i][j]) res[i][index++] = array[j]; } return res; } public static long[][] bitAllFilter(boolean[][] use, long[] array) { long[][] res = new long[use.length][]; for (int i = 0; i < use.length; i++) { int size = 0; for (int j = 0; j < use[i].length; j++) if (use[i][j]) size++; res[i] = new long[size]; int index = 0; for (int j = 0; j < array.length; j++) if (use[i][j]) res[i][index++] = array[j]; } return res; } public static double[][] bitAllFilter(boolean[][] use, double[] array) { double[][] res = new double[use.length][]; for (int i = 0; i < use.length; i++) { int size = 0; for (int j = 0; j < use[i].length; j++) if (use[i][j]) size++; res[i] = new double[size]; int index = 0; for (int j = 0; j < array.length; j++) if (use[i][j]) res[i][index++] = array[j]; } return res; } public static Object[][] bitAllFilter(boolean[][] use, Object[] array) { Object[][] res = new Object[use.length][]; for (int i = 0; i < use.length; i++) { int size = 0; for (int j = 0; j < use[i].length; j++) if (use[i][j]) size++; res[i] = new Object[size]; int index = 0; for (int j = 0; j < array.length; j++) if (use[i][j]) res[i][index++] = array[j]; } return res; } public static int[][][] bitAllFilter(boolean[][] use, int[][] array) { int[][][] res = new int[use.length][][]; for (int i = 0; i < use.length; i++) { int size = 0; for (int j = 0; j < use[i].length; j++) if (use[i][j]) size++; res[i] = new int[size][]; int index = 0; for (int j = 0; j < array.length; j++) if (use[i][j]) res[i][index++] = array[j]; } return res; } public static long[][][] bitAllFilter(boolean[][] use, long[][] array) { long[][][] res = new long[use.length][][]; for (int i = 0; i < use.length; i++) { int size = 0; for (int j = 0; j < use[i].length; j++) if (use[i][j]) size++; res[i] = new long[size][]; int index = 0; for (int j = 0; j < array.length; j++) if (use[i][j]) res[i][index++] = array[j]; } return res; } public static int[] arrayRange(int start, int end, int headspace, int tailspace) { int n = end - start + 1; int[] res = new int[n + headspace + tailspace]; int cur = start; for (int i = headspace; i < n + headspace; i++) res[i] = cur++; return res; } public static int[] arrayRange(int start, int end) { return arrayRange(start, end, 0, 0); } public static long[] arrayRange(long start, long end, int headspace, int tailspace) { long n = end - start + 1; long[] res = new long[(int)n + headspace + tailspace]; long cur = start; for (int i = headspace; i < n + headspace; i++) res[i] = cur++; return res; } public static long[] arrayRange(long start, long end) { return arrayRange(start, end, 0, 0); } public static long[] toLongArray(Collection<?> list) { return list.stream().mapToLong(i -> (long)i).toArray(); } public static int[] toIntArray(Collection<?> list) { return list.stream().mapToInt(i -> (int)i).toArray(); } public static double[] toDoubleArray(Collection<?> list) { return list.stream().mapToDouble(i -> (double)i).toArray(); } public static boolean[] toBooleanArray(Collection<?> list) { Object[] a = list.toArray(); boolean[] b = new boolean[a.length]; for (int i = 0; i < b.length; i++) { b[i] = (boolean)a[i]; } return b; } public static String[] toStringArray(Collection<?> list) { return list.stream().map(i -> i.toString()).toArray(String[]::new); } public static long[][] toLongArrayArray(Collection<?> list) { return list.toArray(long[][]::new); } public static int[][] toIntArrayArray(Collection<?> list) { return list.toArray(int[][]::new); } public static double[][] toDoubleArrayArray(Collection<?> list) { return list.toArray(double[][]::new); } public static boolean[][] toBooleanArrayArray(Collection<?> list) { return list.toArray(boolean[][]::new); } public static String[][] toStringArrayArray(Collection<?> list) { return list.toArray(String[][]::new); } public static <T> void reverse(T[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(boolean[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(int[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(long[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(double[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(float[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(byte[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static void reverse(char[] array) { int len = array.length; for (int i = 0; i < len / 2; i++) swap(array, i, len - i - 1); } public static int[] distinct(int[] a) { return Arrays.stream(a).distinct().toArray(); } public static long[] distinct(long[] a) { return Arrays.stream(a).distinct().toArray(); } public static double[] distinct(double[] a) { return Arrays.stream(a).distinct().toArray(); } public static void fill(int[] a, int v) { Arrays.fill(a, v); } public static void fill(long[] a, long v) { Arrays.fill(a, v); } public static void fill(double[] a, double v) { Arrays.fill(a, v); } public static void fill(boolean[] a, boolean v) { Arrays.fill(a, v); } public static void fill(char[] a, char v) { Arrays.fill(a, v); } public static void fill(int[][] a, int v) { for (int[] i : a) fill(i, v); } public static void fill(long[][] a, long v) { for (long[] i : a) fill(i, v); } public static void fill(double[][] a, double v) { for (double[] i : a) fill(i, v); } public static void fill(boolean[][] a, boolean v) { for (boolean[] i : a) fill(i, v); } public static void fill(char[][] a, char v) { for (char[] i : a) fill(i, v); } public static void fill(int[][][] a, int v) { for (int[][] i : a) fill(i, v); } public static void fill(long[][][] a, long v) { for (long[][] i : a) fill(i, v); } public static void fill(double[][][] a, double v) { for (double[][] i : a) fill(i, v); } public static void fill(boolean[][][] a, boolean v) { for (boolean[][] i : a) fill(i, v); } public static void fill(char[][][] a, char v) { for (char[][] i : a) fill(i, v); } public static void fill(int[][][][] a, int v) { for (int[][][] i : a) fill(i, v); } public static void fill(long[][][][] a, long v) { for (long[][][] i : a) fill(i, v); } public static void fill(double[][][][] a, double v) { for (double[][][] i : a) fill(i, v); } public static void fill(boolean[][][][] a, boolean v) { for (boolean[][][] i : a) fill(i, v); } public static void fill(char[][][][] a, char v) { for (char[][][] i : a) fill(i, v); } // NOTE: These methods require Java 16 or higher. public static List<Long> arrayToList(long[] array) { return Arrays.stream(array).boxed().collect(Collectors.toList()); //return Arrays.stream(array).boxed().toList(); } public static List<Integer> arrayToList(int[] array) { return Arrays.stream(array).boxed().collect(Collectors.toList()); //return Arrays.stream(array).boxed().toList(); } public static List<Double> arrayToList(double[] array) { return Arrays.stream(array).boxed().collect(Collectors.toList()); //return Arrays.stream(array).boxed().toList(); } public static List<Boolean> arrayToList(boolean[] array) { Boolean[] a = new Boolean[array.length]; for (int i = 0; i < a.length; i++) a[i] = array[i]; return Arrays.stream(a).collect(Collectors.toList()); //return Arrays.stream(a).toList(); } public static List<Character> arrayToList(char[] array) { return Arrays.stream(arrayBoxed(array)).collect(Collectors.toList()); } public static <T> List<T> arrayToList(T[] array) { return Arrays.stream(array).collect(Collectors.toList()); //return Arrays.stream(array).toList(); } public static Long[] arrayBoxed(long[] array) { return Arrays.stream(array).boxed().toArray(Long[]::new); } public static Integer[] arrayBoxed(int[] array) { return Arrays.stream(array).boxed().toArray(Integer[]::new); } public static Double[] arrayBoxed(double[] array) { return Arrays.stream(array).boxed().toArray(Double[]::new); } public static Boolean[] arrayBoxed(boolean[] array) { Boolean[] a = new Boolean[array.length]; for (int i = 0; i < array.length; i++) { a[i] = array[i]; } return a; } public static Character[] arrayBoxed(char[] array) { Character[] a = new Character[array.length]; for (int i = 0; i < array.length; i++) { a[i] = array[i]; } return a; } public static long[] arrayUnboxed(Long[] array) { return Arrays.stream(array).mapToLong(i -> i).toArray(); } public static int[] arrayUnboxed(Integer[] array) { return Arrays.stream(array).mapToInt(i -> i).toArray(); } public static double[] arrayUnboxed(Double[] array) { return Arrays.stream(array).mapToDouble(i -> i).toArray(); } public static boolean[] arrayUnboxed(Boolean[] array) { boolean[] a = new boolean[array.length]; for (int i = 0; i < array.length; i++) { a[i] = array[i]; } return a; } public static char[] arrayUnboxed(Character[] array) { char[] a = new char[array.length]; for (int i = 0; i < array.length; i++) { a[i] = array[i]; } return a; } // 最大値 (int) public static int max(int a, int b) { return Math.max(a, b); } public static int max(int a, int ... nums) { return max(a, max(nums)); } public static int max(int[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = a[0]; for (int i = start; i <= end; i++) res = Math.max(res, a[i]); return res; } public static int max(int[] a, int start) { return max(a, start, a.length - 1); } public static int max(int[] a) { return max(a, 0, a.length - 1); } public static int maxIndex(int[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = start; for (int i = start; i <= end; i++) { if (a[i] > a[res]) res = i; } return res; } public static int maxIndex(int[] a, int start) { return maxIndex(a, start, a.length - 1); } public static int maxIndex(int[] a) { return maxIndex(a, 0, a.length - 1); } // 最小値 (int) public static int min(int a, int b) { return Math.min(a, b); } public static int min(int a, int ... nums) { return min(a, min(nums)); } public static int min(int[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = a[0]; for (int i = start; i <= end; i++) res = Math.min(res, a[i]); return res; } public static int min(int[] a, int start) { return min(a, start, a.length - 1); } public static int min(int[] a) { return min(a, 0, a.length - 1); } public static int minIndex(int[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = start; for (int i = start; i <= end; i++) { if (a[i] < a[res]) res = i; } return res; } public static int minIndex(int[] a, int start) { return minIndex(a, start, a.length - 1); } public static int minIndex(int[] a) { return minIndex(a, 0, a.length - 1); } // 最大値 (long) public static long max(long a, long b) { return Math.max(a, b); } public static long max(long a, long ... nums) { return max(a, max(nums)); } public static long max(long[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; long res = a[0]; for (int i = start; i <= end; i++) res = Math.max(res, a[i]); return res; } public static long max(long[] a, int start) { return max(a, start, a.length - 1); } public static long max(long[] a) { return max(a, 0, a.length - 1); } public static int maxIndex(long[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = start; for (int i = start; i <= end; i++) { if (a[i] > a[res]) res = i; } return res; } public static int maxIndex(long[] a, int start) { return maxIndex(a, start, a.length - 1); } public static int maxIndex(long[] a) { return maxIndex(a, 0, a.length - 1); } // 最小値 (long) public static long min(long a, long b) { return Math.min(a, b); } public static long min(long a, long ... nums) { return min(a, min(nums)); } public static long min(long[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; long res = a[0]; for (int i = start; i <= end; i++) res = Math.min(res, a[i]); return res; } public static long min(long[] a, int start) { return min(a, start, a.length - 1); } public static long min(long[] a) { return min(a, 0, a.length - 1); } public static int minIndex(long[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = start; for (int i = start; i <= end; i++) { if (a[i] < a[res]) res = i; } return res; } public static int minIndex(long[] a, int start) { return minIndex(a, start, a.length - 1); } public static int minIndex(long[] a) { return minIndex(a, 0, a.length - 1); } // 最大値 (double) public static double max(double a, double b) { return Math.max(a, b); } public static double max(double a, double ... nums) { return max(a, max(nums)); } public static double max(double[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; double res = a[0]; for (int i = start; i <= end; i++) res = Math.max(res, a[i]); return res; } public static double max(double[] a, int start) { return max(a, start, a.length - 1); } public static double max(double[] a) { return max(a, 0, a.length - 1); } public static int maxIndex(double[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = start; for (int i = start; i <= end; i++) { if (a[i] > a[res]) res = i; } return res; } public static int maxIndex(double[] a, int start) { return maxIndex(a, start, a.length - 1); } public static int maxIndex(double[] a) { return maxIndex(a, 0, a.length - 1); } // 最小値 (double) public static double min(double a, double b) { return Math.min(a, b); } public static double min(double a, double ... nums) { return min(a, min(nums)); } public static double min(double[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; double res = a[0]; for (int i = start; i <= end; i++) res = Math.min(res, a[i]); return res; } public static double min(double[] a, int start) { return min(a, start, a.length - 1); } public static double min(double[] a) { return min(a, 0, a.length - 1); } public static int minIndex(double[] a, int start, int end) { assert start >= 0 && end < a.length && start <= end; int res = start; for (int i = start; i <= end; i++) { if (a[i] < a[res]) res = i; } return res; } public static int minIndex(double[] a, int start) { return minIndex(a, start, a.length - 1); } public static int minIndex(double[] a) { return minIndex(a, 0, a.length - 1); } // 絶対値 public static int abs(int a) { return Math.abs(a); } public static long abs(long a) { return Math.abs(a); } public static double abs(double a) { return Math.abs(a); } // チェビシェフ距離(チェス盤距離) public static long chebyshevDistance(long x1, long y1, long x2, long y2) { return max(abs(x1 - x2), abs(y1 - y2)); } public static int chebyshevDistance(int x1, int y1, int x2, int y2) { return max(abs(x1 - x2), abs(y1 - y2)); } // マンハッタン距離 public static long manhattanDistance(long x1, long y1, long x2, long y2) { return abs(x1 - x2) + abs(y1 - y2); } public static int manhattanDistance(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } // ユークリッド距離 public static int euclideanDistance(int x1, int y1, int x2, int y2) { return (int) Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); } public static long euclideanDistance(long x1, long y1, long x2, long y2) { return (long) Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); } // 外積 public static long cross(long ox, long oy, long ax, long ay, long bx, long by) { // 外積: |a||b|sinθ = axby - bxay return (ax - ox) * (by - oy) - (bx - ox) * (ay - oy); } public static long cross(long ax, long xy, long bx, long by) { // 外積: |a||b|sinθ = axby - bxay return cross(0, 0, ax, xy, bx, by); } // 内積 public static long dot(long ox, long oy, long ax, long ay, long bx, long by) { // 内積: |a||b|cosθ = axbx + ayby return (ax - ox) * (bx - ox) + (ay - oy) * (by - oy); } public static long dot(long ax, long xy, long bx, long by) { // 内積: |a||b|cosθ = axbx + ayby return dot(0, 0, ax, xy, bx, by); } // swap public static String swap(String s, int i, int j) { char[] cs = s.toCharArray(); char tmp = cs[i]; cs[i] = cs[j]; cs[j] = tmp; return String.valueOf(cs); } public static void swap(boolean[] a, int i, int j) { boolean tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void swap(long[] a, int i, int j) { long tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void swap(double[] a, int i, int j) { double tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void swap(float[] a, int i, int j) { float tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void swap(byte[] a, int i, int j) { byte tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void swap(char[] a, int i, int j) { char tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static <T> void swap(T[] a, int i, int j) { T tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static <T> void swap(List<T> a, int i, int j) { T tmp = a.get(i); a.set(i, a.get(j)); a.set(j, tmp); } // 間にあるかどうか public static boolean between(int a, int x, int b) { if (a > b) return between(b, x, a); return a <= x && x <= b; } public static boolean between(long a, long x, long b) { if (a > b) return between(b, x, a); return a <= x && x <= b; } public static boolean between(double a, double x, double b) { if (a > b) return between(b, x, a); return a <= x && x <= b; } public static boolean between(float a, float x, float b) { if (a > b) return between(b, x, a); return a <= x && x <= b; } public static boolean between(byte a, byte x, byte b) { if (a > b) return between(b, x, a); return a <= x && x <= b; } public static boolean between(char a, char x, char b) { if (a > b) return between(b, x, a); return a <= x && x <= b; } } class MyMath { // 最大公約数 (Greatest Common Divisor) public static long gcd(long a, long b) { if (a < b) { long tmp = a; a = b; b = tmp; } while (b != 0) { long tmp = a % b; a = b; b = tmp; } return a; } public static int gcd(int a, int b) { if (a < b) { int tmp = a; a = b; b = tmp; } while (b != 0) { int tmp = a % b; a = b; b = tmp; } return a; } // 最小公倍数 (Least Common Multiple) public static long lcm(long a, long b) { return a * b / gcd(a, b); } public static int lcm(int a, int b) { return a * b / gcd(a, b); } // 素数列挙 (Prime enumeration) public static int[] primes(int max) { return primes_base((int)Math.sqrt(max) + 1); } public static int[] primes_base(int max) { boolean[] is_prime = new boolean[max]; for (int i = 0; i < max; i++) { is_prime[i] = true; } for (int i = 2; i < max; i++) { if (is_prime[i]) { for (int j = i * 2; j < max; j += i) { is_prime[j] = false; } } } int cnt = 0; for (int i = 2; i < max; i++) { if (is_prime[i]) cnt++; } int[] primes = new int[cnt]; int index = 0; for (int i = 2; i < max && index < cnt; i++) { if (is_prime[i]) primes[index++] = i; } return primes; } // TODO: public static int[] primes_base_bit(int max) { long[] is_prime = new long[max/64+1]; for (int i = 0; i < max; i++) { is_prime[i/64] = is_prime[i/64] | (1 << (i%64)); // is_prime[i] = true } for (int i = 2; i < max; i++) { if ((is_prime[i/64] & (1 << (i%64))) != 0) { // is_prime[i] for (int j = i * 2; j < max; j += i) { is_prime[j/64] = is_prime[j/64] & (~(1 << (j%64))); // is_prime[j] = false } } } int cnt = 0; for (int i = 2; i < max; i++) { if ((is_prime[i/64] & (1 << (i%64))) != 0) cnt++; // is_prime[i] } int[] primes = new int[cnt]; int index = 0; for (int i = 2; i < max && index < cnt; i++) { if ((is_prime[i/64] & (1 << (i%64))) != 0) primes[index++] = i; // is_prime[i] } return primes; } } class In { private final InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; public In(InputStream in) { this.in = in; } public In() { this.in = System.in; } private final boolean hasNextByte() { if (ptr < buflen) return true; ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) return false; return true; } private final int readByte() { return hasNextByte() ? buffer[ptr++] : -1; } private static final boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public final boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) { ptr++; } return hasNextByte(); } public final String s() { StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public final void nextThrow(int n) { for (int i = 0; i < n; i++) this.s(); } public final void nextThrow() { this.nextThrow(1); } public final long l() { long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } assert '0' <= b && b <= '9' : "NumberFormatException"; while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else { //assert b == ' ' || b == '\n' : "NumberFormatException"; return minus ? -n : n; } b = readByte(); } } public long[] la(int n, int headspace, int tailspace) { long[] result = new long[n + headspace + tailspace]; for (int i = headspace; i < n + headspace; i++) result[i] = l(); return result; } public long[] la(int n, int headspace) { return la(n, headspace, 0); } public long[] la(int n) { return la(n, 0, 0); } // TODO: public long[][] laa(int n, int m) { long[][] result = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) result[i][j] = l(); } return result; } public final int i() { long nl = l(); assert (Integer.MIN_VALUE <= nl || nl <= Integer.MAX_VALUE) : "NumberFormatException"; return (int)nl; } public int[] ia(int n, int headspace, int tailspace) { int[] result = new int[n + headspace + tailspace]; for (int i = headspace; i < n + headspace; i++) result[i] = i(); return result; } public int[] ia(int n, int headspace) { return ia(n, headspace, 0); } public int[] ia(int n) { return ia(n, 0, 0); } // TODO: public int[][] iaa(int n, int m) { int[][] result = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) result[i][j] = i(); } return result; } public int[][] ias(int ncol, int n) { int[][] result = new int[ncol][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < ncol; j++) result[j][i] = i(); } return result; } public double d() { return Double.parseDouble(s()); } public boolean[] b(char True) { String s = this.s(); int n = s.length(); boolean[] array = new boolean[n]; for (int i = 0; i < n; i++) array[i] = s.charAt(i) == True; return array; } } class Out { PrintWriter out; Out() { this.out = new PrintWriter(System.out); } public final void as() { out.print(' '); } public final void an() { out.print('\n'); } public final <T> void a(T n) { out.print(n); } public final <T> void as(T n) { out.print(n); out.print(' '); } public final <T> void an(T n) { out.println(n); } public final void yesno(boolean b) { out.println(b ? "Yes" : "No"); } public final void aas(int[] n) { int nm = n.length-1; for (int i = 0; i < nm; i++) { out.print(n[i]); out.print(' '); } out.println(n[nm]); } public final void aan(int[] n) { int nm = n.length-1; for (int i = 0; i < nm; i++) { out.println(n[i]); } out.println(n[nm]); } public final void aas(int[][] n) { int nm = n.length; for (int i = 0; i < nm; i++) { aas(n[i]); } } public final void aas(long[] n) { int nm = n.length-1; for (int i = 0; i < nm; i++) { out.print(n[i]); out.print(' '); } out.println(n[nm]); } public final void aan(long[] n) { int nm = n.length-1; for (int i = 0; i < nm; i++) { out.println(n[i]); } out.println(n[nm]); } public final void aas(long[][] n) { int nm = n.length; for (int i = 0; i < nm; i++) { aas(n[i]); } } public final void flush() { out.flush(); } public final void flushln() { out.print('\n'); out.flush(); } } // Edge class E { int u; int v; int w; public E(int u, int v, int w) { this.u = u; this.v = v; this.w = w; } public E(int u, int v) { this(u, v, 0); } } // Union-Find class UF { int[] parent; int[] rank; int[] size; public UF(int n) { parent = new int[n+1]; rank = new int[n+1]; size = new int[n+1]; for (int i = 1; i <= n; i++) { parent[i] = i; rank[i] = 0; size[i] = 1; } } public int find(int x) { assert (0 < x && x < parent.length) : "IndexOutOfBoundsException"; if (parent[x] == x) return x; return parent[x] = find(parent[x]); } public void union(int x, int y) { assert (0 < x && x < parent.length) : "IndexOutOfBoundsException"; assert (0 < y && y < parent.length) : "IndexOutOfBoundsException"; x = find(x); y = find(y); if (x == y) return; if (rank[x] < rank[y]) { parent[x] = y; size[y] += size[x]; } else { parent[y] = x; size[x] += size[y]; if (rank[x] == rank[y]) rank[x]++; } } public boolean same(int x, int y) { assert (0 < x && x < parent.length) : "IndexOutOfBoundsException"; assert (0 < y && y < parent.length) : "IndexOutOfBoundsException"; return find(x) == find(y); } public int size(int x) { assert (0 < x && x < parent.length) : "IndexOutOfBoundsException"; return size[find(x)]; } } class MyComparator { private static Comparator<int[]> dictIntArray = null; static Comparator<int[]> dictIntArray() { if (dictIntArray == null) dictIntArray = (a, b) -> Arrays.compare(a, b); return dictIntArray; } private static Comparator<int[][]> dictIntArrayArray = null; static Comparator<int[][]> dictIntArrayArray() { if (dictIntArrayArray == null) dictIntArrayArray = (a, b) -> { for (int i = 0; i < a.length; i++) { int c = Arrays.compare(a[i], b[i]); if (c != 0) return c; } return 0; }; return dictIntArrayArray; } }
ConDefects/ConDefects/Code/abc294_f/Java/39894051
condefects-java_data_415
import java.io.*; import java.util.*; public class Main { void go() { int m1 = nextInt(); int m2 = nextInt(); long K = nextLong(); long[][] c1 = new long[m1][2]; c2 = new long[m2][2]; for (int i = 0; i < m1; ++i) { c1[i][0] = nextLong(); c1[i][1] = nextLong() + c1[i][0]; } for (int i = 0; i < m2; ++i) { c2[i][0] = nextLong(); c2[i][1] = nextLong() + c2[i][0]; } double l = 0, r = 1, eps = 1e-10; while (l + eps < r) { double mid = (l + r) / 2; //ruffle(c2); Arrays.sort(c2, (x, y) -> Double.compare(x[0] - mid * x[1], y[0] - mid * y[1])); long ge = 0; for (int i = 0; i < m1; ++i) { ge += more(mid, c1[i][0], c1[i][1]); } if (ge < K) r = mid; else l = mid; } sl(l * 100); } long[][] c2; long more(double tar, long x, long y) { int l = 0, r = c2.length - 1; int m2 = c2.length; if ((x + c2[0][0]) * 1.0 / (y + c2[0][1]) >= tar) return c2.length; if ((x + c2[m2 - 1][0]) * 1.0 / (y + c2[m2 - 1][1]) < tar) return 0; while (l + 1 < r) { int mid = (l + r) / 2; if ((x + c2[mid][0]) * 1.0 / (y + c2[mid][1]) < tar) l = mid; else r = mid; } return m2 - r; } /** * NOTE: Ignore following codes. */ void goMultiple() { int T = nextInt(); for (int i = 0; i < T; ++i) { go(); } } /** * Toolkit. */ void ruffleSort(int[] a) { Random random = new Random(); int n = a.length; for (int i = 0; i < n; i++) { int x = random.nextInt(n); int temp = a[x]; a[x] = a[i]; a[i] = temp; } Arrays.sort(a); } void ruffle(long[][] a) { Random random = new Random(); int n = a.length; for (int i = 0; i < n; i++) { int x = random.nextInt(n); long[] temp = a[x]; a[x] = a[i]; a[i] = temp; } } /** * Input. */ InputStream inStream; byte[] inBuff = new byte[1024]; int inBuffCursor = 0; int inBuffLen = 0; boolean isVisibleChar(int c) { return 33 <= c && c <= 126; } boolean hasNextByte() { if (inBuffCursor < inBuffLen) return true; inBuffCursor = 0; try { inBuffLen = inStream.read(inBuff); } catch (Exception e) { e.printStackTrace(); } return inBuffLen > 0; } boolean hasNext() { while (hasNextByte() && !isVisibleChar(inBuff[inBuffCursor])) inBuffCursor++; return hasNextByte(); } int nextByte() { return hasNextByte() ? inBuff[inBuffCursor++] : -1; } String next() { if (!hasNext()) throw new RuntimeException("no next."); StringBuilder sb = new StringBuilder(); int b = nextByte(); while (isVisibleChar(b)) { sb.appendCodePoint(b); b = nextByte(); } return sb.toString(); } long nextLong() { if (!hasNext()) throw new RuntimeException("no next."); long result = 0; boolean negative = false; int b = nextByte(); if (b < '0') { if (b == '-') negative = true; else if (b != '+') throw new RuntimeException("long number must start with +/-."); b = nextByte(); } while (isVisibleChar(b)) { if (b < '0' || b > '9') throw new RuntimeException("wrong digit in long:" + (char) b); // TODO: may overflow here, even if it is a valid Long, eg.-(1<<63). result = result * 10 + (b - '0'); b = nextByte(); } return negative ? -result : result; } int nextInt() { long x = nextLong(); if (x < Integer.MIN_VALUE || x > Integer.MAX_VALUE) throw new RuntimeException("int overflow:" + x); return (int) x; } double nextDouble() { return Double.parseDouble(next()); } /** * Output. */ PrintWriter printOut = new PrintWriter(System.out); void so(Object obj) { printOut.print(obj); } void sl(Object obj) { printOut.println(obj); } void sl() { printOut.println(); } /** * Main. */ void mainGo(boolean isMultiple) { try { inStream = new FileInputStream("src/main.in"); } catch (Exception e) { inStream = System.in; } while (hasNext()) { if (isMultiple) goMultiple(); else go(); } printOut.flush(); } public static void main(String[] args) throws Exception { new Main().mainGo(false); } } import java.io.*; import java.util.*; public class Main { void go() { int m1 = nextInt(); int m2 = nextInt(); long K = nextLong(); long[][] c1 = new long[m1][2]; c2 = new long[m2][2]; for (int i = 0; i < m1; ++i) { c1[i][0] = nextLong(); c1[i][1] = nextLong() + c1[i][0]; } for (int i = 0; i < m2; ++i) { c2[i][0] = nextLong(); c2[i][1] = nextLong() + c2[i][0]; } double l = 0, r = 1, eps = 1e-11; while (l + eps < r) { double mid = (l + r) / 2; //ruffle(c2); Arrays.sort(c2, (x, y) -> Double.compare(x[0] - mid * x[1], y[0] - mid * y[1])); long ge = 0; for (int i = 0; i < m1; ++i) { ge += more(mid, c1[i][0], c1[i][1]); } if (ge < K) r = mid; else l = mid; } sl(l * 100); } long[][] c2; long more(double tar, long x, long y) { int l = 0, r = c2.length - 1; int m2 = c2.length; if ((x + c2[0][0]) * 1.0 / (y + c2[0][1]) >= tar) return c2.length; if ((x + c2[m2 - 1][0]) * 1.0 / (y + c2[m2 - 1][1]) < tar) return 0; while (l + 1 < r) { int mid = (l + r) / 2; if ((x + c2[mid][0]) * 1.0 / (y + c2[mid][1]) < tar) l = mid; else r = mid; } return m2 - r; } /** * NOTE: Ignore following codes. */ void goMultiple() { int T = nextInt(); for (int i = 0; i < T; ++i) { go(); } } /** * Toolkit. */ void ruffleSort(int[] a) { Random random = new Random(); int n = a.length; for (int i = 0; i < n; i++) { int x = random.nextInt(n); int temp = a[x]; a[x] = a[i]; a[i] = temp; } Arrays.sort(a); } void ruffle(long[][] a) { Random random = new Random(); int n = a.length; for (int i = 0; i < n; i++) { int x = random.nextInt(n); long[] temp = a[x]; a[x] = a[i]; a[i] = temp; } } /** * Input. */ InputStream inStream; byte[] inBuff = new byte[1024]; int inBuffCursor = 0; int inBuffLen = 0; boolean isVisibleChar(int c) { return 33 <= c && c <= 126; } boolean hasNextByte() { if (inBuffCursor < inBuffLen) return true; inBuffCursor = 0; try { inBuffLen = inStream.read(inBuff); } catch (Exception e) { e.printStackTrace(); } return inBuffLen > 0; } boolean hasNext() { while (hasNextByte() && !isVisibleChar(inBuff[inBuffCursor])) inBuffCursor++; return hasNextByte(); } int nextByte() { return hasNextByte() ? inBuff[inBuffCursor++] : -1; } String next() { if (!hasNext()) throw new RuntimeException("no next."); StringBuilder sb = new StringBuilder(); int b = nextByte(); while (isVisibleChar(b)) { sb.appendCodePoint(b); b = nextByte(); } return sb.toString(); } long nextLong() { if (!hasNext()) throw new RuntimeException("no next."); long result = 0; boolean negative = false; int b = nextByte(); if (b < '0') { if (b == '-') negative = true; else if (b != '+') throw new RuntimeException("long number must start with +/-."); b = nextByte(); } while (isVisibleChar(b)) { if (b < '0' || b > '9') throw new RuntimeException("wrong digit in long:" + (char) b); // TODO: may overflow here, even if it is a valid Long, eg.-(1<<63). result = result * 10 + (b - '0'); b = nextByte(); } return negative ? -result : result; } int nextInt() { long x = nextLong(); if (x < Integer.MIN_VALUE || x > Integer.MAX_VALUE) throw new RuntimeException("int overflow:" + x); return (int) x; } double nextDouble() { return Double.parseDouble(next()); } /** * Output. */ PrintWriter printOut = new PrintWriter(System.out); void so(Object obj) { printOut.print(obj); } void sl(Object obj) { printOut.println(obj); } void sl() { printOut.println(); } /** * Main. */ void mainGo(boolean isMultiple) { try { inStream = new FileInputStream("src/main.in"); } catch (Exception e) { inStream = System.in; } while (hasNext()) { if (isMultiple) goMultiple(); else go(); } printOut.flush(); } public static void main(String[] args) throws Exception { new Main().mainGo(false); } }
ConDefects/ConDefects/Code/abc294_f/Java/39920354
condefects-java_data_416
import java.util.Scanner; class Main { public static void main(String args[]){ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); long T = sc.nextLong(); int A[] = new int[N]; int sum = 0; for (int i = 0; i < N; i++){ A[i] = sc.nextInt(); sum += A[i]; } T %= sum; for (int i = 0; i < N; i++){ if (T > A[i]){ T -= A[i]; } else{ System.out.print(i + 1); System.out.print(" "); System.out.print(T); sc.close(); System.exit(0); } } } } import java.util.Scanner; class Main { public static void main(String args[]){ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); long T = sc.nextLong(); int A[] = new int[N]; long sum = 0; for (int i = 0; i < N; i++){ A[i] = sc.nextInt(); sum += A[i]; } T %= sum; for (int i = 0; i < N; i++){ if (T > A[i]){ T -= A[i]; } else{ System.out.print(i + 1); System.out.print(" "); System.out.print(T); sc.close(); System.exit(0); } } } }
ConDefects/ConDefects/Code/abc281_c/Java/40391146
condefects-java_data_417
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan= new Scanner(System.in); String row1=scan.nextLine(); String row2=scan.nextLine(); int n=Integer.parseInt(row1); int sum=0; for(int i=1;i<=n;i++) { sum+=4*i; } int sum2=0; String[] str = row2.split(" "); for(int i=0;i<str.length;i++) { sum2+=Integer.parseInt(str[i]); } System.out.println(sum=sum2); } } import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan= new Scanner(System.in); String row1=scan.nextLine(); String row2=scan.nextLine(); int n=Integer.parseInt(row1); int sum=0; for(int i=1;i<=n;i++) { sum+=4*i; } int sum2=0; String[] str = row2.split(" "); for(int i=0;i<str.length;i++) { sum2+=Integer.parseInt(str[i]); } System.out.println(sum-sum2); } }
ConDefects/ConDefects/Code/abc236_b/Java/35930572
condefects-java_data_418
// temprate import java.util.*; import static java.lang.Math.*; public class Main{ public static void main(String[] args){ var in = new Scanner(System.in); // ~~~ int n = in.nextInt(); int ans = 4 * n - 2 ; var A = new ArrayList<String>(); for ( int i = 0 ; 4 * n - 1 > i ; i++ ){ A.add( in.next() ); } Collections.sort(A); for ( int i = 0 ; 4 * ( n - 1) - 1 > i ; i += 4){ if ( !(A.get( i ).equals( A.get( i + 3 ) )) ){ ans = i + 3; break; } } System.out.println( A.get( ans ) ); } } // temprate import java.util.*; import static java.lang.Math.*; public class Main{ public static void main(String[] args){ var in = new Scanner(System.in); // ~~~ int n = in.nextInt(); int ans = 4 * n - 2 ; var A = new ArrayList<String>(); for ( int i = 0 ; 4 * n - 1 > i ; i++ ){ A.add( in.next() ); } Collections.sort(A); for ( int i = 0 ; 4 * ( n - 1) - 1 > i ; i += 4){ if ( !(A.get( i ).equals( A.get( i + 3 ) )) ){ ans = i + 3; break; } } System.out.println( A.get( ans - 1 ) ); } }
ConDefects/ConDefects/Code/abc236_b/Java/39559464
condefects-java_data_419
import java.util.*; class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n=scan.nextInt(); int ans = n*(n*1)*2; for(int i=0;i<n*4-1;i++){ ans-=scan.nextInt(); } System.out.println(ans); } } import java.util.*; class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n=scan.nextInt(); int ans = n*(n+1)*2; for(int i=0;i<n*4-1;i++){ ans-=scan.nextInt(); } System.out.println(ans); } }
ConDefects/ConDefects/Code/abc236_b/Java/38171978
condefects-java_data_420
import java.io.IOException; import java.io.PrintWriter; import java.lang.management.ManagementFactory; import java.util.Scanner; import java.util.function.IntFunction; import java.util.stream.IntStream; class Main{ long st = ManagementFactory.getRuntimeMXBean().getStartTime(); boolean isDebug = ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("-agentlib:jdwp"); AbstractScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); public static void main(final String[] args){ new Main().exe(); } void exe(){ input(); preCalc(); solve(); pw.flush(); } int N = sc.it(); int[] A = sc.it(4 *N -1); void input(){} void preCalc(){} void solve(){ long ret = N *(N +1) *2; for (var a:A) ret -= a; out(ret); } /* Util */ int min(int a,int b){ return Math.min(a,b); } long min(long a,long b){ return Math.min(a,b); } double min(double a,double b){ return Math.min(a,b); } int max(int a,int b){ return Math.max(a,b); } long max(long a,long b){ return Math.max(a,b); } double max(double a,double b){ return Math.max(a,b); } /* 出力 */ void out(final Object ret){ pw.println(ret); } void out(final int[] ret){ final StringBuilder sb = new StringBuilder(); sb.append(ret[0]); for (int i = 1;i < ret.length;i++) sb.append(" " +ret[i]); pw.println(sb.toString()); } void debug(final boolean b){ if (b) info(null); } void info(final Object info){ if (isDebug) System.out.println(info); } /* 入力 */ static abstract class AbstractScanner{ abstract long lg(); long[] lg(final int N){ return IntStream.range(0,N).mapToLong(i -> lg()).toArray(); } long[][] lg(final int H,final int W){ return arr(new long[H][],i -> lg(W)); } double dbl(){ return Double.parseDouble(str()); } int it(){ return Math.toIntExact(lg()); } int[] it(final int N){ return IntStream.range(0,N).map(i -> it()).toArray(); } int[][] it(final int H,final int W){ return arr(new int[H][],i -> it(W)); } int idx(){ return it() -1; } int[] idx(final int N){ return IntStream.range(0,N).map(i -> idx()).toArray(); } int[][] idx(final int H,final int W){ return arr(new int[H][],i -> idx(W)); } abstract String str(); char[] ch(){ return str().toCharArray(); } char[][] ch(final int H){ return arr(new char[H][],i -> ch()); } <T> T[] arr(final T[] arr,final IntFunction<T> func){ return IntStream.range(0,arr.length).mapToObj(func).toArray(t -> arr); } } static class FastScanner extends AbstractScanner{ int buflen = 1024; byte[] buf = new byte[buflen]; int ptr = buflen -1; int readByte(){ final int ret = buf[ptr++]; ptr %= buflen; if (ptr == 0) try { System.in.read(buf); } catch (final IOException e) { e.printStackTrace(); } return ret; } boolean isPrintableChar(final int c){ return 32 < c && c < 127; } boolean isNumeric(final int c){ return 47 < c && c < 58; } int nextPrintableChar(){ int ret = readByte(); while (!isPrintableChar(ret)) ret = readByte(); return ret; } @Override long lg(){ final int s = nextPrintableChar(); final boolean negative = s == 45; long ret = 0; for (int b = negative ? readByte() : s;isPrintableChar(b);b = readByte()) if (isNumeric(b)) ret = ret *10 +b -48; else throw new NumberFormatException(); return negative ? -ret : ret; } @Override String str(){ final StringBuilder ret = new StringBuilder(); for (int b = nextPrintableChar();isPrintableChar(b);b = readByte()) ret.appendCodePoint(b); return ret.toString(); } } static class InteractiveScanner extends AbstractScanner{ Scanner org = new Scanner(System.in); @Override long lg(){ return org.nextLong(); } @Override String str(){ return org.next(); } } } import java.io.IOException; import java.io.PrintWriter; import java.lang.management.ManagementFactory; import java.util.Scanner; import java.util.function.IntFunction; import java.util.stream.IntStream; class Main{ long st = ManagementFactory.getRuntimeMXBean().getStartTime(); boolean isDebug = ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("-agentlib:jdwp"); AbstractScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); public static void main(final String[] args){ new Main().exe(); } void exe(){ input(); preCalc(); solve(); pw.flush(); } int N = sc.it(); int[] A = sc.it(4 *N -1); void input(){} void preCalc(){} void solve(){ long ret = 2L *N *(N +1); for (var a:A) ret -= a; out(ret); } /* Util */ int min(int a,int b){ return Math.min(a,b); } long min(long a,long b){ return Math.min(a,b); } double min(double a,double b){ return Math.min(a,b); } int max(int a,int b){ return Math.max(a,b); } long max(long a,long b){ return Math.max(a,b); } double max(double a,double b){ return Math.max(a,b); } /* 出力 */ void out(final Object ret){ pw.println(ret); } void out(final int[] ret){ final StringBuilder sb = new StringBuilder(); sb.append(ret[0]); for (int i = 1;i < ret.length;i++) sb.append(" " +ret[i]); pw.println(sb.toString()); } void debug(final boolean b){ if (b) info(null); } void info(final Object info){ if (isDebug) System.out.println(info); } /* 入力 */ static abstract class AbstractScanner{ abstract long lg(); long[] lg(final int N){ return IntStream.range(0,N).mapToLong(i -> lg()).toArray(); } long[][] lg(final int H,final int W){ return arr(new long[H][],i -> lg(W)); } double dbl(){ return Double.parseDouble(str()); } int it(){ return Math.toIntExact(lg()); } int[] it(final int N){ return IntStream.range(0,N).map(i -> it()).toArray(); } int[][] it(final int H,final int W){ return arr(new int[H][],i -> it(W)); } int idx(){ return it() -1; } int[] idx(final int N){ return IntStream.range(0,N).map(i -> idx()).toArray(); } int[][] idx(final int H,final int W){ return arr(new int[H][],i -> idx(W)); } abstract String str(); char[] ch(){ return str().toCharArray(); } char[][] ch(final int H){ return arr(new char[H][],i -> ch()); } <T> T[] arr(final T[] arr,final IntFunction<T> func){ return IntStream.range(0,arr.length).mapToObj(func).toArray(t -> arr); } } static class FastScanner extends AbstractScanner{ int buflen = 1024; byte[] buf = new byte[buflen]; int ptr = buflen -1; int readByte(){ final int ret = buf[ptr++]; ptr %= buflen; if (ptr == 0) try { System.in.read(buf); } catch (final IOException e) { e.printStackTrace(); } return ret; } boolean isPrintableChar(final int c){ return 32 < c && c < 127; } boolean isNumeric(final int c){ return 47 < c && c < 58; } int nextPrintableChar(){ int ret = readByte(); while (!isPrintableChar(ret)) ret = readByte(); return ret; } @Override long lg(){ final int s = nextPrintableChar(); final boolean negative = s == 45; long ret = 0; for (int b = negative ? readByte() : s;isPrintableChar(b);b = readByte()) if (isNumeric(b)) ret = ret *10 +b -48; else throw new NumberFormatException(); return negative ? -ret : ret; } @Override String str(){ final StringBuilder ret = new StringBuilder(); for (int b = nextPrintableChar();isPrintableChar(b);b = readByte()) ret.appendCodePoint(b); return ret.toString(); } } static class InteractiveScanner extends AbstractScanner{ Scanner org = new Scanner(System.in); @Override long lg(){ return org.nextLong(); } @Override String str(){ return org.next(); } } }
ConDefects/ConDefects/Code/abc236_b/Java/34641363
condefects-java_data_421
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); long M = sc.nextLong(); long[] A = new long[N+1]; for(int i=1;i<=N;i++) { A[i]=sc.nextLong(); } A[0]=-1; Arrays.sort(A); int r=1; long ans = 0; for(int l=1;l<=N;l++) { while(r<N && A[l] <= A[r] && A[r] < A[l]+M ) { r++; } ans=Math.max(ans, r-l); } System.out.println(ans); } } import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); long M = sc.nextLong(); long[] A = new long[N+1]; for(int i=1;i<=N;i++) { A[i]=sc.nextLong(); } A[0]=-1; Arrays.sort(A); int r=1; long ans = 0; for(int l=1;l<=N;l++) { while(r<=N && A[r] < A[l]+M ) { r++; } ans=Math.max(ans, r-l); } System.out.println(ans); } }
ConDefects/ConDefects/Code/abc326_c/Java/54734632
condefects-java_data_422
import java.util.Scanner; import java.util.Arrays; import java.util.TreeSet; import java.util.HashMap; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); int[] A = new int[N]; TreeSet<Integer> hoge = new TreeSet<>(); for(int i=0; i<N; i++){ int a = sc.nextInt(); A[i] = a; hoge.add(a); } Arrays.sort(A); HashMap<Integer, Integer> present = new HashMap<>(); int count = 1; int tmp = A[0]; present.put(A[0], count); for(int i=1; i<N; i++){ if(tmp==A[i]){ count++; present.put(A[i], count); tmp = A[i]; }else{ count = 1; present.put(A[i], count); tmp = A[i]; } } Integer[] check = hoge.toArray(new Integer[0]); int l = 0; int r = 1; int sum = present.get(check[l]); int max = 0; //lを固定し、そこからM個の範囲内でとれるだけプレゼントを取得 → lを1増やす(rはできる限り増やす) ...のループ while(l<check.length-1){ while(r<check.length && check[r]-check[l]<=M-1){ sum += present.get(check[r]); r++; } //System.out.println(check[l]+" から "+check[r-1]+" のプレゼント合計は "+sum); max = Math.max(sum, max); sum -= present.get(check[l]); l++; } System.out.println(max); } } import java.util.Scanner; import java.util.Arrays; import java.util.TreeSet; import java.util.HashMap; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); int[] A = new int[N]; TreeSet<Integer> hoge = new TreeSet<>(); for(int i=0; i<N; i++){ int a = sc.nextInt(); A[i] = a; hoge.add(a); } Arrays.sort(A); HashMap<Integer, Integer> present = new HashMap<>(); int count = 1; int tmp = A[0]; present.put(A[0], count); for(int i=1; i<N; i++){ if(tmp==A[i]){ count++; present.put(A[i], count); tmp = A[i]; }else{ count = 1; present.put(A[i], count); tmp = A[i]; } } Integer[] check = hoge.toArray(new Integer[0]); int l = 0; int r = 1; int sum = present.get(check[l]); int max = 0; //lを固定し、そこからM個の範囲内でとれるだけプレゼントを取得 → lを1増やす(rはできる限り増やす) ...のループ while(l<check.length){ while(r<check.length && check[r]-check[l]<=M-1){ sum += present.get(check[r]); r++; } //System.out.println(check[l]+" から "+check[r-1]+" のプレゼント合計は "+sum); max = Math.max(sum, max); sum -= present.get(check[l]); l++; } System.out.println(max); } }
ConDefects/ConDefects/Code/abc326_c/Java/54996505
condefects-java_data_423
import java.io.BufferedReader; import java.io.InputStreamReader; /* --- ABC337E --- */ public class Main { static int[] pow2 = {1, 2, 4, 8, 16, 32, 64, 128}; static int[][] drink = { {0}, {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100}, {0, 3, 4, 7, 8, 11, 12, 15, 16, 19, 20, 23, 24, 27, 28, 31, 32, 35, 36, 39, 40, 43, 44, 47, 48, 51, 52, 55, 56, 59, 60, 63, 64, 67, 68, 71, 72, 75, 76, 79, 80, 83, 84, 87, 88, 91, 92, 95, 96, 99, 100}, {0, 5, 6, 7, 8, 13, 14, 15, 16, 21, 22, 23, 24, 29, 30, 31, 32, 37, 38, 39, 40, 45, 46, 47, 48, 53, 54, 55, 56, 61, 62, 63, 64, 69, 70, 71, 72, 77, 78, 79, 80, 85, 86, 87, 88, 93, 94, 95, 96}, {0, 9, 10, 11, 12, 13, 14, 15, 16, 25, 26, 27, 28, 29, 30, 31, 32, 41, 42, 43, 44, 45, 46, 47, 48, 57, 58, 59, 60, 61, 62, 63, 64, 73, 74, 75, 76, 77, 78, 79, 80, 89, 90, 91, 92, 93, 94, 95, 96}, {0, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96}, {0, 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, 97, 98, 99, 100}, {0, 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} }; static String[] onaka = {"xxxxxxx", "0000000", "1000000", "0100000", "1100000", "0010000", "1010000", "0110000", "1110000", "0001000", "1001000", "0101000", "1101000", "0011000", "1011000", "0111000", "1111000", "0000100", "1000100", "0100100", "1100100", "0010100", "1010100", "0110100", "1110100", "0001100", "1001100", "0101100", "1101100", "0011100", "1011100", "0111100", "1111100", "0000010", "1000010", "0100010", "1100010", "0010010", "1010010", "0110010", "1110010", "0001010", "1001010", "0101010", "1101010", "0011010", "1011010", "0111010", "1111010", "0000110", "1000110", "0100110", "1100110", "0010110", "1010110", "0110110", "1110110", "0001110", "1001110", "0101110", "1101110", "0011110", "1011110", "0111110", "1111110", "0000001", "1000001", "0100001", "1100001", "0010001", "1010001", "0110001", "1110001", "0001001", "1001001", "0101001", "1101001", "0011001", "1011001", "0111001", "1111001", "0000101", "1000101", "0100101", "1100101", "0010101", "1010101", "0110101", "1110101", "0001101", "1001101", "0101101", "1101101", "0011101", "1011101", "0111101", "1111101", "0000011", "1000011", "0100011", "1100011", "0010011"}; public static void main(String[] args) throws Exception { /* --- Input --- */ var br = new BufferedReader(new InputStreamReader(System.in)); var N = Integer.parseInt(br.readLine()); /* --- Process --- */ var M = 0; for (int i = 1; i < pow2.length; i++) { if (N <= pow2[i]) { M = i; break; } } System.out.println(M); System.out.flush(); for (int i = 1; i <= M; i++) { var K = 0; var A = new StringBuilder(); for (var j = 1; j < drink[i].length; j++) { if (drink[i][j] > N) break; A.append(drink[i][j]); K = j; } System.out.print(K + " "); System.out.println(A); System.out.flush(); } var S = br.readLine(); br.close(); var X = 0; for(var i=1; i<onaka.length; i++){ if(S.equals(onaka[i].substring(0, M))){ X = i; break; } } System.out.println(X); System.out.flush(); } } import java.io.BufferedReader; import java.io.InputStreamReader; /* --- ABC337E --- */ public class Main { static int[] pow2 = {1, 2, 4, 8, 16, 32, 64, 128}; static int[][] drink = { {0}, {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100}, {0, 3, 4, 7, 8, 11, 12, 15, 16, 19, 20, 23, 24, 27, 28, 31, 32, 35, 36, 39, 40, 43, 44, 47, 48, 51, 52, 55, 56, 59, 60, 63, 64, 67, 68, 71, 72, 75, 76, 79, 80, 83, 84, 87, 88, 91, 92, 95, 96, 99, 100}, {0, 5, 6, 7, 8, 13, 14, 15, 16, 21, 22, 23, 24, 29, 30, 31, 32, 37, 38, 39, 40, 45, 46, 47, 48, 53, 54, 55, 56, 61, 62, 63, 64, 69, 70, 71, 72, 77, 78, 79, 80, 85, 86, 87, 88, 93, 94, 95, 96}, {0, 9, 10, 11, 12, 13, 14, 15, 16, 25, 26, 27, 28, 29, 30, 31, 32, 41, 42, 43, 44, 45, 46, 47, 48, 57, 58, 59, 60, 61, 62, 63, 64, 73, 74, 75, 76, 77, 78, 79, 80, 89, 90, 91, 92, 93, 94, 95, 96}, {0, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96}, {0, 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, 97, 98, 99, 100}, {0, 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} }; static String[] onaka = {"xxxxxxx", "0000000", "1000000", "0100000", "1100000", "0010000", "1010000", "0110000", "1110000", "0001000", "1001000", "0101000", "1101000", "0011000", "1011000", "0111000", "1111000", "0000100", "1000100", "0100100", "1100100", "0010100", "1010100", "0110100", "1110100", "0001100", "1001100", "0101100", "1101100", "0011100", "1011100", "0111100", "1111100", "0000010", "1000010", "0100010", "1100010", "0010010", "1010010", "0110010", "1110010", "0001010", "1001010", "0101010", "1101010", "0011010", "1011010", "0111010", "1111010", "0000110", "1000110", "0100110", "1100110", "0010110", "1010110", "0110110", "1110110", "0001110", "1001110", "0101110", "1101110", "0011110", "1011110", "0111110", "1111110", "0000001", "1000001", "0100001", "1100001", "0010001", "1010001", "0110001", "1110001", "0001001", "1001001", "0101001", "1101001", "0011001", "1011001", "0111001", "1111001", "0000101", "1000101", "0100101", "1100101", "0010101", "1010101", "0110101", "1110101", "0001101", "1001101", "0101101", "1101101", "0011101", "1011101", "0111101", "1111101", "0000011", "1000011", "0100011", "1100011", "0010011"}; public static void main(String[] args) throws Exception { /* --- Input --- */ var br = new BufferedReader(new InputStreamReader(System.in)); var N = Integer.parseInt(br.readLine()); /* --- Process --- */ var M = 0; for (int i = 1; i < pow2.length; i++) { if (N <= pow2[i]) { M = i; break; } } System.out.println(M); System.out.flush(); for (int i = 1; i <= M; i++) { var K = 0; var A = new StringBuilder(); for (var j = 1; j < drink[i].length; j++) { if (drink[i][j] > N) break; A.append(drink[i][j]).append(" "); K = j; } System.out.print(K + " "); System.out.println(A); System.out.flush(); } var S = br.readLine(); br.close(); var X = 0; for(var i=1; i<onaka.length; i++){ if(S.equals(onaka[i].substring(0, M))){ X = i; break; } } System.out.println(X); System.out.flush(); } }
ConDefects/ConDefects/Code/abc337_e/Java/49518965
condefects-java_data_424
//package atcoder.abc337; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ //static int[] ps; static List<List<Integer>> p; static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { int n = in.nextInt(); p = new ArrayList<>(); for (int i = 0; i < (int)(Math.ceil(Math.log(n)) / Math.log(2)); i++) { List<Integer> l = new ArrayList<>(); for (int x = 1; x <= n; x++) { if((x & (1 << i)) != 0) { l.add(x); } } p.add(l); } out.println(p.size()); out.flush(); for (List<Integer> l : p) { out.print(l.size() + " "); for (int x : l) { out.print(x + " "); } out.println(); out.flush(); } char[] s = in.next().toCharArray(); int ans = 0; for(int i = s.length - 1; i >= 0; i--) { ans = ans * 2 + (s[i] - '0'); } if(ans == 0) { ans = n; } out.println(ans); out.flush(); return; } out.close(); } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { x %= mod; y %= mod; return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("input.in")); out = new PrintWriter(new FileOutputStream("output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } } //package atcoder.abc337; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ //static int[] ps; static List<List<Integer>> p; static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { int n = in.nextInt(); p = new ArrayList<>(); for (int i = 0; i < (int)(Math.ceil(Math.log(n) / Math.log(2))); i++) { List<Integer> l = new ArrayList<>(); for (int x = 1; x <= n; x++) { if((x & (1 << i)) != 0) { l.add(x); } } p.add(l); } out.println(p.size()); out.flush(); for (List<Integer> l : p) { out.print(l.size() + " "); for (int x : l) { out.print(x + " "); } out.println(); out.flush(); } char[] s = in.next().toCharArray(); int ans = 0; for(int i = s.length - 1; i >= 0; i--) { ans = ans * 2 + (s[i] - '0'); } if(ans == 0) { ans = n; } out.println(ans); out.flush(); return; } out.close(); } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { x %= mod; y %= mod; return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("input.in")); out = new PrintWriter(new FileOutputStream("output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } }
ConDefects/ConDefects/Code/abc337_e/Java/49565326
condefects-java_data_425
import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f, mod = 1000000007, mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = false; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static void solve(PrintWriter o) { try { int n = fReader.nextInt(); int m = 0; while((1<<m) < n) m++; o.println(m); o.flush(); for(int i=0;i<m;i++) { List<Integer> li = new ArrayList<>(); for(int j=0;j<n;j++) if((j>>i&1) == 1) li.add(j+1); o.print(li.size()); for(int num: li) o.print(" " + num); o.println(); o.flush(); } String s = fReader.nextString(); int res = 0; for(int i=0;i<m;i++) if(s.charAt(i) == '1') res |= 1<<i; o.println(res); o.flush(); } catch (Exception e) { e.printStackTrace(); } } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } public static long lcm(long a, long b){ return a / gcd(a,b)*b; } public static long qpow(long a, long n, int md){ a %= md; long ret = 1l; while(n > 0){ if((n & 1) == 1){ ret = ret * a % md; } n >>= 1; a = a * a % md; } return ret; } public static class FenWick { int n; long[] a; long[] tree; public FenWick(int n){ this.n = n; a = new long[n+1]; tree = new long[n+1]; } private void add(int x, long val){ while(x <= n){ tree[x] += val; x += x&-x; } } private void addMx(int x, long val) { a[x] += val; tree[x] = a[x]; while(x <= n) { for(int i=1;i<(x&-x);i<<=1) { tree[x] = Math.max(tree[x], tree[x-i]); } x += x&-x; } } private long query(int x){ long ret = 0l; while(x > 0){ ret += tree[x]; x -= x&-x; } return ret; } private long queryMx(int l, int r) { long res = 0l; while(l <= r) { if(r-(r&-r) >= l) { res = Math.max(res, tree[r]); r -= r&-r; } else { res = Math.max(res, a[r]); r--; } } return res; } } public static class Pair{ Integer c1; String str; public Pair(Integer c1, String str) { this.c1 = c1; this.str = str; } @Override public int hashCode() { int prime = 31, ret = 1; ret = ret*prime + c1.hashCode(); return ret; } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { return c1.equals(((Pair) obj).c1); } return false; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } } import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f, mod = 1000000007, mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = false; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static void solve(PrintWriter o) { try { int n = fReader.nextInt(); int m = 0; while((1<<m) < n) m++; o.println(m); o.flush(); for(int i=0;i<m;i++) { List<Integer> li = new ArrayList<>(); for(int j=0;j<n;j++) if((j>>i&1) == 1) li.add(j+1); o.print(li.size()); for(int num: li) o.print(" " + num); o.println(); o.flush(); } String s = fReader.nextString(); int res = 0; for(int i=0;i<m;i++) if(s.charAt(i) == '1') res |= 1<<i; o.println(res+1); o.flush(); } catch (Exception e) { e.printStackTrace(); } } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } public static long lcm(long a, long b){ return a / gcd(a,b)*b; } public static long qpow(long a, long n, int md){ a %= md; long ret = 1l; while(n > 0){ if((n & 1) == 1){ ret = ret * a % md; } n >>= 1; a = a * a % md; } return ret; } public static class FenWick { int n; long[] a; long[] tree; public FenWick(int n){ this.n = n; a = new long[n+1]; tree = new long[n+1]; } private void add(int x, long val){ while(x <= n){ tree[x] += val; x += x&-x; } } private void addMx(int x, long val) { a[x] += val; tree[x] = a[x]; while(x <= n) { for(int i=1;i<(x&-x);i<<=1) { tree[x] = Math.max(tree[x], tree[x-i]); } x += x&-x; } } private long query(int x){ long ret = 0l; while(x > 0){ ret += tree[x]; x -= x&-x; } return ret; } private long queryMx(int l, int r) { long res = 0l; while(l <= r) { if(r-(r&-r) >= l) { res = Math.max(res, tree[r]); r -= r&-r; } else { res = Math.max(res, a[r]); r--; } } return res; } } public static class Pair{ Integer c1; String str; public Pair(Integer c1, String str) { this.c1 = c1; this.str = str; } @Override public int hashCode() { int prime = 31, ret = 1; ret = ret*prime + c1.hashCode(); return ret; } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { return c1.equals(((Pair) obj).c1); } return false; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } }
ConDefects/ConDefects/Code/abc337_e/Java/49568719
condefects-java_data_426
import java.io.*; import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); int n = sc.nextInt(); int size = 0; while ((1 << size) < n) { size++; } ArrayList<ArrayList<Integer>> list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(new ArrayList<>()); } for (int i = 1; i < (1 << size) && i <= n; i++) { for (int j = 0; j < size; j++) { if ((i & (1 << j)) > 0) { list.get(j).add(i); } } } StringBuilder sb = new StringBuilder(); sb.append(size).append("\n"); for (ArrayList<Integer> each : list) { sb.append(each.size()); for (int x : each) { sb.append(" ").append(x); } sb.append("\n"); } System.out.print(sb); System.out.flush(); char[] inputs = sc.next().toCharArray(); int ans = 0; for (int i = 0; i < size; i++) { if (inputs[size - i - 1] == '1') { ans += (1 << i); } } if (ans == 0) { ans = n; } System.out.println(ans); } } class Utilities { static String arrayToLineString(Object[] arr) { return Arrays.stream(arr).map(x -> x.toString()).collect(Collectors.joining("\n")); } static String arrayToLineString(int[] arr) { return String.join("\n", Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new)); } } class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); StringBuilder sb = new StringBuilder(); public Scanner() throws Exception { } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public int[] nextIntArray() throws Exception { return Stream.of(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } public String next() throws Exception { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } } import java.io.*; import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); int n = sc.nextInt(); int size = 0; while ((1 << size) < n) { size++; } ArrayList<ArrayList<Integer>> list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(new ArrayList<>()); } for (int i = 1; i < (1 << size) && i <= n; i++) { for (int j = 0; j < size; j++) { if ((i & (1 << j)) > 0) { list.get(j).add(i); } } } StringBuilder sb = new StringBuilder(); sb.append(size).append("\n"); for (ArrayList<Integer> each : list) { sb.append(each.size()); for (int x : each) { sb.append(" ").append(x); } sb.append("\n"); } System.out.print(sb); System.out.flush(); char[] inputs = sc.next().toCharArray(); int ans = 0; for (int i = 0; i < size; i++) { if (inputs[i] == '1') { ans += (1 << i); } } if (ans == 0) { ans = n; } System.out.println(ans); } } class Utilities { static String arrayToLineString(Object[] arr) { return Arrays.stream(arr).map(x -> x.toString()).collect(Collectors.joining("\n")); } static String arrayToLineString(int[] arr) { return String.join("\n", Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new)); } } class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); StringBuilder sb = new StringBuilder(); public Scanner() throws Exception { } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public int[] nextIntArray() throws Exception { return Stream.of(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } public String next() throws Exception { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }
ConDefects/ConDefects/Code/abc337_e/Java/49567026
condefects-java_data_427
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { try(Scanner sc = new Scanner(System.in);) { int n = Integer.parseInt(sc.next()); int m = 0; int v = 1; while(v < n) { m++; v *= 2; } List<List<Integer>> drink = new ArrayList<List<Integer>>(); for(int i = 0; i < m; i++) drink.add(new ArrayList<Integer>()); for(int i = 1; i <= n; i++) { for(int j = 0; j < m; j++) { if((i & 1 << j) == 0) continue; drink.get(j).add(i); } } StringBuilder sb = new StringBuilder(); System.out.println(m); for(int i = 0; i < m; i++) { sb.append(drink.get(i).size()); for(int d : drink.get(i)) { sb.append(" ").append(d); } sb.append("\n"); } System.out.print(sb.toString()); sb.setLength(0); String s = sc.next(); s = sb.append(s).reverse().toString(); int doku = Integer.parseInt(s, 2); if(doku == 0) doku = 8; System.out.println(doku); } } } import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { try(Scanner sc = new Scanner(System.in);) { int n = Integer.parseInt(sc.next()); int m = 0; int v = 1; while(v < n) { m++; v *= 2; } List<List<Integer>> drink = new ArrayList<List<Integer>>(); for(int i = 0; i < m; i++) drink.add(new ArrayList<Integer>()); for(int i = 1; i <= n; i++) { for(int j = 0; j < m; j++) { if((i & 1 << j) == 0) continue; drink.get(j).add(i); } } StringBuilder sb = new StringBuilder(); System.out.println(m); for(int i = 0; i < m; i++) { sb.append(drink.get(i).size()); for(int d : drink.get(i)) { sb.append(" ").append(d); } sb.append("\n"); } System.out.print(sb.toString()); sb.setLength(0); String s = sc.next(); s = sb.append(s).reverse().toString(); int doku = Integer.parseInt(s, 2); if(doku == 0) doku = n; System.out.println(doku); } } }
ConDefects/ConDefects/Code/abc337_e/Java/49682966
condefects-java_data_428
import java.util.*; class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); if(n>=5){ System.out.println("Yes"); }else{ System.out.println("No"); } } } import java.util.*; class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); if(n>4||n<2){ System.out.println("Yes"); }else{ System.out.println("No"); } } }
ConDefects/ConDefects/Code/abc238_a/Java/32621700
condefects-java_data_429
import java.util.*; public class Main { public static void main(String args[]) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); if(n>4) { System.out.println("Yes"); } else { System.out.println("No"); } } } import java.util.*; public class Main { public static void main(String args[]) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); if(n>4||n<2) { System.out.println("Yes"); } else { System.out.println("No"); } } }
ConDefects/ConDefects/Code/abc238_a/Java/38942864
condefects-java_data_430
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.Buffer; /* * Solution: 1m * Coding: 4m * Time: 5m * */ public class Main { public static void main(String[] args) throws IOException { //BufferedReader br = new BufferedReader(new FileReader("atcoder_abc/input.in")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); if(n < 5){ System.out.println("No"); } else { System.out.println("Yes"); } br.close(); } } import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.Buffer; /* * Solution: 1m * Coding: 4m * Time: 5m * */ public class Main { public static void main(String[] args) throws IOException { //BufferedReader br = new BufferedReader(new FileReader("atcoder_abc/input.in")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); if(n > 1 && n < 5){ System.out.println("No"); } else { System.out.println("Yes"); } br.close(); } }
ConDefects/ConDefects/Code/abc238_a/Java/40552182
condefects-java_data_431
import java.util.Scanner; public class Main { public static void main(String[] args) { @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println(n > 4 ? "Yes" : "No"); } } import java.util.Scanner; public class Main { public static void main(String[] args) { @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println(n > 4 || n == 1 ? "Yes" : "No"); } }
ConDefects/ConDefects/Code/abc238_a/Java/31751326
condefects-java_data_432
import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if(n<=4){ System.out.println("No"); } else{ System.out.println("Yes"); } } } import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if(n<=4 && n!=1){ System.out.println("No"); } else{ System.out.println("Yes"); } } }
ConDefects/ConDefects/Code/abc238_a/Java/38759774
condefects-java_data_433
import java.io.IOException; import java.io.PrintWriter; import java.lang.management.ManagementFactory; import java.util.NoSuchElementException; import java.util.function.IntFunction; import java.util.stream.IntStream; public class Main{ long st = ManagementFactory.getRuntimeMXBean().getStartTime(); boolean isDebug = ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0; FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args){ new Main().exe(); } void exe(){ input(); preCalc(); solve(); pw.flush(); info(System.currentTimeMillis() -st); } int N = sc.it(); void input(){} void preCalc(){} void solve(){ out(N < 3 || N==1 ? "No" : "Yes"); } /* 出力 */ void out(Object ret){ pw.println(ret); } void out(int[] ret){ StringBuilder sb = new StringBuilder(); sb.append(ret[0]); for (int i = 1;i < ret.length;i++) sb.append(" " +ret[i]); pw.println(sb.toString()); } void debug(boolean info){ if (isDebug && info) System.out.println(); } void info(Object info){ if (isDebug) System.out.println(info); } /* 入力 */ static class FastScanner{ byte[] buf = new byte[1024]; int ptr = 0; int buflen = 0; boolean hasNextByte(){ if (ptr >= buflen) { ptr = 0; try { buflen = System.in.read(buf); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) return false; } return true; } int readByte(){ if (hasNextByte()) return buf[ptr++]; else return -1; } boolean isPrintableChar(int c){ return 33 <= c && c <= 126; } boolean isNumeric(int c){ return '0' <= c && c <= '9'; } void skipToNextPrintableChar(){ while (hasNextByte() && !isPrintableChar(buf[ptr])) ptr++; } boolean hasNext(){ skipToNextPrintableChar(); return hasNextByte(); } long lg(){ if (!hasNext()) throw new NoSuchElementException(); long ret = 0; int b = readByte(); boolean negative = false; if (b == '-') { negative = true; if (hasNextByte()) b = readByte(); } if (!isNumeric(b)) throw new NumberFormatException(); while (true) { if (isNumeric(b)) ret = ret *10 +b -'0'; else if (b == -1 || !isPrintableChar(b)) return negative ? -ret : ret; else throw new NumberFormatException(); b = readByte(); } } long[] lg(int N){ return IntStream.range(0,N).mapToLong(i -> lg()).toArray(); } long[][] lg(int H,int W){ return arr(new long[H][],i -> lg(W)); } double dbl(){ return Double.parseDouble(str()); } int it(){ return Math.toIntExact(lg()); } int[] it(int N){ return IntStream.range(0,N).map(i -> it()).toArray(); } int[][] it(int H,int W){ return arr(new int[H][],i -> it(W)); } int idx(){ return it() -1; } int[] idx(int N){ return IntStream.range(0,N).map(i -> idx()).toArray(); } String str(){ if (!hasNext()) throw new NoSuchElementException(); StringBuilder ret = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { ret.appendCodePoint(b); b = readByte(); } return ret.toString(); } char[] ch(){ return str().toCharArray(); } char[][] ch(int H){ return arr(new char[H][],i -> ch()); } <T> T[] arr(T[] arr,IntFunction<T> func){ return IntStream.range(0,arr.length).mapToObj(func).toArray(t -> arr); } } } import java.io.IOException; import java.io.PrintWriter; import java.lang.management.ManagementFactory; import java.util.NoSuchElementException; import java.util.function.IntFunction; import java.util.stream.IntStream; public class Main{ long st = ManagementFactory.getRuntimeMXBean().getStartTime(); boolean isDebug = ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0; FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args){ new Main().exe(); } void exe(){ input(); preCalc(); solve(); pw.flush(); info(System.currentTimeMillis() -st); } int N = sc.it(); void input(){} void preCalc(){} void solve(){ out(1<N &&N < 5 ? "No" : "Yes"); } /* 出力 */ void out(Object ret){ pw.println(ret); } void out(int[] ret){ StringBuilder sb = new StringBuilder(); sb.append(ret[0]); for (int i = 1;i < ret.length;i++) sb.append(" " +ret[i]); pw.println(sb.toString()); } void debug(boolean info){ if (isDebug && info) System.out.println(); } void info(Object info){ if (isDebug) System.out.println(info); } /* 入力 */ static class FastScanner{ byte[] buf = new byte[1024]; int ptr = 0; int buflen = 0; boolean hasNextByte(){ if (ptr >= buflen) { ptr = 0; try { buflen = System.in.read(buf); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) return false; } return true; } int readByte(){ if (hasNextByte()) return buf[ptr++]; else return -1; } boolean isPrintableChar(int c){ return 33 <= c && c <= 126; } boolean isNumeric(int c){ return '0' <= c && c <= '9'; } void skipToNextPrintableChar(){ while (hasNextByte() && !isPrintableChar(buf[ptr])) ptr++; } boolean hasNext(){ skipToNextPrintableChar(); return hasNextByte(); } long lg(){ if (!hasNext()) throw new NoSuchElementException(); long ret = 0; int b = readByte(); boolean negative = false; if (b == '-') { negative = true; if (hasNextByte()) b = readByte(); } if (!isNumeric(b)) throw new NumberFormatException(); while (true) { if (isNumeric(b)) ret = ret *10 +b -'0'; else if (b == -1 || !isPrintableChar(b)) return negative ? -ret : ret; else throw new NumberFormatException(); b = readByte(); } } long[] lg(int N){ return IntStream.range(0,N).mapToLong(i -> lg()).toArray(); } long[][] lg(int H,int W){ return arr(new long[H][],i -> lg(W)); } double dbl(){ return Double.parseDouble(str()); } int it(){ return Math.toIntExact(lg()); } int[] it(int N){ return IntStream.range(0,N).map(i -> it()).toArray(); } int[][] it(int H,int W){ return arr(new int[H][],i -> it(W)); } int idx(){ return it() -1; } int[] idx(int N){ return IntStream.range(0,N).map(i -> idx()).toArray(); } String str(){ if (!hasNext()) throw new NoSuchElementException(); StringBuilder ret = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { ret.appendCodePoint(b); b = readByte(); } return ret.toString(); } char[] ch(){ return str().toCharArray(); } char[][] ch(int H){ return arr(new char[H][],i -> ch()); } <T> T[] arr(T[] arr,IntFunction<T> func){ return IntStream.range(0,arr.length).mapToObj(func).toArray(t -> arr); } } }
ConDefects/ConDefects/Code/abc238_a/Java/34319352
condefects-java_data_434
import java.util.*; import java.io.*; public class Main { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter out = new PrintWriter(System.out); //解答作成用 public static void solve() throws IOException{ // io long n = Long.parseLong(IO.input_string()); String result = "No"; if(2 * n < n * n){ result = "Yes"; } System.out.println(result); } public static void main(String[] args) throws IOException { solve(); out.flush(); } static class IO { public static char input_char() throws IOException { Scanner sc = new Scanner(System.in); return sc.next().charAt(0); } public static String input_string() throws IOException { return br.readLine(); } public static String[] input_n_array() throws IOException { return br.readLine().split(""); } public static String[] input_b_array() throws IOException { return br.readLine().split(" "); } public static String[] input_c_array() throws IOException { return br.readLine().split("\\."); } public static String[][] input_matrix(String[] str_array) throws IOException{ int len = Convert.str2int(str_array[0]); String[][] matrix = new String[len][]; for(int i=0;i<len;i++){ matrix[i]=input_b_array(); } return matrix; } public static void output_array(String[] str_array){ for(String str:str_array){ out.printf(str + " "); } out.println(); } public static void output_array(int[] int_array){ for(int i:int_array){ out.printf(i + " "); } out.println(); } } static class Convert { public static int str2int(String str){ return Integer.parseInt(str); } public static int[] str2int(String[] str_array){ return Arrays.stream(str_array).mapToInt(Integer::parseInt).toArray(); } } } import java.util.*; import java.io.*; public class Main { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter out = new PrintWriter(System.out); //解答作成用 public static void solve() throws IOException{ // io long n = Long.parseLong(IO.input_string()); String result = "No"; if((long)Math.pow(2,n) > n * n){ result = "Yes"; } System.out.println(result); } public static void main(String[] args) throws IOException { solve(); out.flush(); } static class IO { public static char input_char() throws IOException { Scanner sc = new Scanner(System.in); return sc.next().charAt(0); } public static String input_string() throws IOException { return br.readLine(); } public static String[] input_n_array() throws IOException { return br.readLine().split(""); } public static String[] input_b_array() throws IOException { return br.readLine().split(" "); } public static String[] input_c_array() throws IOException { return br.readLine().split("\\."); } public static String[][] input_matrix(String[] str_array) throws IOException{ int len = Convert.str2int(str_array[0]); String[][] matrix = new String[len][]; for(int i=0;i<len;i++){ matrix[i]=input_b_array(); } return matrix; } public static void output_array(String[] str_array){ for(String str:str_array){ out.printf(str + " "); } out.println(); } public static void output_array(int[] int_array){ for(int i:int_array){ out.printf(i + " "); } out.println(); } } static class Convert { public static int str2int(String str){ return Integer.parseInt(str); } public static int[] str2int(String[] str_array){ return Arrays.stream(str_array).mapToInt(Integer::parseInt).toArray(); } } }
ConDefects/ConDefects/Code/abc238_a/Java/36008869
condefects-java_data_435
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { Solver.SOLVE(); } } class UnionFind { private int[] roots; public UnionFind(int n){ roots = new int[n]; for (int i = 0; i < n; i++) { roots[i] = i; } } public int root(int x){ if(roots[x] == x){ return x; } return roots[x] = root(roots[x]); } public void unite(int x,int y){ int rx = root(x); int ry = root(y); if(rx == ry){ return; } roots[rx] = ry; } public boolean same(int x,int y){ int rx = root(x); int ry = root(y); return rx == ry; } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } ArrayList<ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } ArrayList<ArrayList<Integer>> result = new ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(ArrayList::isEmpty); return result; } } class PairL implements Comparable<PairL>, Comparator<PairL> { public long x,y; public PairL(long x,long y) { this.x = x; this.y = y; } public void swap(){ long t = x; x = y; y = t; } @Override public int compare(PairL o1, PairL o2) { return o1.compareTo(o2); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairL pairl = (PairL) o; return x == pairl.x && y == pairl.y; } @Override public int hashCode() { return Objects.hash(x, y); } public PairL add(PairL p){ return new PairL(x+p.x,y+p.y); } @Override public int compareTo(PairL o) { return Long.compare(x,o.x); } } class PairI implements Comparable<PairI>, Comparator<PairI> { public int x,y; public PairI(int x,int y) { this.x = x; this.y = y; } public void swap(){ int t = x; x = y; y = t; } @Override public int compare(PairI o1, PairI o2) { return o1.compareTo(o2); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairI pairI = (PairI) o; return x == pairI.x && y == pairI.y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public int compareTo(PairI o) { return Integer.compare(x,o.x); } public PairI add(PairI p){ return new PairI(x+p.x,y+p.y); } public PairI sub(PairI p){ return new PairI(x-p.x,y-p.y); } public PairI addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new PairI(x,y); } return null; } } class Dist extends PairI{ int d; public Dist(int x,int y,int d){ super(x,y); this.d = d; } public Dist addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new Dist(x,y,d+1); } return null; } } class Three implements Comparable<Three>{ public int x,y,z; public Three(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Three three = (Three) o; return x == three.x && y == three.y && z == three.z; } @Override public int hashCode() { return Objects.hash(x, y, z); } @Override public int compareTo(Three o) { return 0; } } class Node implements Comparable<Node>{ public int to; public long d; public Node(int to,int d){ this.to = to; this.d = d; } @Override public int compareTo(Node o) { return Long.compare(d,o.d); } } class PairC{ char a,b; public PairC(char a, char b){ this.a = a; this.b = b; } } class IB{ int i; boolean b; IB(int i,boolean b){ this.i = i; this.b = b; } } class CI{ char c; int i; CI(char c,int i){ this.c = c; this.i = i; } } class Pair<K,V>{ K k; V v; public Pair(K k,V v){ this.k = k; this.v = v; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(k, pair.k) && Objects.equals(v, pair.v); } @Override public int hashCode() { return Objects.hash(k, v); } } class Solver { public static final int MOD1 = 1000000007; public static final int MOD2 = 998244353; public static Scanner sc = new Scanner(System.in); public static final int inf = 2000000000; public static final int ninf = -inf; public static final char[] alpha = "abcdefghijklmnopqrstuvwxyz".toCharArray(); public static final char[] ALPHA = "abcdefghijklmnopqrstuvwxyz".toUpperCase().toCharArray(); public static FastScanner fs = new FastScanner(); public static PrintWriter out = new PrintWriter(System.out); public static final PairI[] move = new PairI[]{new PairI(1,0),new PairI(0,1),new PairI(-1,0),new PairI(0,-1)}; public static void solve(){ int n = rI(); if(n == 0){ oS("Yes"); return; } yes_no(n > 4); } public static int toIntC(char c){ for (int i = 0; i < ALPHA.length; i++) { if(c == ALPHA[i]){ return i+1; } } throw new IllegalArgumentException("not an alphabet"); } public static int toInt(char c){ for (int i = 0; i < alpha.length; i++) { if(c == alpha[i]){ return i+1; } } throw new IllegalArgumentException("not an alphabet"); } public static void reverse(int[] a){ int[] tmp = a.clone(); for (int i = 0; i < a.length; i++) { a[i] = tmp[a.length - 1 - i]; } } public static int ceilDiv(int a,int b){ if(a%b == 0){ return a/b; }else { return a/b + 1; } } public static int abs(int a){ return Math.abs(a); } public static long abs(long a){ return Math.abs(a); } public static int max(int a,int b){ return Math.max(a,b); } public static int max(int... a){ int max = ninf; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static long max(long a,long b){ return Math.max(a,b); } public static long max(long... a){ long max = Long.MAX_VALUE; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static int min(int a,int b){ return Math.min(a,b); } public static int min(int... a){ int min = inf; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static long min(long a,long b){ return Math.min(a, b); } public static long min(long... a){ long min = inf; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static final class MC { private final int mod; public MC(final int mod) { this.mod = mod; } public long mod(long x) { x %= mod; if (x < 0) { x += mod; } return x; } public long add(final long a, final long b) { return mod(a + b); } public long mul(final long a, final long b) { return mod(a * b); } public long div(final long numerator, final long denominator) { return mod(numerator * inverse(denominator)); } public long power(long base, long exp) { long ret = 1; base %= mod; while (exp > 0) { if ((exp & 1) == 1) { ret = mul(ret, base); } base = mul(base, base); exp >>= 1; } return ret; } public long inverse(final long x) { return power(x, mod - 2); } public long factorial(final int n) { return product(1, n); } public long product(final int start, final int end) { long result = 1; for (int i = start; i <= end; i++) { result *= i; result %= mod; } return result; } public long combination(final int n, int r) { if (r > n) { return 0; } return div(product(n - r + 1, n), factorial(r)); } } public static long pow(long x,long n){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; } tmp *=tmp; n = n >> 1; } return ans; } public static long modPow(long x,long n,long m){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; ans%=m; } tmp *=tmp; tmp%=m; n = n >> 1; } return ans; } public static int gcd(int a,int b){ if(b == 0) return a; else return gcd(b,a%b); } public static long gcd(long a,long b){ if(b == 0) return a; else return gcd(b,a%b); } public static int gcd(int... a){ int ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long gcd(long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long lcm(int a,int b){ return (long) a / gcd(a, b) * b; } public static long lcm(long a,long b){ return a / gcd(a,b) * b; } public static boolean isPrime(long x){ if(x < 2) return false; else if(x == 2) return true; if(x%2 == 0) return false; for(long i = 3; i*i <= x; i+= 2){ if(x%i == 0) return false; } return true; } public static int rI() { return fs.nextInt(); } public static int[] rIv(int length) { int[] res = new int[length]; for (int i = 0; i < length; i++) { res[i] = fs.nextInt(); } return res; } public static String rS() { return fs.next(); } public static String[] rSv(int length) { String[] res = new String[length]; for (int i = 0; i < length; i++) res[i] = fs.next(); return res; } public static long rL() { return fs.nextLong(); } public static long[] rLv(int length) { long[] res = new long[length]; for (int i = 0; i < length; i++) res[i] = fs.nextLong(); return res; } public static double rD(){ return fs.nextDouble(); } public static double[] rDv(int length){ double[] res = new double[length]; for (int i = 0; i < length; i++) res[i] = rD(); return res; } public static void oI(int a) { out.println(a); } public static void oIv(int[] a) { for (int i = 0; i < a.length; i++) oI(a[i]); } public static void oS(String s) { out.println(s); } public static void oSv(String[] a) { for (int i = 0; i < a.length; i++) { oS(a[i]); } } public static void oL(long l) { out.println(l); } public static void oLv(long[] a) { for (int i = 0; i < a.length; i++) oL(a[i]); } public static void oD(double d){ out.println(d); } public static void oDv(double[] d){ for(double i:d)oD(i); } public static void yes_no(boolean yes){ if(yes){ oS("Yes"); return; } oS("No"); } public static int fact(int num) { if (num == 0) { return 1; } else if (num == 1) { return 1; } else if (num < 0) { throw new IllegalArgumentException("factorial should be bigger than 0"); } return num * fact(num - 1); } public static int[] conVI(ArrayList<Integer> list) { int[] res = new int[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static String[] conVS(ArrayList<String> list) { String[] res = new String[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static ArrayList<Integer> conLI(int[] vec) { ArrayList<Integer> list = new ArrayList<>(); for (int i : vec) list.add(i); return list; } public static ArrayList<String> conLS(String[] vec) { return new ArrayList<>(Arrays.asList(vec)); } public static ArrayList<ArrayList<Integer>> permutation(int a) { int[] list = new int[a]; for (int i = 0; i < a; i++) { list[i] = i; } return permutation(list); } public static ArrayList<ArrayList<Integer>> permutation(int[] seed) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); int[] perm = new int[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(int[] seed, int[] perm, boolean[] used, int index,ArrayList<ArrayList<Integer>> res) { if (index == seed.length) { res.add(conLI(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static void swap(int[] a,int i1,int i2){ int t = a[i1]; a[i1] = a[i2]; a[i2] = a[t]; } public static void swap(char[] a,int i1,int i2){ char t = a[i1]; a[i1] = a[i2]; a[i2] = a[t]; } public static void SOLVE(){ solve(); out.flush(); } } class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next());} } import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { Solver.SOLVE(); } } class UnionFind { private int[] roots; public UnionFind(int n){ roots = new int[n]; for (int i = 0; i < n; i++) { roots[i] = i; } } public int root(int x){ if(roots[x] == x){ return x; } return roots[x] = root(roots[x]); } public void unite(int x,int y){ int rx = root(x); int ry = root(y); if(rx == ry){ return; } roots[rx] = ry; } public boolean same(int x,int y){ int rx = root(x); int ry = root(y); return rx == ry; } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } ArrayList<ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } ArrayList<ArrayList<Integer>> result = new ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(ArrayList::isEmpty); return result; } } class PairL implements Comparable<PairL>, Comparator<PairL> { public long x,y; public PairL(long x,long y) { this.x = x; this.y = y; } public void swap(){ long t = x; x = y; y = t; } @Override public int compare(PairL o1, PairL o2) { return o1.compareTo(o2); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairL pairl = (PairL) o; return x == pairl.x && y == pairl.y; } @Override public int hashCode() { return Objects.hash(x, y); } public PairL add(PairL p){ return new PairL(x+p.x,y+p.y); } @Override public int compareTo(PairL o) { return Long.compare(x,o.x); } } class PairI implements Comparable<PairI>, Comparator<PairI> { public int x,y; public PairI(int x,int y) { this.x = x; this.y = y; } public void swap(){ int t = x; x = y; y = t; } @Override public int compare(PairI o1, PairI o2) { return o1.compareTo(o2); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairI pairI = (PairI) o; return x == pairI.x && y == pairI.y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public int compareTo(PairI o) { return Integer.compare(x,o.x); } public PairI add(PairI p){ return new PairI(x+p.x,y+p.y); } public PairI sub(PairI p){ return new PairI(x-p.x,y-p.y); } public PairI addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new PairI(x,y); } return null; } } class Dist extends PairI{ int d; public Dist(int x,int y,int d){ super(x,y); this.d = d; } public Dist addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new Dist(x,y,d+1); } return null; } } class Three implements Comparable<Three>{ public int x,y,z; public Three(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Three three = (Three) o; return x == three.x && y == three.y && z == three.z; } @Override public int hashCode() { return Objects.hash(x, y, z); } @Override public int compareTo(Three o) { return 0; } } class Node implements Comparable<Node>{ public int to; public long d; public Node(int to,int d){ this.to = to; this.d = d; } @Override public int compareTo(Node o) { return Long.compare(d,o.d); } } class PairC{ char a,b; public PairC(char a, char b){ this.a = a; this.b = b; } } class IB{ int i; boolean b; IB(int i,boolean b){ this.i = i; this.b = b; } } class CI{ char c; int i; CI(char c,int i){ this.c = c; this.i = i; } } class Pair<K,V>{ K k; V v; public Pair(K k,V v){ this.k = k; this.v = v; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(k, pair.k) && Objects.equals(v, pair.v); } @Override public int hashCode() { return Objects.hash(k, v); } } class Solver { public static final int MOD1 = 1000000007; public static final int MOD2 = 998244353; public static Scanner sc = new Scanner(System.in); public static final int inf = 2000000000; public static final int ninf = -inf; public static final char[] alpha = "abcdefghijklmnopqrstuvwxyz".toCharArray(); public static final char[] ALPHA = "abcdefghijklmnopqrstuvwxyz".toUpperCase().toCharArray(); public static FastScanner fs = new FastScanner(); public static PrintWriter out = new PrintWriter(System.out); public static final PairI[] move = new PairI[]{new PairI(1,0),new PairI(0,1),new PairI(-1,0),new PairI(0,-1)}; public static void solve(){ int n = rI(); if(n == 1){ oS("Yes"); return; } yes_no(n > 4); } public static int toIntC(char c){ for (int i = 0; i < ALPHA.length; i++) { if(c == ALPHA[i]){ return i+1; } } throw new IllegalArgumentException("not an alphabet"); } public static int toInt(char c){ for (int i = 0; i < alpha.length; i++) { if(c == alpha[i]){ return i+1; } } throw new IllegalArgumentException("not an alphabet"); } public static void reverse(int[] a){ int[] tmp = a.clone(); for (int i = 0; i < a.length; i++) { a[i] = tmp[a.length - 1 - i]; } } public static int ceilDiv(int a,int b){ if(a%b == 0){ return a/b; }else { return a/b + 1; } } public static int abs(int a){ return Math.abs(a); } public static long abs(long a){ return Math.abs(a); } public static int max(int a,int b){ return Math.max(a,b); } public static int max(int... a){ int max = ninf; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static long max(long a,long b){ return Math.max(a,b); } public static long max(long... a){ long max = Long.MAX_VALUE; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static int min(int a,int b){ return Math.min(a,b); } public static int min(int... a){ int min = inf; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static long min(long a,long b){ return Math.min(a, b); } public static long min(long... a){ long min = inf; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static final class MC { private final int mod; public MC(final int mod) { this.mod = mod; } public long mod(long x) { x %= mod; if (x < 0) { x += mod; } return x; } public long add(final long a, final long b) { return mod(a + b); } public long mul(final long a, final long b) { return mod(a * b); } public long div(final long numerator, final long denominator) { return mod(numerator * inverse(denominator)); } public long power(long base, long exp) { long ret = 1; base %= mod; while (exp > 0) { if ((exp & 1) == 1) { ret = mul(ret, base); } base = mul(base, base); exp >>= 1; } return ret; } public long inverse(final long x) { return power(x, mod - 2); } public long factorial(final int n) { return product(1, n); } public long product(final int start, final int end) { long result = 1; for (int i = start; i <= end; i++) { result *= i; result %= mod; } return result; } public long combination(final int n, int r) { if (r > n) { return 0; } return div(product(n - r + 1, n), factorial(r)); } } public static long pow(long x,long n){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; } tmp *=tmp; n = n >> 1; } return ans; } public static long modPow(long x,long n,long m){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; ans%=m; } tmp *=tmp; tmp%=m; n = n >> 1; } return ans; } public static int gcd(int a,int b){ if(b == 0) return a; else return gcd(b,a%b); } public static long gcd(long a,long b){ if(b == 0) return a; else return gcd(b,a%b); } public static int gcd(int... a){ int ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long gcd(long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long lcm(int a,int b){ return (long) a / gcd(a, b) * b; } public static long lcm(long a,long b){ return a / gcd(a,b) * b; } public static boolean isPrime(long x){ if(x < 2) return false; else if(x == 2) return true; if(x%2 == 0) return false; for(long i = 3; i*i <= x; i+= 2){ if(x%i == 0) return false; } return true; } public static int rI() { return fs.nextInt(); } public static int[] rIv(int length) { int[] res = new int[length]; for (int i = 0; i < length; i++) { res[i] = fs.nextInt(); } return res; } public static String rS() { return fs.next(); } public static String[] rSv(int length) { String[] res = new String[length]; for (int i = 0; i < length; i++) res[i] = fs.next(); return res; } public static long rL() { return fs.nextLong(); } public static long[] rLv(int length) { long[] res = new long[length]; for (int i = 0; i < length; i++) res[i] = fs.nextLong(); return res; } public static double rD(){ return fs.nextDouble(); } public static double[] rDv(int length){ double[] res = new double[length]; for (int i = 0; i < length; i++) res[i] = rD(); return res; } public static void oI(int a) { out.println(a); } public static void oIv(int[] a) { for (int i = 0; i < a.length; i++) oI(a[i]); } public static void oS(String s) { out.println(s); } public static void oSv(String[] a) { for (int i = 0; i < a.length; i++) { oS(a[i]); } } public static void oL(long l) { out.println(l); } public static void oLv(long[] a) { for (int i = 0; i < a.length; i++) oL(a[i]); } public static void oD(double d){ out.println(d); } public static void oDv(double[] d){ for(double i:d)oD(i); } public static void yes_no(boolean yes){ if(yes){ oS("Yes"); return; } oS("No"); } public static int fact(int num) { if (num == 0) { return 1; } else if (num == 1) { return 1; } else if (num < 0) { throw new IllegalArgumentException("factorial should be bigger than 0"); } return num * fact(num - 1); } public static int[] conVI(ArrayList<Integer> list) { int[] res = new int[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static String[] conVS(ArrayList<String> list) { String[] res = new String[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static ArrayList<Integer> conLI(int[] vec) { ArrayList<Integer> list = new ArrayList<>(); for (int i : vec) list.add(i); return list; } public static ArrayList<String> conLS(String[] vec) { return new ArrayList<>(Arrays.asList(vec)); } public static ArrayList<ArrayList<Integer>> permutation(int a) { int[] list = new int[a]; for (int i = 0; i < a; i++) { list[i] = i; } return permutation(list); } public static ArrayList<ArrayList<Integer>> permutation(int[] seed) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); int[] perm = new int[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(int[] seed, int[] perm, boolean[] used, int index,ArrayList<ArrayList<Integer>> res) { if (index == seed.length) { res.add(conLI(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static void swap(int[] a,int i1,int i2){ int t = a[i1]; a[i1] = a[i2]; a[i2] = a[t]; } public static void swap(char[] a,int i1,int i2){ char t = a[i1]; a[i1] = a[i2]; a[i2] = a[t]; } public static void SOLVE(){ solve(); out.flush(); } } class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next());} }
ConDefects/ConDefects/Code/abc238_a/Java/38085350
condefects-java_data_436
import java.util.*; public class Main { public static void main(String[] args) throws Exception { // Your code here! Scanner sc = new Scanner(System.in); int N = sc.nextInt(); sc.nextLine(); StringBuilder S = new StringBuilder(sc.nextLine()); StringBuilder T = new StringBuilder(sc.nextLine()); List<String> replacablePatterns = Arrays.asList("ABC", "BCA", "CAB"); for (int i=S.length()-3; i>-1; i--) { if (S.length() < i+3) { continue; } if (replacablePatterns.contains(S.substring(i, i+3))) { // S = S.substring(0, i) + S.substring(i+3); S.delete(i, i+3); } } for (int i=T.length()-3; i>-1; i--) { if (T.length() < i + 3) { break; } if (replacablePatterns.contains(T.substring(i, i+3))) { // T = T.substring(0, i) + T.substring(i+3); T.delete(i, i+3); } } if (S.toString().contentEquals(T)) { System.out.println("YES"); } else { System.out.println("NO"); } } } import java.util.*; public class Main { public static void main(String[] args) throws Exception { // Your code here! Scanner sc = new Scanner(System.in); int N = sc.nextInt(); sc.nextLine(); StringBuilder S = new StringBuilder(sc.nextLine()); StringBuilder T = new StringBuilder(sc.nextLine()); List<String> replacablePatterns = Arrays.asList("ABC", "BCA", "CAB"); for (int i=S.length()-3; i>-1; i--) { if (S.length() < i+3) { continue; } if (replacablePatterns.contains(S.substring(i, i+3))) { // S = S.substring(0, i) + S.substring(i+3); S.delete(i, i+3); } } for (int i=T.length()-3; i>-1; i--) { if (T.length() < i + 3) { continue; } if (replacablePatterns.contains(T.substring(i, i+3))) { // T = T.substring(0, i) + T.substring(i+3); T.delete(i, i+3); } } if (S.toString().contentEquals(T)) { System.out.println("YES"); } else { System.out.println("NO"); } } }
ConDefects/ConDefects/Code/agc055_b/Java/27490539
condefects-java_data_437
//package com.example.practice; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.StringTokenizer; public class Main { final static char bl = '#'; final static char wh = '.'; public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster final BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); // input file name goes above //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("inflate.out"))); StringTokenizer st = new StringTokenizer(input.readLine()); int N=Integer.parseInt(st.nextToken()); char[] S = input.readLine().toCharArray(); char[] T = input.readLine().toCharArray(); if (check(N, S, T)) { System.out.println("YES"); } else { System.out.println("NO"); } //out.close(); // close the output file } private static boolean check(final int N, final char[] S, final char[] T) { int p = 0, q = 0; LinkedList<Character> ll = new LinkedList<>(); while(p < N){ if(ll.isEmpty()){ ll.add(S[q++]); } if(ll.peek()==T[p]){ ll.poll(); p++; }else { if (q>=N)return false; while (q < N){ if (ll.size()<2){ ll.add(S[q++]); }else { char c = ll.pollLast(); String k = "" + ll.peekLast() + c + S[q]; if(k.equals("ABC") || k.equals("BCA") || k.equals("CAB")){ ll.poll(); if (T[p]=='A'){ ll.addFirst('C'); ll.addFirst('B'); }else if (T[p]=='B'){ ll.addFirst('A'); ll.addFirst('C'); }else { ll.addFirst('B'); ll.addFirst('A'); } p++; q++; break; }else { ll.add(c); ll.add(S[q++]); } } } } } return p==N; } } //package com.example.practice; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.StringTokenizer; public class Main { final static char bl = '#'; final static char wh = '.'; public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster final BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); // input file name goes above //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("inflate.out"))); StringTokenizer st = new StringTokenizer(input.readLine()); int N=Integer.parseInt(st.nextToken()); char[] S = input.readLine().toCharArray(); char[] T = input.readLine().toCharArray(); if (check(N, S, T)) { System.out.println("YES"); } else { System.out.println("NO"); } //out.close(); // close the output file } private static boolean check(final int N, final char[] S, final char[] T) { int p = 0, q = 0; LinkedList<Character> ll = new LinkedList<>(); while(p < N){ if(ll.isEmpty()){ ll.add(S[q++]); } if(ll.peek()==T[p]){ ll.poll(); p++; }else { if (q>=N)return false; while (q < N){ if (ll.size()<2){ ll.add(S[q++]); }else { char c = ll.pollLast(); String k = "" + ll.peekLast() + c + S[q]; if(k.equals("ABC") || k.equals("BCA") || k.equals("CAB")){ ll.pollLast(); if (T[p]=='A'){ ll.addFirst('C'); ll.addFirst('B'); }else if (T[p]=='B'){ ll.addFirst('A'); ll.addFirst('C'); }else { ll.addFirst('B'); ll.addFirst('A'); } p++; q++; break; }else { ll.add(c); ll.add(S[q++]); } } } } } return p==N; } }
ConDefects/ConDefects/Code/agc055_b/Java/28764385
condefects-java_data_438
import com.sun.source.tree.Tree; import com.sun.source.util.Trees; import javax.print.attribute.standard.PrinterResolution; import java.util.*; import java.io.*; public class Main { static FastReader in; static PrintWriter out; static final Random random=new Random(); static long mod= 998244353L; static boolean isPrime[]; static long p[]; static long invFac[]; public static void main(String args[]) throws IOException { in = new FastReader(); out = new PrintWriter(System.out); boolean flag = false; int t = flag ? in.nextInt() : 1; int n = 1001; long inv[] = new long[n]; inv[1] = 1; for(int i = 2; i < n; i++){ inv[i] = (mod-(mod/i)*(inv[(int)(mod%i)]%mod))%mod; } p = new long[1001]; invFac = new long[n]; p[0] = 1; invFac[1] = 1; for(int i = 1; i < 1001; i++){ p[i] = (i*p[i-1])%mod; if(i != 1){ invFac[i] = (invFac[i-1]*inv[i])%mod; } } Main m = new Main(); while (t-- > 0) { m.solve(); } out.close(); } long dp[][]; void solve() { int k = in.nextInt(); int c[] = new int[26]; for(int i = 0; i < 26; i++) c[i] = in.nextInt(); dp = new long[26][k+1]; for(long it[] : dp){ Arrays.fill(it, -1); } System.out.println(f(0, k, c, k)-1); } long f(int i,int k, int c[], int r){ if(i == 26){ return p[r-k]; } if(dp[i][k] != -1) return dp[i][k]; long aus = f(i+1, k, c, r); for(int j = 1; j <= c[i]; j++){ if(k-j >= 0){ aus = (aus+(f(i+1, k-j, c, r)*invFac[j])%mod)%mod; } } return dp[i][k] = aus; } long cal(long n){ return n*(n-1)/2; } static < E > void println(E res) { System.out.println(res); } static < E > void print(E res) { System.out.println(res); } static int dir[][]=new int[][]{{1,0},{-1,0},{0,1},{0,-1}}; static int dir8[][]=new int[][]{{1,0},{-1,0},{0,1},{0,-1},{1,-1},{-1,-1},{-1,1},{1,1}}; public static int binarySearch(int i,int nums[]){int a=(int)1e9;int left=0,right=nums.length-1;while(left<=right){int mid=(left+right)/2;if(nums[mid]>nums[i]){right=mid-1;a=mid;} else left=mid+1;}return a;} public static void print(int a[]) { StringBuilder str = new StringBuilder(""); for (int i : a) str.append(i+" "); System.out.println(str);}; public static List<Integer> factors(int n){List<Integer> factors = new ArrayList<>();for (int i = 1; i <= Math.sqrt(n); i++) {if (n % i == 0) {factors.add(i);if (i != n / i) {factors.add(n / i);}}}return factors;} public static void println(){System.out.println();} public static int gcd(int a,int b){if(b==0)return a;return gcd(b,a%b);} public static int lcm(int a,int b){return (a/(gcd(a,b))*b);} public static boolean[] prime(int n){boolean a[]=new boolean[n+1];Arrays.fill(a,true);for(int i=2;i*i<=n;i++){if(a[i]==true){for(int j=i+i;j<=n;j+=i){a[i]=false;}}}return a;} public static boolean isPrime(int n) {if (n <= 1) {return false;}if (n <= 3) {return true;}if (n % 2 == 0 || n % 3 == 0) {return false;}for (int i = 5; i * i <= n; i = i + 6) {if (n % i == 0 || n % (i + 2) == 0) {return false;}}return true;} public static long factorial(int n) {if (n == 0) {return 1;}long fact = 1;for (int i = 1; i <= n; i++) {fact *= i;}return fact;} public static long power(long a, long b) {long result = 1;while (b > 0) {if ((b & 1) != 0) {result = (result * a)%mod;}a = (a * a)%mod;b >>= 1;}return result;} public static void read2DArray(int a[][],int n,int m){for(int i=0;i<n;i++){for(int j=0;j<m;j++)a[i][j]=in.nextInt();}} static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int [] readintarray(int n) { int res [] = new int [n]; for(int i = 0; i<n; i++)res[i] = nextInt(); return res; } long [] readlongarray(int n) { long res [] = new long [n]; for(int i = 0; i<n; i++)res[i] = nextLong(); return res; } } } import com.sun.source.tree.Tree; import com.sun.source.util.Trees; import javax.print.attribute.standard.PrinterResolution; import java.util.*; import java.io.*; public class Main { static FastReader in; static PrintWriter out; static final Random random=new Random(); static long mod= 998244353L; static boolean isPrime[]; static long p[]; static long invFac[]; public static void main(String args[]) throws IOException { in = new FastReader(); out = new PrintWriter(System.out); boolean flag = false; int t = flag ? in.nextInt() : 1; int n = 1001; long inv[] = new long[n]; inv[1] = 1; for(int i = 2; i < n; i++){ inv[i] = mod-inv[(int)(mod%i)]*(mod/i)%mod; } p = new long[1001]; invFac = new long[n]; p[0] = 1; invFac[1] = 1; for(int i = 1; i < 1001; i++){ p[i] = (i*p[i-1])%mod; if(i != 1){ invFac[i] = (invFac[i-1]*inv[i])%mod; } } Main m = new Main(); while (t-- > 0) { m.solve(); } out.close(); } long dp[][]; void solve() { int k = in.nextInt(); int c[] = new int[26]; for(int i = 0; i < 26; i++) c[i] = in.nextInt(); dp = new long[26][k+1]; for(long it[] : dp){ Arrays.fill(it, -1); } System.out.println(f(0, k, c, k)-1); } long f(int i,int k, int c[], int r){ if(i == 26){ return p[r-k]; } if(dp[i][k] != -1) return dp[i][k]; long aus = f(i+1, k, c, r); for(int j = 1; j <= c[i]; j++){ if(k-j >= 0){ aus = (aus+(f(i+1, k-j, c, r)*invFac[j])%mod)%mod; } } return dp[i][k] = aus; } long cal(long n){ return n*(n-1)/2; } static < E > void println(E res) { System.out.println(res); } static < E > void print(E res) { System.out.println(res); } static int dir[][]=new int[][]{{1,0},{-1,0},{0,1},{0,-1}}; static int dir8[][]=new int[][]{{1,0},{-1,0},{0,1},{0,-1},{1,-1},{-1,-1},{-1,1},{1,1}}; public static int binarySearch(int i,int nums[]){int a=(int)1e9;int left=0,right=nums.length-1;while(left<=right){int mid=(left+right)/2;if(nums[mid]>nums[i]){right=mid-1;a=mid;} else left=mid+1;}return a;} public static void print(int a[]) { StringBuilder str = new StringBuilder(""); for (int i : a) str.append(i+" "); System.out.println(str);}; public static List<Integer> factors(int n){List<Integer> factors = new ArrayList<>();for (int i = 1; i <= Math.sqrt(n); i++) {if (n % i == 0) {factors.add(i);if (i != n / i) {factors.add(n / i);}}}return factors;} public static void println(){System.out.println();} public static int gcd(int a,int b){if(b==0)return a;return gcd(b,a%b);} public static int lcm(int a,int b){return (a/(gcd(a,b))*b);} public static boolean[] prime(int n){boolean a[]=new boolean[n+1];Arrays.fill(a,true);for(int i=2;i*i<=n;i++){if(a[i]==true){for(int j=i+i;j<=n;j+=i){a[i]=false;}}}return a;} public static boolean isPrime(int n) {if (n <= 1) {return false;}if (n <= 3) {return true;}if (n % 2 == 0 || n % 3 == 0) {return false;}for (int i = 5; i * i <= n; i = i + 6) {if (n % i == 0 || n % (i + 2) == 0) {return false;}}return true;} public static long factorial(int n) {if (n == 0) {return 1;}long fact = 1;for (int i = 1; i <= n; i++) {fact *= i;}return fact;} public static long power(long a, long b) {long result = 1;while (b > 0) {if ((b & 1) != 0) {result = (result * a)%mod;}a = (a * a)%mod;b >>= 1;}return result;} public static void read2DArray(int a[][],int n,int m){for(int i=0;i<n;i++){for(int j=0;j<m;j++)a[i][j]=in.nextInt();}} static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int [] readintarray(int n) { int res [] = new int [n]; for(int i = 0; i<n; i++)res[i] = nextInt(); return res; } long [] readlongarray(int n) { long res [] = new long [n]; for(int i = 0; i<n; i++)res[i] = nextLong(); return res; } } }
ConDefects/ConDefects/Code/abc358_e/Java/54617478
condefects-java_data_439
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { public static void main(String[] args) { // Scanner sc = new Scanner(System.in); // int x = sc.nextInt(); // int y = sc.nextInt(); // int width = 0; // // for (int i = 0; i < x ; i++){ // int z = sc.nextInt(); // if (z > y) // width+=2; // else // width+=1; // } // System.out.println(width); Queue <Integer> queue = new LinkedList<>(); Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int y = sc.nextInt(); for (int i = 0 ; i <x ; i++){ int z = sc.nextInt(); queue.add(z); } for (int i = 0 ; i < y ; i++){ queue.remove(); queue.add(0); } for (int i = 0 ; i < queue.size(); i++) System.out.print(queue.remove()+" "); // Scanner sc = new Scanner(System.in); // int x = sc.nextInt(); // int y = sc.nextInt(); // int z = sc.nextInt(); // if () } } import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { public static void main(String[] args) { // Scanner sc = new Scanner(System.in); // int x = sc.nextInt(); // int y = sc.nextInt(); // int width = 0; // // for (int i = 0; i < x ; i++){ // int z = sc.nextInt(); // if (z > y) // width+=2; // else // width+=1; // } // System.out.println(width); Queue <Integer> queue = new LinkedList<>(); Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int y = sc.nextInt(); for (int i = 0 ; i <x ; i++){ int z = sc.nextInt(); queue.add(z); } for (int i = 0 ; i < y ; i++){ queue.remove(); queue.add(0); } for (int i = 0 ; i < x; i++) System.out.print(queue.remove()+" "); // Scanner sc = new Scanner(System.in); // int x = sc.nextInt(); // int y = sc.nextInt(); // int z = sc.nextInt(); // if () } }
ConDefects/ConDefects/Code/abc278_a/Java/39175872
condefects-java_data_440
import java.util.ArrayList; import java.util.List; import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sn = new Scanner(System.in); int n = sn.nextInt(); int k = sn.nextInt(); List<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) { a.add(sn.nextInt()); } for (int i = 0; i < k; i++) { a.remove(0); a.add(0); } sn.close(); for (int nItem : a) { System.out.print(nItem); } } } import java.util.ArrayList; import java.util.List; import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sn = new Scanner(System.in); int n = sn.nextInt(); int k = sn.nextInt(); List<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) { a.add(sn.nextInt()); } for (int i = 0; i < k; i++) { a.remove(0); a.add(0); } sn.close(); for (int nItem : a) { System.out.print(nItem + " "); } } }
ConDefects/ConDefects/Code/abc278_a/Java/44077283
condefects-java_data_441
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner kbs = new Scanner(System.in); long n1 = kbs.nextLong(); long n2 = kbs.nextLong(); do { if (n1 % 10 + n2 % 10 > 10) { System.out.println("Hard"); return; } n1 /= 10; n2 /= 10; } while (n1 != 0 && n2 != 0); System.out.println("Easy"); } } import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner kbs = new Scanner(System.in); long n1 = kbs.nextLong(); long n2 = kbs.nextLong(); do { if (n1 % 10 + n2 % 10 >= 10) { System.out.println("Hard"); return; } n1 /= 10; n2 /= 10; } while (n1 != 0 && n2 != 0); System.out.println("Easy"); } }
ConDefects/ConDefects/Code/abc229_b/Java/36884154
condefects-java_data_442
import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); String a = sc.next(); String b = sc.next(); String[] aarr = a.split(""); String[] barr = b.split(""); int n = aarr.length < barr.length ? aarr.length : barr.length; String result = "Easy"; for(int i = 0; i < n; i++){ int aint = Integer.parseInt(aarr[aarr.length - 1 - i]); int bint = Integer.parseInt(barr[barr.length - 1 - i]); if(aint + bint > 10){ result = "Hard"; } } System.out.println(result); } } import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); String a = sc.next(); String b = sc.next(); String[] aarr = a.split(""); String[] barr = b.split(""); int n = aarr.length < barr.length ? aarr.length : barr.length; String result = "Easy"; for(int i = 0; i < n; i++){ int aint = Integer.parseInt(aarr[aarr.length - 1 - i]); int bint = Integer.parseInt(barr[barr.length - 1 - i]); if(aint + bint >= 10){ result = "Hard"; } } System.out.println(result); } }
ConDefects/ConDefects/Code/abc229_b/Java/45939520
condefects-java_data_443
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; class Main { private static void solve() throws IOException { long A = IO.nextLong(); long B = IO.nextLong(); while (A > 0 && B > 0) { if (A % 10 + B % 10 > 10) { out.println("Hard"); return; } A = A / 10; B = B / 10; } out.println("Easy"); } public static void main(String[] args) throws Exception { solve(); out.flush(); } private static Scanner sc = new Scanner(System.in); private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter out = new PrintWriter(System.out); static class IO { public static String next() throws IOException { return sc.next(); } public static int nextInt() throws IOException { return Integer.parseInt(sc.next()); } public static long nextLong() throws IOException { return Long.parseLong(sc.next()); } public static double nextDouble() throws IOException { return Double.parseDouble(sc.next()); } public static int[] nextIntArray(int n) throws IOException { int[] intArray = new int[n]; for (int i = 0; i < n; i++) { intArray[i] = Integer.parseInt(sc.next()); } return intArray; } public static String readLine() throws IOException { return br.readLine(); } public static String[] inputStringArray(String split) throws IOException { return readLine().split(split); } public static int[] inputIntArray(String split) throws IOException { return Arrays.stream(inputStringArray(split)).mapToInt(Integer::parseInt).toArray(); } } } import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; class Main { private static void solve() throws IOException { long A = IO.nextLong(); long B = IO.nextLong(); while (A > 0 && B > 0) { if (A % 10 + B % 10 >= 10) { out.println("Hard"); return; } A = A / 10; B = B / 10; } out.println("Easy"); } public static void main(String[] args) throws Exception { solve(); out.flush(); } private static Scanner sc = new Scanner(System.in); private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter out = new PrintWriter(System.out); static class IO { public static String next() throws IOException { return sc.next(); } public static int nextInt() throws IOException { return Integer.parseInt(sc.next()); } public static long nextLong() throws IOException { return Long.parseLong(sc.next()); } public static double nextDouble() throws IOException { return Double.parseDouble(sc.next()); } public static int[] nextIntArray(int n) throws IOException { int[] intArray = new int[n]; for (int i = 0; i < n; i++) { intArray[i] = Integer.parseInt(sc.next()); } return intArray; } public static String readLine() throws IOException { return br.readLine(); } public static String[] inputStringArray(String split) throws IOException { return readLine().split(split); } public static int[] inputIntArray(String split) throws IOException { return Arrays.stream(inputStringArray(split)).mapToInt(Integer::parseInt).toArray(); } } }
ConDefects/ConDefects/Code/abc229_b/Java/39538384
condefects-java_data_444
import java.util.*; import java.io.*; class Main { private static final void solve() throws IOException { final int r = ni(), g = ni(), b = ni(), k = ni(); final int n1 = r - k, n2 = g - k, n3 = b, n4 = k; var fa = new ModIntFactory(998244353); var ans = fa.factorial(n1 + n3 + n4).div(fa.factorial(n1)).div(fa.factorial(n3)).div(fa.factorial(n4)); ans.mulAsg(fa.combination(n1 + n2 + n4, n2)); ou.println(ans); } public static void main(String[] args) throws IOException { solve(); ou.flush(); } private static final int ni() throws IOException { return sc.nextInt(); } private static final int[] ni(int n) throws IOException { return sc.nextIntArray(n); } private static final long nl() throws IOException { return sc.nextLong(); } private static final long[] nl(int n) throws IOException { return sc.nextLongArray(n); } private static final String ns() throws IOException { return sc.next(); } private static final double nd() throws IOException { return sc.nextDouble(); } private static final ContestInputStream sc = new ContestInputStream(); private static final ContestOutputStream ou = new ContestOutputStream(); } class ModIntFactory { private final ModArithmetic ma; private final int mod; private final boolean usesMontgomery; private final ModArithmetic.ModArithmeticMontgomery maMontgomery; private ArrayList<Integer> factorial; public ModIntFactory(int mod) { this.ma = ModArithmetic.of(mod); this.usesMontgomery = ma instanceof ModArithmetic.ModArithmeticMontgomery; this.maMontgomery = usesMontgomery ? (ModArithmetic.ModArithmeticMontgomery) ma : null; this.mod = mod; this.factorial = new ArrayList<>(); } public ModIntFactory(double mod) { this((int) mod); } public ModInt create(long value) { if ((value %= mod) < 0) value += mod; if (usesMontgomery) { return new ModInt(maMontgomery.generate(value)); } else { return new ModInt((int) value); } } private void prepareFactorial(int max) { factorial.ensureCapacity(max + 1); if (factorial.size() == 0) factorial.add(1); for (int i = factorial.size(); i <= max; i++) { if (usesMontgomery) factorial.add(ma.mul(factorial.get(i - 1), maMontgomery.generate(i))); else factorial.add(ma.mul(factorial.get(i - 1), i)); } } public ModInt factorial(int i) { prepareFactorial(i); return create(factorial.get(i)); } public ModInt permutation(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); return create(ma.div(factorial.get(n), factorial.get(r))); } public ModInt combination(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); return create(ma.div(factorial.get(n), ma.mul(factorial.get(r), factorial.get(n - r)))); } public int getMod() { return mod; } public class ModInt { private int value; private ModInt(int value) { this.value = value; } public int mod() { return mod; } public int value() { if (usesMontgomery) { return maMontgomery.reduce(value); } return value; } public ModInt add(ModInt mi) { return new ModInt(ma.add(value, mi.value)); } public ModInt add(ModInt mi1, ModInt mi2) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt add(ModInt mi1, ModInt... mis) { ModInt mi = add(mi1); for (ModInt m : mis) mi.addAsg(m); return mi; } public ModInt add(long mi) { return new ModInt(ma.add(value, ma.remainder(mi))); } public ModInt sub(ModInt mi) { return new ModInt(ma.sub(value, mi.value)); } public ModInt sub(long mi) { return new ModInt(ma.sub(value, ma.remainder(mi))); } public ModInt mul(ModInt mi) { return new ModInt(ma.mul(value, mi.value)); } public ModInt mul(ModInt mi1, ModInt mi2) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mul(ModInt mi1, ModInt... mis) { ModInt mi = mul(mi1); for (ModInt m : mis) mi.mulAsg(m); return mi; } public ModInt mul(long mi) { return new ModInt(ma.mul(value, ma.remainder(mi))); } public ModInt div(ModInt mi) { return new ModInt(ma.div(value, mi.value)); } public ModInt div(long mi) { return new ModInt(ma.div(value, ma.remainder(mi))); } public ModInt inv() { return new ModInt(ma.inv(value)); } public ModInt pow(long b) { return new ModInt(ma.pow(value, b)); } public ModInt pow(ModInt mi) { return new ModInt(ma.pow(value, mi.value)); } public ModInt addAsg(ModInt mi) { this.value = ma.add(value, mi.value); return this; } public ModInt addAsg(ModInt mi1, ModInt mi2) { return addAsg(mi1).addAsg(mi2); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return addAsg(mi1).addAsg(mi2).addAsg(mi3); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return addAsg(mi1).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt addAsg(ModInt... mis) { for (ModInt m : mis) addAsg(m); return this; } public ModInt addAsg(long mi) { this.value = ma.add(value, ma.remainder(mi)); return this; } public ModInt subAsg(ModInt mi) { this.value = ma.sub(value, mi.value); return this; } public ModInt subAsg(long mi) { this.value = ma.sub(value, ma.remainder(mi)); return this; } public ModInt mulAsg(ModInt mi) { this.value = ma.mul(value, mi.value); return this; } public ModInt mulAsg(ModInt mi1, ModInt mi2) { return mulAsg(mi1).mulAsg(mi2); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mulAsg(ModInt... mis) { for (ModInt m : mis) mulAsg(m); return this; } public ModInt mulAsg(long mi) { this.value = ma.mul(value, ma.remainder(mi)); return this; } public ModInt divAsg(ModInt mi) { this.value = ma.div(value, mi.value); return this; } public ModInt divAsg(long mi) { this.value = ma.div(value, ma.remainder(mi)); return this; } public ModInt powAsg(ModInt mi) { this.value = ma.pow(value, mi.value()); return this; } public ModInt powAsg(long mi) { this.value = ma.pow(value, mi); return this; } @Override public String toString() { return String.valueOf(value()); } @Override public boolean equals(Object o) { if (o instanceof ModInt) { ModInt mi = (ModInt) o; return mod() == mi.mod() && value() == mi.value(); } return false; } @Override public int hashCode() { return (1 * 37 + mod()) * 37 + value(); } } private static abstract class ModArithmetic { abstract int mod(); abstract int remainder(long value); abstract int add(int a, int b); abstract int sub(int a, int b); abstract int mul(int a, int b); int div(int a, int b) { return mul(a, inv(b)); } int inv(int a) { int b = mod(); if (b == 1) return 0; long u = 1, v = 0; while (b >= 1) { int t = a / b; a -= t * b; int tmp1 = a; a = b; b = tmp1; u -= t * v; long tmp2 = u; u = v; v = tmp2; } if (a != 1) throw new ArithmeticException("divide by zero"); return remainder(u); } int pow(int a, long b) { if (b < 0) throw new ArithmeticException("negative power"); int r = 1; int x = a; while (b > 0) { if ((b & 1) == 1) r = mul(r, x); x = mul(x, x); b >>= 1; } return r; } static ModArithmetic of(int mod) { if (mod <= 0) { throw new IllegalArgumentException(); } else if (mod == 1) { return new ModArithmetic1(); } else if (mod == 2) { return new ModArithmetic2(); } else if (mod == 998244353) { return new ModArithmetic998244353(); } else if (mod == 1000000007) { return new ModArithmetic1000000007(); } else if ((mod & 1) == 1) { return new ModArithmeticMontgomery(mod); } else { return new ModArithmeticBarrett(mod); } } private static final class ModArithmetic1 extends ModArithmetic { int mod() { return 1; } int remainder(long value) { return 0; } int add(int a, int b) { return 0; } int sub(int a, int b) { return 0; } int mul(int a, int b) { return 0; } int pow(int a, long b) { return 0; } } private static final class ModArithmetic2 extends ModArithmetic { int mod() { return 2; } int remainder(long value) { return (int) (value & 1); } int add(int a, int b) { return a ^ b; } int sub(int a, int b) { return a ^ b; } int mul(int a, int b) { return a & b; } } private static final class ModArithmetic998244353 extends ModArithmetic { private final int mod = 998244353; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmetic1000000007 extends ModArithmetic { private final int mod = 1000000007; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmeticMontgomery extends ModArithmeticDynamic { private final long negInv; private final long r2; private ModArithmeticMontgomery(int mod) { super(mod); long inv = 0; long s = 1, t = 0; for (int i = 0; i < 32; i++) { if ((t & 1) == 0) { t += mod; inv += s; } t >>= 1; s <<= 1; } long r = (1l << 32) % mod; this.negInv = inv; this.r2 = (r * r) % mod; } private int generate(long x) { return reduce(x * r2); } private int reduce(long x) { x = (x + ((x * negInv) & 0xffff_ffffl) * mod) >>> 32; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return generate((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } @Override int inv(int a) { return super.inv(reduce(a)); } @Override int pow(int a, long b) { return generate(super.pow(a, b)); } } private static final class ModArithmeticBarrett extends ModArithmeticDynamic { private static final long mask = 0xffff_ffffl; private final long mh; private final long ml; private ModArithmeticBarrett(int mod) { super(mod); long a = (1l << 32) / mod; long b = (1l << 32) % mod; long m = a * a * mod + 2 * a * b + (b * b) / mod; mh = m >>> 32; ml = m & mask; } private int reduce(long x) { long z = (x & mask) * ml; z = (x & mask) * mh + (x >>> 32) * ml + (z >>> 32); z = (x >>> 32) * mh + (z >>> 32); x -= z * mod; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } } private static class ModArithmeticDynamic extends ModArithmetic { final int mod; ModArithmeticDynamic(int mod) { this.mod = mod; } int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int sum = a + b; return sum >= mod ? sum - mod : sum; } int sub(int a, int b) { int sum = a - b; return sum < 0 ? sum + mod : sum; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } } } final class ContestInputStream extends FilterInputStream { protected final byte[] buf; protected int pos = 0; protected int lim = 0; private final char[] cbuf; public ContestInputStream() { super(System.in); this.buf = new byte[1 << 13]; this.cbuf = new char[1 << 20]; } boolean hasRemaining() throws IOException { if (pos < lim) return true; lim = in.read(buf); pos = 0; return lim > 0; } final int remaining() throws IOException { if (pos >= lim) { lim = in.read(buf); pos = 0; } return lim - pos; } @Override public final int available() throws IOException { if (pos < lim) return lim - pos + in.available(); return in.available(); } @Override public final long skip(long n) throws IOException { if (pos < lim) { int rem = lim - pos; if (n < rem) { pos += n; return n; } pos = lim; return rem; } return in.skip(n); } @Override public final int read() throws IOException { if (hasRemaining()) return buf[pos++]; return -1; } @Override public final int read(byte[] b, int off, int len) throws IOException { if (pos < lim) { int rem = Math.min(lim - pos, len); for (int i = 0; i < rem; i++) b[off + i] = buf[pos + i]; pos += rem; return rem; } return in.read(b, off, len); } public final char[] readToken() throws IOException { int cpos = 0; int rem; byte b; l: while ((rem = remaining()) > 0) { for (int i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } char[] arr = new char[cpos]; for (int i = 0; i < cpos; i++) arr[i] = cbuf[i]; return arr; } public final int readToken(char[] cbuf, int off) throws IOException { int cpos = off; int rem; byte b; l: while ((rem = remaining()) > 0) { for (int i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } return cpos - off; } public final int readToken(char[] cbuf) throws IOException { return readToken(cbuf, 0); } public final String next() throws IOException { int cpos = 0; int rem; byte b; l: while ((rem = remaining()) > 0) { for (int i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } return String.valueOf(cbuf, 0, cpos); } public final char[] nextCharArray() throws IOException { return readToken(); } public final int nextInt() throws IOException { if (!hasRemaining()) return 0; int value = 0; byte b = buf[pos++]; if (b == 0x2d) { while (hasRemaining() && (b = buf[pos++]) > 0x20) value = value * 10 - b + 0x30; } else { do { value = value * 10 + b - 0x30; } while (hasRemaining() && (b = buf[pos++]) > 0x20); } if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; return value; } public final long nextLong() throws IOException { if (!hasRemaining()) return 0L; long value = 0L; byte b = buf[pos++]; if (b == 0x2d) { while (hasRemaining() && (b = buf[pos++]) > 0x20) value = value * 10 - b + 0x30; } else { do { value = value * 10 + b - 0x30; } while (hasRemaining() && (b = buf[pos++]) > 0x20); } if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; return value; } public final char nextChar() throws IOException { if (!hasRemaining()) throw new EOFException(); final char c = (char) buf[pos++]; if (hasRemaining() && buf[pos++] == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; return c; } public final float nextFloat() throws IOException { return Float.parseFloat(next()); } public final double nextDouble() throws IOException { return Double.parseDouble(next()); } public final boolean[] nextBooleanArray(char ok) throws IOException { char[] s = readToken(); int n = s.length; boolean[] t = new boolean[n]; for (int i = 0; i < n; i++) t[i] = s[i] == ok; return t; } public final boolean[][] nextBooleanMatrix(int h, int w, char ok) throws IOException { boolean[][] s = new boolean[h][]; for (int i = 0; i < h; i++) { char[] t = readToken(); int n = t.length; s[i] = new boolean[n]; for (int j = 0; j < n; j++) s[i][j] = t[j] == ok; } return s; } public final String[] nextStringArray(int len) throws IOException { String[] arr = new String[len]; for (int i = 0; i < len; i++) arr[i] = next(); return arr; } public final int[] nextIntArray(int len) throws IOException { int[] arr = new int[len]; for (int i = 0; i < len; i++) arr[i] = nextInt(); return arr; } public final int[] nextIntArray(int len, java.util.function.IntUnaryOperator map) throws IOException { int[] arr = new int[len]; for (int i = 0; i < len; i++) arr[i] = map.applyAsInt(nextInt()); return arr; } public final long[] nextLongArray(int len, java.util.function.LongUnaryOperator map) throws IOException { long[] arr = new long[len]; for (int i = 0; i < len; i++) arr[i] = map.applyAsLong(nextLong()); return arr; } public final int[][] nextIntMatrix(int h, int w) throws IOException { int[][] arr = new int[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = nextInt(); return arr; } public final int[][] nextIntMatrix(int h, int w, java.util.function.IntUnaryOperator map) throws IOException { int[][] arr = new int[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = map.applyAsInt(nextInt()); return arr; } public final long[] nextLongArray(int len) throws IOException { long[] arr = new long[len]; for (int i = 0; i < len; i++) arr[i] = nextLong(); return arr; } public final long[][] nextLongMatrix(int h, int w) throws IOException { long[][] arr = new long[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = nextLong(); return arr; } public final float[] nextFloatArray(int len) throws IOException { float[] arr = new float[len]; for (int i = 0; i < len; i++) arr[i] = nextFloat(); return arr; } public final double[] nextDoubleArray(int len) throws IOException { double[] arr = new double[len]; for (int i = 0; i < len; i++) arr[i] = nextDouble(); return arr; } public final char[][] nextCharMatrix(int h, int w) throws IOException { char[][] arr = new char[h][]; for (int i = 0; i < h; i++) arr[i] = readToken(); return arr; } public final void nextThrow() throws IOException { next(); return; } public final void nextThrow(int n) throws IOException { for (int i = 0; i < n; i++) nextThrow(); return; } } final class ContestOutputStream extends FilterOutputStream implements Appendable { protected final byte[] buf; protected int pos = 0; public ContestOutputStream() { super(System.out); this.buf = new byte[1 << 13]; } @Override public void flush() throws IOException { out.write(buf, 0, pos); pos = 0; out.flush(); } void put(byte b) throws IOException { if (pos >= buf.length) flush(); buf[pos++] = b; } int remaining() throws IOException { if (pos >= buf.length) flush(); return buf.length - pos; } @Override public void write(int b) throws IOException { put((byte) b); } @Override public void write(byte[] b, int off, int len) throws IOException { int o = off; int l = len; while (l > 0) { int rem = Math.min(remaining(), l); for (int i = 0; i < rem; i++) buf[pos + i] = b[o + i]; pos += rem; o += rem; l -= rem; } } @Override public ContestOutputStream append(char c) throws IOException { put((byte) c); return this; } @Override public ContestOutputStream append(CharSequence csq, int start, int end) throws IOException { int off = start; int len = end - start; while (len > 0) { int rem = Math.min(remaining(), len); for (int i = 0; i < rem; i++) buf[pos + i] = (byte) csq.charAt(off + i); pos += rem; off += rem; len -= rem; } return this; } @Override public ContestOutputStream append(CharSequence csq) throws IOException { return append(csq, 0, csq.length()); } public ContestOutputStream append(char[] arr, int off, int len) throws IOException { int o = off; int l = len; while (l > 0) { int rem = Math.min(remaining(), l); for (int i = 0; i < rem; i++) buf[pos + i] = (byte) arr[o + i]; pos += rem; o += rem; l -= rem; } return this; } public ContestOutputStream print(char[] arr) throws IOException { return append(arr, 0, arr.length).newLine(); } public ContestOutputStream print(boolean value) throws IOException { if (value) return append("o"); return append("x"); } public ContestOutputStream println(boolean value) throws IOException { if (value) return append("o\n"); return append("x\n"); } public ContestOutputStream print(boolean[][] value) throws IOException { final int n = value.length, m = value[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) print(value[i][j]); newLine(); } return this; } public ContestOutputStream print(int value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(int value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(long value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(long value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(float value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(float value) throws IOException { return append(String.valueOf(value)).newLine(); } private ContestOutputStream dtos(double x, int n) throws IOException { if (x < 0) { append('-'); x = -x; } x += Math.pow(10, -n) / 2; long longx = (long) x; print(longx); append('.'); x -= longx; for (int i = 0; i < n; i++) { x *= 10; int intx = (int) x; print(intx); x -= intx; } return this; } public ContestOutputStream print(double value) throws IOException { return dtos(value, 20); } public ContestOutputStream println(double value) throws IOException { return dtos(value, 20).newLine(); } public ContestOutputStream print(char value) throws IOException { return append(value); } public ContestOutputStream println(char value) throws IOException { return append(value).newLine(); } public ContestOutputStream print(String value) throws IOException { return append(value); } public ContestOutputStream println(String value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(Object value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(Object value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream printYN(boolean yes) throws IOException { if (yes) return println("Yes"); return println("No"); } public ContestOutputStream printAB(boolean yes) throws IOException { if (yes) return println("Alice"); return println("Bob"); } public ContestOutputStream print(CharSequence[] arr) throws IOException { if (arr.length > 0) { append(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').append(arr[i]); } return this; } public ContestOutputStream print(int[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream print(int[] arr, int length) throws IOException { if (length > 0) print(arr[0]); for (int i = 1; i < length; i++) append('\u0020').print(arr[i]); newLine(); return this; } public ContestOutputStream println(int[] arr) throws IOException { for (int i : arr) print(i).newLine(); return this; } public ContestOutputStream println(int[] arr, int length) throws IOException { for (int i = 0; i < length; i++) println(arr[i]); return this; } public ContestOutputStream print(boolean[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream print(long[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream print(long[] arr, int length) throws IOException { if (length > 0) print(arr[0]); for (int i = 1; i < length; i++) append('\u0020').print(arr[i]); newLine(); return this; } public ContestOutputStream println(long[] arr, int length) throws IOException { for (int i = 0; i < length; i++) println(arr[i]); return this; } public ContestOutputStream println(long[] arr) throws IOException { for (long i : arr) print(i).newLine(); return this; } public ContestOutputStream print(float[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return this; } public ContestOutputStream println(float[] arr) throws IOException { for (float i : arr) print(i).newLine(); return this; } public ContestOutputStream print(double[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return newLine(); } public ContestOutputStream println(double[] arr) throws IOException { for (double i : arr) print(i).newLine(); return this; } public ContestOutputStream print(java.util.ArrayList<?> arr) throws IOException { if (!arr.isEmpty()) { final int n = arr.size(); print(arr.get(0)); for (int i = 1; i < n; i++) print(" ").print(arr.get(i)); } return newLine(); } public ContestOutputStream println(java.util.ArrayList<?> arr) throws IOException { final int n = arr.size(); for (int i = 0; i < n; i++) println(arr.get(i)); return this; } public ContestOutputStream newLine() throws IOException { return append(System.lineSeparator()); } public ContestOutputStream endl() throws IOException { newLine().flush(); return this; } public ContestOutputStream print(int[][] arr) throws IOException { for (int[] i : arr) print(i); return this; } public ContestOutputStream print(long[][] arr) throws IOException { for (long[] i : arr) print(i); return this; } public ContestOutputStream print(char[][] arr) throws IOException { for (char[] i : arr) print(i); return this; } public ContestOutputStream print(Object[][] arr) throws IOException { for (Object[] i : arr) print(i); return this; } public ContestOutputStream println() throws IOException { return newLine(); } public ContestOutputStream print(Object... arr) throws IOException { for (Object i : arr) print(i); return this; } public ContestOutputStream println(Object... arr) throws IOException { for (Object i : arr) print(i); return newLine(); } } import java.util.*; import java.io.*; class Main { private static final void solve() throws IOException { final int r = ni(), g = ni(), b = ni(), k = ni(); final int n1 = r - k, n2 = g - k, n3 = b, n4 = k; var fa = new ModIntFactory(998244353); var ans = fa.factorial(n1 + n3 + n4).div(fa.factorial(n1)).div(fa.factorial(n3)).div(fa.factorial(n4)); ans.mulAsg(fa.combination(n2 + n3 + n4, n2)); ou.println(ans); } public static void main(String[] args) throws IOException { solve(); ou.flush(); } private static final int ni() throws IOException { return sc.nextInt(); } private static final int[] ni(int n) throws IOException { return sc.nextIntArray(n); } private static final long nl() throws IOException { return sc.nextLong(); } private static final long[] nl(int n) throws IOException { return sc.nextLongArray(n); } private static final String ns() throws IOException { return sc.next(); } private static final double nd() throws IOException { return sc.nextDouble(); } private static final ContestInputStream sc = new ContestInputStream(); private static final ContestOutputStream ou = new ContestOutputStream(); } class ModIntFactory { private final ModArithmetic ma; private final int mod; private final boolean usesMontgomery; private final ModArithmetic.ModArithmeticMontgomery maMontgomery; private ArrayList<Integer> factorial; public ModIntFactory(int mod) { this.ma = ModArithmetic.of(mod); this.usesMontgomery = ma instanceof ModArithmetic.ModArithmeticMontgomery; this.maMontgomery = usesMontgomery ? (ModArithmetic.ModArithmeticMontgomery) ma : null; this.mod = mod; this.factorial = new ArrayList<>(); } public ModIntFactory(double mod) { this((int) mod); } public ModInt create(long value) { if ((value %= mod) < 0) value += mod; if (usesMontgomery) { return new ModInt(maMontgomery.generate(value)); } else { return new ModInt((int) value); } } private void prepareFactorial(int max) { factorial.ensureCapacity(max + 1); if (factorial.size() == 0) factorial.add(1); for (int i = factorial.size(); i <= max; i++) { if (usesMontgomery) factorial.add(ma.mul(factorial.get(i - 1), maMontgomery.generate(i))); else factorial.add(ma.mul(factorial.get(i - 1), i)); } } public ModInt factorial(int i) { prepareFactorial(i); return create(factorial.get(i)); } public ModInt permutation(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); return create(ma.div(factorial.get(n), factorial.get(r))); } public ModInt combination(int n, int r) { if (n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); return create(ma.div(factorial.get(n), ma.mul(factorial.get(r), factorial.get(n - r)))); } public int getMod() { return mod; } public class ModInt { private int value; private ModInt(int value) { this.value = value; } public int mod() { return mod; } public int value() { if (usesMontgomery) { return maMontgomery.reduce(value); } return value; } public ModInt add(ModInt mi) { return new ModInt(ma.add(value, mi.value)); } public ModInt add(ModInt mi1, ModInt mi2) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt add(ModInt mi1, ModInt... mis) { ModInt mi = add(mi1); for (ModInt m : mis) mi.addAsg(m); return mi; } public ModInt add(long mi) { return new ModInt(ma.add(value, ma.remainder(mi))); } public ModInt sub(ModInt mi) { return new ModInt(ma.sub(value, mi.value)); } public ModInt sub(long mi) { return new ModInt(ma.sub(value, ma.remainder(mi))); } public ModInt mul(ModInt mi) { return new ModInt(ma.mul(value, mi.value)); } public ModInt mul(ModInt mi1, ModInt mi2) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mul(ModInt mi1, ModInt... mis) { ModInt mi = mul(mi1); for (ModInt m : mis) mi.mulAsg(m); return mi; } public ModInt mul(long mi) { return new ModInt(ma.mul(value, ma.remainder(mi))); } public ModInt div(ModInt mi) { return new ModInt(ma.div(value, mi.value)); } public ModInt div(long mi) { return new ModInt(ma.div(value, ma.remainder(mi))); } public ModInt inv() { return new ModInt(ma.inv(value)); } public ModInt pow(long b) { return new ModInt(ma.pow(value, b)); } public ModInt pow(ModInt mi) { return new ModInt(ma.pow(value, mi.value)); } public ModInt addAsg(ModInt mi) { this.value = ma.add(value, mi.value); return this; } public ModInt addAsg(ModInt mi1, ModInt mi2) { return addAsg(mi1).addAsg(mi2); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return addAsg(mi1).addAsg(mi2).addAsg(mi3); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return addAsg(mi1).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt addAsg(ModInt... mis) { for (ModInt m : mis) addAsg(m); return this; } public ModInt addAsg(long mi) { this.value = ma.add(value, ma.remainder(mi)); return this; } public ModInt subAsg(ModInt mi) { this.value = ma.sub(value, mi.value); return this; } public ModInt subAsg(long mi) { this.value = ma.sub(value, ma.remainder(mi)); return this; } public ModInt mulAsg(ModInt mi) { this.value = ma.mul(value, mi.value); return this; } public ModInt mulAsg(ModInt mi1, ModInt mi2) { return mulAsg(mi1).mulAsg(mi2); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mulAsg(ModInt... mis) { for (ModInt m : mis) mulAsg(m); return this; } public ModInt mulAsg(long mi) { this.value = ma.mul(value, ma.remainder(mi)); return this; } public ModInt divAsg(ModInt mi) { this.value = ma.div(value, mi.value); return this; } public ModInt divAsg(long mi) { this.value = ma.div(value, ma.remainder(mi)); return this; } public ModInt powAsg(ModInt mi) { this.value = ma.pow(value, mi.value()); return this; } public ModInt powAsg(long mi) { this.value = ma.pow(value, mi); return this; } @Override public String toString() { return String.valueOf(value()); } @Override public boolean equals(Object o) { if (o instanceof ModInt) { ModInt mi = (ModInt) o; return mod() == mi.mod() && value() == mi.value(); } return false; } @Override public int hashCode() { return (1 * 37 + mod()) * 37 + value(); } } private static abstract class ModArithmetic { abstract int mod(); abstract int remainder(long value); abstract int add(int a, int b); abstract int sub(int a, int b); abstract int mul(int a, int b); int div(int a, int b) { return mul(a, inv(b)); } int inv(int a) { int b = mod(); if (b == 1) return 0; long u = 1, v = 0; while (b >= 1) { int t = a / b; a -= t * b; int tmp1 = a; a = b; b = tmp1; u -= t * v; long tmp2 = u; u = v; v = tmp2; } if (a != 1) throw new ArithmeticException("divide by zero"); return remainder(u); } int pow(int a, long b) { if (b < 0) throw new ArithmeticException("negative power"); int r = 1; int x = a; while (b > 0) { if ((b & 1) == 1) r = mul(r, x); x = mul(x, x); b >>= 1; } return r; } static ModArithmetic of(int mod) { if (mod <= 0) { throw new IllegalArgumentException(); } else if (mod == 1) { return new ModArithmetic1(); } else if (mod == 2) { return new ModArithmetic2(); } else if (mod == 998244353) { return new ModArithmetic998244353(); } else if (mod == 1000000007) { return new ModArithmetic1000000007(); } else if ((mod & 1) == 1) { return new ModArithmeticMontgomery(mod); } else { return new ModArithmeticBarrett(mod); } } private static final class ModArithmetic1 extends ModArithmetic { int mod() { return 1; } int remainder(long value) { return 0; } int add(int a, int b) { return 0; } int sub(int a, int b) { return 0; } int mul(int a, int b) { return 0; } int pow(int a, long b) { return 0; } } private static final class ModArithmetic2 extends ModArithmetic { int mod() { return 2; } int remainder(long value) { return (int) (value & 1); } int add(int a, int b) { return a ^ b; } int sub(int a, int b) { return a ^ b; } int mul(int a, int b) { return a & b; } } private static final class ModArithmetic998244353 extends ModArithmetic { private final int mod = 998244353; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmetic1000000007 extends ModArithmetic { private final int mod = 1000000007; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmeticMontgomery extends ModArithmeticDynamic { private final long negInv; private final long r2; private ModArithmeticMontgomery(int mod) { super(mod); long inv = 0; long s = 1, t = 0; for (int i = 0; i < 32; i++) { if ((t & 1) == 0) { t += mod; inv += s; } t >>= 1; s <<= 1; } long r = (1l << 32) % mod; this.negInv = inv; this.r2 = (r * r) % mod; } private int generate(long x) { return reduce(x * r2); } private int reduce(long x) { x = (x + ((x * negInv) & 0xffff_ffffl) * mod) >>> 32; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return generate((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } @Override int inv(int a) { return super.inv(reduce(a)); } @Override int pow(int a, long b) { return generate(super.pow(a, b)); } } private static final class ModArithmeticBarrett extends ModArithmeticDynamic { private static final long mask = 0xffff_ffffl; private final long mh; private final long ml; private ModArithmeticBarrett(int mod) { super(mod); long a = (1l << 32) / mod; long b = (1l << 32) % mod; long m = a * a * mod + 2 * a * b + (b * b) / mod; mh = m >>> 32; ml = m & mask; } private int reduce(long x) { long z = (x & mask) * ml; z = (x & mask) * mh + (x >>> 32) * ml + (z >>> 32); z = (x >>> 32) * mh + (z >>> 32); x -= z * mod; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } } private static class ModArithmeticDynamic extends ModArithmetic { final int mod; ModArithmeticDynamic(int mod) { this.mod = mod; } int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int sum = a + b; return sum >= mod ? sum - mod : sum; } int sub(int a, int b) { int sum = a - b; return sum < 0 ? sum + mod : sum; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } } } final class ContestInputStream extends FilterInputStream { protected final byte[] buf; protected int pos = 0; protected int lim = 0; private final char[] cbuf; public ContestInputStream() { super(System.in); this.buf = new byte[1 << 13]; this.cbuf = new char[1 << 20]; } boolean hasRemaining() throws IOException { if (pos < lim) return true; lim = in.read(buf); pos = 0; return lim > 0; } final int remaining() throws IOException { if (pos >= lim) { lim = in.read(buf); pos = 0; } return lim - pos; } @Override public final int available() throws IOException { if (pos < lim) return lim - pos + in.available(); return in.available(); } @Override public final long skip(long n) throws IOException { if (pos < lim) { int rem = lim - pos; if (n < rem) { pos += n; return n; } pos = lim; return rem; } return in.skip(n); } @Override public final int read() throws IOException { if (hasRemaining()) return buf[pos++]; return -1; } @Override public final int read(byte[] b, int off, int len) throws IOException { if (pos < lim) { int rem = Math.min(lim - pos, len); for (int i = 0; i < rem; i++) b[off + i] = buf[pos + i]; pos += rem; return rem; } return in.read(b, off, len); } public final char[] readToken() throws IOException { int cpos = 0; int rem; byte b; l: while ((rem = remaining()) > 0) { for (int i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } char[] arr = new char[cpos]; for (int i = 0; i < cpos; i++) arr[i] = cbuf[i]; return arr; } public final int readToken(char[] cbuf, int off) throws IOException { int cpos = off; int rem; byte b; l: while ((rem = remaining()) > 0) { for (int i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } return cpos - off; } public final int readToken(char[] cbuf) throws IOException { return readToken(cbuf, 0); } public final String next() throws IOException { int cpos = 0; int rem; byte b; l: while ((rem = remaining()) > 0) { for (int i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } return String.valueOf(cbuf, 0, cpos); } public final char[] nextCharArray() throws IOException { return readToken(); } public final int nextInt() throws IOException { if (!hasRemaining()) return 0; int value = 0; byte b = buf[pos++]; if (b == 0x2d) { while (hasRemaining() && (b = buf[pos++]) > 0x20) value = value * 10 - b + 0x30; } else { do { value = value * 10 + b - 0x30; } while (hasRemaining() && (b = buf[pos++]) > 0x20); } if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; return value; } public final long nextLong() throws IOException { if (!hasRemaining()) return 0L; long value = 0L; byte b = buf[pos++]; if (b == 0x2d) { while (hasRemaining() && (b = buf[pos++]) > 0x20) value = value * 10 - b + 0x30; } else { do { value = value * 10 + b - 0x30; } while (hasRemaining() && (b = buf[pos++]) > 0x20); } if (b == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; return value; } public final char nextChar() throws IOException { if (!hasRemaining()) throw new EOFException(); final char c = (char) buf[pos++]; if (hasRemaining() && buf[pos++] == 0x0d && hasRemaining() && buf[pos] == 0x0a) pos++; return c; } public final float nextFloat() throws IOException { return Float.parseFloat(next()); } public final double nextDouble() throws IOException { return Double.parseDouble(next()); } public final boolean[] nextBooleanArray(char ok) throws IOException { char[] s = readToken(); int n = s.length; boolean[] t = new boolean[n]; for (int i = 0; i < n; i++) t[i] = s[i] == ok; return t; } public final boolean[][] nextBooleanMatrix(int h, int w, char ok) throws IOException { boolean[][] s = new boolean[h][]; for (int i = 0; i < h; i++) { char[] t = readToken(); int n = t.length; s[i] = new boolean[n]; for (int j = 0; j < n; j++) s[i][j] = t[j] == ok; } return s; } public final String[] nextStringArray(int len) throws IOException { String[] arr = new String[len]; for (int i = 0; i < len; i++) arr[i] = next(); return arr; } public final int[] nextIntArray(int len) throws IOException { int[] arr = new int[len]; for (int i = 0; i < len; i++) arr[i] = nextInt(); return arr; } public final int[] nextIntArray(int len, java.util.function.IntUnaryOperator map) throws IOException { int[] arr = new int[len]; for (int i = 0; i < len; i++) arr[i] = map.applyAsInt(nextInt()); return arr; } public final long[] nextLongArray(int len, java.util.function.LongUnaryOperator map) throws IOException { long[] arr = new long[len]; for (int i = 0; i < len; i++) arr[i] = map.applyAsLong(nextLong()); return arr; } public final int[][] nextIntMatrix(int h, int w) throws IOException { int[][] arr = new int[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = nextInt(); return arr; } public final int[][] nextIntMatrix(int h, int w, java.util.function.IntUnaryOperator map) throws IOException { int[][] arr = new int[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = map.applyAsInt(nextInt()); return arr; } public final long[] nextLongArray(int len) throws IOException { long[] arr = new long[len]; for (int i = 0; i < len; i++) arr[i] = nextLong(); return arr; } public final long[][] nextLongMatrix(int h, int w) throws IOException { long[][] arr = new long[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = nextLong(); return arr; } public final float[] nextFloatArray(int len) throws IOException { float[] arr = new float[len]; for (int i = 0; i < len; i++) arr[i] = nextFloat(); return arr; } public final double[] nextDoubleArray(int len) throws IOException { double[] arr = new double[len]; for (int i = 0; i < len; i++) arr[i] = nextDouble(); return arr; } public final char[][] nextCharMatrix(int h, int w) throws IOException { char[][] arr = new char[h][]; for (int i = 0; i < h; i++) arr[i] = readToken(); return arr; } public final void nextThrow() throws IOException { next(); return; } public final void nextThrow(int n) throws IOException { for (int i = 0; i < n; i++) nextThrow(); return; } } final class ContestOutputStream extends FilterOutputStream implements Appendable { protected final byte[] buf; protected int pos = 0; public ContestOutputStream() { super(System.out); this.buf = new byte[1 << 13]; } @Override public void flush() throws IOException { out.write(buf, 0, pos); pos = 0; out.flush(); } void put(byte b) throws IOException { if (pos >= buf.length) flush(); buf[pos++] = b; } int remaining() throws IOException { if (pos >= buf.length) flush(); return buf.length - pos; } @Override public void write(int b) throws IOException { put((byte) b); } @Override public void write(byte[] b, int off, int len) throws IOException { int o = off; int l = len; while (l > 0) { int rem = Math.min(remaining(), l); for (int i = 0; i < rem; i++) buf[pos + i] = b[o + i]; pos += rem; o += rem; l -= rem; } } @Override public ContestOutputStream append(char c) throws IOException { put((byte) c); return this; } @Override public ContestOutputStream append(CharSequence csq, int start, int end) throws IOException { int off = start; int len = end - start; while (len > 0) { int rem = Math.min(remaining(), len); for (int i = 0; i < rem; i++) buf[pos + i] = (byte) csq.charAt(off + i); pos += rem; off += rem; len -= rem; } return this; } @Override public ContestOutputStream append(CharSequence csq) throws IOException { return append(csq, 0, csq.length()); } public ContestOutputStream append(char[] arr, int off, int len) throws IOException { int o = off; int l = len; while (l > 0) { int rem = Math.min(remaining(), l); for (int i = 0; i < rem; i++) buf[pos + i] = (byte) arr[o + i]; pos += rem; o += rem; l -= rem; } return this; } public ContestOutputStream print(char[] arr) throws IOException { return append(arr, 0, arr.length).newLine(); } public ContestOutputStream print(boolean value) throws IOException { if (value) return append("o"); return append("x"); } public ContestOutputStream println(boolean value) throws IOException { if (value) return append("o\n"); return append("x\n"); } public ContestOutputStream print(boolean[][] value) throws IOException { final int n = value.length, m = value[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) print(value[i][j]); newLine(); } return this; } public ContestOutputStream print(int value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(int value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(long value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(long value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(float value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(float value) throws IOException { return append(String.valueOf(value)).newLine(); } private ContestOutputStream dtos(double x, int n) throws IOException { if (x < 0) { append('-'); x = -x; } x += Math.pow(10, -n) / 2; long longx = (long) x; print(longx); append('.'); x -= longx; for (int i = 0; i < n; i++) { x *= 10; int intx = (int) x; print(intx); x -= intx; } return this; } public ContestOutputStream print(double value) throws IOException { return dtos(value, 20); } public ContestOutputStream println(double value) throws IOException { return dtos(value, 20).newLine(); } public ContestOutputStream print(char value) throws IOException { return append(value); } public ContestOutputStream println(char value) throws IOException { return append(value).newLine(); } public ContestOutputStream print(String value) throws IOException { return append(value); } public ContestOutputStream println(String value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(Object value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(Object value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream printYN(boolean yes) throws IOException { if (yes) return println("Yes"); return println("No"); } public ContestOutputStream printAB(boolean yes) throws IOException { if (yes) return println("Alice"); return println("Bob"); } public ContestOutputStream print(CharSequence[] arr) throws IOException { if (arr.length > 0) { append(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').append(arr[i]); } return this; } public ContestOutputStream print(int[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream print(int[] arr, int length) throws IOException { if (length > 0) print(arr[0]); for (int i = 1; i < length; i++) append('\u0020').print(arr[i]); newLine(); return this; } public ContestOutputStream println(int[] arr) throws IOException { for (int i : arr) print(i).newLine(); return this; } public ContestOutputStream println(int[] arr, int length) throws IOException { for (int i = 0; i < length; i++) println(arr[i]); return this; } public ContestOutputStream print(boolean[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream print(long[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream print(long[] arr, int length) throws IOException { if (length > 0) print(arr[0]); for (int i = 1; i < length; i++) append('\u0020').print(arr[i]); newLine(); return this; } public ContestOutputStream println(long[] arr, int length) throws IOException { for (int i = 0; i < length; i++) println(arr[i]); return this; } public ContestOutputStream println(long[] arr) throws IOException { for (long i : arr) print(i).newLine(); return this; } public ContestOutputStream print(float[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return this; } public ContestOutputStream println(float[] arr) throws IOException { for (float i : arr) print(i).newLine(); return this; } public ContestOutputStream print(double[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return newLine(); } public ContestOutputStream println(double[] arr) throws IOException { for (double i : arr) print(i).newLine(); return this; } public ContestOutputStream print(java.util.ArrayList<?> arr) throws IOException { if (!arr.isEmpty()) { final int n = arr.size(); print(arr.get(0)); for (int i = 1; i < n; i++) print(" ").print(arr.get(i)); } return newLine(); } public ContestOutputStream println(java.util.ArrayList<?> arr) throws IOException { final int n = arr.size(); for (int i = 0; i < n; i++) println(arr.get(i)); return this; } public ContestOutputStream newLine() throws IOException { return append(System.lineSeparator()); } public ContestOutputStream endl() throws IOException { newLine().flush(); return this; } public ContestOutputStream print(int[][] arr) throws IOException { for (int[] i : arr) print(i); return this; } public ContestOutputStream print(long[][] arr) throws IOException { for (long[] i : arr) print(i); return this; } public ContestOutputStream print(char[][] arr) throws IOException { for (char[] i : arr) print(i); return this; } public ContestOutputStream print(Object[][] arr) throws IOException { for (Object[] i : arr) print(i); return this; } public ContestOutputStream println() throws IOException { return newLine(); } public ContestOutputStream print(Object... arr) throws IOException { for (Object i : arr) print(i); return this; } public ContestOutputStream println(Object... arr) throws IOException { for (Object i : arr) print(i); return newLine(); } }
ConDefects/ConDefects/Code/abc266_g/Java/37104778
condefects-java_data_445
import java.io.PrintWriter; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.Stack; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Predicate; public class Main { public static void main(String[] args) throws Exception { ContestScanner in = new ContestScanner(System.in); ContestPrinter out = new ContestPrinter(System.out); Task solver = new Task(); solver.solve(in, out); out.flush(); out.close(); } } class Task { long mod = 998244353; long powmod(long a, long b) { long ans = 1, d = a; while (b > 0) { if (b % 2 == 1) ans = ans * d % mod; b >>= 1; d = d * d % mod; } return ans; } long[] fac, inv; long getC(int n, int m) { return fac[n] * inv[m] % mod * inv[n - m] % mod; } long f(int k, int r, int g, int b) { return fac[k + r + g + b] * inv[k] % mod * inv[r] % mod * inv[g] % mod * inv[b] % mod; } public void solve(ContestScanner in, ContestPrinter out) throws Exception { int r = in.nextInt(); int g = in.nextInt(); int b = in.nextInt(); int k = in.nextInt(); fac = new long[r + g + b + 1]; inv = new long[r + g + b + 1]; fac[0] = 1; inv[0] = 1; for (int i = 1; i <= r + g + b; i++) { fac[i] = fac[i - 1] * i % mod; inv[i] = inv[i - 1] * powmod(i, mod - 2) % mod; } long ans = 0; int m = Math.min(r, g); for (int i = k; i <= m; i++) { if (((m - i) & 1) == 0) { ans += getC(i, k) * f(i, r - i, g - i, b) % mod; ans %= mod; } else { ans -= getC(i, k) * f(i, r - i, g - i, b) % mod; ans = (ans % mod + mod) % mod; } } out.println(ans); } } class Pair<S extends Comparable<S>, T extends Comparable<T>> implements Comparable<Pair<S,T>>{ S first; T second; public Pair(S s, T t){ first = s; second = t; } public S getFirst(){return first;} public T getSecond(){return second;} public boolean equals(Object another){ if(this==another) return true; if(!(another instanceof Pair)) return false; Pair otherPair = (Pair)another; return this.first.equals(otherPair.first) && this.second.equals(otherPair.second); } public int compareTo(Pair<S,T> another){ java.util.Comparator<Pair<S,T>> comp1 = java.util.Comparator.comparing(Pair::getFirst); java.util.Comparator<Pair<S,T>> comp2 = comp1.thenComparing(Pair::getSecond); return comp2.compare(this, another); } public int hashCode(){ return first.hashCode() * 10007 + second.hashCode(); } public String toString(){ return String.format("(%s, %s)", first, second); } } class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in){ this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner(){ this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = this.nextInt(); return array; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = this.next(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } } class ContestPrinter extends java.io.PrintWriter { public ContestPrinter(java.io.PrintStream stream) { super(stream); } public ContestPrinter(java.io.File file) throws java.io.FileNotFoundException { super(new java.io.PrintStream(file)); } public ContestPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public void printArray(int[] array){ this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n-1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map){ this.printArray(array, " ", map); } public void printArray(long[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public void printArray(long[] array){ this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n-1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map){ this.printArray(array, " ", map); } public <T> void printArray(T[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public <T> void printArray(T[] array){ this.printArray(array, " "); } public <T> void printArray(T[] array, String separator, java.util.function.UnaryOperator<T> map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.apply(array[i])); super.print(separator); } super.println(map.apply(array[n-1])); } public <T> void printArray(T[] array, java.util.function.UnaryOperator<T> map){ this.printArray(array, " ", map); } } import java.io.PrintWriter; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.Stack; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Predicate; public class Main { public static void main(String[] args) throws Exception { ContestScanner in = new ContestScanner(System.in); ContestPrinter out = new ContestPrinter(System.out); Task solver = new Task(); solver.solve(in, out); out.flush(); out.close(); } } class Task { long mod = 998244353; long powmod(long a, long b) { long ans = 1, d = a; while (b > 0) { if (b % 2 == 1) ans = ans * d % mod; b >>= 1; d = d * d % mod; } return ans; } long[] fac, inv; long getC(int n, int m) { return fac[n] * inv[m] % mod * inv[n - m] % mod; } long f(int k, int r, int g, int b) { return fac[k + r + g + b] * inv[k] % mod * inv[r] % mod * inv[g] % mod * inv[b] % mod; } public void solve(ContestScanner in, ContestPrinter out) throws Exception { int r = in.nextInt(); int g = in.nextInt(); int b = in.nextInt(); int k = in.nextInt(); fac = new long[r + g + b + 1]; inv = new long[r + g + b + 1]; fac[0] = 1; inv[0] = 1; for (int i = 1; i <= r + g + b; i++) { fac[i] = fac[i - 1] * i % mod; inv[i] = inv[i - 1] * powmod(i, mod - 2) % mod; } long ans = 0; int m = Math.min(r, g); for (int i = k; i <= m; i++) { if (((i - k) & 1) == 0) { ans += getC(i, k) * f(i, r - i, g - i, b) % mod; ans %= mod; } else { ans -= getC(i, k) * f(i, r - i, g - i, b) % mod; ans = (ans % mod + mod) % mod; } } out.println(ans); } } class Pair<S extends Comparable<S>, T extends Comparable<T>> implements Comparable<Pair<S,T>>{ S first; T second; public Pair(S s, T t){ first = s; second = t; } public S getFirst(){return first;} public T getSecond(){return second;} public boolean equals(Object another){ if(this==another) return true; if(!(another instanceof Pair)) return false; Pair otherPair = (Pair)another; return this.first.equals(otherPair.first) && this.second.equals(otherPair.second); } public int compareTo(Pair<S,T> another){ java.util.Comparator<Pair<S,T>> comp1 = java.util.Comparator.comparing(Pair::getFirst); java.util.Comparator<Pair<S,T>> comp2 = comp1.thenComparing(Pair::getSecond); return comp2.compare(this, another); } public int hashCode(){ return first.hashCode() * 10007 + second.hashCode(); } public String toString(){ return String.format("(%s, %s)", first, second); } } class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in){ this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner(){ this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = this.nextInt(); return array; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = this.next(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } } class ContestPrinter extends java.io.PrintWriter { public ContestPrinter(java.io.PrintStream stream) { super(stream); } public ContestPrinter(java.io.File file) throws java.io.FileNotFoundException { super(new java.io.PrintStream(file)); } public ContestPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public void printArray(int[] array){ this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n-1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map){ this.printArray(array, " ", map); } public void printArray(long[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public void printArray(long[] array){ this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n-1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map){ this.printArray(array, " ", map); } public <T> void printArray(T[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public <T> void printArray(T[] array){ this.printArray(array, " "); } public <T> void printArray(T[] array, String separator, java.util.function.UnaryOperator<T> map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.apply(array[i])); super.print(separator); } super.println(map.apply(array[n-1])); } public <T> void printArray(T[] array, java.util.function.UnaryOperator<T> map){ this.printArray(array, " ", map); } }
ConDefects/ConDefects/Code/abc266_g/Java/37942863
condefects-java_data_446
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = sc.nextInt(); } int maxDiff[] = new int[n]; int minDiff[] = new int[n]; int max = 0; int min = Integer.MAX_VALUE; for(int i = 0; i < n; i++) { if(i == 0) { maxDiff[i] = minDiff[i] = a[i] == 1 ? 1 : -1; } else { if(a[i] == 0) { maxDiff[i] = Math.max(-1, maxDiff[i - 1] - 1); minDiff[i] = Math.min(-1, minDiff[i - 1] - 1); } else { maxDiff[i] = Math.max(1, maxDiff[i - 1] + 1); minDiff[i] = Math.min(1, minDiff[i - 1] + 1); } } max = Math.max(max, maxDiff[i]); min = Math.min(min, minDiff[i]); // System.out.println("i = " + i + " " + maxDiff[i] + " " + minDiff[i]); } // System.out.println(max + " " + min); System.out.println(max - min + 1); } } import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = sc.nextInt(); } int maxDiff[] = new int[n]; int minDiff[] = new int[n]; int max = 0; int min = 0; for(int i = 0; i < n; i++) { if(i == 0) { maxDiff[i] = minDiff[i] = a[i] == 1 ? 1 : -1; } else { if(a[i] == 0) { maxDiff[i] = Math.max(-1, maxDiff[i - 1] - 1); minDiff[i] = Math.min(-1, minDiff[i - 1] - 1); } else { maxDiff[i] = Math.max(1, maxDiff[i - 1] + 1); minDiff[i] = Math.min(1, minDiff[i - 1] + 1); } } max = Math.max(max, maxDiff[i]); min = Math.min(min, minDiff[i]); // System.out.println("i = " + i + " " + maxDiff[i] + " " + minDiff[i]); } // System.out.println(max + " " + min); System.out.println(max - min + 1); } }
ConDefects/ConDefects/Code/arc137_b/Java/31957035
condefects-java_data_447
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int h = Integer.parseInt(br.readLine()); h *= (12800000 + h); System.out.println(Math.sqrt(h)); } } import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Double h = Double.parseDouble(br.readLine()); h *= (12800000 + h); System.out.println(Math.sqrt(h)); } }
ConDefects/ConDefects/Code/abc239_a/Java/31478784
condefects-java_data_448
import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int a = sc.nextInt(); if (1 <= a && a <= 100000){ double b = a * (12800000 + a); System.out.println(Math.sqrt(b)); } } } import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); double a = sc.nextInt(); if (1 <= a && a <= 100000){ double b = a * (12800000 + a); System.out.println(Math.sqrt(b)); } } }
ConDefects/ConDefects/Code/abc239_a/Java/39784740
condefects-java_data_449
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { private static final boolean DEBUG = false; public static class Counts { private long multiplier; private long counts; private long minCounts; public Counts(long multiplier, long counts) { this.multiplier = multiplier; this.counts = counts; } public long getMultiplier() { return multiplier; } public void setCounts(long counts) { this.counts = counts; } public long getCounts() { return counts; } public void setMinCounts(long minCounts) { this.minCounts = minCounts; } public long getMinCounts() { return minCounts; } } public static Counts createCounts(long n, long k, long c) { // 3の累乗系列で分割する Counts counts = new Counts(c, n / c); long sum = 0; while (c > 1) { long count = n / c; sum += count; n -= c * count; c /= 3; } sum += n; counts.setMinCounts(sum); return counts; } public static boolean test(long n, long k, long c) { if (DEBUG) { System.err.println("N: " + n + ", K: " + k + ", C: " + c); } if (c <= 1) { return n == k; } Counts counts = createCounts(n, k, c); if (DEBUG) { System.err.println("multiplier: " + counts.getMultiplier() + ", counts: " + counts.getCounts() + ", minCounts: " + counts.getMinCounts()); } long minCounts = counts.getMinCounts(); long count = counts.getCounts(); if (minCounts > k) { // どうにもならない return false; } else if (minCounts == k) { // 現状の構成で成立している return true; } else { if ((k - minCounts) % 2 != 0) { return false; } else { return true; } // // この階層から減らすべき数を計算する // long t = (k - minCounts) / 2; // if (t > count) { // t = count; // } // if (DEBUG) { // System.err.println("K: " + k + ", T: " + t + ", counts: " + count // + ", minCounts: " + minCounts); // } // long countMinusT = count - t; // return test(n - counts.getMultiplier() * countMinusT, // k - countMinusT, c / 3); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); long[] n = new long[t]; long[] k = new long[t]; for (int i = 0; i < t; ++i) { n[i] = scanner.nextLong(); k[i] = scanner.nextLong(); } scanner.close(); for (int i = 0; i < t; ++i) { long n0 = n[i]; long k0 = k[i]; long c0 = 1; if (n[i] >= 3) { while (c0 < n[i]) { c0 *= 3; } c0 /= 3; if (test(n0, k0, c0)) { System.out.println("Yes"); } else { System.out.println("No"); } } else { System.out.println(n[i] == k[i]? "Yes": "No"); } } } } import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { private static final boolean DEBUG = false; public static class Counts { private long multiplier; private long counts; private long minCounts; public Counts(long multiplier, long counts) { this.multiplier = multiplier; this.counts = counts; } public long getMultiplier() { return multiplier; } public void setCounts(long counts) { this.counts = counts; } public long getCounts() { return counts; } public void setMinCounts(long minCounts) { this.minCounts = minCounts; } public long getMinCounts() { return minCounts; } } public static Counts createCounts(long n, long k, long c) { // 3の累乗系列で分割する Counts counts = new Counts(c, n / c); long sum = 0; while (c > 1) { long count = n / c; sum += count; n -= c * count; c /= 3; } sum += n; counts.setMinCounts(sum); return counts; } public static boolean test(long n, long k, long c) { if (DEBUG) { System.err.println("N: " + n + ", K: " + k + ", C: " + c); } if (c <= 1) { return n == k; } Counts counts = createCounts(n, k, c); if (DEBUG) { System.err.println("multiplier: " + counts.getMultiplier() + ", counts: " + counts.getCounts() + ", minCounts: " + counts.getMinCounts()); } long minCounts = counts.getMinCounts(); long count = counts.getCounts(); if (minCounts > k) { // どうにもならない return false; } else if (minCounts == k) { // 現状の構成で成立している return true; } else { if ((k - minCounts) % 2 != 0) { return false; } else { return true; } // // この階層から減らすべき数を計算する // long t = (k - minCounts) / 2; // if (t > count) { // t = count; // } // if (DEBUG) { // System.err.println("K: " + k + ", T: " + t + ", counts: " + count // + ", minCounts: " + minCounts); // } // long countMinusT = count - t; // return test(n - counts.getMultiplier() * countMinusT, // k - countMinusT, c / 3); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); long[] n = new long[t]; long[] k = new long[t]; for (int i = 0; i < t; ++i) { n[i] = scanner.nextLong(); k[i] = scanner.nextLong(); } scanner.close(); for (int i = 0; i < t; ++i) { long n0 = n[i]; long k0 = k[i]; long c0 = 1; if (n[i] >= 3) { while (c0 <= n[i]) { c0 *= 3; } c0 /= 3; if (test(n0, k0, c0)) { System.out.println("Yes"); } else { System.out.println("No"); } } else { System.out.println(n[i] == k[i]? "Yes": "No"); } } } }
ConDefects/ConDefects/Code/arc164_a/Java/43466334
condefects-java_data_450
import java.io.*; import java.util.*; class Main{ static boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null; static void dbg(Object... o){if(LOCAL)System.err.println(Arrays.deepToString(o));} public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out = new PrintWriter(System.out); int T = fs.nextInt(); for (int tt=0; tt<T; tt++) { long n = fs.nextLong(); long k = fs.nextLong(); long min = 0; long N = n; long pow3 = 1; for(int i=0; i<36; i++) pow3*=3; while(n>0) { if(pow3>n) { pow3/=3; continue; } min+=n/pow3; n = n%pow3; } // out.println(min); if(k>=min && k%2==N%2) { out.println("Yes"); } else { out.println("No"); } } out.close(); } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readArrayLong(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } } import java.io.*; import java.util.*; class Main{ static boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null; static void dbg(Object... o){if(LOCAL)System.err.println(Arrays.deepToString(o));} public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out = new PrintWriter(System.out); int T = fs.nextInt(); for (int tt=0; tt<T; tt++) { long n = fs.nextLong(); long k = fs.nextLong(); long min = 0; long N = n; long pow3 = 1; for(int i=0; i<39; i++) pow3*=3; while(n>0) { if(pow3>n) { pow3/=3; continue; } min+=n/pow3; n = n%pow3; } // out.println(min); if(k>=min && k%2==N%2) { out.println("Yes"); } else { out.println("No"); } } out.close(); } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readArrayLong(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } }
ConDefects/ConDefects/Code/arc164_a/Java/43440901
condefects-java_data_451
import static java.lang.Math.*; import static java.util.Arrays.*; import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.function.*; class Solver{ long st = System.currentTimeMillis(); long elapsed(){ return System.currentTimeMillis() -st; } void reset(){ st = System.currentTimeMillis(); } static int infI = (int) 1e9; static long infL = (long) 1e18; // static long mod = (int) 1e9 +7; static long mod = 998244353; static String yes = "Yes"; static String no = "No"; Random rd = ThreadLocalRandom.current(); MyReader in = new MyReader(System.in); MyWriter out = new MyWriter(System.out); MyWriter log = new MyWriter(System.err){ @Override void println(Object obj){ super.println(obj == null ? "null" : obj); }; @Override protected void ln(){ super.ln(); flush(); }; }; int T = in.it(); Object solve(){ while (T-- > 0) out.println(solve(in.lg(),in.lg())); return null; } private Object solve(long N,long K){ char[] S = Long.toString(N,3).toCharArray(); int cnt = 0; for (var c:S) cnt += c -'0'; return N >= K && ((cnt ^K) &1) == 0; } Node search(Node root,char[] s){ Node nd = root; for (var c:s) { if (nd.cld[c] == null) nd.cld[c] = new Node(nd,c); nd = nd.cld[c]; } return nd; } } class Node{ Node par; int c; int cnt = 0; Node[] cld = new Node[26]; public Node(Node par,int c){ this.par = par; this.c = c; } } class Util{ static int[] arrI(int N,IntUnaryOperator f){ int[] ret = new int[N]; setAll(ret,f); return ret; } static long[] arrL(int N,IntToLongFunction f){ long[] ret = new long[N]; setAll(ret,f); return ret; } static double[] arrD(int N,IntToDoubleFunction f){ double[] ret = new double[N]; setAll(ret,f); return ret; } static <T> T[] arr(T[] arr,IntFunction<T> f){ setAll(arr,f); return arr; } } class MyReader{ byte[] buf = new byte[1 <<16]; int ptr = 0; int tail = 0; InputStream in; MyReader(InputStream in){ this.in = in; } byte read(){ if (ptr == tail) try { tail = in.read(buf); ptr = 0; } catch (IOException e) {} return buf[ptr++]; } boolean isPrintable(byte c){ return 32 < c && c < 127; } boolean isNum(byte c){ return 47 < c && c < 58; } byte nextPrintable(){ byte ret = read(); while (!isPrintable(ret)) ret = read(); return ret; } int it(){ return toIntExact(lg()); } int[] it(int N){ return Util.arrI(N,i -> it()); } int[][] it(int H,int W){ return Util.arr(new int[H][],i -> it(W)); } int idx(){ return it() -1; } int[] idx(int N){ return Util.arrI(N,i -> idx()); } int[][] idx(int H,int W){ return Util.arr(new int[H][],i -> idx(W)); } int[][] qry(int Q){ return Util.arr(new int[Q][],i -> new int[]{idx(), idx(), i}); } long lg(){ byte i = nextPrintable(); boolean negative = i == 45; long n = negative ? 0 : i -'0'; while (isPrintable(i = read())) n = 10 *n +i -'0'; return negative ? -n : n; } long[] lg(int N){ return Util.arrL(N,i -> lg()); } long[][] lg(int H,int W){ return Util.arr(new long[H][],i -> lg(W)); } double dbl(){ return Double.parseDouble(str()); } double[] dbl(int N){ return Util.arrD(N,i -> dbl()); } double[][] dbl(int H,int W){ return Util.arr(new double[H][],i -> dbl(W)); } char[] ch(){ return str().toCharArray(); } char[][] ch(int H){ return Util.arr(new char[H][],i -> ch()); } String line(){ StringBuilder sb = new StringBuilder(); for (byte c;(c = read()) != '\n';) sb.append((char) c); return sb.toString(); } String str(){ StringBuilder sb = new StringBuilder(); sb.append((char) nextPrintable()); for (byte c;isPrintable(c = read());) sb.append((char) c); return sb.toString(); } String[] str(int N){ return Util.arr(new String[N],i -> str()); } } class MyWriter{ OutputStream out; byte[] buf = new byte[1 <<16]; byte[] ibuf = new byte[20]; int tail = 0; MyWriter(OutputStream out){ this.out = out; } void flush(){ try { out.write(buf,0,tail); tail = 0; } catch (IOException e) { e.printStackTrace(); } } protected void ln(){ write((byte) '\n'); } private void write(byte b){ buf[tail++] = b; if (tail == buf.length) flush(); } private void write(byte[] b,int off,int len){ for (int i = off;i < off +len;i++) write(b[i]); } private void write(long n){ if (n < 0) { n = -n; write((byte) '-'); } int i = ibuf.length; do { ibuf[--i] = (byte) (n %10 +'0'); n /= 10; } while (n > 0); write(ibuf,i,ibuf.length -i); } private void print(Object obj){ if (obj instanceof Boolean) print((boolean) obj ? Solver.yes : Solver.no); else if (obj instanceof Character) write((byte) (char) obj); else if (obj instanceof Integer) write((int) obj); else if (obj instanceof Long) write((long) obj); else if (obj instanceof char[]) for (char b:(char[]) obj) write((byte) b); else if (obj.getClass().isArray()) { int l = Array.getLength(obj); for (int i = 0;i < l;i++) { print(Array.get(obj,i)); if (i +1 < l) write((byte) ' '); } } else for (char b:Objects.toString(obj).toCharArray()) write((byte) b); } void println(Object obj){ if (obj == null) return; if (obj instanceof Collection<?>) for (Object e:(Collection<?>) obj) println(e); else if (obj.getClass().isArray() && Array.getLength(obj) > 0 && !(Array.get(obj,0) instanceof char[]) && Array.get(obj,0).getClass().isArray()) { int l = Array.getLength(obj); for (int i = 0;i < l;i++) println(Array.get(obj,i)); } else { print(obj); ln(); } } } class Main{ public static void main(String[] args) throws Exception{ Solver solver = new Solver(); Optional.ofNullable(solver.solve()).ifPresent(solver.out::println); solver.out.flush(); solver.log.println(solver.elapsed()); } } import static java.lang.Math.*; import static java.util.Arrays.*; import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.function.*; class Solver{ long st = System.currentTimeMillis(); long elapsed(){ return System.currentTimeMillis() -st; } void reset(){ st = System.currentTimeMillis(); } static int infI = (int) 1e9; static long infL = (long) 1e18; // static long mod = (int) 1e9 +7; static long mod = 998244353; static String yes = "Yes"; static String no = "No"; Random rd = ThreadLocalRandom.current(); MyReader in = new MyReader(System.in); MyWriter out = new MyWriter(System.out); MyWriter log = new MyWriter(System.err){ @Override void println(Object obj){ super.println(obj == null ? "null" : obj); }; @Override protected void ln(){ super.ln(); flush(); }; }; int T = in.it(); Object solve(){ while (T-- > 0) out.println(solve(in.lg(),in.lg())); return null; } private Object solve(long N,long K){ char[] S = Long.toString(N,3).toCharArray(); int cnt = 0; for (var c:S) cnt += c -'0'; return N >= K && cnt <= K && ((cnt ^K) &1) == 0; } Node search(Node root,char[] s){ Node nd = root; for (var c:s) { if (nd.cld[c] == null) nd.cld[c] = new Node(nd,c); nd = nd.cld[c]; } return nd; } } class Node{ Node par; int c; int cnt = 0; Node[] cld = new Node[26]; public Node(Node par,int c){ this.par = par; this.c = c; } } class Util{ static int[] arrI(int N,IntUnaryOperator f){ int[] ret = new int[N]; setAll(ret,f); return ret; } static long[] arrL(int N,IntToLongFunction f){ long[] ret = new long[N]; setAll(ret,f); return ret; } static double[] arrD(int N,IntToDoubleFunction f){ double[] ret = new double[N]; setAll(ret,f); return ret; } static <T> T[] arr(T[] arr,IntFunction<T> f){ setAll(arr,f); return arr; } } class MyReader{ byte[] buf = new byte[1 <<16]; int ptr = 0; int tail = 0; InputStream in; MyReader(InputStream in){ this.in = in; } byte read(){ if (ptr == tail) try { tail = in.read(buf); ptr = 0; } catch (IOException e) {} return buf[ptr++]; } boolean isPrintable(byte c){ return 32 < c && c < 127; } boolean isNum(byte c){ return 47 < c && c < 58; } byte nextPrintable(){ byte ret = read(); while (!isPrintable(ret)) ret = read(); return ret; } int it(){ return toIntExact(lg()); } int[] it(int N){ return Util.arrI(N,i -> it()); } int[][] it(int H,int W){ return Util.arr(new int[H][],i -> it(W)); } int idx(){ return it() -1; } int[] idx(int N){ return Util.arrI(N,i -> idx()); } int[][] idx(int H,int W){ return Util.arr(new int[H][],i -> idx(W)); } int[][] qry(int Q){ return Util.arr(new int[Q][],i -> new int[]{idx(), idx(), i}); } long lg(){ byte i = nextPrintable(); boolean negative = i == 45; long n = negative ? 0 : i -'0'; while (isPrintable(i = read())) n = 10 *n +i -'0'; return negative ? -n : n; } long[] lg(int N){ return Util.arrL(N,i -> lg()); } long[][] lg(int H,int W){ return Util.arr(new long[H][],i -> lg(W)); } double dbl(){ return Double.parseDouble(str()); } double[] dbl(int N){ return Util.arrD(N,i -> dbl()); } double[][] dbl(int H,int W){ return Util.arr(new double[H][],i -> dbl(W)); } char[] ch(){ return str().toCharArray(); } char[][] ch(int H){ return Util.arr(new char[H][],i -> ch()); } String line(){ StringBuilder sb = new StringBuilder(); for (byte c;(c = read()) != '\n';) sb.append((char) c); return sb.toString(); } String str(){ StringBuilder sb = new StringBuilder(); sb.append((char) nextPrintable()); for (byte c;isPrintable(c = read());) sb.append((char) c); return sb.toString(); } String[] str(int N){ return Util.arr(new String[N],i -> str()); } } class MyWriter{ OutputStream out; byte[] buf = new byte[1 <<16]; byte[] ibuf = new byte[20]; int tail = 0; MyWriter(OutputStream out){ this.out = out; } void flush(){ try { out.write(buf,0,tail); tail = 0; } catch (IOException e) { e.printStackTrace(); } } protected void ln(){ write((byte) '\n'); } private void write(byte b){ buf[tail++] = b; if (tail == buf.length) flush(); } private void write(byte[] b,int off,int len){ for (int i = off;i < off +len;i++) write(b[i]); } private void write(long n){ if (n < 0) { n = -n; write((byte) '-'); } int i = ibuf.length; do { ibuf[--i] = (byte) (n %10 +'0'); n /= 10; } while (n > 0); write(ibuf,i,ibuf.length -i); } private void print(Object obj){ if (obj instanceof Boolean) print((boolean) obj ? Solver.yes : Solver.no); else if (obj instanceof Character) write((byte) (char) obj); else if (obj instanceof Integer) write((int) obj); else if (obj instanceof Long) write((long) obj); else if (obj instanceof char[]) for (char b:(char[]) obj) write((byte) b); else if (obj.getClass().isArray()) { int l = Array.getLength(obj); for (int i = 0;i < l;i++) { print(Array.get(obj,i)); if (i +1 < l) write((byte) ' '); } } else for (char b:Objects.toString(obj).toCharArray()) write((byte) b); } void println(Object obj){ if (obj == null) return; if (obj instanceof Collection<?>) for (Object e:(Collection<?>) obj) println(e); else if (obj.getClass().isArray() && Array.getLength(obj) > 0 && !(Array.get(obj,0) instanceof char[]) && Array.get(obj,0).getClass().isArray()) { int l = Array.getLength(obj); for (int i = 0;i < l;i++) println(Array.get(obj,i)); } else { print(obj); ln(); } } } class Main{ public static void main(String[] args) throws Exception{ Solver solver = new Solver(); Optional.ofNullable(solver.solve()).ifPresent(solver.out::println); solver.out.flush(); solver.log.println(solver.elapsed()); } }
ConDefects/ConDefects/Code/arc164_a/Java/43929051
condefects-java_data_452
import java.util.*; import java.math.*; public class Main { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int t = sc.nextInt(); while(t-->0){ Long n = sc.nextLong(), k =sc.nextLong(); Long ans=0L; while(n>0) { ans+=n%3; n/=3; } if(ans<=k) System.out.println("Yes"); else System.out.println("No"); } } } import java.util.*; import java.math.*; public class Main { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int t = sc.nextInt(); while(t-->0){ Long n = sc.nextLong(), k =sc.nextLong(); Long ans=0L; while(n>0) { ans+=n%3; n/=3; } if(ans<=k && (k-ans)%2==0) System.out.println("Yes"); else System.out.println("No"); } } }
ConDefects/ConDefects/Code/arc164_a/Java/43981582
condefects-java_data_453
import java.io.*; import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); ArrayList<Long> threes = new ArrayList<>(); long x = 1; while (x <= 1000000000000000000L) { threes.add(x); x *= 3; } int t = sc.nextInt(); StringBuilder sb = new StringBuilder(); while (t-- > 0) { long n = sc.nextLong(); long k = sc.nextLong(); long count = 0; for (int i = threes.size() - 1; i >= 0; i--) { count += n / threes.get(i); n %= threes.get(i); } if (k % 2 == count % 2) { sb.append("Yes\n"); } else { sb.append("No\n"); } } System.out.print(sb); } } class Utilities { static String arrayToLineString(Object[] arr) { return Arrays.stream(arr).map(x -> x.toString()).collect(Collectors.joining("\n")); } static String arrayToLineString(int[] arr) { return String.join("\n", Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new)); } } class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); StringBuilder sb = new StringBuilder(); public Scanner() throws Exception { } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public int[] nextIntArray() throws Exception { return Stream.of(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } public String next() throws Exception { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } } import java.io.*; import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); ArrayList<Long> threes = new ArrayList<>(); long x = 1; while (x <= 1000000000000000000L) { threes.add(x); x *= 3; } int t = sc.nextInt(); StringBuilder sb = new StringBuilder(); while (t-- > 0) { long n = sc.nextLong(); long k = sc.nextLong(); long count = 0; for (int i = threes.size() - 1; i >= 0; i--) { count += n / threes.get(i); n %= threes.get(i); } if (k >= count && k % 2 == count % 2) { sb.append("Yes\n"); } else { sb.append("No\n"); } } System.out.print(sb); } } class Utilities { static String arrayToLineString(Object[] arr) { return Arrays.stream(arr).map(x -> x.toString()).collect(Collectors.joining("\n")); } static String arrayToLineString(int[] arr) { return String.join("\n", Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new)); } } class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); StringBuilder sb = new StringBuilder(); public Scanner() throws Exception { } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public int[] nextIntArray() throws Exception { return Stream.of(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } public String next() throws Exception { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }
ConDefects/ConDefects/Code/arc164_a/Java/43471677
condefects-java_data_454
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long t = sc.nextLong(); for(int i=0; i<t; i++) { long n = sc.nextLong(); long k = sc.nextLong(); boolean ans = false; Long l = 0L; String s = Long.toString(n, 3); String[] num = s.split(""); for(int j=0; j<s.length(); j++) { l += Integer.parseInt(num[j]); } if(k%2 != 0 && n%2 != 0) { if(l<=k && k<=n) { ans = true; } }else { if(l<=k && k<=n) { ans = true; } } System.out.println(ans ? "Yes":"No"); } } } import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long t = sc.nextLong(); for(int i=0; i<t; i++) { long n = sc.nextLong(); long k = sc.nextLong(); boolean ans = false; Long l = 0L; String s = Long.toString(n, 3); String[] num = s.split(""); for(int j=0; j<s.length(); j++) { l += Integer.parseInt(num[j]); } if(k%2 != 0 && n%2 != 0) { if(l<=k && k<=n) { ans = true; } }else if(k%2 == 0 && n%2 ==0){ if(l<=k && k<=n) { ans = true; } } System.out.println(ans ? "Yes":"No"); } } }
ConDefects/ConDefects/Code/arc164_a/Java/43464380
condefects-java_data_455
import java.util.*; public class Main{ public static void main (String args[]){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ long n=sc.nextLong(); long k=sc.nextLong(); long sum=0; while(n-->0){ sum+=n%3; n/=3; } if(sum<=k){ if((k-sum)%2==0){ System. out.println("Yes"); } else{ System. out.println("No"); }} else{ System.out.println("No");} } }} import java.util.*; public class Main{ public static void main (String args[]){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ long n=sc.nextLong(); long k=sc.nextLong(); long sum=0; while(n>0){ sum+=n%3; n/=3; } if(sum<=k){ if((k-sum)%2==0){ System. out.println("Yes"); } else{ System. out.println("No"); }} else{ System.out.println("No");} } }}
ConDefects/ConDefects/Code/arc164_a/Java/43439188
condefects-java_data_456
import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f, mod = 1000000007, mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = false; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static void solve(PrintWriter o) { try { int n = fReader.nextInt(); char[] s = fReader.nextString().toCharArray(); int q = fReader.nextInt(); int lower = -2, upper = -2; int[] time = new int[n]; Arrays.fill(time, -1); for(int i=0;i<q;i++) { int t = fReader.nextInt(); int x = fReader.nextInt(); x--; char c = fReader.nextChar(); if(t == 1) { s[x] = c; time[x] = i; } else if(t == 2) lower = i; else upper = i; } for(int i=0;i<n;i++) { if(upper > lower) { if(time[i] > upper) o.print(s[i]); else o.print(String.valueOf(s[i]).toUpperCase(Locale.ROOT)); } else if(upper < lower){ if(time[i] > upper) o.print(s[i]); else o.print(String.valueOf(s[i]).toLowerCase(Locale.ROOT)); } else { o.print(s[i]); } } o.println(); } catch (Exception e) { e.printStackTrace(); } } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } public static long lcm(long a, long b){ return a / gcd(a,b)*b; } public static long qpow(long a, long n, int md){ a %= md; long ret = 1l; while(n > 0){ if((n & 1) == 1){ ret = ret * a % md; } n >>= 1; a = a * a % md; } return ret; } public static class DSU { int[] parent; int[] size; int n; public DSU(int n){ this.n = n; parent = new int[n]; size = new int[n]; for(int i=0;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int p){ while(parent[p] != p){ parent[p] = parent[parent[p]]; p = parent[p]; } return p; } public void union(int p, int q){ int root_p = find(p); int root_q = find(q); if(root_p == root_q) return; if(size[root_p] >= size[root_q]){ parent[root_q] = root_p; size[root_p] += size[root_q]; size[root_q] = 0; } else{ parent[root_p] = root_q; size[root_q] += size[root_p]; size[root_p] = 0; } n--; } public int getTotalComNum(){ return n; } public int getSize(int i){ return size[find(i)]; } } public static class FenWick { int n; long[] a; long[] tree; public FenWick(int n){ this.n = n; a = new long[n+1]; tree = new long[n+1]; } private void add(int x, long val){ while(x <= n){ tree[x] += val; x += x&-x; } } private void addMx(int x, long val) { a[x] += val; tree[x] = a[x]; while(x <= n) { for(int i=1;i<(x&-x);i<<=1) { tree[x] = Math.max(tree[x], tree[x-i]); } x += x&-x; } } private long query(int x){ long ret = 0l; while(x > 0){ ret += tree[x]; x -= x&-x; } return ret; } private long queryMx(int l, int r) { long res = 0l; while(l <= r) { if(r-(r&-r) >= l) { res = Math.max(res, tree[r]); r -= r&-r; } else { res = Math.max(res, a[r]); r--; } } return res; } } public static class Pair{ Integer c1; Integer c2; Integer c3; Integer c4; public Pair(Integer c1, Integer c2, Integer c3, Integer c4) { this.c1 = c1; this.c2 = c2; this.c3 = c3; this.c4 = c4; } @Override public int hashCode() { int prime = 31, ret = 1; ret = ret*prime + c1.hashCode(); ret = ret*prime + c2.hashCode(); ret = ret*prime + c3.hashCode(); ret = ret*prime + c4.hashCode(); return ret; } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { return c1.equals(((Pair) obj).c1) && c2.equals(((Pair) obj).c2) && c3.equals(((Pair) obj).c3) && c4.equals(((Pair) obj).c4); } return false; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } } import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f, mod = 1000000007, mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = false; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static void solve(PrintWriter o) { try { int n = fReader.nextInt(); char[] s = fReader.nextString().toCharArray(); int q = fReader.nextInt(); int lower = -2, upper = -2; int[] time = new int[n]; Arrays.fill(time, -1); for(int i=0;i<q;i++) { int t = fReader.nextInt(); int x = fReader.nextInt(); x--; char c = fReader.nextChar(); if(t == 1) { s[x] = c; time[x] = i; } else if(t == 2) lower = i; else upper = i; } for(int i=0;i<n;i++) { if(upper > lower) { if(time[i] > upper) o.print(s[i]); else o.print(String.valueOf(s[i]).toUpperCase(Locale.ROOT)); } else if(upper < lower){ if(time[i] > lower) o.print(s[i]); else o.print(String.valueOf(s[i]).toLowerCase(Locale.ROOT)); } else { o.print(s[i]); } } o.println(); } catch (Exception e) { e.printStackTrace(); } } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } public static long lcm(long a, long b){ return a / gcd(a,b)*b; } public static long qpow(long a, long n, int md){ a %= md; long ret = 1l; while(n > 0){ if((n & 1) == 1){ ret = ret * a % md; } n >>= 1; a = a * a % md; } return ret; } public static class DSU { int[] parent; int[] size; int n; public DSU(int n){ this.n = n; parent = new int[n]; size = new int[n]; for(int i=0;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int p){ while(parent[p] != p){ parent[p] = parent[parent[p]]; p = parent[p]; } return p; } public void union(int p, int q){ int root_p = find(p); int root_q = find(q); if(root_p == root_q) return; if(size[root_p] >= size[root_q]){ parent[root_q] = root_p; size[root_p] += size[root_q]; size[root_q] = 0; } else{ parent[root_p] = root_q; size[root_q] += size[root_p]; size[root_p] = 0; } n--; } public int getTotalComNum(){ return n; } public int getSize(int i){ return size[find(i)]; } } public static class FenWick { int n; long[] a; long[] tree; public FenWick(int n){ this.n = n; a = new long[n+1]; tree = new long[n+1]; } private void add(int x, long val){ while(x <= n){ tree[x] += val; x += x&-x; } } private void addMx(int x, long val) { a[x] += val; tree[x] = a[x]; while(x <= n) { for(int i=1;i<(x&-x);i<<=1) { tree[x] = Math.max(tree[x], tree[x-i]); } x += x&-x; } } private long query(int x){ long ret = 0l; while(x > 0){ ret += tree[x]; x -= x&-x; } return ret; } private long queryMx(int l, int r) { long res = 0l; while(l <= r) { if(r-(r&-r) >= l) { res = Math.max(res, tree[r]); r -= r&-r; } else { res = Math.max(res, a[r]); r--; } } return res; } } public static class Pair{ Integer c1; Integer c2; Integer c3; Integer c4; public Pair(Integer c1, Integer c2, Integer c3, Integer c4) { this.c1 = c1; this.c2 = c2; this.c3 = c3; this.c4 = c4; } @Override public int hashCode() { int prime = 31, ret = 1; ret = ret*prime + c1.hashCode(); ret = ret*prime + c2.hashCode(); ret = ret*prime + c3.hashCode(); ret = ret*prime + c4.hashCode(); return ret; } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { return c1.equals(((Pair) obj).c1) && c2.equals(((Pair) obj).c2) && c3.equals(((Pair) obj).c3) && c4.equals(((Pair) obj).c4); } return false; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } }
ConDefects/ConDefects/Code/abc314_d/Java/44857826
condefects-java_data_457
import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ PrintWriter output = new PrintWriter(System.out); Scanner sc = new Scanner(System.in); int N = sc.nextInt(); char[] c = sc.next().toCharArray(); int Q = sc.nextInt(); char[] order = new char[Q]; char[] lastOrderPreBS = new char[N]; char[] lastOrder = new char[N]; char[] result = new char[N]; int[][] table = new int[Q][2]; for(int i=0;i<Q;i++) { table[i][0] = sc.nextInt(); table[i][1] = sc.nextInt(); order[i] = sc.next().toCharArray()[0]; } int lastBS = 0; int BS = 0; for(int i=Q-1;i>=0;i--) { if(table[i][0]==2||table[i][0]==3) { lastBS = i; BS = table[i][0]; break; } } //BS前 for(int i=0;i<lastBS;i++) { if(table[i][0]==1) lastOrderPreBS[table[i][1]-1] = order[i]; } //BS後 for(int i=lastBS+1;i<Q;i++) { if(table[i][0]==1) lastOrder[table[i][1]-1] = order[i]; } //BS前,初期融合 result = lastOrderPreBS; for(int i=0;i<N;i++) { if(result[i]==0) result[i] = c[i]; } //BS前にBS適用 if(BS==2) { for(int i=0;i<N;i++) { if(result[i]>=65 && result[i]<=90) result[i] += 32; } } else if(BS==3) { for(int i=0;i<N;i++) { if(result[i]>=97 && result[i]<=122) result[i] -= 32; } } //融合、初期融合 for(int i=0;i<N;i++) { if(lastOrder[i]!=0) result[i] = lastOrder[i]; } for(int i=0;i<N;i++) { output.print(result[i]); } output.print("\n"); output.flush(); sc.close(); } } import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ PrintWriter output = new PrintWriter(System.out); Scanner sc = new Scanner(System.in); int N = sc.nextInt(); char[] c = sc.next().toCharArray(); int Q = sc.nextInt(); char[] order = new char[Q]; char[] lastOrderPreBS = new char[N]; char[] lastOrder = new char[N]; char[] result = new char[N]; int[][] table = new int[Q][2]; for(int i=0;i<Q;i++) { table[i][0] = sc.nextInt(); table[i][1] = sc.nextInt(); order[i] = sc.next().toCharArray()[0]; } int lastBS = -1; int BS = 0; for(int i=Q-1;i>=0;i--) { if(table[i][0]==2||table[i][0]==3) { lastBS = i; BS = table[i][0]; break; } } //BS前 for(int i=0;i<lastBS;i++) { if(table[i][0]==1) lastOrderPreBS[table[i][1]-1] = order[i]; } //BS後 for(int i=lastBS+1;i<Q;i++) { if(table[i][0]==1) lastOrder[table[i][1]-1] = order[i]; } //BS前,初期融合 result = lastOrderPreBS; for(int i=0;i<N;i++) { if(result[i]==0) result[i] = c[i]; } //BS前にBS適用 if(BS==2) { for(int i=0;i<N;i++) { if(result[i]>=65 && result[i]<=90) result[i] += 32; } } else if(BS==3) { for(int i=0;i<N;i++) { if(result[i]>=97 && result[i]<=122) result[i] -= 32; } } //融合、初期融合 for(int i=0;i<N;i++) { if(lastOrder[i]!=0) result[i] = lastOrder[i]; } for(int i=0;i<N;i++) { output.print(result[i]); } output.print("\n"); output.flush(); sc.close(); } }
ConDefects/ConDefects/Code/abc314_d/Java/45235089
condefects-java_data_458
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = sc.next(); char[] chars = s.toCharArray(); int q = sc.nextInt(); int[][] queries = new int[q][2]; char[] x = new char[q]; for (int i = 0; i < q; i++) { for (int j = 0; j < 2; j++) { queries[i][j] = sc.nextInt(); } x[i] = sc.next().charAt(0); } int last = q - 1;//最后一次改变字母大小写的操作 int type = -1; for (int i = q - 1; i >= 0; i--) { if (queries[i][0] != 1) { last = i; type = queries[i][0]; break; } } for (int i = 0; i < last; i++) { if (queries[i][0] == 1) { chars[queries[i][1] - 1] = x[i]; } } if (type == 2) { for (int i = 0; i < n; i++) { if (Character.isUpperCase(chars[i])) { chars[i] = (char) (chars[i] ^ 32); } } } else if (type == 3) { for (int i = 0; i < n; i++) { if (Character.isLowerCase(chars[i])) { chars[i] = (char) (chars[i] ^ 32); } } } for (int i = last + 1; i < q; i++) { chars[queries[i][1] - 1] = x[i]; } StringBuffer sb = new StringBuffer(); for (char c : chars) sb.append(c); System.out.println(sb); } } import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = sc.next(); char[] chars = s.toCharArray(); int q = sc.nextInt(); int[][] queries = new int[q][2]; char[] x = new char[q]; for (int i = 0; i < q; i++) { for (int j = 0; j < 2; j++) { queries[i][j] = sc.nextInt(); } x[i] = sc.next().charAt(0); } int last = q ;//最后一次改变字母大小写的操作 int type = -1; for (int i = q - 1; i >= 0; i--) { if (queries[i][0] != 1) { last = i; type = queries[i][0]; break; } } for (int i = 0; i < last; i++) { if (queries[i][0] == 1) { chars[queries[i][1] - 1] = x[i]; } } if (type == 2) { for (int i = 0; i < n; i++) { if (Character.isUpperCase(chars[i])) { chars[i] = (char) (chars[i] ^ 32); } } } else if (type == 3) { for (int i = 0; i < n; i++) { if (Character.isLowerCase(chars[i])) { chars[i] = (char) (chars[i] ^ 32); } } } for (int i = last + 1; i < q; i++) { chars[queries[i][1] - 1] = x[i]; } StringBuffer sb = new StringBuffer(); for (char c : chars) sb.append(c); System.out.println(sb); } }
ConDefects/ConDefects/Code/abc314_d/Java/45301629
condefects-java_data_459
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import java.util.Map.Entry; public class Main { public static int[] dijkstraDistance; static ContestPrinter printer = new ContestPrinter(System.out); public static void main(String[] args) { ContestScanner scan = new ContestScanner(); int N = scan.nextInt(); char[] S = scan.next().toCharArray(); int Q = scan.nextInt(); int[] last1 = new int[N]; int last2 = -1; int last3 = -1; for (int i = 0; i < Q; i++) { int t = scan.nextInt(); int x = scan.nextInt() - 1; char c = scan.next().charAt(0); if (t == 1) { last1[x] = i; S[x] = c; } if (t == 2) last2 = i; if (t == 3) last3 = i; } for (int i = 0; i < N; i++) { if (last2 > last3) printer.print(last1[i] > last2 ? S[i] : (S[i] + "").toLowerCase()); else printer.print(last1[i] > last2 ? S[i] : (S[i] + "").toUpperCase()); } print(); printer.flush(); printer.close(); } public static void write(Object... objs) { try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("", true)))) { for (Object o : objs) { pw.println(o); } } catch (IOException e) { e.printStackTrace(); } } public static long gcd(long l, long r) { if (r == 0) return l; return gcd(r, l % r); } public static long lcm(long l, long r) { return lcm(new BigInteger(String.valueOf(l)), new BigInteger(String.valueOf(r))).longValue(); } public static BigInteger gcd(BigInteger l, BigInteger r) { return l.gcd(r); } public static BigInteger lcm(BigInteger l, BigInteger r) { return l.multiply(r).divide(gcd(l, r)); } @SafeVarargs public static <T extends Comparable<T>> T max(T... values) { return Collections.max(Arrays.asList(values)); } public static <T extends Comparable<T>> T max(Collection<T> values) { return Collections.max(values); } @SafeVarargs public static <T extends Comparable<T>> T min(T... values) { return Collections.min(Arrays.asList(values)); } public static <T extends Comparable<T>> T min(Collection<T> values) { return Collections.min(values); } public static <T extends Comparable<T>> int lowerBound(List<T> list, T key) { return ~Collections.binarySearch(list, key, (x, y) -> x.compareTo(y) >= 0 ? 1 : -1); } public static <T extends Comparable<T>> int upperBound(List<T> list, T key) { return ~Collections.binarySearch(list, key, (x, y) -> x.compareTo(y) > 0 ? -1 : 1); } public static <T1 extends Comparable<T1>, T2 extends Comparable<T2>> LinkedHashMap<T1, T2> sortMapByKey(Map<T1, T2> map) { return sortMapByKey(map, false); } public static <T1 extends Comparable<T1>, T2 extends Comparable<T2>> LinkedHashMap<T1, T2> sortMapByKey(Map<T1, T2> map, boolean isReverse) { List<Entry<T1, T2>> entries = new LinkedList<>(map.entrySet()); if (isReverse) entries.sort(Entry.comparingByKey(Collections.reverseOrder())); else entries.sort(Entry.comparingByKey()); LinkedHashMap<T1, T2> result = new LinkedHashMap<>(); for (Entry<T1, T2> entry : entries) { result.put(entry.getKey(), entry.getValue()); } return result; } public static <T1 extends Comparable<T1>, T2 extends Comparable<T2>> LinkedHashMap<T1, T2> sortMapByValue(Map<T1, T2> map) { return sortMapByValue(map, false); } public static <T1 extends Comparable<T1>, T2 extends Comparable<T2>> LinkedHashMap<T1, T2> sortMapByValue(Map<T1, T2> map, boolean isReverse) { List<Entry<T1, T2>> entries = new LinkedList<>(map.entrySet()); if (isReverse) entries.sort(Entry.comparingByValue(Collections.reverseOrder())); else entries.sort(Entry.comparingByValue()); LinkedHashMap<T1, T2> result = new LinkedHashMap<>(); for (Entry<T1, T2> entry : entries) { result.put(entry.getKey(), entry.getValue()); } return result; } public static long nCr(long n, long r) { long result = 1; for (int i = 1; i <= r; i++) { result = result * (n - i + 1) / i; } return result; } public static <T extends Comparable<T>> int[] lis(List<T> array) { int N = array.size(); int[] result = new int[N]; List<T> B = new ArrayList<>(); for (int i = 0; i < N; i++) { int k = lowerBound(B, array.get(i)); if (k == B.size()) B.add(array.get(i)); else B.set(k, array.get(i)); result[i] = k + 1; } return result; } public static long lsqrt(long x) { long b = (long) Math.sqrt(x); if (b * b > x) b--; if (b * b < x) b++; return b; } public static void print() { print(""); } public static void print(Object o) { printer.println(o); } public static void print(Object... objs) { for (Object o : objs) { printer.print(o + " "); } print(); } } class DijkstraComparator<T> implements Comparator<T> { @Override public int compare(T o1, T o2) { return Integer.compare(Main.dijkstraDistance[(int) o1], Main.dijkstraDistance[(int) o2]); } } class IndexedObject<T extends Comparable<T>> implements Comparable<IndexedObject> { int i; T value; public IndexedObject(int i, T value) { this.i = i; this.value = value; } @Override public boolean equals(Object o) { if (!(o instanceof IndexedObject)) return false; return this.i == ((IndexedObject<?>)o).i && this.value.equals(((IndexedObject<?>)o).value); } @Override public int compareTo(IndexedObject o) { if (o.value.getClass() != this.value.getClass()) throw new IllegalArgumentException(); return value.compareTo((T) o.value); } @Override public int hashCode() { return this.i + this.value.hashCode(); } @Override public String toString() { return "IndexedObject{" + "i=" + i + ", value=" + value + '}'; } } class Point { int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (!(o instanceof Point)) return false; return this.x == ((Point)o).x && this.y == ((Point)o).y; } @Override public int hashCode() { return Integer.hashCode(x) * 524287 + Integer.hashCode(y); } } class GraphBuilder { private Map<Integer, List<Integer>> edges = new HashMap<>(); private final int N; private final boolean isDirected; public GraphBuilder(int N, boolean isDirected) { this.isDirected = isDirected; this.N = N; for (int i = 0; i < N; i++) { edges.put(i, new ArrayList<>()); } } public GraphBuilder(int N) { this(N, false); } public void addEdge(int u, int v) { edges.get(u).add(v); if (!isDirected) edges.get(v).add(u); } public Map<Integer, List<Integer>> getEdges() { return edges; } public int getN() { return N; } } class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in){ this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner(){ this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = this.nextInt(); return array; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = this.next(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } } class ContestPrinter extends java.io.PrintWriter{ public ContestPrinter(java.io.PrintStream stream){ super(stream); } public ContestPrinter(java.io.File file) throws java.io.FileNotFoundException{ super(new java.io.PrintStream(file)); } public ContestPrinter(){ super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if(x < 0){ sb.append('-'); x = -x; } x += Math.pow(10, -n)/2; sb.append((long)x); sb.append("."); x -= (long)x; for(int i = 0;i < n;i++){ x *= 10; sb.append((int)x); x -= (int)x; } return sb.toString(); } @Override public void print(float f){ super.print(dtos(f, 20)); } @Override public void println(float f){ super.println(dtos(f, 20)); } @Override public void print(double d){ super.print(dtos(d, 20)); } @Override public void println(double d){ super.println(dtos(d, 20)); } public void printArray(int[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public void printArray(int[] array){ this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n-1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map){ this.printArray(array, " ", map); } public void printArray(long[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public void printArray(long[] array){ this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n-1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map){ this.printArray(array, " ", map); } public <T> void printArray(T[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public <T> void printArray(T[] array){ this.printArray(array, " "); } public <T> void printArray(T[] array, String separator, java.util.function.UnaryOperator<T> map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.apply(array[i])); super.print(separator); } super.println(map.apply(array[n-1])); } public <T> void printArray(T[] array, java.util.function.UnaryOperator<T> map){ this.printArray(array, " ", map); } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } java.util.ArrayList<java.util.ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new java.util.ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(java.util.ArrayList::isEmpty); return result; } } class ModIntFactory { private final ModArithmetic ma; private final int mod; private final boolean usesMontgomery; private final ModArithmetic.ModArithmeticMontgomery maMontgomery; private ArrayList<Integer> factorial; public ModIntFactory(int mod) { this.ma = ModArithmetic.of(mod); this.usesMontgomery = ma instanceof ModArithmetic.ModArithmeticMontgomery; this.maMontgomery = usesMontgomery ? (ModArithmetic.ModArithmeticMontgomery) ma : null; this.mod = mod; this.factorial = new ArrayList<>(); } public ModInt create(long value) { if ((value %= mod) < 0) value += mod; if (usesMontgomery) { return new ModInt(maMontgomery.generate(value)); } else { return new ModInt((int) value); } } private void prepareFactorial(int max){ factorial.ensureCapacity(max+1); if(factorial.size()==0) factorial.add(1); if (usesMontgomery) { for(int i=factorial.size(); i<=max; i++){ factorial.add(ma.mul(factorial.get(i-1), maMontgomery.generate(i))); } } else { for(int i=factorial.size(); i<=max; i++){ factorial.add(ma.mul(factorial.get(i-1), i)); } } } public ModInt factorial(int i){ prepareFactorial(i); return create(factorial.get(i)); } public ModInt permutation(int n, int r){ if(n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); return create(ma.div(factorial.get(n), factorial.get(r))); } public ModInt combination(int n, int r){ if(n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); return create(ma.div(factorial.get(n), ma.mul(factorial.get(r),factorial.get(n-r)))); } public int getMod() { return mod; } public class ModInt { private int value; private ModInt(int value) { this.value = value; } public int mod() { return mod; } public int value() { if (usesMontgomery) { return maMontgomery.reduce(value); } return value; } public ModInt add(ModInt mi) { return new ModInt(ma.add(value, mi.value)); } public ModInt add(ModInt mi1, ModInt mi2) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt add(ModInt mi1, ModInt... mis) { ModInt mi = add(mi1); for (ModInt m : mis) mi.addAsg(m); return mi; } public ModInt add(long mi) { return new ModInt(ma.add(value, ma.remainder(mi))); } public ModInt sub(ModInt mi) { return new ModInt(ma.sub(value, mi.value)); } public ModInt sub(long mi) { return new ModInt(ma.sub(value, ma.remainder(mi))); } public ModInt mul(ModInt mi) { return new ModInt(ma.mul(value, mi.value)); } public ModInt mul(ModInt mi1, ModInt mi2) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mul(ModInt mi1, ModInt... mis) { ModInt mi = mul(mi1); for (ModInt m : mis) mi.mulAsg(m); return mi; } public ModInt mul(long mi) { return new ModInt(ma.mul(value, ma.remainder(mi))); } public ModInt div(ModInt mi) { return new ModInt(ma.div(value, mi.value)); } public ModInt div(long mi) { return new ModInt(ma.div(value, ma.remainder(mi))); } public ModInt inv() { return new ModInt(ma.inv(value)); } public ModInt pow(long b) { return new ModInt(ma.pow(value, b)); } public ModInt addAsg(ModInt mi) { this.value = ma.add(value, mi.value); return this; } public ModInt addAsg(ModInt mi1, ModInt mi2) { return addAsg(mi1).addAsg(mi2); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return addAsg(mi1).addAsg(mi2).addAsg(mi3); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return addAsg(mi1).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt addAsg(ModInt... mis) { for (ModInt m : mis) addAsg(m); return this; } public ModInt addAsg(long mi) { this.value = ma.add(value, ma.remainder(mi)); return this; } public ModInt subAsg(ModInt mi) { this.value = ma.sub(value, mi.value); return this; } public ModInt subAsg(long mi) { this.value = ma.sub(value, ma.remainder(mi)); return this; } public ModInt mulAsg(ModInt mi) { this.value = ma.mul(value, mi.value); return this; } public ModInt mulAsg(ModInt mi1, ModInt mi2) { return mulAsg(mi1).mulAsg(mi2); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mulAsg(ModInt... mis) { for (ModInt m : mis) mulAsg(m); return this; } public ModInt mulAsg(long mi) { this.value = ma.mul(value, ma.remainder(mi)); return this; } public ModInt divAsg(ModInt mi) { this.value = ma.div(value, mi.value); return this; } public ModInt divAsg(long mi) { this.value = ma.div(value, ma.remainder(mi)); return this; } @Override public String toString() { return String.valueOf(value()); } @Override public boolean equals(Object o) { if (o instanceof ModInt) { ModInt mi = (ModInt) o; return mod() == mi.mod() && value() == mi.value(); } return false; } @Override public int hashCode() { return (1 * 37 + mod()) * 37 + value(); } } private static abstract class ModArithmetic { abstract int mod(); abstract int remainder(long value); abstract int add(int a, int b); abstract int sub(int a, int b); abstract int mul(int a, int b); int div(int a, int b) { return mul(a, inv(b)); } int inv(int a) { int b = mod(); if (b == 1) return 0; long u = 1, v = 0; while (b >= 1) { int t = a / b; a -= t * b; int tmp1 = a; a = b; b = tmp1; u -= t * v; long tmp2 = u; u = v; v = tmp2; } if (a != 1) { throw new ArithmeticException("divide by zero"); } return remainder(u); } int pow(int a, long b) { if (b < 0) throw new ArithmeticException("negative power"); int r = 1; int x = a; while (b > 0) { if ((b & 1) == 1) r = mul(r, x); x = mul(x, x); b >>= 1; } return r; } static ModArithmetic of(int mod) { if (mod <= 0) { throw new IllegalArgumentException(); } else if (mod == 1) { return new ModArithmetic1(); } else if (mod == 2) { return new ModArithmetic2(); } else if (mod == 998244353) { return new ModArithmetic998244353(); } else if (mod == 1000000007) { return new ModArithmetic1000000007(); } else if ((mod & 1) == 1) { return new ModArithmeticMontgomery(mod); } else { return new ModArithmeticBarrett(mod); } } private static final class ModArithmetic1 extends ModArithmetic { int mod() {return 1;} int remainder(long value) {return 0;} int add(int a, int b) {return 0;} int sub(int a, int b) {return 0;} int mul(int a, int b) {return 0;} int pow(int a, long b) {return 0;} } private static final class ModArithmetic2 extends ModArithmetic { int mod() {return 2;} int remainder(long value) {return (int) (value & 1);} int add(int a, int b) {return a ^ b;} int sub(int a, int b) {return a ^ b;} int mul(int a, int b) {return a & b;} } private static final class ModArithmetic998244353 extends ModArithmetic { private final int mod = 998244353; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmetic1000000007 extends ModArithmetic { private final int mod = 1000000007; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmeticMontgomery extends ModArithmeticDynamic { private final long negInv; private final long r2; private ModArithmeticMontgomery(int mod) { super(mod); long inv = 0; long s = 1, t = 0; for (int i = 0; i < 32; i++) { if ((t & 1) == 0) { t += mod; inv += s; } t >>= 1; s <<= 1; } long r = (1l << 32) % mod; this.negInv = inv; this.r2 = (r * r) % mod; } private int generate(long x) { return reduce(x * r2); } private int reduce(long x) { x = (x + ((x * negInv) & 0xffff_ffffl) * mod) >>> 32; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return generate((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } @Override int inv(int a) { return super.inv(reduce(a)); } @Override int pow(int a, long b) { return generate(super.pow(a, b)); } } private static final class ModArithmeticBarrett extends ModArithmeticDynamic { private static final long mask = 0xffff_ffffl; private final long mh; private final long ml; private ModArithmeticBarrett(int mod) { super(mod); /** * m = floor(2^64/mod) * 2^64 = p*mod + q, 2^32 = a*mod + b * => (a*mod + b)^2 = p*mod + q * => p = mod*a^2 + 2ab + floor(b^2/mod) */ long a = (1l << 32) / mod; long b = (1l << 32) % mod; long m = a * a * mod + 2 * a * b + (b * b) / mod; mh = m >>> 32; ml = m & mask; } private int reduce(long x) { long z = (x & mask) * ml; z = (x & mask) * mh + (x >>> 32) * ml + (z >>> 32); z = (x >>> 32) * mh + (z >>> 32); x -= z * mod; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } } private static class ModArithmeticDynamic extends ModArithmetic { final int mod; ModArithmeticDynamic(int mod) { this.mod = mod; } int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int sum = a + b; return sum >= mod ? sum - mod : sum; } int sub(int a, int b) { int sum = a - b; return sum < 0 ? sum + mod : sum; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } } } class SCC { static class Edge { int from, to; public Edge(int from, int to) { this.from = from; this.to = to; } } final int n; int m; final java.util.ArrayList<Edge> unorderedEdges; final int[] start; final int[] ids; boolean hasBuilt = false; public SCC(int n) { this.n = n; this.unorderedEdges = new java.util.ArrayList<>(); this.start = new int[n + 1]; this.ids = new int[n]; } public void addEdge(int from, int to) { rangeCheck(from); rangeCheck(to); unorderedEdges.add(new Edge(from, to)); start[from + 1]++; this.m++; } public int id(int i) { if (!hasBuilt) { throw new UnsupportedOperationException( "Graph hasn't been built." ); } rangeCheck(i); return ids[i]; } public int[][] build() { for (int i = 1; i <= n; i++) { start[i] += start[i - 1]; } Edge[] orderedEdges = new Edge[m]; int[] count = new int[n + 1]; System.arraycopy(start, 0, count, 0, n + 1); for (Edge e : unorderedEdges) { orderedEdges[count[e.from]++] = e; } int nowOrd = 0; int groupNum = 0; int k = 0; // parent int[] par = new int[n]; int[] vis = new int[n]; int[] low = new int[n]; int[] ord = new int[n]; java.util.Arrays.fill(ord, -1); // u = lower32(stack[i]) : visiting vertex // j = upper32(stack[i]) : jth child long[] stack = new long[n]; // size of stack int ptr = 0; // non-recursional DFS for (int i = 0; i < n; i++) { if (ord[i] >= 0) continue; par[i] = -1; // vertex i, 0th child. stack[ptr++] = 0l << 32 | i; // stack is not empty while (ptr > 0) { // last element long p = stack[--ptr]; // vertex int u = (int) (p & 0xffff_ffffl); // jth child int j = (int) (p >>> 32); if (j == 0) { // first visit low[u] = ord[u] = nowOrd++; vis[k++] = u; } if (start[u] + j < count[u]) { // there are more children // jth child int to = orderedEdges[start[u] + j].to; // incr children counter stack[ptr++] += 1l << 32; if (ord[to] == -1) { // new vertex stack[ptr++] = 0l << 32 | to; par[to] = u; } else { // backward edge low[u] = Math.min(low[u], ord[to]); } } else { // no more children (leaving) while (j --> 0) { int to = orderedEdges[start[u] + j].to; // update lowlink if (par[to] == u) low[u] = Math.min(low[u], low[to]); } if (low[u] == ord[u]) { // root of a component while (true) { // gathering verticies int v = vis[--k]; ord[v] = n; ids[v] = groupNum; if (v == u) break; } groupNum++; // incr the number of components } } } } for (int i = 0; i < n; i++) { ids[i] = groupNum - 1 - ids[i]; } int[] counts = new int[groupNum]; for (int x : ids) counts[x]++; int[][] groups = new int[groupNum][]; for (int i = 0; i < groupNum; i++) { groups[i] = new int[counts[i]]; } for (int i = 0; i < n; i++) { int cmp = ids[i]; groups[cmp][--counts[cmp]] = i; } hasBuilt = true; return groups; } private void rangeCheck(int i) { if (i < 0 || i >= n) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, n) ); } } } class LazySegTree<S, F> { final int MAX; final int N; final int Log; final java.util.function.BinaryOperator<S> Op; final S E; final java.util.function.BiFunction<F, S, S> Mapping; final java.util.function.BinaryOperator<F> Composition; final F Id; final S[] Dat; final F[] Laz; @SuppressWarnings("unchecked") public LazySegTree(int n, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.Log = Integer.numberOfTrailingZeros(N); this.Op = op; this.E = e; this.Mapping = mapping; this.Composition = composition; this.Id = id; this.Dat = (S[]) new Object[N << 1]; this.Laz = (F[]) new Object[N]; java.util.Arrays.fill(Dat, E); java.util.Arrays.fill(Laz, Id); } public LazySegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this(dat.length, op, e, mapping, composition, id); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, Dat, N, l); for (int i = N - 1; i > 0; i--) { Dat[i] = Op.apply(Dat[i << 1 | 0], Dat[i << 1 | 1]); } } private void push(int k) { if (Laz[k] == Id) return; int lk = k << 1 | 0, rk = k << 1 | 1; Dat[lk] = Mapping.apply(Laz[k], Dat[lk]); Dat[rk] = Mapping.apply(Laz[k], Dat[rk]); if (lk < N) Laz[lk] = Composition.apply(Laz[k], Laz[lk]); if (rk < N) Laz[rk] = Composition.apply(Laz[k], Laz[rk]); Laz[k] = Id; } private void pushTo(int k) { for (int i = Log; i > 0; i--) push(k >> i); } private void pushTo(int lk, int rk) { for (int i = Log; i > 0; i--) { if (((lk >> i) << i) != lk) push(lk >> i); if (((rk >> i) << i) != rk) push(rk >> i); } } private void updateFrom(int k) { k >>= 1; while (k > 0) { Dat[k] = Op.apply(Dat[k << 1 | 0], Dat[k << 1 | 1]); k >>= 1; } } private void updateFrom(int lk, int rk) { for (int i = 1; i <= Log; i++) { if (((lk >> i) << i) != lk) { int lki = lk >> i; Dat[lki] = Op.apply(Dat[lki << 1 | 0], Dat[lki << 1 | 1]); } if (((rk >> i) << i) != rk) { int rki = (rk - 1) >> i; Dat[rki] = Op.apply(Dat[rki << 1 | 0], Dat[rki << 1 | 1]); } } } public void set(int p, S x) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = x; updateFrom(p); } public S get(int p) { exclusiveRangeCheck(p); p += N; pushTo(p); return Dat[p]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return E; l += N; r += N; pushTo(l, r); S sumLeft = E, sumRight = E; while (l < r) { if ((l & 1) == 1) sumLeft = Op.apply(sumLeft, Dat[l++]); if ((r & 1) == 1) sumRight = Op.apply(Dat[--r], sumRight); l >>= 1; r >>= 1; } return Op.apply(sumLeft, sumRight); } public S allProd() { return Dat[1]; } public void apply(int p, F f) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = Mapping.apply(f, Dat[p]); updateFrom(p); } public void apply(int l, int r, F f) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return; l += N; r += N; pushTo(l, r); for (int l2 = l, r2 = r; l2 < r2;) { if ((l2 & 1) == 1) { Dat[l2] = Mapping.apply(f, Dat[l2]); if (l2 < N) Laz[l2] = Composition.apply(f, Laz[l2]); l2++; } if ((r2 & 1) == 1) { r2--; Dat[r2] = Mapping.apply(f, Dat[r2]); if (r2 < N) Laz[r2] = Composition.apply(f, Laz[r2]); } l2 >>= 1; r2 >>= 1; } updateFrom(l, r); } public int maxRight(int l, java.util.function.Predicate<S> g) { inclusiveRangeCheck(l); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; pushTo(l); S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!g.test(Op.apply(sum, Dat[l]))) { while (l < N) { push(l); l = l << 1; if (g.test(Op.apply(sum, Dat[l]))) { sum = Op.apply(sum, Dat[l]); l++; } } return l - N; } sum = Op.apply(sum, Dat[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> g) { inclusiveRangeCheck(r); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; pushTo(r - 1); S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!g.test(Op.apply(Dat[r], sum))) { while (r < N) { push(r); r = r << 1 | 1; if (g.test(Op.apply(Dat[r], sum))) { sum = Op.apply(Dat[r], sum); r--; } } return r + 1 - N; } sum = Op.apply(Dat[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d is not in [%d, %d).", p, 0, MAX) ); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d is not in [%d, %d].", p, 0, MAX) ); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } private S[] simulatePushAll() { S[] simDat = java.util.Arrays.copyOf(Dat, 2 * N); F[] simLaz = java.util.Arrays.copyOf(Laz, 2 * N); for (int k = 1; k < N; k++) { if (simLaz[k] == Id) continue; int lk = k << 1 | 0, rk = k << 1 | 1; simDat[lk] = Mapping.apply(simLaz[k], simDat[lk]); simDat[rk] = Mapping.apply(simLaz[k], simDat[rk]); if (lk < N) simLaz[lk] = Composition.apply(simLaz[k], simLaz[lk]); if (rk < N) simLaz[rk] = Composition.apply(simLaz[k], simLaz[rk]); simLaz[k] = Id; } return simDat; } public String toDetailedString() { return toDetailedString(1, 0, simulatePushAll()); } private String toDetailedString(int k, int sp, S[] dat) { if (k >= N) return indent(sp) + dat[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent, dat); s += "\n"; s += indent(sp) + dat[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent, dat); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n --> 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { S[] dat = simulatePushAll(); StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(dat[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } class Permutation implements java.util.Iterator<int[]>, Iterable<int[]> { private int[] next; public Permutation(int n) { next = java.util.stream.IntStream.range(0, n).toArray(); } @Override public boolean hasNext() { return next != null; } @Override public int[] next() { int[] r = next.clone(); next = nextPermutation(next); return r; } @Override public java.util.Iterator<int[]> iterator() { return this; } public static int[] nextPermutation(int[] a) { if (a == null || a.length < 2) return null; int p = 0; for (int i = a.length - 2; i >= 0; i--) { if (a[i] >= a[i + 1]) continue; p = i; break; } int q = 0; for (int i = a.length - 1; i > p; i--) { if (a[i] <= a[p]) continue; q = i; break; } if (p == 0 && q == 0) return null; int temp = a[p]; a[p] = a[q]; a[q] = temp; int l = p, r = a.length; while (++l < --r) { temp = a[l]; a[l] = a[r]; a[r] = temp; } return a; } } class SegTree<S> { final int MAX; final int N; final java.util.function.BinaryOperator<S> op; final S E; final S[] data; @SuppressWarnings("unchecked") public SegTree(int n, java.util.function.BinaryOperator<S> op, S e) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.E = e; this.op = op; this.data = (S[]) new Object[N << 1]; java.util.Arrays.fill(data, E); } public SegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e) { this(dat.length, op, e); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, data, N, l); for (int i = N - 1; i > 0; i--) { data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]); } } public void set(int p, S x) { exclusiveRangeCheck(p); data[p += N] = x; p >>= 1; while (p > 0) { data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]); p >>= 1; } } public S get(int p) { exclusiveRangeCheck(p); return data[p + N]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); S sumLeft = E; S sumRight = E; l += N; r += N; while (l < r) { if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]); if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight); l >>= 1; r >>= 1; } return op.apply(sumLeft, sumRight); } public S allProd() { return data[1]; } public int maxRight(int l, java.util.function.Predicate<S> f) { inclusiveRangeCheck(l); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!f.test(op.apply(sum, data[l]))) { while (l < N) { l = l << 1; if (f.test(op.apply(sum, data[l]))) { sum = op.apply(sum, data[l]); l++; } } return l - N; } sum = op.apply(sum, data[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> f) { inclusiveRangeCheck(r); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!f.test(op.apply(data[r], sum))) { while (r < N) { r = r << 1 | 1; if (f.test(op.apply(data[r], sum))) { sum = op.apply(data[r], sum); r--; } } return r + 1 - N; } sum = op.apply(data[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d).", p, 0, MAX) ); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d].", p, 0, MAX) ); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } public String toDetailedString() { return toDetailedString(1, 0); } private String toDetailedString(int k, int sp) { if (k >= N) return indent(sp) + data[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent); s += "\n"; s += indent(sp) + data[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n --> 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(data[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } class Pair<S extends Comparable<S>, T extends Comparable<T>> implements Comparable<Pair<S,T>>{ S first; T second; public Pair(S s, T t){ first = s; second = t; } public S getFirst(){return first;} public T getSecond(){return second;} public boolean equals(Object another){ if(this==another) return true; if(!(another instanceof Pair)) return false; Pair otherPair = (Pair)another; return this.first.equals(otherPair.first) && this.second.equals(otherPair.second); } public int compareTo(Pair<S,T> another){ java.util.Comparator<Pair<S,T>> comp1 = java.util.Comparator.comparing(Pair::getFirst); java.util.Comparator<Pair<S,T>> comp2 = comp1.thenComparing(Pair::getSecond); return comp2.compare(this, another); } public int hashCode(){ return first.hashCode() * 10007 + second.hashCode(); } public String toString(){ return String.format("(%s, %s)", first, second); } } import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import java.util.Map.Entry; public class Main { public static int[] dijkstraDistance; static ContestPrinter printer = new ContestPrinter(System.out); public static void main(String[] args) { ContestScanner scan = new ContestScanner(); int N = scan.nextInt(); char[] S = scan.next().toCharArray(); int Q = scan.nextInt(); int[] last1 = new int[N]; int last2 = -1; int last3 = -1; for (int i = 0; i < Q; i++) { int t = scan.nextInt(); int x = scan.nextInt() - 1; char c = scan.next().charAt(0); if (t == 1) { last1[x] = i; S[x] = c; } if (t == 2) last2 = i; if (t == 3) last3 = i; } for (int i = 0; i < N; i++) { if (last2 > last3) printer.print(last1[i] > last2 ? S[i] : (S[i] + "").toLowerCase()); else printer.print(last1[i] > last3 ? S[i] : (S[i] + "").toUpperCase()); } print(); printer.flush(); printer.close(); } public static void write(Object... objs) { try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("", true)))) { for (Object o : objs) { pw.println(o); } } catch (IOException e) { e.printStackTrace(); } } public static long gcd(long l, long r) { if (r == 0) return l; return gcd(r, l % r); } public static long lcm(long l, long r) { return lcm(new BigInteger(String.valueOf(l)), new BigInteger(String.valueOf(r))).longValue(); } public static BigInteger gcd(BigInteger l, BigInteger r) { return l.gcd(r); } public static BigInteger lcm(BigInteger l, BigInteger r) { return l.multiply(r).divide(gcd(l, r)); } @SafeVarargs public static <T extends Comparable<T>> T max(T... values) { return Collections.max(Arrays.asList(values)); } public static <T extends Comparable<T>> T max(Collection<T> values) { return Collections.max(values); } @SafeVarargs public static <T extends Comparable<T>> T min(T... values) { return Collections.min(Arrays.asList(values)); } public static <T extends Comparable<T>> T min(Collection<T> values) { return Collections.min(values); } public static <T extends Comparable<T>> int lowerBound(List<T> list, T key) { return ~Collections.binarySearch(list, key, (x, y) -> x.compareTo(y) >= 0 ? 1 : -1); } public static <T extends Comparable<T>> int upperBound(List<T> list, T key) { return ~Collections.binarySearch(list, key, (x, y) -> x.compareTo(y) > 0 ? -1 : 1); } public static <T1 extends Comparable<T1>, T2 extends Comparable<T2>> LinkedHashMap<T1, T2> sortMapByKey(Map<T1, T2> map) { return sortMapByKey(map, false); } public static <T1 extends Comparable<T1>, T2 extends Comparable<T2>> LinkedHashMap<T1, T2> sortMapByKey(Map<T1, T2> map, boolean isReverse) { List<Entry<T1, T2>> entries = new LinkedList<>(map.entrySet()); if (isReverse) entries.sort(Entry.comparingByKey(Collections.reverseOrder())); else entries.sort(Entry.comparingByKey()); LinkedHashMap<T1, T2> result = new LinkedHashMap<>(); for (Entry<T1, T2> entry : entries) { result.put(entry.getKey(), entry.getValue()); } return result; } public static <T1 extends Comparable<T1>, T2 extends Comparable<T2>> LinkedHashMap<T1, T2> sortMapByValue(Map<T1, T2> map) { return sortMapByValue(map, false); } public static <T1 extends Comparable<T1>, T2 extends Comparable<T2>> LinkedHashMap<T1, T2> sortMapByValue(Map<T1, T2> map, boolean isReverse) { List<Entry<T1, T2>> entries = new LinkedList<>(map.entrySet()); if (isReverse) entries.sort(Entry.comparingByValue(Collections.reverseOrder())); else entries.sort(Entry.comparingByValue()); LinkedHashMap<T1, T2> result = new LinkedHashMap<>(); for (Entry<T1, T2> entry : entries) { result.put(entry.getKey(), entry.getValue()); } return result; } public static long nCr(long n, long r) { long result = 1; for (int i = 1; i <= r; i++) { result = result * (n - i + 1) / i; } return result; } public static <T extends Comparable<T>> int[] lis(List<T> array) { int N = array.size(); int[] result = new int[N]; List<T> B = new ArrayList<>(); for (int i = 0; i < N; i++) { int k = lowerBound(B, array.get(i)); if (k == B.size()) B.add(array.get(i)); else B.set(k, array.get(i)); result[i] = k + 1; } return result; } public static long lsqrt(long x) { long b = (long) Math.sqrt(x); if (b * b > x) b--; if (b * b < x) b++; return b; } public static void print() { print(""); } public static void print(Object o) { printer.println(o); } public static void print(Object... objs) { for (Object o : objs) { printer.print(o + " "); } print(); } } class DijkstraComparator<T> implements Comparator<T> { @Override public int compare(T o1, T o2) { return Integer.compare(Main.dijkstraDistance[(int) o1], Main.dijkstraDistance[(int) o2]); } } class IndexedObject<T extends Comparable<T>> implements Comparable<IndexedObject> { int i; T value; public IndexedObject(int i, T value) { this.i = i; this.value = value; } @Override public boolean equals(Object o) { if (!(o instanceof IndexedObject)) return false; return this.i == ((IndexedObject<?>)o).i && this.value.equals(((IndexedObject<?>)o).value); } @Override public int compareTo(IndexedObject o) { if (o.value.getClass() != this.value.getClass()) throw new IllegalArgumentException(); return value.compareTo((T) o.value); } @Override public int hashCode() { return this.i + this.value.hashCode(); } @Override public String toString() { return "IndexedObject{" + "i=" + i + ", value=" + value + '}'; } } class Point { int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (!(o instanceof Point)) return false; return this.x == ((Point)o).x && this.y == ((Point)o).y; } @Override public int hashCode() { return Integer.hashCode(x) * 524287 + Integer.hashCode(y); } } class GraphBuilder { private Map<Integer, List<Integer>> edges = new HashMap<>(); private final int N; private final boolean isDirected; public GraphBuilder(int N, boolean isDirected) { this.isDirected = isDirected; this.N = N; for (int i = 0; i < N; i++) { edges.put(i, new ArrayList<>()); } } public GraphBuilder(int N) { this(N, false); } public void addEdge(int u, int v) { edges.get(u).add(v); if (!isDirected) edges.get(v).add(u); } public Map<Integer, List<Integer>> getEdges() { return edges; } public int getN() { return N; } } class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in){ this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner(){ this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = this.nextInt(); return array; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = this.next(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } } class ContestPrinter extends java.io.PrintWriter{ public ContestPrinter(java.io.PrintStream stream){ super(stream); } public ContestPrinter(java.io.File file) throws java.io.FileNotFoundException{ super(new java.io.PrintStream(file)); } public ContestPrinter(){ super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if(x < 0){ sb.append('-'); x = -x; } x += Math.pow(10, -n)/2; sb.append((long)x); sb.append("."); x -= (long)x; for(int i = 0;i < n;i++){ x *= 10; sb.append((int)x); x -= (int)x; } return sb.toString(); } @Override public void print(float f){ super.print(dtos(f, 20)); } @Override public void println(float f){ super.println(dtos(f, 20)); } @Override public void print(double d){ super.print(dtos(d, 20)); } @Override public void println(double d){ super.println(dtos(d, 20)); } public void printArray(int[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public void printArray(int[] array){ this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n-1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map){ this.printArray(array, " ", map); } public void printArray(long[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public void printArray(long[] array){ this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n-1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map){ this.printArray(array, " ", map); } public <T> void printArray(T[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public <T> void printArray(T[] array){ this.printArray(array, " "); } public <T> void printArray(T[] array, String separator, java.util.function.UnaryOperator<T> map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.apply(array[i])); super.print(separator); } super.println(map.apply(array[n-1])); } public <T> void printArray(T[] array, java.util.function.UnaryOperator<T> map){ this.printArray(array, " ", map); } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } java.util.ArrayList<java.util.ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new java.util.ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(java.util.ArrayList::isEmpty); return result; } } class ModIntFactory { private final ModArithmetic ma; private final int mod; private final boolean usesMontgomery; private final ModArithmetic.ModArithmeticMontgomery maMontgomery; private ArrayList<Integer> factorial; public ModIntFactory(int mod) { this.ma = ModArithmetic.of(mod); this.usesMontgomery = ma instanceof ModArithmetic.ModArithmeticMontgomery; this.maMontgomery = usesMontgomery ? (ModArithmetic.ModArithmeticMontgomery) ma : null; this.mod = mod; this.factorial = new ArrayList<>(); } public ModInt create(long value) { if ((value %= mod) < 0) value += mod; if (usesMontgomery) { return new ModInt(maMontgomery.generate(value)); } else { return new ModInt((int) value); } } private void prepareFactorial(int max){ factorial.ensureCapacity(max+1); if(factorial.size()==0) factorial.add(1); if (usesMontgomery) { for(int i=factorial.size(); i<=max; i++){ factorial.add(ma.mul(factorial.get(i-1), maMontgomery.generate(i))); } } else { for(int i=factorial.size(); i<=max; i++){ factorial.add(ma.mul(factorial.get(i-1), i)); } } } public ModInt factorial(int i){ prepareFactorial(i); return create(factorial.get(i)); } public ModInt permutation(int n, int r){ if(n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); return create(ma.div(factorial.get(n), factorial.get(r))); } public ModInt combination(int n, int r){ if(n < 0 || r < 0 || n < r) return create(0); prepareFactorial(n); return create(ma.div(factorial.get(n), ma.mul(factorial.get(r),factorial.get(n-r)))); } public int getMod() { return mod; } public class ModInt { private int value; private ModInt(int value) { this.value = value; } public int mod() { return mod; } public int value() { if (usesMontgomery) { return maMontgomery.reduce(value); } return value; } public ModInt add(ModInt mi) { return new ModInt(ma.add(value, mi.value)); } public ModInt add(ModInt mi1, ModInt mi2) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3); } public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt add(ModInt mi1, ModInt... mis) { ModInt mi = add(mi1); for (ModInt m : mis) mi.addAsg(m); return mi; } public ModInt add(long mi) { return new ModInt(ma.add(value, ma.remainder(mi))); } public ModInt sub(ModInt mi) { return new ModInt(ma.sub(value, mi.value)); } public ModInt sub(long mi) { return new ModInt(ma.sub(value, ma.remainder(mi))); } public ModInt mul(ModInt mi) { return new ModInt(ma.mul(value, mi.value)); } public ModInt mul(ModInt mi1, ModInt mi2) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3); } public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mul(ModInt mi1, ModInt... mis) { ModInt mi = mul(mi1); for (ModInt m : mis) mi.mulAsg(m); return mi; } public ModInt mul(long mi) { return new ModInt(ma.mul(value, ma.remainder(mi))); } public ModInt div(ModInt mi) { return new ModInt(ma.div(value, mi.value)); } public ModInt div(long mi) { return new ModInt(ma.div(value, ma.remainder(mi))); } public ModInt inv() { return new ModInt(ma.inv(value)); } public ModInt pow(long b) { return new ModInt(ma.pow(value, b)); } public ModInt addAsg(ModInt mi) { this.value = ma.add(value, mi.value); return this; } public ModInt addAsg(ModInt mi1, ModInt mi2) { return addAsg(mi1).addAsg(mi2); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return addAsg(mi1).addAsg(mi2).addAsg(mi3); } public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return addAsg(mi1).addAsg(mi2).addAsg(mi3).addAsg(mi4); } public ModInt addAsg(ModInt... mis) { for (ModInt m : mis) addAsg(m); return this; } public ModInt addAsg(long mi) { this.value = ma.add(value, ma.remainder(mi)); return this; } public ModInt subAsg(ModInt mi) { this.value = ma.sub(value, mi.value); return this; } public ModInt subAsg(long mi) { this.value = ma.sub(value, ma.remainder(mi)); return this; } public ModInt mulAsg(ModInt mi) { this.value = ma.mul(value, mi.value); return this; } public ModInt mulAsg(ModInt mi1, ModInt mi2) { return mulAsg(mi1).mulAsg(mi2); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3); } public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) { return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4); } public ModInt mulAsg(ModInt... mis) { for (ModInt m : mis) mulAsg(m); return this; } public ModInt mulAsg(long mi) { this.value = ma.mul(value, ma.remainder(mi)); return this; } public ModInt divAsg(ModInt mi) { this.value = ma.div(value, mi.value); return this; } public ModInt divAsg(long mi) { this.value = ma.div(value, ma.remainder(mi)); return this; } @Override public String toString() { return String.valueOf(value()); } @Override public boolean equals(Object o) { if (o instanceof ModInt) { ModInt mi = (ModInt) o; return mod() == mi.mod() && value() == mi.value(); } return false; } @Override public int hashCode() { return (1 * 37 + mod()) * 37 + value(); } } private static abstract class ModArithmetic { abstract int mod(); abstract int remainder(long value); abstract int add(int a, int b); abstract int sub(int a, int b); abstract int mul(int a, int b); int div(int a, int b) { return mul(a, inv(b)); } int inv(int a) { int b = mod(); if (b == 1) return 0; long u = 1, v = 0; while (b >= 1) { int t = a / b; a -= t * b; int tmp1 = a; a = b; b = tmp1; u -= t * v; long tmp2 = u; u = v; v = tmp2; } if (a != 1) { throw new ArithmeticException("divide by zero"); } return remainder(u); } int pow(int a, long b) { if (b < 0) throw new ArithmeticException("negative power"); int r = 1; int x = a; while (b > 0) { if ((b & 1) == 1) r = mul(r, x); x = mul(x, x); b >>= 1; } return r; } static ModArithmetic of(int mod) { if (mod <= 0) { throw new IllegalArgumentException(); } else if (mod == 1) { return new ModArithmetic1(); } else if (mod == 2) { return new ModArithmetic2(); } else if (mod == 998244353) { return new ModArithmetic998244353(); } else if (mod == 1000000007) { return new ModArithmetic1000000007(); } else if ((mod & 1) == 1) { return new ModArithmeticMontgomery(mod); } else { return new ModArithmeticBarrett(mod); } } private static final class ModArithmetic1 extends ModArithmetic { int mod() {return 1;} int remainder(long value) {return 0;} int add(int a, int b) {return 0;} int sub(int a, int b) {return 0;} int mul(int a, int b) {return 0;} int pow(int a, long b) {return 0;} } private static final class ModArithmetic2 extends ModArithmetic { int mod() {return 2;} int remainder(long value) {return (int) (value & 1);} int add(int a, int b) {return a ^ b;} int sub(int a, int b) {return a ^ b;} int mul(int a, int b) {return a & b;} } private static final class ModArithmetic998244353 extends ModArithmetic { private final int mod = 998244353; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmetic1000000007 extends ModArithmetic { private final int mod = 1000000007; int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int res = a + b; return res >= mod ? res - mod : res; } int sub(int a, int b) { int res = a - b; return res < 0 ? res + mod : res; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } private static final class ModArithmeticMontgomery extends ModArithmeticDynamic { private final long negInv; private final long r2; private ModArithmeticMontgomery(int mod) { super(mod); long inv = 0; long s = 1, t = 0; for (int i = 0; i < 32; i++) { if ((t & 1) == 0) { t += mod; inv += s; } t >>= 1; s <<= 1; } long r = (1l << 32) % mod; this.negInv = inv; this.r2 = (r * r) % mod; } private int generate(long x) { return reduce(x * r2); } private int reduce(long x) { x = (x + ((x * negInv) & 0xffff_ffffl) * mod) >>> 32; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return generate((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } @Override int inv(int a) { return super.inv(reduce(a)); } @Override int pow(int a, long b) { return generate(super.pow(a, b)); } } private static final class ModArithmeticBarrett extends ModArithmeticDynamic { private static final long mask = 0xffff_ffffl; private final long mh; private final long ml; private ModArithmeticBarrett(int mod) { super(mod); /** * m = floor(2^64/mod) * 2^64 = p*mod + q, 2^32 = a*mod + b * => (a*mod + b)^2 = p*mod + q * => p = mod*a^2 + 2ab + floor(b^2/mod) */ long a = (1l << 32) / mod; long b = (1l << 32) % mod; long m = a * a * mod + 2 * a * b + (b * b) / mod; mh = m >>> 32; ml = m & mask; } private int reduce(long x) { long z = (x & mask) * ml; z = (x & mask) * mh + (x >>> 32) * ml + (z >>> 32); z = (x >>> 32) * mh + (z >>> 32); x -= z * mod; return (int) (x < mod ? x : x - mod); } @Override int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } @Override int mul(int a, int b) { return reduce((long) a * b); } } private static class ModArithmeticDynamic extends ModArithmetic { final int mod; ModArithmeticDynamic(int mod) { this.mod = mod; } int mod() { return mod; } int remainder(long value) { return (int) ((value %= mod) < 0 ? value + mod : value); } int add(int a, int b) { int sum = a + b; return sum >= mod ? sum - mod : sum; } int sub(int a, int b) { int sum = a - b; return sum < 0 ? sum + mod : sum; } int mul(int a, int b) { return (int) (((long) a * b) % mod); } } } } class SCC { static class Edge { int from, to; public Edge(int from, int to) { this.from = from; this.to = to; } } final int n; int m; final java.util.ArrayList<Edge> unorderedEdges; final int[] start; final int[] ids; boolean hasBuilt = false; public SCC(int n) { this.n = n; this.unorderedEdges = new java.util.ArrayList<>(); this.start = new int[n + 1]; this.ids = new int[n]; } public void addEdge(int from, int to) { rangeCheck(from); rangeCheck(to); unorderedEdges.add(new Edge(from, to)); start[from + 1]++; this.m++; } public int id(int i) { if (!hasBuilt) { throw new UnsupportedOperationException( "Graph hasn't been built." ); } rangeCheck(i); return ids[i]; } public int[][] build() { for (int i = 1; i <= n; i++) { start[i] += start[i - 1]; } Edge[] orderedEdges = new Edge[m]; int[] count = new int[n + 1]; System.arraycopy(start, 0, count, 0, n + 1); for (Edge e : unorderedEdges) { orderedEdges[count[e.from]++] = e; } int nowOrd = 0; int groupNum = 0; int k = 0; // parent int[] par = new int[n]; int[] vis = new int[n]; int[] low = new int[n]; int[] ord = new int[n]; java.util.Arrays.fill(ord, -1); // u = lower32(stack[i]) : visiting vertex // j = upper32(stack[i]) : jth child long[] stack = new long[n]; // size of stack int ptr = 0; // non-recursional DFS for (int i = 0; i < n; i++) { if (ord[i] >= 0) continue; par[i] = -1; // vertex i, 0th child. stack[ptr++] = 0l << 32 | i; // stack is not empty while (ptr > 0) { // last element long p = stack[--ptr]; // vertex int u = (int) (p & 0xffff_ffffl); // jth child int j = (int) (p >>> 32); if (j == 0) { // first visit low[u] = ord[u] = nowOrd++; vis[k++] = u; } if (start[u] + j < count[u]) { // there are more children // jth child int to = orderedEdges[start[u] + j].to; // incr children counter stack[ptr++] += 1l << 32; if (ord[to] == -1) { // new vertex stack[ptr++] = 0l << 32 | to; par[to] = u; } else { // backward edge low[u] = Math.min(low[u], ord[to]); } } else { // no more children (leaving) while (j --> 0) { int to = orderedEdges[start[u] + j].to; // update lowlink if (par[to] == u) low[u] = Math.min(low[u], low[to]); } if (low[u] == ord[u]) { // root of a component while (true) { // gathering verticies int v = vis[--k]; ord[v] = n; ids[v] = groupNum; if (v == u) break; } groupNum++; // incr the number of components } } } } for (int i = 0; i < n; i++) { ids[i] = groupNum - 1 - ids[i]; } int[] counts = new int[groupNum]; for (int x : ids) counts[x]++; int[][] groups = new int[groupNum][]; for (int i = 0; i < groupNum; i++) { groups[i] = new int[counts[i]]; } for (int i = 0; i < n; i++) { int cmp = ids[i]; groups[cmp][--counts[cmp]] = i; } hasBuilt = true; return groups; } private void rangeCheck(int i) { if (i < 0 || i >= n) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, n) ); } } } class LazySegTree<S, F> { final int MAX; final int N; final int Log; final java.util.function.BinaryOperator<S> Op; final S E; final java.util.function.BiFunction<F, S, S> Mapping; final java.util.function.BinaryOperator<F> Composition; final F Id; final S[] Dat; final F[] Laz; @SuppressWarnings("unchecked") public LazySegTree(int n, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.Log = Integer.numberOfTrailingZeros(N); this.Op = op; this.E = e; this.Mapping = mapping; this.Composition = composition; this.Id = id; this.Dat = (S[]) new Object[N << 1]; this.Laz = (F[]) new Object[N]; java.util.Arrays.fill(Dat, E); java.util.Arrays.fill(Laz, Id); } public LazySegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this(dat.length, op, e, mapping, composition, id); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, Dat, N, l); for (int i = N - 1; i > 0; i--) { Dat[i] = Op.apply(Dat[i << 1 | 0], Dat[i << 1 | 1]); } } private void push(int k) { if (Laz[k] == Id) return; int lk = k << 1 | 0, rk = k << 1 | 1; Dat[lk] = Mapping.apply(Laz[k], Dat[lk]); Dat[rk] = Mapping.apply(Laz[k], Dat[rk]); if (lk < N) Laz[lk] = Composition.apply(Laz[k], Laz[lk]); if (rk < N) Laz[rk] = Composition.apply(Laz[k], Laz[rk]); Laz[k] = Id; } private void pushTo(int k) { for (int i = Log; i > 0; i--) push(k >> i); } private void pushTo(int lk, int rk) { for (int i = Log; i > 0; i--) { if (((lk >> i) << i) != lk) push(lk >> i); if (((rk >> i) << i) != rk) push(rk >> i); } } private void updateFrom(int k) { k >>= 1; while (k > 0) { Dat[k] = Op.apply(Dat[k << 1 | 0], Dat[k << 1 | 1]); k >>= 1; } } private void updateFrom(int lk, int rk) { for (int i = 1; i <= Log; i++) { if (((lk >> i) << i) != lk) { int lki = lk >> i; Dat[lki] = Op.apply(Dat[lki << 1 | 0], Dat[lki << 1 | 1]); } if (((rk >> i) << i) != rk) { int rki = (rk - 1) >> i; Dat[rki] = Op.apply(Dat[rki << 1 | 0], Dat[rki << 1 | 1]); } } } public void set(int p, S x) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = x; updateFrom(p); } public S get(int p) { exclusiveRangeCheck(p); p += N; pushTo(p); return Dat[p]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return E; l += N; r += N; pushTo(l, r); S sumLeft = E, sumRight = E; while (l < r) { if ((l & 1) == 1) sumLeft = Op.apply(sumLeft, Dat[l++]); if ((r & 1) == 1) sumRight = Op.apply(Dat[--r], sumRight); l >>= 1; r >>= 1; } return Op.apply(sumLeft, sumRight); } public S allProd() { return Dat[1]; } public void apply(int p, F f) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = Mapping.apply(f, Dat[p]); updateFrom(p); } public void apply(int l, int r, F f) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return; l += N; r += N; pushTo(l, r); for (int l2 = l, r2 = r; l2 < r2;) { if ((l2 & 1) == 1) { Dat[l2] = Mapping.apply(f, Dat[l2]); if (l2 < N) Laz[l2] = Composition.apply(f, Laz[l2]); l2++; } if ((r2 & 1) == 1) { r2--; Dat[r2] = Mapping.apply(f, Dat[r2]); if (r2 < N) Laz[r2] = Composition.apply(f, Laz[r2]); } l2 >>= 1; r2 >>= 1; } updateFrom(l, r); } public int maxRight(int l, java.util.function.Predicate<S> g) { inclusiveRangeCheck(l); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; pushTo(l); S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!g.test(Op.apply(sum, Dat[l]))) { while (l < N) { push(l); l = l << 1; if (g.test(Op.apply(sum, Dat[l]))) { sum = Op.apply(sum, Dat[l]); l++; } } return l - N; } sum = Op.apply(sum, Dat[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> g) { inclusiveRangeCheck(r); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; pushTo(r - 1); S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!g.test(Op.apply(Dat[r], sum))) { while (r < N) { push(r); r = r << 1 | 1; if (g.test(Op.apply(Dat[r], sum))) { sum = Op.apply(Dat[r], sum); r--; } } return r + 1 - N; } sum = Op.apply(Dat[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d is not in [%d, %d).", p, 0, MAX) ); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d is not in [%d, %d].", p, 0, MAX) ); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } private S[] simulatePushAll() { S[] simDat = java.util.Arrays.copyOf(Dat, 2 * N); F[] simLaz = java.util.Arrays.copyOf(Laz, 2 * N); for (int k = 1; k < N; k++) { if (simLaz[k] == Id) continue; int lk = k << 1 | 0, rk = k << 1 | 1; simDat[lk] = Mapping.apply(simLaz[k], simDat[lk]); simDat[rk] = Mapping.apply(simLaz[k], simDat[rk]); if (lk < N) simLaz[lk] = Composition.apply(simLaz[k], simLaz[lk]); if (rk < N) simLaz[rk] = Composition.apply(simLaz[k], simLaz[rk]); simLaz[k] = Id; } return simDat; } public String toDetailedString() { return toDetailedString(1, 0, simulatePushAll()); } private String toDetailedString(int k, int sp, S[] dat) { if (k >= N) return indent(sp) + dat[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent, dat); s += "\n"; s += indent(sp) + dat[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent, dat); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n --> 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { S[] dat = simulatePushAll(); StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(dat[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } class Permutation implements java.util.Iterator<int[]>, Iterable<int[]> { private int[] next; public Permutation(int n) { next = java.util.stream.IntStream.range(0, n).toArray(); } @Override public boolean hasNext() { return next != null; } @Override public int[] next() { int[] r = next.clone(); next = nextPermutation(next); return r; } @Override public java.util.Iterator<int[]> iterator() { return this; } public static int[] nextPermutation(int[] a) { if (a == null || a.length < 2) return null; int p = 0; for (int i = a.length - 2; i >= 0; i--) { if (a[i] >= a[i + 1]) continue; p = i; break; } int q = 0; for (int i = a.length - 1; i > p; i--) { if (a[i] <= a[p]) continue; q = i; break; } if (p == 0 && q == 0) return null; int temp = a[p]; a[p] = a[q]; a[q] = temp; int l = p, r = a.length; while (++l < --r) { temp = a[l]; a[l] = a[r]; a[r] = temp; } return a; } } class SegTree<S> { final int MAX; final int N; final java.util.function.BinaryOperator<S> op; final S E; final S[] data; @SuppressWarnings("unchecked") public SegTree(int n, java.util.function.BinaryOperator<S> op, S e) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.E = e; this.op = op; this.data = (S[]) new Object[N << 1]; java.util.Arrays.fill(data, E); } public SegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e) { this(dat.length, op, e); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, data, N, l); for (int i = N - 1; i > 0; i--) { data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]); } } public void set(int p, S x) { exclusiveRangeCheck(p); data[p += N] = x; p >>= 1; while (p > 0) { data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]); p >>= 1; } } public S get(int p) { exclusiveRangeCheck(p); return data[p + N]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); S sumLeft = E; S sumRight = E; l += N; r += N; while (l < r) { if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]); if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight); l >>= 1; r >>= 1; } return op.apply(sumLeft, sumRight); } public S allProd() { return data[1]; } public int maxRight(int l, java.util.function.Predicate<S> f) { inclusiveRangeCheck(l); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!f.test(op.apply(sum, data[l]))) { while (l < N) { l = l << 1; if (f.test(op.apply(sum, data[l]))) { sum = op.apply(sum, data[l]); l++; } } return l - N; } sum = op.apply(sum, data[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> f) { inclusiveRangeCheck(r); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!f.test(op.apply(data[r], sum))) { while (r < N) { r = r << 1 | 1; if (f.test(op.apply(data[r], sum))) { sum = op.apply(data[r], sum); r--; } } return r + 1 - N; } sum = op.apply(data[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d).", p, 0, MAX) ); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d].", p, 0, MAX) ); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } public String toDetailedString() { return toDetailedString(1, 0); } private String toDetailedString(int k, int sp) { if (k >= N) return indent(sp) + data[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent); s += "\n"; s += indent(sp) + data[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n --> 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(data[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } class Pair<S extends Comparable<S>, T extends Comparable<T>> implements Comparable<Pair<S,T>>{ S first; T second; public Pair(S s, T t){ first = s; second = t; } public S getFirst(){return first;} public T getSecond(){return second;} public boolean equals(Object another){ if(this==another) return true; if(!(another instanceof Pair)) return false; Pair otherPair = (Pair)another; return this.first.equals(otherPair.first) && this.second.equals(otherPair.second); } public int compareTo(Pair<S,T> another){ java.util.Comparator<Pair<S,T>> comp1 = java.util.Comparator.comparing(Pair::getFirst); java.util.Comparator<Pair<S,T>> comp2 = comp1.thenComparing(Pair::getSecond); return comp2.compare(this, another); } public int hashCode(){ return first.hashCode() * 10007 + second.hashCode(); } public String toString(){ return String.format("(%s, %s)", first, second); } }
ConDefects/ConDefects/Code/abc314_d/Java/44840861
condefects-java_data_460
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); C_MinDiffSum solver = new C_MinDiffSum(); solver.solve(1, in, out); out.close(); } static class C_MinDiffSum { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int[] ls = new int[n]; int[] rs = new int[n]; for (int i = 0; i < n; i++) { ls[i] = in.nextInt(); rs[i] = in.nextInt(); } Arrays.sort(ls); Arrays.sort(rs); int[] coef = new int[n]; coef[0] = -(n - 1); for (int i = 1; i < n; i++) { coef[i] = coef[i - 1] + 2; } long[] sumCoef = new long[n + 1]; for (int i = 0; i < n; i++) { sumCoef[i + 1] = sumCoef[i] + coef[i]; } long[] sl = new long[n + 1]; long[] sr = new long[n + 1]; for (int i = 0; i < n; i++) { sr[i + 1] = sr[i] + (long) coef[i] * rs[i]; } for (int i = 0; i < n; i++) { sl[i + 1] = sl[i] + (long) coef[n - 1 - i] * ls[n - 1 - i]; } long ans = Long.MAX_VALUE; for (int who = 0; who < 2 * n; who++) { int x = who < n ? ls[who] : rs[who - n]; int numR = numSmaller(rs, x); int numL = numGreater(ls, x); long cur = sl[numL] + sr[numR]; cur += (sumCoef[n - numL] - sumCoef[numR]) * x; ans = Math.min(ans, cur); } out.println(ans); } private int numSmaller(int[] a, int x) { int l = -1; int r = a.length; while (r - l > 1) { int m = (l + r) / 2; if (a[m] < x) { l = m; } else { r = m; } } return r; } private int numGreater(int[] a, int x) { int l = -1; int r = a.length; while (r - l > 1) { int m = (l + r) / 2; if (a[m] > x) { r = m; } else { l = m; } } return a.length - l; } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } } import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); C_MinDiffSum solver = new C_MinDiffSum(); solver.solve(1, in, out); out.close(); } static class C_MinDiffSum { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int[] ls = new int[n]; int[] rs = new int[n]; for (int i = 0; i < n; i++) { ls[i] = in.nextInt(); rs[i] = in.nextInt(); } Arrays.sort(ls); Arrays.sort(rs); int[] coef = new int[n]; coef[0] = -(n - 1); for (int i = 1; i < n; i++) { coef[i] = coef[i - 1] + 2; } long[] sumCoef = new long[n + 1]; for (int i = 0; i < n; i++) { sumCoef[i + 1] = sumCoef[i] + coef[i]; } long[] sl = new long[n + 1]; long[] sr = new long[n + 1]; for (int i = 0; i < n; i++) { sr[i + 1] = sr[i] + (long) coef[i] * rs[i]; } for (int i = 0; i < n; i++) { sl[i + 1] = sl[i] + (long) coef[n - 1 - i] * ls[n - 1 - i]; } long ans = Long.MAX_VALUE; for (int who = 0; who < 2 * n; who++) { int x = who < n ? ls[who] : rs[who - n]; int numR = numSmaller(rs, x); int numL = numGreater(ls, x); long cur = sl[numL] + sr[numR]; cur += (sumCoef[n - numL] - sumCoef[numR]) * x; ans = Math.min(ans, cur); } out.println(ans); } private int numSmaller(int[] a, int x) { int l = -1; int r = a.length; while (r - l > 1) { int m = (l + r) / 2; if (a[m] < x) { l = m; } else { r = m; } } return r; } private int numGreater(int[] a, int x) { int l = -1; int r = a.length; while (r - l > 1) { int m = (l + r) / 2; if (a[m] > x) { r = m; } else { l = m; } } return a.length - r; } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
ConDefects/ConDefects/Code/arc147_c/Java/34688799
condefects-java_data_461
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.NoSuchElementException; public class Main { public static void main(String[] args) { new Main().run(); } ArrayList<int[]> list = new ArrayList<>(); // A[s] += 1 // A[t] -= 1 void g(int s, int t, long[] A) { int[] P = new int[A.length]; int[] Q = new int[A.length]; int cnt = 2; for (int i = 0; i < A.length; ++i) { if (i == s) { P[i] = 2; Q[i] = A.length; } else if (i == t) { P[i] = 1; Q[i] = A.length - 1; } else { P[i] = cnt; Q[i] = A.length - cnt + 1; ++cnt; } } for (int i = 0; i < A.length; ++i) { A[i] += P[i] + Q[i]; } list.add(P); list.add(Q); } void swap(int a, int b, int[] A) { if (a == b) throw new AssertionError(); A[a] ^= A[b]; A[b] ^= A[a]; A[a] ^= A[b]; } void run() { FastScanner sc = new FastScanner(); int N = sc.nextInt(); long[] A = new long[N]; for (int i = 0; i < N; ++i) { A[i] = sc.nextInt(); } long sum = 0; for (long a : A) sum += a; if (sum % N != 0) { int[] P = new int[N]; for (int i = 0; i < N; ++i) { P[i] = i + 1; A[i] += P[i]; } list.add(P); } while (Arrays.stream(A).max().getAsLong() > Arrays.stream(A).min().getAsLong() + 1) { long min = Arrays.stream(A).min().getAsLong(); long max = Arrays.stream(A).max().getAsLong(); int s = 0; int t = 0; while (min != A[s]) ++s; while (max != A[t]) ++t; g(s, t, A); } PrintWriter pw = new PrintWriter(System.out); if (Arrays.stream(A).max().getAsLong() != Arrays.stream(A).min().getAsLong()) { pw.println("No"); } else { pw.println("Yes"); pw.println(list.size()); for (int[] P : list) { for (int i = 0; i < N; ++i) { pw.print(P[i] + (i == N - 1 ? "\n" : " ")); } } } pw.close(); } void tr(Object...objects) {System.out.println(Arrays.deepToString(objects));} } class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} private void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;} public boolean hasNext() { skipUnprintable(); return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } int nextInt() { return (int) nextLong(); } } import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.NoSuchElementException; public class Main { public static void main(String[] args) { new Main().run(); } ArrayList<int[]> list = new ArrayList<>(); // A[s] += 1 // A[t] -= 1 void g(int s, int t, long[] A) { int[] P = new int[A.length]; int[] Q = new int[A.length]; int cnt = 3; for (int i = 0; i < A.length; ++i) { if (i == s) { P[i] = 2; Q[i] = A.length; } else if (i == t) { P[i] = 1; Q[i] = A.length - 1; } else { P[i] = cnt; Q[i] = A.length - cnt + 1; ++cnt; } } for (int i = 0; i < A.length; ++i) { A[i] += P[i] + Q[i]; } list.add(P); list.add(Q); } void swap(int a, int b, int[] A) { if (a == b) throw new AssertionError(); A[a] ^= A[b]; A[b] ^= A[a]; A[a] ^= A[b]; } void run() { FastScanner sc = new FastScanner(); int N = sc.nextInt(); long[] A = new long[N]; for (int i = 0; i < N; ++i) { A[i] = sc.nextInt(); } long sum = 0; for (long a : A) sum += a; if (sum % N != 0) { int[] P = new int[N]; for (int i = 0; i < N; ++i) { P[i] = i + 1; A[i] += P[i]; } list.add(P); } while (Arrays.stream(A).max().getAsLong() > Arrays.stream(A).min().getAsLong() + 1) { long min = Arrays.stream(A).min().getAsLong(); long max = Arrays.stream(A).max().getAsLong(); int s = 0; int t = 0; while (min != A[s]) ++s; while (max != A[t]) ++t; g(s, t, A); } PrintWriter pw = new PrintWriter(System.out); if (Arrays.stream(A).max().getAsLong() != Arrays.stream(A).min().getAsLong()) { pw.println("No"); } else { pw.println("Yes"); pw.println(list.size()); for (int[] P : list) { for (int i = 0; i < N; ++i) { pw.print(P[i] + (i == N - 1 ? "\n" : " ")); } } } pw.close(); } void tr(Object...objects) {System.out.println(Arrays.deepToString(objects));} } class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} private void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;} public boolean hasNext() { skipUnprintable(); return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } int nextInt() { return (int) nextLong(); } }
ConDefects/ConDefects/Code/arc159_c/Java/41238682
condefects-java_data_462
import java.util.*; public class Main { static int minFactor[]; static boolean prime[]; static void prepareOsaK(int n){ prime = new boolean[n+1]; Arrays.fill(prime, true); prime[0] = prime[1] = false; minFactor = new int[n+1]; Arrays.fill(minFactor, -1); minFactor[1] = 1; for(int i = 2;i <= n;i++){ if(!prime[i]) continue; minFactor[i] = i; for(int j = i * 2;j <= n; j+=i){ prime[j] = false; if(minFactor[j] == -1) minFactor[j] = i; } } } public static void main(String[] args) { prepareOsaK(10000); int a = getInt(); int b = getInt(); int c = getInt(); int d = getInt(); for(int i = a;i <= b;i++){ boolean find = false; for(int j = c;j <= d;j++){ if(prime[i+j]){ find = true; } } if(!find){ out("Takahashi"); break; } } out("Aoki"); } static Comparator<Long> lower = (x, y) -> x.compareTo(y) >= 0 ? 1 : -1; // 指定した値以上の初めての要素の位置 static Comparator<Long> upper = (x, y) -> x.compareTo(y) > 0 ? 1 : -1;// 指定した値より大きい初めての要素の位置 static long ceil(long n, long d){ return (n + d - 1) / d; } static int sqrtI(long n){ return toInt(Math.sqrt(n)); } static long toLong(double v) { return Double.valueOf(v).longValue(); } static int toInt(double v) { return Double.valueOf(v).intValue(); } static String[] createTiles(int w, int h, String out){ String[] s = new String[h + 2]; s[0] = s[h + 1] = out.repeat(w + 2); for (int i = 1; i <= h; i++) { s[i] = out + getString() + out; } return s; } static void outH(List<?> o){ int nl = o.size()-1; for (int i = 0; i < o.size(); i++) { System.out.print(o.get(i)+(i != nl ? " ":"\n")); } } static void out(List<?> o){ for (Object oo: o) { System.out.println(oo); } } static void outH(Object[] o){ int nl = o.length-1; for (int i = 0; i < o.length; i++) { System.out.print(o[i]+(i != nl ? " ":"")); } out(); } static void outH(char[] d){ int nl = d.length-1; for (int i = 0; i < d.length; i++) { System.out.print(d[i]+(i != nl ? " ":"")); } out(); } static void outH(double[] d){ int nl = d.length-1; for (int i = 0; i < d.length; i++) { System.out.print(d[i]+(i != nl ? " ":"")); } out(); } static void outH(int[] in){ int nl = in.length-1; for (int i = 0; i < in.length; i++) { System.out.print(in[i]+(i != nl ? " ":"")); } out(); } static void outH(long[] l){ int nl = l.length-1; for (int i = 0; i < l.length; i++) { System.out.print(l[i]+(i != nl ? " ":"")); } out(); } static void outH(String[] s){ int nl = s.length-1; for (int i = 0; i < s.length; i++) { System.out.print(s[i]+(i != nl ? " ":"")); } out(); } static void out(){ System.out.println(); } static void out(Object[] o){ for (Object oo : o) { System.out.println(oo); } } static String sortString(String s) { char[] a = s.toCharArray(); Arrays.sort(a); return new String(a); } static String sortStringDesc(String s) { return new StringBuilder(sortString(s)).reverse().toString(); } static void out(char[] c){ for (Character aChar : c) { System.out.println(aChar); } } static void out(double[] d){ for (Double aDouble : d) { System.out.println(aDouble); } } static void out(int[] i){ for (Integer iInteger: i) { System.out.println(iInteger); } } static void out(long[] l){ for (Long lLong: l) { System.out.println(lLong); } } static void out(String[] s){ for (String sString: s) { System.out.println(sString); } } static void out(Double d){ System.out.println(d); } static void out(Integer i){ System.out.println(i); } static void out(Long l){ System.out.println(l); } static void out(String s){ System.out.println(s); } static void YesOrNo(boolean b){ System.out.println(b ? "Yes" : "No"); } static void YesOrNo(boolean b, String yes, String no){ System.out.println(b ? yes : no); } static void Yes(){ System.out.println("Yes"); } static void No(){ System.out.println("No"); } /* static StringTokenizer st; static InputStreamReader isr = new InputStreamReader(System.in); static BufferedReader br = new BufferedReader(isr); static String getString() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine().trim()); } catch (IOException e) { System.exit(0); } } return st.nextToken(); } static long getLong() { return Long.parseLong(getString()); } static int getInt() { return Integer.parseInt(getString()); } static Double getDouble() { return parseDouble(getString()); } */ private static final java.io.InputStream in = System.in; private static final byte[] buffer = new byte[1024]; private static int ptr = 0; private static int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; static boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } static int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } static boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } static String getString() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } static long getLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } static public int getInt() { long nl = getLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } static public double getDouble() { return Double.parseDouble(getString()); } static public Long[] getLongArray(int length){ Long[] array = new Long[length]; for(int i=0; i<length; i++) array[i] = getLong(); return array; } static public Long[] getLongArray(int length, java.util.function.LongUnaryOperator map){ Long[] array = new Long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(getLong()); return array; } static public int[] getIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = getInt(); return array; } static public int[] getIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(getInt()); return array; } static public double[] getDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = getDouble(); return array; } static public double[] getDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(getDouble()); return array; } static public long[][] getLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = getLong(); } return mat; } static int[][] getIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = getInt(); } return mat; } static public double[][] getDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = getDouble(); } return mat; } static public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = getString(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } public static long mod1097 = 1000000007L; public static long mod9982 = 998244353L; } import java.util.*; public class Main { static int minFactor[]; static boolean prime[]; static void prepareOsaK(int n){ prime = new boolean[n+1]; Arrays.fill(prime, true); prime[0] = prime[1] = false; minFactor = new int[n+1]; Arrays.fill(minFactor, -1); minFactor[1] = 1; for(int i = 2;i <= n;i++){ if(!prime[i]) continue; minFactor[i] = i; for(int j = i * 2;j <= n; j+=i){ prime[j] = false; if(minFactor[j] == -1) minFactor[j] = i; } } } public static void main(String[] args) { prepareOsaK(10000); int a = getInt(); int b = getInt(); int c = getInt(); int d = getInt(); for(int i = a;i <= b;i++){ boolean find = false; for(int j = c;j <= d;j++){ if(prime[i+j]){ find = true; } } if(!find){ out("Takahashi"); return; } } out("Aoki"); } static Comparator<Long> lower = (x, y) -> x.compareTo(y) >= 0 ? 1 : -1; // 指定した値以上の初めての要素の位置 static Comparator<Long> upper = (x, y) -> x.compareTo(y) > 0 ? 1 : -1;// 指定した値より大きい初めての要素の位置 static long ceil(long n, long d){ return (n + d - 1) / d; } static int sqrtI(long n){ return toInt(Math.sqrt(n)); } static long toLong(double v) { return Double.valueOf(v).longValue(); } static int toInt(double v) { return Double.valueOf(v).intValue(); } static String[] createTiles(int w, int h, String out){ String[] s = new String[h + 2]; s[0] = s[h + 1] = out.repeat(w + 2); for (int i = 1; i <= h; i++) { s[i] = out + getString() + out; } return s; } static void outH(List<?> o){ int nl = o.size()-1; for (int i = 0; i < o.size(); i++) { System.out.print(o.get(i)+(i != nl ? " ":"\n")); } } static void out(List<?> o){ for (Object oo: o) { System.out.println(oo); } } static void outH(Object[] o){ int nl = o.length-1; for (int i = 0; i < o.length; i++) { System.out.print(o[i]+(i != nl ? " ":"")); } out(); } static void outH(char[] d){ int nl = d.length-1; for (int i = 0; i < d.length; i++) { System.out.print(d[i]+(i != nl ? " ":"")); } out(); } static void outH(double[] d){ int nl = d.length-1; for (int i = 0; i < d.length; i++) { System.out.print(d[i]+(i != nl ? " ":"")); } out(); } static void outH(int[] in){ int nl = in.length-1; for (int i = 0; i < in.length; i++) { System.out.print(in[i]+(i != nl ? " ":"")); } out(); } static void outH(long[] l){ int nl = l.length-1; for (int i = 0; i < l.length; i++) { System.out.print(l[i]+(i != nl ? " ":"")); } out(); } static void outH(String[] s){ int nl = s.length-1; for (int i = 0; i < s.length; i++) { System.out.print(s[i]+(i != nl ? " ":"")); } out(); } static void out(){ System.out.println(); } static void out(Object[] o){ for (Object oo : o) { System.out.println(oo); } } static String sortString(String s) { char[] a = s.toCharArray(); Arrays.sort(a); return new String(a); } static String sortStringDesc(String s) { return new StringBuilder(sortString(s)).reverse().toString(); } static void out(char[] c){ for (Character aChar : c) { System.out.println(aChar); } } static void out(double[] d){ for (Double aDouble : d) { System.out.println(aDouble); } } static void out(int[] i){ for (Integer iInteger: i) { System.out.println(iInteger); } } static void out(long[] l){ for (Long lLong: l) { System.out.println(lLong); } } static void out(String[] s){ for (String sString: s) { System.out.println(sString); } } static void out(Double d){ System.out.println(d); } static void out(Integer i){ System.out.println(i); } static void out(Long l){ System.out.println(l); } static void out(String s){ System.out.println(s); } static void YesOrNo(boolean b){ System.out.println(b ? "Yes" : "No"); } static void YesOrNo(boolean b, String yes, String no){ System.out.println(b ? yes : no); } static void Yes(){ System.out.println("Yes"); } static void No(){ System.out.println("No"); } /* static StringTokenizer st; static InputStreamReader isr = new InputStreamReader(System.in); static BufferedReader br = new BufferedReader(isr); static String getString() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine().trim()); } catch (IOException e) { System.exit(0); } } return st.nextToken(); } static long getLong() { return Long.parseLong(getString()); } static int getInt() { return Integer.parseInt(getString()); } static Double getDouble() { return parseDouble(getString()); } */ private static final java.io.InputStream in = System.in; private static final byte[] buffer = new byte[1024]; private static int ptr = 0; private static int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; static boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } static int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } static boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } static String getString() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } static long getLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } static public int getInt() { long nl = getLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } static public double getDouble() { return Double.parseDouble(getString()); } static public Long[] getLongArray(int length){ Long[] array = new Long[length]; for(int i=0; i<length; i++) array[i] = getLong(); return array; } static public Long[] getLongArray(int length, java.util.function.LongUnaryOperator map){ Long[] array = new Long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(getLong()); return array; } static public int[] getIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = getInt(); return array; } static public int[] getIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(getInt()); return array; } static public double[] getDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = getDouble(); return array; } static public double[] getDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(getDouble()); return array; } static public long[][] getLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = getLong(); } return mat; } static int[][] getIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = getInt(); } return mat; } static public double[][] getDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = getDouble(); } return mat; } static public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = getString(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } public static long mod1097 = 1000000007L; public static long mod9982 = 998244353L; }
ConDefects/ConDefects/Code/abc239_d/Java/54146576
condefects-java_data_463
import java.util.*; import java.io.*; public class Main { public static boolean isPrime(int n){ if(n<=1) return false; for(int i = 2; i<=n/2; i++){ if(n%i==0){ return false; } } return true; } public static void main(String[] args) { FastScanner sc = new FastScanner(); List<Integer> primes = new ArrayList<>(); for(int i = 2; i<=200; i++){ if(isPrime(i)) primes.add(i); } int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); int cnt1 = 0; for(int i = a; i<=b; i++){ int cnt = 0; for(int j = c; j<=d; j++){ if(primes.contains(i+j)) cnt++; } if(cnt==0) cnt1++; } if(cnt1 != 0){ System.out.println("Takanashi"); } else{ System.out.println("Aoki"); } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } import java.util.*; import java.io.*; public class Main { public static boolean isPrime(int n){ if(n<=1) return false; for(int i = 2; i<=n/2; i++){ if(n%i==0){ return false; } } return true; } public static void main(String[] args) { FastScanner sc = new FastScanner(); List<Integer> primes = new ArrayList<>(); for(int i = 2; i<=200; i++){ if(isPrime(i)) primes.add(i); } int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); int cnt1 = 0; for(int i = a; i<=b; i++){ int cnt = 0; for(int j = c; j<=d; j++){ if(primes.contains(i+j)) cnt++; } if(cnt==0) cnt1++; } if(cnt1 != 0){ System.out.println("Takahashi"); } else{ System.out.println("Aoki"); } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
ConDefects/ConDefects/Code/abc239_d/Java/30136984
condefects-java_data_464
import java.util.*; import java.io.*; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static long pow(long a , long b , long c) { if(b == 0) return 1; long ans = pow(a,b/2,c); if(b%2 == 0) return ans*ans%c; return ans*ans%c*a%c; } public static void main(String []args) throws IOException { Reader sc = new Reader(); long a = sc.nextLong(); long b = sc.nextLong(); long pr = 1; boolean found = false; long mod = 998244353; long lim = (long)Math.sqrt(a); for(int i = 2 ; i <= lim ; i++) { if(a%i == 0) { int cnt = 0; while(a%i == 0) { a /= i; cnt++; } if(cnt%2 == 1 && b%2 == 1) { found = true; // System.out.println(cnt + " " + b + " " + i); } long prr = b%mod*(long)cnt%mod; pr *= (1+prr)%mod; pr %= mod; } } // System.out.println(pr); if(a > 1) { pr *= (1+(b%mod)); pr %= mod; } if(b%2 == 0) found = true; pr = pr*(b%mod)%mod; pr %= mod; //System.out.println(pr + " " + found); if(!found) { pr--; pr = (pr+mod)%mod; } pr *= pow(2,mod-2,mod); pr %= mod; System.out.println(pr); } } import java.util.*; import java.io.*; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static long pow(long a , long b , long c) { if(b == 0) return 1; long ans = pow(a,b/2,c); if(b%2 == 0) return ans*ans%c; return ans*ans%c*a%c; } public static void main(String []args) throws IOException { Reader sc = new Reader(); long a = sc.nextLong(); long b = sc.nextLong(); long pr = 1; boolean found = false; long mod = 998244353; long lim = (long)Math.sqrt(a); for(int i = 2 ; i <= lim ; i++) { if(a%i == 0) { int cnt = 0; while(a%i == 0) { a /= i; cnt++; } if(cnt%2 == 1 && b%2 == 1) { found = true; // System.out.println(cnt + " " + b + " " + i); } long prr = b%mod*(long)cnt%mod; pr *= (1+prr)%mod; pr %= mod; } } // System.out.println(pr); if(a > 1) { pr *= (1+(b%mod)); if(b%2 == 1) found = true; pr %= mod; } if(b%2 == 0) found = true; pr = pr*(b%mod)%mod; pr %= mod; //System.out.println(pr + " " + found); if(!found) { pr--; pr = (pr+mod)%mod; } pr *= pow(2,mod-2,mod); pr %= mod; System.out.println(pr); } }
ConDefects/ConDefects/Code/arc167_b/Java/46633148
condefects-java_data_465
import java.math.BigInteger; import java.util.Scanner; /** * @ProjectName: study3 * @FileName: Ex14 * @author:HWJ * @Data: 2023/10/15 20:28 */ public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); long A = input.nextLong(); long B = input.nextLong(); BigInteger[] num = new BigInteger[1000005]; int p = 0; for (int i = 2; i <= Math.sqrt(A); i++) { long cont = 0; while (A % i == 0) { A /= i; cont++; } if (cont > 0) { num[p++] = new BigInteger(String.valueOf(cont)); } if (A == 1) { break; } if (i > A) { break; } } if (A > 0){ num[p++] = new BigInteger("1"); } BigInteger ans = new BigInteger(String.valueOf(B)); for (int i = 0; i < p; i++) { ans = (ans.multiply((num[i].multiply(new BigInteger(String.valueOf(B)))).add(new BigInteger("1")))); } ans = ans.divide(new BigInteger("2")); ans = ans.mod(new BigInteger("998244353")); System.out.println(ans); } } import java.math.BigInteger; import java.util.Scanner; /** * @ProjectName: study3 * @FileName: Ex14 * @author:HWJ * @Data: 2023/10/15 20:28 */ public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); long A = input.nextLong(); long B = input.nextLong(); BigInteger[] num = new BigInteger[1000005]; int p = 0; for (int i = 2; i <= Math.sqrt(A); i++) { long cont = 0; while (A % i == 0) { A /= i; cont++; } if (cont > 0) { num[p++] = new BigInteger(String.valueOf(cont)); } if (A == 1) { break; } if (i > A) { break; } } if (A > 1){ num[p++] = new BigInteger("1"); } BigInteger ans = new BigInteger(String.valueOf(B)); for (int i = 0; i < p; i++) { ans = (ans.multiply((num[i].multiply(new BigInteger(String.valueOf(B)))).add(new BigInteger("1")))); } ans = ans.divide(new BigInteger("2")); ans = ans.mod(new BigInteger("998244353")); System.out.println(ans); } }
ConDefects/ConDefects/Code/arc167_b/Java/46648579
condefects-java_data_466
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.util.function.*; import java.util.stream.IntStream; public class Main implements Runnable{ public static void main(String[] args) { //Thread.setDefaultUncaughtExceptionHandler((t,e)->System.exit(1)); //new Thread(null,new Main(),"",16L*1024*1024).start(); Solver.SOLVE(); } public void run(){ Solver.SOLVE(); } } class UnionFind { private int[] roots; public UnionFind(int n){ roots = new int[n]; for (int i = 0; i < n; i++) { roots[i] = i; } } public int root(int x){ if(roots[x] == x){ return x; } return roots[x] = root(roots[x]); } public void unite(int x,int y){ int rx = root(x); int ry = root(y); if(rx == ry){ return; } roots[rx] = ry; } public boolean same(int x,int y){ int rx = root(x); int ry = root(y); return rx == ry; } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } ArrayList<ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } ArrayList<ArrayList<Integer>> result = new ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(ArrayList::isEmpty); return result; } } class PairL implements Comparable<PairL>, Comparator<PairL> { public long x,y; public PairL(long x,long y) { this.x = x; this.y = y; } public void swap(){ long t = x; x = y; y = t; } @Override public int compare(PairL o1, PairL o2) { return o1.compareTo(o2); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairL pairl = (PairL) o; return x == pairl.x && y == pairl.y; } @Override public int hashCode() { return Objects.hash(x, y); } public PairL add(PairL p){ return new PairL(x+p.x,y+p.y); } @Override public int compareTo(PairL o) { return Long.compare(x,o.x); } } class PairI implements Comparable<PairI>, Comparator<PairI> { public int x,y; public PairI(int x,int y) { this.x = x; this.y = y; } public void swap(){ int t = x; x = y; y = t; } @Override public int compare(PairI o1, PairI o2) { if(o1.x == o2.x){ return Integer.compare(o1.y,o2.y); } return Integer.compare(o1.x,o2.x); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairI pairI = (PairI) o; return x == pairI.x && y == pairI.y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public int compareTo(PairI o) { if(x == o.x){ return Integer.compare(y,o.y); } return Integer.compare(x,o.x); } public PairI add(PairI p){ return new PairI(x+p.x,y+p.y); } public PairI sub(PairI p){ return new PairI(x-p.x,y-p.y); } public PairI addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new PairI(x,y); } return null; } } class PairISet{ int x,y; PairISet(int x,int y){ this.x = x; this.y = y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairI pairI = (PairI) o; return (x == pairI.x && y == pairI.y)||(x == pairI.y && y == pairI.x); } } class Line{ //ax+bx+c=0 long a,b,c; public Line(int x0, int y0, int x1, int y1) { long dx = x1-x0; long dy = y1-y0; long gcd = Solver.gcd(dx,dy); dx/=gcd; dy/=gcd; if(dx < 0){ dx=-dx; dy=-dy; } if(dx == 0 && dy < 0){ dy=-dy; } a = dy; b = -dx; c = dx*y0-dy*x0; } public boolean onLine(int x,int y){ return a*x + b*y + c == 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Line line = (Line) o; return a == line.a && b == line.b && c == line.c; } @Override public int hashCode() { return Objects.hash(a, b, c); } } class Dist extends PairI{ int d; public Dist(int x,int y,int d){ super(x,y); this.d = d; } public Dist addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new Dist(x,y,d+1); } return null; } } class Tuple implements Comparable<Tuple>{ public int x,y,z; public Tuple(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Tuple three = (Tuple) o; return x == three.x && y == three.y && z == three.z; } @Override public int hashCode() { return Objects.hash(x, y, z); } @Override public int compareTo(Tuple o) { if(x == o.x){ return Integer.compare(y,o.y); } return Integer.compare(x,o.x); } } class Edge implements Comparable<Edge>{ public int from; public int to; public int name; public long d; public Edge(int to){ this.to = to; } public Edge(int to, long d){ this.to = to; this.d = d; } public Edge setName(int name){ this.name = name; return this; } public Edge(int from, int to, long d){ this.to = to; this.from = from; this.d = d; } @Override public int compareTo(Edge o) { return Long.compare(d,o.d); } } class PairC{ char a,b; public PairC(char a, char b){ this.a = a; this.b = b; } } class IB{ int i; boolean b; IB(int i,boolean b){ this.i = i; this.b = b; } } class CI{ char c; int i; CI(char c,int i){ this.c = c; this.i = i; } } class SortedMultiSet extends TreeMap<Long,Integer>{ public void add(long a){ put(a,getOrDefault(a,0)+1); } public void remove(long a){ if(get(a) == 1){ super.remove(a); }else{ put(a,get(a)-1); } } public void lower(long a){ } } class MultiSet extends HashMap<Integer,Integer>{ public void add(int a){ put(a,getOrDefault(a,0)+1); } public void remove(int a){ if(get(a) == 1){ super.remove(a); }else{ put(a,get(a)-1); } } public boolean contains(int a){ return containsKey(a); } } class PP{ PairI s,t; int name; public PP(PairI s, PairI t,int name) { this.s = s; this.t = t; this.name = name; } } class Pair<T extends Comparable<T>,U> implements Comparable<Pair<T,U>>{ T t; U u; public Pair(T t, U u) { this.t = t; this.u = u; } @Override public int compareTo(Pair<T,U> o) { return t.compareTo(o.t); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(t, pair.t) && Objects.equals(u, pair.u); } @Override public int hashCode() { return Objects.hash(t, u); } } class Matrix{ int row; int column; int[][] nums; public Matrix(int row,int column){ this.row = row; this.column = column; nums = new int[row][column]; } } class SquareMatrix{ int size; long[][] nums; public SquareMatrix(int size){ this.size = size; nums = new long[size][size]; } public SquareMatrix(long[][] nums){ size = nums.length; this.nums = new long[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { this.nums[i][j] = nums[i][j]; } } } public static SquareMatrix identityMatrix(int size){ long[][] mat = new long[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if(i == j){ mat[i][j] = 1; } } } return new SquareMatrix(mat); } public SquareMatrix mul(SquareMatrix m){ if(m.size != size){ throw new IllegalArgumentException(); } SquareMatrix ans = new SquareMatrix(size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { ans.nums[i][k] += nums[i][j]*m.nums[j][k]; } } } return ans; } public SquareMatrix modMul(SquareMatrix m,long mod){ if(m.size != size){ throw new IllegalArgumentException(); } SquareMatrix ans = new SquareMatrix(size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { ans.nums[i][k] += nums[i][j]*m.nums[j][k]; ans.nums[i][k]%=mod; } } } return ans; } public long[] mulVec(long[] vec){ if(vec.length != size){ throw new IllegalArgumentException(); } long[] ans = new long[size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { ans[i] += vec[j]*nums[i][j]; } } return ans; } public long[] modMulVec(long[] vec,long mod){ if(vec.length != size){ throw new IllegalArgumentException(); } long[] ans = new long[size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { ans[i] += vec[j]*nums[i][j]; ans[i]%=mod; } } return ans; } public static SquareMatrix pow(SquareMatrix base,long exp){ SquareMatrix ans = identityMatrix(base.size); while (exp > 0){ if ((exp & 1) == 1) { ans = base.mul(ans); } base = base.mul(base); exp >>= 1; } return ans; } public SquareMatrix pow(long exp){ return pow(this,exp); } public static SquareMatrix modPow(SquareMatrix base,long exp,long mod){ SquareMatrix ans = identityMatrix(base.size); while (exp > 0){ if ((exp & 1) == 1) { ans = base.modMul(ans,mod); } base = base.modMul(base,mod); exp >>= 1; } return ans; } public SquareMatrix modPow(long exp,long mod){ return modPow(this,exp,mod); } } class Fraction implements Comparable<Fraction>{ long de,num; int name; public Fraction(long de,long num) { this.de = de; this.num = num; } @Override public int compareTo(Fraction o) { long a = de * o.num; long b = num* o.de; return Long.compare(a,b); } public double doubleValue(){ return (double) de/num; } } class Solver { public static final int MOD1 = 1000000007; public static final int MOD9 = 998244353; public static Scanner sc = new Scanner(System.in); public static final int inf = 2000000000; public static final int ninf = -inf; public static final long infl = 2000000000000000000L; public static final long ninfl = -infl; public static final char[] alpha = "abcdefghijklmnopqrstuvwxyz".toCharArray(); public static final char[] ALPHA = "abcdefghijklmnopqrstuvwxyz".toUpperCase().toCharArray(); public static FastScanner fs = new FastScanner(); public static PrintWriter out = new PrintWriter(System.out); public static final PairI[] move = new PairI[]{new PairI(1,0),new PairI(0,1),new PairI(-1,0),new PairI(0,-1)}; public static final PairI[] move8 = new PairI[]{ new PairI(1,0),new PairI(0,1),new PairI(-1,0),new PairI(0,-1), new PairI(1,1),new PairI(-1,1),new PairI(1,-1),new PairI(-1,-1) }; public static void solve() { long a = rL(); long b = rL(); ArrayList<PairL> pf = new ArrayList<>(); long v = a; for (int i = 2; (long)i*i <= a; i++) { int div = 0; while (v%i==0){ v/=i; div++; } if(div!=0){ pf.add(new PairL(i,div)); } } if(v == a){ pf.add(new PairL(v,1)); } MC m = new MC(MOD9); long pnum = 1; boolean iseven = false; boolean divd = false; if(b%2==0){ iseven = true; } for(PairL p:pf){ long mult = ((p.y)*(b%MOD9)+1)%MOD9; if((p.y)*(b%MOD9)+1 == MOD9){ divd = true; } if(p.y%2==1&&b%2==1){ iseven = true; } pnum *= mult; pnum%=MOD9; } if(iseven&&!divd){ oL((m.div(((b%MOD9)*pnum)%MOD9,2))%MOD9); }else { oL((m.div(((b%MOD9)*pnum-1)%MOD9,2))%MOD9); } } static void sort(int[] a){ Arrays.sort(a); } static void sort(int[] a,Comparator<Integer> c){ ArrayList<Integer> list = convI(a); list.sort(c); for (int i = 0; i < a.length; i++) { a[i] = list.get(i); } } static char toLower(char a){ return String.valueOf(a).toLowerCase().charAt(0); } static char toUpper(char a){ return String.valueOf(a).toUpperCase().charAt(0); } static int nand(int a,int b){ if(a == 1&&b == 1){ return 0; } return 1; } static int standingBits(long n){ String bits = toBits(n); int ans = 0; for (int i = 0; i < bits.length(); i++) { if(bits.charAt(i) == '1'){ ans++; } } return ans; } static boolean contain(String s,char c){ for (int i = 0; i < s.length(); i++) { if(s.charAt(i) == c){ return true; } } return false; } static String toBits(long n){ StringBuilder ans = new StringBuilder(); while (n > 0){ ans.append(n%2); n/=2; } return ans.reverse().toString(); } static long toLong(String anss){ long ansi = 0; for (int i = 0; i < anss.length(); i++) { if(anss.charAt(i) == '1'){ ansi += (1L<<(anss.length()-1-i)); } } return ansi; } static int perfectPowNum(long n){ int res = 0; double range = Math.log(n)/Math.log(2); range++; for (int i = 2; i < range; i++) { long a = (long) Math.pow(n,1d/i); if(pow(a,i) == n||pow(a+1,i)==n){ res++; } } return res; } static boolean[] eratosthenes(int n){ boolean[] res = new boolean[n+1]; for (int i = 2; i <= n; i++) { res[i] = true; } for (int i = 2; i <= n; i++) { if(res[i]){ int k = i*2; while (k <= n){ res[k] = false; k+=i; } } } return res; } static BitSet and(BitSet set1,BitSet set2){ BitSet ans = (BitSet) set1.clone(); ans.and(set2); return ans; } static BitSet or(BitSet set1,BitSet set2){ BitSet ans = (BitSet) set1.clone(); ans.or(set2); return ans; } static BitSet xor(BitSet set1,BitSet set2){ BitSet ans = (BitSet) set1.clone(); ans.xor(set2); return ans; } static BitSet toBitset(long n){ return BitSet.valueOf(new long[]{n}); } static long toLong(BitSet set){ if(set.length() > 63) { throw new IllegalArgumentException(); } if(set.length() == 0){ return 0; } return set.toLongArray()[0]; } static int deg(long x){ return String.valueOf(x).length(); } static int nthdeg(long x,int d){ x/=pow(10,d); return (int)(x%10); } static boolean isPalindrome(int a,int b,String s){ int dif = b-a; boolean ok = true; for (int i = 0; i < dif; i++) { if (s.charAt(i + a) != s.charAt(b - i)) { ok = false; break; } } return ok; } static int intValue(char c){ return Integer.parseInt(String.valueOf(c)); } public static int toIntC(char c){ for (int i = 0; i < ALPHA.length; i++) { if(c == ALPHA[i]){ return i; } } throw new IllegalArgumentException("not an alphabet"); } public static int toInt(char c){ for (int i = 0; i < alpha.length; i++) { if(c == alpha[i]){ return i; } } throw new IllegalArgumentException("not an alphabet"); } public static void reverse(int[] a){ int[] tmp = a.clone(); for (int i = 0; i < a.length; i++) { a[i] = tmp[a.length - 1 - i]; } } public static int[] compress(int[] a){ int[] ans = new int[a.length]; int[] b = erase(a); Arrays.sort(b); for (int i = 0; i < a.length; i++) { ans[i] = lower(b,a[i]); } return ans; } public static int lower(int[] a,int x){ int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x <= a[mid]) { high = mid; } else { low = mid + 1; } } if (low < a.length && a[low] < x) { low++; } return low; } public static int lower(long[] a,long x) { int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x <= a[mid]) { high = mid; } else { low = mid + 1; } } if (low < a.length && a[low] < x) { low++; } return low; } public static <T extends Comparable<? super T>> int lower(T[] a,T x){ int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x.compareTo(a[mid]) < 1) { high = mid; } else { low = mid + 1; } } if (low < a.length && x.compareTo(a[low]) > 0) { low++; } return low; } public static int upper(int[] a,int x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x >= a[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static int upper(long[] a,long x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x >= a[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static <T extends Comparable<? super T>> int upper(T[] a,T x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x.compareTo(a[mid]) > -1) { low = mid + 1; } else { high = mid; } } return low; } public static int[] erase(int[] a){ HashSet<Integer> used = new HashSet<>(); ArrayList<Integer> ans = new ArrayList<>(); for (int i = 0; i < a.length; i++) { if(!used.contains(a[i])){ used.add(a[i]); ans.add(a[i]); } } return convI(ans); } public static int abs(int a){ return Math.abs(a); } public static long abs(long a){ return Math.abs(a); } public static int max(int a,int b){ return Math.max(a,b); } public static int max(int... a){ int max = Integer.MIN_VALUE; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static long max(long a,long b){ return Math.max(a,b); } public static long max(long... a){ long max = Long.MIN_VALUE; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static <T extends Comparable<? super T>> T max(T a,T b){ if(a.compareTo(b) > 0){ return a; }else { return b; } } public static int min(int a,int b){ return Math.min(a,b); } public static int min(int... a){ int min = Integer.MAX_VALUE; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static <T extends Comparable<? super T>> T min(T a,T b){ if(a.compareTo(b) > 0){ return b; }else { return a; } } public static long min(long a,long b){ return Math.min(a, b); } public static long min(long... a){ long min = Long.MAX_VALUE; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static final class MC { private final int mod; public MC(final int mod) { this.mod = mod; } public long mod(long x) { x %= mod; if (x < 0) { x += mod; } return x; } public long add(final long a, final long b) { return mod(mod(a) + mod(b)); } public long add(final long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = add(ans,a[i]); } return mod(ans); } public long mul(final long a, final long b) { return mod(mod(a) * mod(b)); } public long mul(final long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = mul(ans,a[i]); } return mod(ans); } public long div(final long numerator, final long denominator) { return mod(numerator * inverse(denominator)); } public long power(long base, long exp) { long ret = 1; base %= mod; while (exp > 0) { if ((exp & 1) == 1) { ret = mul(ret, base); } base = mul(base, base); exp >>= 1; } return ret; } public long inverse(final long x) { return power(x, mod - 2); } public long fact(final int n) { return product(1, n); } public long permutation(int n,int r){ return product(n-r+1,n); } public long product(final int start, final int end) { long result = 1; for (int i = start; i <= end; i++) { result *= i; result %= mod; } return result; } public long combination(final int n, int r) { if (r > n) { return 0; } r = min(r,n-r); return div(product(n - r + 1, n), fact(r)); } } public static long pow(long x,long n){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; } tmp *=tmp; n = n >> 1; } return ans; } public static long powSafe(long x,long n){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ if(Long.MAX_VALUE/tmp < ans){ return -1; } ans*=tmp; } if(Long.MAX_VALUE/tmp < tmp&&n > 1){ return -1; } tmp *=tmp; n = n >> 1; } return ans; } public static long modPow(long x,long n,long m){ long ans = 1L; long tmp = x%m; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; ans%=m; } tmp *=tmp; tmp%=m; n = n >> 1; } return ans; } public static int gcd(int a,int b){ if(b == 0) return a; else return gcd(b,a%b); } public static long gcd(long a,long b){ if(b == 0) return a; else return gcd(b,a%b); } public static int gcd(int... a){ int ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long gcd(long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long lcm(int a,int b){ return (long) a / gcd(a, b) * b; } public static long lcm(long a,long b){ return a / gcd(a,b) * b; } public static boolean isPrime(long x){ if(x < 2) return false; else if(x == 2) return true; if(x%2 == 0) return false; for(long i = 3; i*i <= x; i+= 2){ if(x%i == 0) return false; } return true; } public static int rI() { return fs.nextInt(); } public static int[] rIv(int length) { int[] res = new int[length]; for (int i = 0; i < length; i++) { res[i] = fs.nextInt(); } return res; } public static int[] rIv(int length,int change) { int[] res = new int[length]; for (int i = 0; i < length; i++) { res[i] = fs.nextInt()+change; } return res; } public static String rS() { return fs.next(); } public static String[] rSv(int length) { String[] res = new String[length]; for (int i = 0; i < length; i++) res[i] = fs.next(); return res; } public static long rL() { return fs.nextLong(); } public static long[] rLv(int length) { long[] res = new long[length]; for (int i = 0; i < length; i++) res[i] = fs.nextLong(); return res; } public static double rD(){ return fs.nextDouble(); } public static double[] rDv(int length){ double[] res = new double[length]; for (int i = 0; i < length; i++) res[i] = rD(); return res; } public static String aiS(int[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String alS(long[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String adS(double[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String acS(char[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String asS(String[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String liS(ArrayList<Integer> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String liS(ArrayList<Integer> a, IntUnaryOperator o){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(o.applyAsInt(a.get(i))); } return ans.toString(); } public static String llS(ArrayList<Long> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String llS(ArrayList<Long> a, LongUnaryOperator o){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(o.applyAsLong(a.get(i))); } return ans.toString(); } public static String ldS(ArrayList<Double> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String lcS(ArrayList<Character> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String lsS(ArrayList<String> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static void nL(){ out.println(); } public static void oI(int a) { out.println(a); } public static void onI(int a){ out.print(a); } public static void oIv(int... a) { oS(aiS(a)); } public static void oS(String s) { out.println(s); } public static void onS(String s) { out.print(s); } public static void oSv(String[] a) { oS(asS(a)); } public static void oL(long l) { out.println(l); } public static void onL(long l) { out.print(l); } public static void oLv(long... a) { oS(alS(a)); } public static void oD(double d){ out.println(d); } public static void onD(double d){ out.print(d); } public static void oDv(double... d){ oS(adS(d)); } public static void oC(char c){ out.println(c); } public static void onC(char c){ out.print(c); } public static void oCv(char... c){ oS(acS(c)); } public static void fl(){ out.flush(); } public static void yes_no(boolean yes){ if(yes){ oS("Yes"); return; } oS("No"); } public static int fact(int num) { if (num == 0) { return 1; } else if (num == 1) { return 1; } else if (num < 0) { throw new IllegalArgumentException("factorial should be bigger than 0"); } return num * fact(num - 1); } public static int[] convI(ArrayList<Integer> list) { int[] res = new int[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static long[] convL(ArrayList<Long> list) { long[] res = new long[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static String[] convS(ArrayList<String> list) { String[] res = new String[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static ArrayList<Integer> convI(int[] vec) { ArrayList<Integer> list = new ArrayList<>(); for (int i : vec) list.add(i); return list; } public static ArrayList<Long> convL(long[] vec) { ArrayList<Long> list = new ArrayList<>(); for (long i : vec) list.add(i); return list; } public static ArrayList<String> convS(String[] vec) { return new ArrayList<>(Arrays.asList(vec)); } public static ArrayList<ArrayList<Integer>> permutation(int a) { int[] list = new int[a]; for (int i = 0; i < a; i++) { list[i] = i; } return permutation(list); } public static ArrayList<ArrayList<Integer>> permutation1(int a) { int[] list = new int[a]; for (int i = 0; i < a; i++) { list[i] = i+1; } return permutation(list); } public static ArrayList<ArrayList<Integer>> permutation(int[] seed) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); int[] perm = new int[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(int[] seed, int[] perm, boolean[] used, int index,ArrayList<ArrayList<Integer>> res) { if (index == seed.length) { res.add(convI(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static ArrayList<ArrayList<String>> permutation(String[] seed) { ArrayList<ArrayList<String>> res = new ArrayList<>(); String[] perm = new String[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(String[] seed, String[] perm, boolean[] used, int index,ArrayList<ArrayList<String>> res) { if (index == seed.length) { res.add(convS(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static void swap(int[] a,int i1,int i2){ int t = a[i1]; a[i1] = a[i2]; a[i2] = t; } public static void swap(char[] a,int i1,int i2){ char t = a[i1]; a[i1] = a[i2]; a[i2] = t; } public static void SOLVE(){ solve(); out.flush(); } } class SegTree<S> { final int MAX; final int N; final java.util.function.BinaryOperator<S> op; final S E; final S[] data; @SuppressWarnings("unchecked") public SegTree(int n, java.util.function.BinaryOperator<S> op, S e) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.E = e; this.op = op; this.data = (S[]) new Object[N << 1]; java.util.Arrays.fill(data, E); } public SegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e) { this(dat.length, op, e); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, data, N, l); for (int i = N - 1; i > 0; i--) { data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]); } } public void set(int p, S x) { exclusiveRangeCheck(p); data[p += N] = x; p >>= 1; while (p > 0) { data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]); p >>= 1; } } public S get(int p) { exclusiveRangeCheck(p); return data[p + N]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); S sumLeft = E; S sumRight = E; l += N; r += N; while (l < r) { if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]); if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight); l >>= 1; r >>= 1; } return op.apply(sumLeft, sumRight); } public S allProd() { return data[1]; } public int maxRight(int l, java.util.function.Predicate<S> f) { inclusiveRangeCheck(l); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!f.test(op.apply(sum, data[l]))) { while (l < N) { l = l << 1; if (f.test(op.apply(sum, data[l]))) { sum = op.apply(sum, data[l]); l++; } } return l - N; } sum = op.apply(sum, data[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> f) { inclusiveRangeCheck(r); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!f.test(op.apply(data[r], sum))) { while (r < N) { r = r << 1 | 1; if (f.test(op.apply(data[r], sum))) { sum = op.apply(data[r], sum); r--; } } return r + 1 - N; } sum = op.apply(data[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d).", p, 0, MAX) ); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d].", p, 0, MAX) ); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } public String toDetailedString() { return toDetailedString(1, 0); } private String toDetailedString(int k, int sp) { if (k >= N) return indent(sp) + data[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent); s += "\n"; s += indent(sp) + data[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n --> 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(data[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } /** * @verified * - https://atcoder.jp/contests/practice2/tasks/practice2_e * - http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B */ class MinCostFlow { private static final class InternalWeightedCapEdge { final int to, rev; long cap; final long cost; InternalWeightedCapEdge(int to, int rev, long cap, long cost) { this.to = to; this.rev = rev; this.cap = cap; this.cost = cost; } } public static final class WeightedCapEdge { public final int from, to; public final long cap, flow, cost; WeightedCapEdge(int from, int to, long cap, long flow, long cost) { this.from = from; this.to = to; this.cap = cap; this.flow = flow; this.cost = cost; } @Override public boolean equals(Object o) { if (o instanceof WeightedCapEdge) { WeightedCapEdge e = (WeightedCapEdge) o; return from == e.from && to == e.to && cap == e.cap && flow == e.flow && cost == e.cost; } return false; } } private static final class IntPair { final int first, second; IntPair(int first, int second) { this.first = first; this.second = second; } } public static final class FlowAndCost { public final long flow, cost; FlowAndCost(long flow, long cost) { this.flow = flow; this.cost = cost; } @Override public boolean equals(Object o) { if (o instanceof FlowAndCost) { FlowAndCost c = (FlowAndCost) o; return flow == c.flow && cost == c.cost; } return false; } } static final long INF = Long.MAX_VALUE; private final int n; private final java.util.ArrayList<IntPair> pos; public final java.util.ArrayList<InternalWeightedCapEdge>[] g; @SuppressWarnings("unchecked") public MinCostFlow(int n) { this.n = n; this.pos = new java.util.ArrayList<>(); this.g = new java.util.ArrayList[n]; for (int i = 0; i < n; i++) { this.g[i] = new java.util.ArrayList<>(); } } public int addEdge(int from, int to, long cap, long cost) { rangeCheck(from, 0, n); rangeCheck(to, 0, n); nonNegativeCheck(cap, "Capacity"); nonNegativeCheck(cost, "Cost"); int m = pos.size(); pos.add(new IntPair(from, g[from].size())); int fromId = g[from].size(); int toId = g[to].size(); if (from == to) toId++; g[from].add(new InternalWeightedCapEdge(to, toId, cap, cost)); g[to].add(new InternalWeightedCapEdge(from, fromId, 0L, -cost)); return m; } private InternalWeightedCapEdge getInternalEdge(int i) { return g[pos.get(i).first].get(pos.get(i).second); } private InternalWeightedCapEdge getInternalEdgeReversed(InternalWeightedCapEdge e) { return g[e.to].get(e.rev); } public WeightedCapEdge getEdge(int i) { int m = pos.size(); rangeCheck(i, 0, m); InternalWeightedCapEdge e = getInternalEdge(i); InternalWeightedCapEdge re = getInternalEdgeReversed(e); return new WeightedCapEdge(re.to, e.to, e.cap + re.cap, re.cap, e.cost); } public WeightedCapEdge[] getEdges() { WeightedCapEdge[] res = new WeightedCapEdge[pos.size()]; java.util.Arrays.setAll(res, this::getEdge); return res; } public FlowAndCost minCostMaxFlow(int s, int t) { return minCostFlow(s, t, INF); } public FlowAndCost minCostFlow(int s, int t, long flowLimit) { return minCostSlope(s, t, flowLimit).getLast(); } java.util.LinkedList<FlowAndCost> minCostSlope(int s, int t) { return minCostSlope(s, t, INF); } public java.util.LinkedList<FlowAndCost> minCostSlope(int s, int t, long flowLimit) { rangeCheck(s, 0, n); rangeCheck(t, 0, n); if (s == t) { throw new IllegalArgumentException( String.format("%d and %d is the same vertex.", s, t) ); } long[] dual = new long[n]; long[] dist = new long[n]; int[] pv = new int[n]; int[] pe = new int[n]; boolean[] vis = new boolean[n]; long flow = 0; long cost = 0, prev_cost = -1; java.util.LinkedList<FlowAndCost> result = new java.util.LinkedList<>(); result.addLast(new FlowAndCost(flow, cost)); while (flow < flowLimit) { if (!dualRef(s, t, dual, dist, pv, pe, vis)) break; long c = flowLimit - flow; for (int v = t; v != s; v = pv[v]) { c = Math.min(c, g[pv[v]].get(pe[v]).cap); } for (int v = t; v != s; v = pv[v]) { InternalWeightedCapEdge e = g[pv[v]].get(pe[v]); e.cap -= c; g[v].get(e.rev).cap += c; } long d = -dual[s]; flow += c; cost += c * d; if (prev_cost == d) { result.removeLast(); } result.addLast(new FlowAndCost(flow, cost)); prev_cost = cost; } return result; } private boolean dualRef(int s, int t, long[] dual, long[] dist, int[] pv, int[] pe, boolean[] vis) { java.util.Arrays.fill(dist, INF); java.util.Arrays.fill(pv, -1); java.util.Arrays.fill(pe, -1); java.util.Arrays.fill(vis, false); class State implements Comparable<State> { final long key; final int to; State(long key, int to) { this.key = key; this.to = to; } public int compareTo(State q) { return key > q.key ? 1 : -1; } }; java.util.PriorityQueue<State> pq = new java.util.PriorityQueue<>(); dist[s] = 0; pq.add(new State(0L, s)); while (pq.size() > 0) { int v = pq.poll().to; if (vis[v]) continue; vis[v] = true; if (v == t) break; for (int i = 0, deg = g[v].size(); i < deg; i++) { InternalWeightedCapEdge e = g[v].get(i); if (vis[e.to] || e.cap == 0) continue; long cost = e.cost - dual[e.to] + dual[v]; if (dist[e.to] - dist[v] > cost) { dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; pq.add(new State(dist[e.to], e.to)); } } } if (!vis[t]) { return false; } for (int v = 0; v < n; v++) { if (!vis[v]) continue; dual[v] -= dist[t] - dist[v]; } return true; } private void rangeCheck(int i, int minInlusive, int maxExclusive) { if (i < 0 || i >= maxExclusive) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, maxExclusive) ); } } private void nonNegativeCheck(long cap, java.lang.String attribute) { if (cap < 0) { throw new IllegalArgumentException( String.format("%s %d is negative.", attribute, cap) ); } } } class LazySegTree<S, F> { final int MAX; final int N; final int Log; final java.util.function.BinaryOperator<S> Op; final S E; final java.util.function.BiFunction<F, S, S> Mapping; final java.util.function.BinaryOperator<F> Composition; final F Id; final S[] Dat; final F[] Laz; @SuppressWarnings("unchecked") public LazySegTree(int n, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.Log = Integer.numberOfTrailingZeros(N); this.Op = op; this.E = e; this.Mapping = mapping; this.Composition = composition; this.Id = id; this.Dat = (S[]) new Object[N << 1]; this.Laz = (F[]) new Object[N]; java.util.Arrays.fill(Dat, E); java.util.Arrays.fill(Laz, Id); } public LazySegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this(dat.length, op, e, mapping, composition, id); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, Dat, N, l); for (int i = N - 1; i > 0; i--) { Dat[i] = Op.apply(Dat[i << 1 | 0], Dat[i << 1 | 1]); } } private void push(int k) { if (Laz[k] == Id) return; int lk = k << 1 | 0, rk = k << 1 | 1; Dat[lk] = Mapping.apply(Laz[k], Dat[lk]); Dat[rk] = Mapping.apply(Laz[k], Dat[rk]); if (lk < N) Laz[lk] = Composition.apply(Laz[k], Laz[lk]); if (rk < N) Laz[rk] = Composition.apply(Laz[k], Laz[rk]); Laz[k] = Id; } private void pushTo(int k) { for (int i = Log; i > 0; i--) push(k >> i); } private void pushTo(int lk, int rk) { for (int i = Log; i > 0; i--) { if (((lk >> i) << i) != lk) push(lk >> i); if (((rk >> i) << i) != rk) push(rk >> i); } } private void updateFrom(int k) { k >>= 1; while (k > 0) { Dat[k] = Op.apply(Dat[k << 1 | 0], Dat[k << 1 | 1]); k >>= 1; } } private void updateFrom(int lk, int rk) { for (int i = 1; i <= Log; i++) { if (((lk >> i) << i) != lk) { int lki = lk >> i; Dat[lki] = Op.apply(Dat[lki << 1 | 0], Dat[lki << 1 | 1]); } if (((rk >> i) << i) != rk) { int rki = (rk - 1) >> i; Dat[rki] = Op.apply(Dat[rki << 1 | 0], Dat[rki << 1 | 1]); } } } public void set(int p, S x) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = x; updateFrom(p); } public S get(int p) { exclusiveRangeCheck(p); p += N; pushTo(p); return Dat[p]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return E; l += N; r += N; pushTo(l, r); S sumLeft = E, sumRight = E; while (l < r) { if ((l & 1) == 1) sumLeft = Op.apply(sumLeft, Dat[l++]); if ((r & 1) == 1) sumRight = Op.apply(Dat[--r], sumRight); l >>= 1; r >>= 1; } return Op.apply(sumLeft, sumRight); } public S allProd() { return Dat[1]; } public void apply(int p, F f) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = Mapping.apply(f, Dat[p]); updateFrom(p); } public void apply(int l, int r, F f) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return; l += N; r += N; pushTo(l, r); for (int l2 = l, r2 = r; l2 < r2;) { if ((l2 & 1) == 1) { Dat[l2] = Mapping.apply(f, Dat[l2]); if (l2 < N) Laz[l2] = Composition.apply(f, Laz[l2]); l2++; } if ((r2 & 1) == 1) { r2--; Dat[r2] = Mapping.apply(f, Dat[r2]); if (r2 < N) Laz[r2] = Composition.apply(f, Laz[r2]); } l2 >>= 1; r2 >>= 1; } updateFrom(l, r); } public int maxRight(int l, java.util.function.Predicate<S> g) { inclusiveRangeCheck(l); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; pushTo(l); S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!g.test(Op.apply(sum, Dat[l]))) { while (l < N) { push(l); l = l << 1; if (g.test(Op.apply(sum, Dat[l]))) { sum = Op.apply(sum, Dat[l]); l++; } } return l - N; } sum = Op.apply(sum, Dat[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> g) { inclusiveRangeCheck(r); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; pushTo(r - 1); S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!g.test(Op.apply(Dat[r], sum))) { while (r < N) { push(r); r = r << 1 | 1; if (g.test(Op.apply(Dat[r], sum))) { sum = Op.apply(Dat[r], sum); r--; } } return r + 1 - N; } sum = Op.apply(Dat[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d is not in [%d, %d).", p, 0, MAX) ); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d is not in [%d, %d].", p, 0, MAX) ); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } private S[] simulatePushAll() { S[] simDat = java.util.Arrays.copyOf(Dat, 2 * N); F[] simLaz = java.util.Arrays.copyOf(Laz, 2 * N); for (int k = 1; k < N; k++) { if (simLaz[k] == Id) continue; int lk = k << 1 | 0, rk = k << 1 | 1; simDat[lk] = Mapping.apply(simLaz[k], simDat[lk]); simDat[rk] = Mapping.apply(simLaz[k], simDat[rk]); if (lk < N) simLaz[lk] = Composition.apply(simLaz[k], simLaz[lk]); if (rk < N) simLaz[rk] = Composition.apply(simLaz[k], simLaz[rk]); simLaz[k] = Id; } return simDat; } public String toDetailedString() { return toDetailedString(1, 0, simulatePushAll()); } private String toDetailedString(int k, int sp, S[] dat) { if (k >= N) return indent(sp) + dat[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent, dat); s += "\n"; s += indent(sp) + dat[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent, dat); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n --> 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { S[] dat = simulatePushAll(); StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(dat[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } class FenwickTree{ private int _n; private long[] data; public FenwickTree(int n){ this._n = n; data = new long[n]; } /** * @verified https://atcoder.jp/contests/practice2/tasks/practice2_b * @submission https://atcoder.jp/contests/practice2/submissions/16580495 */ public FenwickTree(long[] data) { this(data.length); build(data); } public void set(int p, long x){ add(p, x - get(p)); } public void add(int p, long x){ assert(0<=p && p<_n); p++; while(p<=_n){ data[p-1] += x; p += p&-p; } } public long sum(int l, int r){ assert(0<=l && l<=r && r<=_n); return sum(r)-sum(l); } public long get(int p){ return sum(p, p+1); } private long sum(int r){ long s = 0; while(r>0){ s += data[r-1]; r -= r&-r; } return s; } private void build(long[] dat) { System.arraycopy(dat, 0, data, 0, _n); for (int i=1; i<=_n; i++) { int p = i+(i&-i); if(p<=_n){ data[p-1] += data[i-1]; } } } } class MaxFlow { private static final class InternalCapEdge { final int to; final int rev; long cap; InternalCapEdge(int to, int rev, long cap) { this.to = to; this.rev = rev; this.cap = cap; } } public static final class CapEdge { public final int from, to; public final long cap, flow; CapEdge(int from, int to, long cap, long flow) { this.from = from; this.to = to; this.cap = cap; this.flow = flow; } @Override public boolean equals(Object o) { if (o instanceof CapEdge) { CapEdge e = (CapEdge) o; return from == e.from && to == e.to && cap == e.cap && flow == e.flow; } return false; } } private static final class IntPair { final int first, second; IntPair(int first, int second) { this.first = first; this.second = second; } } static final long INF = Long.MAX_VALUE; private final int n; private final java.util.ArrayList<IntPair> pos; private final java.util.ArrayList<InternalCapEdge>[] g; @SuppressWarnings("unchecked") public MaxFlow(int n) { this.n = n; this.pos = new java.util.ArrayList<>(); this.g = new java.util.ArrayList[n]; for (int i = 0; i < n; i++) { this.g[i] = new java.util.ArrayList<>(); } } public int addEdge(int from, int to, long cap) { rangeCheck(from, 0, n); rangeCheck(to, 0, n); nonNegativeCheck(cap, "Capacity"); int m = pos.size(); pos.add(new IntPair(from, g[from].size())); int fromId = g[from].size(); int toId = g[to].size(); if (from == to) toId++; g[from].add(new InternalCapEdge(to, toId, cap)); g[to].add(new InternalCapEdge(from, fromId, 0L)); return m; } private InternalCapEdge getInternalEdge(int i) { return g[pos.get(i).first].get(pos.get(i).second); } private InternalCapEdge getInternalEdgeReversed(InternalCapEdge e) { return g[e.to].get(e.rev); } public CapEdge getEdge(int i) { int m = pos.size(); rangeCheck(i, 0, m); InternalCapEdge e = getInternalEdge(i); InternalCapEdge re = getInternalEdgeReversed(e); return new CapEdge(re.to, e.to, e.cap + re.cap, re.cap); } public CapEdge[] getEdges() { CapEdge[] res = new CapEdge[pos.size()]; java.util.Arrays.setAll(res, this::getEdge); return res; } public void changeEdge(int i, long newCap, long newFlow) { int m = pos.size(); rangeCheck(i, 0, m); nonNegativeCheck(newCap, "Capacity"); if (newFlow > newCap) { throw new IllegalArgumentException( String.format("Flow %d is greater than the capacity %d.", newCap, newFlow) ); } InternalCapEdge e = getInternalEdge(i); InternalCapEdge re = getInternalEdgeReversed(e); e.cap = newCap - newFlow; re.cap = newFlow; } public long maxFlow(int s, int t) { return flow(s, t, INF); } public long flow(int s, int t, long flowLimit) { rangeCheck(s, 0, n); rangeCheck(t, 0, n); long flow = 0L; int[] level = new int[n]; int[] que = new int[n]; int[] iter = new int[n]; while (flow < flowLimit) { bfs(s, t, level, que); if (level[t] < 0) break; java.util.Arrays.fill(iter, 0); while (flow < flowLimit) { long d = dfs(t, s, flowLimit - flow, iter, level); if (d == 0) break; flow += d; } } return flow; } private void bfs(int s, int t, int[] level, int[] que) { java.util.Arrays.fill(level, -1); int hd = 0, tl = 0; que[tl++] = s; level[s] = 0; while (hd < tl) { int u = que[hd++]; for (InternalCapEdge e : g[u]) { int v = e.to; if (e.cap == 0 || level[v] >= 0) continue; level[v] = level[u] + 1; if (v == t) return; que[tl++] = v; } } } private long dfs(int cur, int s, long flowLimit, int[] iter, int[] level) { if (cur == s) return flowLimit; long res = 0; int curLevel = level[cur]; for (int itMax = g[cur].size(); iter[cur] < itMax; iter[cur]++) { int i = iter[cur]; InternalCapEdge e = g[cur].get(i); InternalCapEdge re = getInternalEdgeReversed(e); if (curLevel <= level[e.to] || re.cap == 0) continue; long d = dfs(e.to, s, Math.min(flowLimit - res, re.cap), iter, level); if (d <= 0) continue; e.cap += d; re.cap -= d; res += d; if (res == flowLimit) break; } return res; } public boolean[] minCut(int s) { rangeCheck(s, 0, n); boolean[] visited = new boolean[n]; int[] stack = new int[n]; int ptr = 0; stack[ptr++] = s; visited[s] = true; while (ptr > 0) { int u = stack[--ptr]; for (InternalCapEdge e : g[u]) { int v = e.to; if (e.cap > 0 && !visited[v]) { visited[v] = true; stack[ptr++] = v; } } } return visited; } private void rangeCheck(int i, int minInclusive, int maxExclusive) { if (i < 0 || i >= maxExclusive) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, maxExclusive) ); } } private void nonNegativeCheck(long cap, String attribute) { if (cap < 0) { throw new IllegalArgumentException( String.format("%s %d is negative.", attribute, cap) ); } } } class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next());} } import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.util.function.*; import java.util.stream.IntStream; public class Main implements Runnable{ public static void main(String[] args) { //Thread.setDefaultUncaughtExceptionHandler((t,e)->System.exit(1)); //new Thread(null,new Main(),"",16L*1024*1024).start(); Solver.SOLVE(); } public void run(){ Solver.SOLVE(); } } class UnionFind { private int[] roots; public UnionFind(int n){ roots = new int[n]; for (int i = 0; i < n; i++) { roots[i] = i; } } public int root(int x){ if(roots[x] == x){ return x; } return roots[x] = root(roots[x]); } public void unite(int x,int y){ int rx = root(x); int ry = root(y); if(rx == ry){ return; } roots[rx] = ry; } public boolean same(int x,int y){ int rx = root(x); int ry = root(y); return rx == ry; } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } ArrayList<ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } ArrayList<ArrayList<Integer>> result = new ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(ArrayList::isEmpty); return result; } } class PairL implements Comparable<PairL>, Comparator<PairL> { public long x,y; public PairL(long x,long y) { this.x = x; this.y = y; } public void swap(){ long t = x; x = y; y = t; } @Override public int compare(PairL o1, PairL o2) { return o1.compareTo(o2); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairL pairl = (PairL) o; return x == pairl.x && y == pairl.y; } @Override public int hashCode() { return Objects.hash(x, y); } public PairL add(PairL p){ return new PairL(x+p.x,y+p.y); } @Override public int compareTo(PairL o) { return Long.compare(x,o.x); } } class PairI implements Comparable<PairI>, Comparator<PairI> { public int x,y; public PairI(int x,int y) { this.x = x; this.y = y; } public void swap(){ int t = x; x = y; y = t; } @Override public int compare(PairI o1, PairI o2) { if(o1.x == o2.x){ return Integer.compare(o1.y,o2.y); } return Integer.compare(o1.x,o2.x); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairI pairI = (PairI) o; return x == pairI.x && y == pairI.y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public int compareTo(PairI o) { if(x == o.x){ return Integer.compare(y,o.y); } return Integer.compare(x,o.x); } public PairI add(PairI p){ return new PairI(x+p.x,y+p.y); } public PairI sub(PairI p){ return new PairI(x-p.x,y-p.y); } public PairI addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new PairI(x,y); } return null; } } class PairISet{ int x,y; PairISet(int x,int y){ this.x = x; this.y = y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairI pairI = (PairI) o; return (x == pairI.x && y == pairI.y)||(x == pairI.y && y == pairI.x); } } class Line{ //ax+bx+c=0 long a,b,c; public Line(int x0, int y0, int x1, int y1) { long dx = x1-x0; long dy = y1-y0; long gcd = Solver.gcd(dx,dy); dx/=gcd; dy/=gcd; if(dx < 0){ dx=-dx; dy=-dy; } if(dx == 0 && dy < 0){ dy=-dy; } a = dy; b = -dx; c = dx*y0-dy*x0; } public boolean onLine(int x,int y){ return a*x + b*y + c == 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Line line = (Line) o; return a == line.a && b == line.b && c == line.c; } @Override public int hashCode() { return Objects.hash(a, b, c); } } class Dist extends PairI{ int d; public Dist(int x,int y,int d){ super(x,y); this.d = d; } public Dist addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new Dist(x,y,d+1); } return null; } } class Tuple implements Comparable<Tuple>{ public int x,y,z; public Tuple(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Tuple three = (Tuple) o; return x == three.x && y == three.y && z == three.z; } @Override public int hashCode() { return Objects.hash(x, y, z); } @Override public int compareTo(Tuple o) { if(x == o.x){ return Integer.compare(y,o.y); } return Integer.compare(x,o.x); } } class Edge implements Comparable<Edge>{ public int from; public int to; public int name; public long d; public Edge(int to){ this.to = to; } public Edge(int to, long d){ this.to = to; this.d = d; } public Edge setName(int name){ this.name = name; return this; } public Edge(int from, int to, long d){ this.to = to; this.from = from; this.d = d; } @Override public int compareTo(Edge o) { return Long.compare(d,o.d); } } class PairC{ char a,b; public PairC(char a, char b){ this.a = a; this.b = b; } } class IB{ int i; boolean b; IB(int i,boolean b){ this.i = i; this.b = b; } } class CI{ char c; int i; CI(char c,int i){ this.c = c; this.i = i; } } class SortedMultiSet extends TreeMap<Long,Integer>{ public void add(long a){ put(a,getOrDefault(a,0)+1); } public void remove(long a){ if(get(a) == 1){ super.remove(a); }else{ put(a,get(a)-1); } } public void lower(long a){ } } class MultiSet extends HashMap<Integer,Integer>{ public void add(int a){ put(a,getOrDefault(a,0)+1); } public void remove(int a){ if(get(a) == 1){ super.remove(a); }else{ put(a,get(a)-1); } } public boolean contains(int a){ return containsKey(a); } } class PP{ PairI s,t; int name; public PP(PairI s, PairI t,int name) { this.s = s; this.t = t; this.name = name; } } class Pair<T extends Comparable<T>,U> implements Comparable<Pair<T,U>>{ T t; U u; public Pair(T t, U u) { this.t = t; this.u = u; } @Override public int compareTo(Pair<T,U> o) { return t.compareTo(o.t); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(t, pair.t) && Objects.equals(u, pair.u); } @Override public int hashCode() { return Objects.hash(t, u); } } class Matrix{ int row; int column; int[][] nums; public Matrix(int row,int column){ this.row = row; this.column = column; nums = new int[row][column]; } } class SquareMatrix{ int size; long[][] nums; public SquareMatrix(int size){ this.size = size; nums = new long[size][size]; } public SquareMatrix(long[][] nums){ size = nums.length; this.nums = new long[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { this.nums[i][j] = nums[i][j]; } } } public static SquareMatrix identityMatrix(int size){ long[][] mat = new long[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if(i == j){ mat[i][j] = 1; } } } return new SquareMatrix(mat); } public SquareMatrix mul(SquareMatrix m){ if(m.size != size){ throw new IllegalArgumentException(); } SquareMatrix ans = new SquareMatrix(size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { ans.nums[i][k] += nums[i][j]*m.nums[j][k]; } } } return ans; } public SquareMatrix modMul(SquareMatrix m,long mod){ if(m.size != size){ throw new IllegalArgumentException(); } SquareMatrix ans = new SquareMatrix(size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { ans.nums[i][k] += nums[i][j]*m.nums[j][k]; ans.nums[i][k]%=mod; } } } return ans; } public long[] mulVec(long[] vec){ if(vec.length != size){ throw new IllegalArgumentException(); } long[] ans = new long[size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { ans[i] += vec[j]*nums[i][j]; } } return ans; } public long[] modMulVec(long[] vec,long mod){ if(vec.length != size){ throw new IllegalArgumentException(); } long[] ans = new long[size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { ans[i] += vec[j]*nums[i][j]; ans[i]%=mod; } } return ans; } public static SquareMatrix pow(SquareMatrix base,long exp){ SquareMatrix ans = identityMatrix(base.size); while (exp > 0){ if ((exp & 1) == 1) { ans = base.mul(ans); } base = base.mul(base); exp >>= 1; } return ans; } public SquareMatrix pow(long exp){ return pow(this,exp); } public static SquareMatrix modPow(SquareMatrix base,long exp,long mod){ SquareMatrix ans = identityMatrix(base.size); while (exp > 0){ if ((exp & 1) == 1) { ans = base.modMul(ans,mod); } base = base.modMul(base,mod); exp >>= 1; } return ans; } public SquareMatrix modPow(long exp,long mod){ return modPow(this,exp,mod); } } class Fraction implements Comparable<Fraction>{ long de,num; int name; public Fraction(long de,long num) { this.de = de; this.num = num; } @Override public int compareTo(Fraction o) { long a = de * o.num; long b = num* o.de; return Long.compare(a,b); } public double doubleValue(){ return (double) de/num; } } class Solver { public static final int MOD1 = 1000000007; public static final int MOD9 = 998244353; public static Scanner sc = new Scanner(System.in); public static final int inf = 2000000000; public static final int ninf = -inf; public static final long infl = 2000000000000000000L; public static final long ninfl = -infl; public static final char[] alpha = "abcdefghijklmnopqrstuvwxyz".toCharArray(); public static final char[] ALPHA = "abcdefghijklmnopqrstuvwxyz".toUpperCase().toCharArray(); public static FastScanner fs = new FastScanner(); public static PrintWriter out = new PrintWriter(System.out); public static final PairI[] move = new PairI[]{new PairI(1,0),new PairI(0,1),new PairI(-1,0),new PairI(0,-1)}; public static final PairI[] move8 = new PairI[]{ new PairI(1,0),new PairI(0,1),new PairI(-1,0),new PairI(0,-1), new PairI(1,1),new PairI(-1,1),new PairI(1,-1),new PairI(-1,-1) }; public static void solve() { long a = rL(); long b = rL(); ArrayList<PairL> pf = new ArrayList<>(); long v = a; for (int i = 2; (long)i*i <= a; i++) { int div = 0; while (v%i==0){ v/=i; div++; } if(div!=0){ pf.add(new PairL(i,div)); } } if(v != 1){ pf.add(new PairL(v,1)); } MC m = new MC(MOD9); long pnum = 1; boolean iseven = false; boolean divd = false; if(b%2==0){ iseven = true; } for(PairL p:pf){ long mult = ((p.y)*(b%MOD9)+1)%MOD9; if((p.y)*(b%MOD9)+1 == MOD9){ divd = true; } if(p.y%2==1&&b%2==1){ iseven = true; } pnum *= mult; pnum%=MOD9; } if(iseven&&!divd){ oL((m.div(((b%MOD9)*pnum)%MOD9,2))%MOD9); }else { oL((m.div(((b%MOD9)*pnum-1)%MOD9,2))%MOD9); } } static void sort(int[] a){ Arrays.sort(a); } static void sort(int[] a,Comparator<Integer> c){ ArrayList<Integer> list = convI(a); list.sort(c); for (int i = 0; i < a.length; i++) { a[i] = list.get(i); } } static char toLower(char a){ return String.valueOf(a).toLowerCase().charAt(0); } static char toUpper(char a){ return String.valueOf(a).toUpperCase().charAt(0); } static int nand(int a,int b){ if(a == 1&&b == 1){ return 0; } return 1; } static int standingBits(long n){ String bits = toBits(n); int ans = 0; for (int i = 0; i < bits.length(); i++) { if(bits.charAt(i) == '1'){ ans++; } } return ans; } static boolean contain(String s,char c){ for (int i = 0; i < s.length(); i++) { if(s.charAt(i) == c){ return true; } } return false; } static String toBits(long n){ StringBuilder ans = new StringBuilder(); while (n > 0){ ans.append(n%2); n/=2; } return ans.reverse().toString(); } static long toLong(String anss){ long ansi = 0; for (int i = 0; i < anss.length(); i++) { if(anss.charAt(i) == '1'){ ansi += (1L<<(anss.length()-1-i)); } } return ansi; } static int perfectPowNum(long n){ int res = 0; double range = Math.log(n)/Math.log(2); range++; for (int i = 2; i < range; i++) { long a = (long) Math.pow(n,1d/i); if(pow(a,i) == n||pow(a+1,i)==n){ res++; } } return res; } static boolean[] eratosthenes(int n){ boolean[] res = new boolean[n+1]; for (int i = 2; i <= n; i++) { res[i] = true; } for (int i = 2; i <= n; i++) { if(res[i]){ int k = i*2; while (k <= n){ res[k] = false; k+=i; } } } return res; } static BitSet and(BitSet set1,BitSet set2){ BitSet ans = (BitSet) set1.clone(); ans.and(set2); return ans; } static BitSet or(BitSet set1,BitSet set2){ BitSet ans = (BitSet) set1.clone(); ans.or(set2); return ans; } static BitSet xor(BitSet set1,BitSet set2){ BitSet ans = (BitSet) set1.clone(); ans.xor(set2); return ans; } static BitSet toBitset(long n){ return BitSet.valueOf(new long[]{n}); } static long toLong(BitSet set){ if(set.length() > 63) { throw new IllegalArgumentException(); } if(set.length() == 0){ return 0; } return set.toLongArray()[0]; } static int deg(long x){ return String.valueOf(x).length(); } static int nthdeg(long x,int d){ x/=pow(10,d); return (int)(x%10); } static boolean isPalindrome(int a,int b,String s){ int dif = b-a; boolean ok = true; for (int i = 0; i < dif; i++) { if (s.charAt(i + a) != s.charAt(b - i)) { ok = false; break; } } return ok; } static int intValue(char c){ return Integer.parseInt(String.valueOf(c)); } public static int toIntC(char c){ for (int i = 0; i < ALPHA.length; i++) { if(c == ALPHA[i]){ return i; } } throw new IllegalArgumentException("not an alphabet"); } public static int toInt(char c){ for (int i = 0; i < alpha.length; i++) { if(c == alpha[i]){ return i; } } throw new IllegalArgumentException("not an alphabet"); } public static void reverse(int[] a){ int[] tmp = a.clone(); for (int i = 0; i < a.length; i++) { a[i] = tmp[a.length - 1 - i]; } } public static int[] compress(int[] a){ int[] ans = new int[a.length]; int[] b = erase(a); Arrays.sort(b); for (int i = 0; i < a.length; i++) { ans[i] = lower(b,a[i]); } return ans; } public static int lower(int[] a,int x){ int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x <= a[mid]) { high = mid; } else { low = mid + 1; } } if (low < a.length && a[low] < x) { low++; } return low; } public static int lower(long[] a,long x) { int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x <= a[mid]) { high = mid; } else { low = mid + 1; } } if (low < a.length && a[low] < x) { low++; } return low; } public static <T extends Comparable<? super T>> int lower(T[] a,T x){ int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x.compareTo(a[mid]) < 1) { high = mid; } else { low = mid + 1; } } if (low < a.length && x.compareTo(a[low]) > 0) { low++; } return low; } public static int upper(int[] a,int x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x >= a[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static int upper(long[] a,long x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x >= a[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static <T extends Comparable<? super T>> int upper(T[] a,T x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x.compareTo(a[mid]) > -1) { low = mid + 1; } else { high = mid; } } return low; } public static int[] erase(int[] a){ HashSet<Integer> used = new HashSet<>(); ArrayList<Integer> ans = new ArrayList<>(); for (int i = 0; i < a.length; i++) { if(!used.contains(a[i])){ used.add(a[i]); ans.add(a[i]); } } return convI(ans); } public static int abs(int a){ return Math.abs(a); } public static long abs(long a){ return Math.abs(a); } public static int max(int a,int b){ return Math.max(a,b); } public static int max(int... a){ int max = Integer.MIN_VALUE; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static long max(long a,long b){ return Math.max(a,b); } public static long max(long... a){ long max = Long.MIN_VALUE; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static <T extends Comparable<? super T>> T max(T a,T b){ if(a.compareTo(b) > 0){ return a; }else { return b; } } public static int min(int a,int b){ return Math.min(a,b); } public static int min(int... a){ int min = Integer.MAX_VALUE; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static <T extends Comparable<? super T>> T min(T a,T b){ if(a.compareTo(b) > 0){ return b; }else { return a; } } public static long min(long a,long b){ return Math.min(a, b); } public static long min(long... a){ long min = Long.MAX_VALUE; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static final class MC { private final int mod; public MC(final int mod) { this.mod = mod; } public long mod(long x) { x %= mod; if (x < 0) { x += mod; } return x; } public long add(final long a, final long b) { return mod(mod(a) + mod(b)); } public long add(final long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = add(ans,a[i]); } return mod(ans); } public long mul(final long a, final long b) { return mod(mod(a) * mod(b)); } public long mul(final long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = mul(ans,a[i]); } return mod(ans); } public long div(final long numerator, final long denominator) { return mod(numerator * inverse(denominator)); } public long power(long base, long exp) { long ret = 1; base %= mod; while (exp > 0) { if ((exp & 1) == 1) { ret = mul(ret, base); } base = mul(base, base); exp >>= 1; } return ret; } public long inverse(final long x) { return power(x, mod - 2); } public long fact(final int n) { return product(1, n); } public long permutation(int n,int r){ return product(n-r+1,n); } public long product(final int start, final int end) { long result = 1; for (int i = start; i <= end; i++) { result *= i; result %= mod; } return result; } public long combination(final int n, int r) { if (r > n) { return 0; } r = min(r,n-r); return div(product(n - r + 1, n), fact(r)); } } public static long pow(long x,long n){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; } tmp *=tmp; n = n >> 1; } return ans; } public static long powSafe(long x,long n){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ if(Long.MAX_VALUE/tmp < ans){ return -1; } ans*=tmp; } if(Long.MAX_VALUE/tmp < tmp&&n > 1){ return -1; } tmp *=tmp; n = n >> 1; } return ans; } public static long modPow(long x,long n,long m){ long ans = 1L; long tmp = x%m; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; ans%=m; } tmp *=tmp; tmp%=m; n = n >> 1; } return ans; } public static int gcd(int a,int b){ if(b == 0) return a; else return gcd(b,a%b); } public static long gcd(long a,long b){ if(b == 0) return a; else return gcd(b,a%b); } public static int gcd(int... a){ int ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long gcd(long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long lcm(int a,int b){ return (long) a / gcd(a, b) * b; } public static long lcm(long a,long b){ return a / gcd(a,b) * b; } public static boolean isPrime(long x){ if(x < 2) return false; else if(x == 2) return true; if(x%2 == 0) return false; for(long i = 3; i*i <= x; i+= 2){ if(x%i == 0) return false; } return true; } public static int rI() { return fs.nextInt(); } public static int[] rIv(int length) { int[] res = new int[length]; for (int i = 0; i < length; i++) { res[i] = fs.nextInt(); } return res; } public static int[] rIv(int length,int change) { int[] res = new int[length]; for (int i = 0; i < length; i++) { res[i] = fs.nextInt()+change; } return res; } public static String rS() { return fs.next(); } public static String[] rSv(int length) { String[] res = new String[length]; for (int i = 0; i < length; i++) res[i] = fs.next(); return res; } public static long rL() { return fs.nextLong(); } public static long[] rLv(int length) { long[] res = new long[length]; for (int i = 0; i < length; i++) res[i] = fs.nextLong(); return res; } public static double rD(){ return fs.nextDouble(); } public static double[] rDv(int length){ double[] res = new double[length]; for (int i = 0; i < length; i++) res[i] = rD(); return res; } public static String aiS(int[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String alS(long[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String adS(double[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String acS(char[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String asS(String[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String liS(ArrayList<Integer> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String liS(ArrayList<Integer> a, IntUnaryOperator o){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(o.applyAsInt(a.get(i))); } return ans.toString(); } public static String llS(ArrayList<Long> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String llS(ArrayList<Long> a, LongUnaryOperator o){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(o.applyAsLong(a.get(i))); } return ans.toString(); } public static String ldS(ArrayList<Double> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String lcS(ArrayList<Character> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String lsS(ArrayList<String> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static void nL(){ out.println(); } public static void oI(int a) { out.println(a); } public static void onI(int a){ out.print(a); } public static void oIv(int... a) { oS(aiS(a)); } public static void oS(String s) { out.println(s); } public static void onS(String s) { out.print(s); } public static void oSv(String[] a) { oS(asS(a)); } public static void oL(long l) { out.println(l); } public static void onL(long l) { out.print(l); } public static void oLv(long... a) { oS(alS(a)); } public static void oD(double d){ out.println(d); } public static void onD(double d){ out.print(d); } public static void oDv(double... d){ oS(adS(d)); } public static void oC(char c){ out.println(c); } public static void onC(char c){ out.print(c); } public static void oCv(char... c){ oS(acS(c)); } public static void fl(){ out.flush(); } public static void yes_no(boolean yes){ if(yes){ oS("Yes"); return; } oS("No"); } public static int fact(int num) { if (num == 0) { return 1; } else if (num == 1) { return 1; } else if (num < 0) { throw new IllegalArgumentException("factorial should be bigger than 0"); } return num * fact(num - 1); } public static int[] convI(ArrayList<Integer> list) { int[] res = new int[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static long[] convL(ArrayList<Long> list) { long[] res = new long[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static String[] convS(ArrayList<String> list) { String[] res = new String[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static ArrayList<Integer> convI(int[] vec) { ArrayList<Integer> list = new ArrayList<>(); for (int i : vec) list.add(i); return list; } public static ArrayList<Long> convL(long[] vec) { ArrayList<Long> list = new ArrayList<>(); for (long i : vec) list.add(i); return list; } public static ArrayList<String> convS(String[] vec) { return new ArrayList<>(Arrays.asList(vec)); } public static ArrayList<ArrayList<Integer>> permutation(int a) { int[] list = new int[a]; for (int i = 0; i < a; i++) { list[i] = i; } return permutation(list); } public static ArrayList<ArrayList<Integer>> permutation1(int a) { int[] list = new int[a]; for (int i = 0; i < a; i++) { list[i] = i+1; } return permutation(list); } public static ArrayList<ArrayList<Integer>> permutation(int[] seed) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); int[] perm = new int[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(int[] seed, int[] perm, boolean[] used, int index,ArrayList<ArrayList<Integer>> res) { if (index == seed.length) { res.add(convI(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static ArrayList<ArrayList<String>> permutation(String[] seed) { ArrayList<ArrayList<String>> res = new ArrayList<>(); String[] perm = new String[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(String[] seed, String[] perm, boolean[] used, int index,ArrayList<ArrayList<String>> res) { if (index == seed.length) { res.add(convS(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static void swap(int[] a,int i1,int i2){ int t = a[i1]; a[i1] = a[i2]; a[i2] = t; } public static void swap(char[] a,int i1,int i2){ char t = a[i1]; a[i1] = a[i2]; a[i2] = t; } public static void SOLVE(){ solve(); out.flush(); } } class SegTree<S> { final int MAX; final int N; final java.util.function.BinaryOperator<S> op; final S E; final S[] data; @SuppressWarnings("unchecked") public SegTree(int n, java.util.function.BinaryOperator<S> op, S e) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.E = e; this.op = op; this.data = (S[]) new Object[N << 1]; java.util.Arrays.fill(data, E); } public SegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e) { this(dat.length, op, e); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, data, N, l); for (int i = N - 1; i > 0; i--) { data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]); } } public void set(int p, S x) { exclusiveRangeCheck(p); data[p += N] = x; p >>= 1; while (p > 0) { data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]); p >>= 1; } } public S get(int p) { exclusiveRangeCheck(p); return data[p + N]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); S sumLeft = E; S sumRight = E; l += N; r += N; while (l < r) { if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]); if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight); l >>= 1; r >>= 1; } return op.apply(sumLeft, sumRight); } public S allProd() { return data[1]; } public int maxRight(int l, java.util.function.Predicate<S> f) { inclusiveRangeCheck(l); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!f.test(op.apply(sum, data[l]))) { while (l < N) { l = l << 1; if (f.test(op.apply(sum, data[l]))) { sum = op.apply(sum, data[l]); l++; } } return l - N; } sum = op.apply(sum, data[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> f) { inclusiveRangeCheck(r); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!f.test(op.apply(data[r], sum))) { while (r < N) { r = r << 1 | 1; if (f.test(op.apply(data[r], sum))) { sum = op.apply(data[r], sum); r--; } } return r + 1 - N; } sum = op.apply(data[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d).", p, 0, MAX) ); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d].", p, 0, MAX) ); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } public String toDetailedString() { return toDetailedString(1, 0); } private String toDetailedString(int k, int sp) { if (k >= N) return indent(sp) + data[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent); s += "\n"; s += indent(sp) + data[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n --> 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(data[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } /** * @verified * - https://atcoder.jp/contests/practice2/tasks/practice2_e * - http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B */ class MinCostFlow { private static final class InternalWeightedCapEdge { final int to, rev; long cap; final long cost; InternalWeightedCapEdge(int to, int rev, long cap, long cost) { this.to = to; this.rev = rev; this.cap = cap; this.cost = cost; } } public static final class WeightedCapEdge { public final int from, to; public final long cap, flow, cost; WeightedCapEdge(int from, int to, long cap, long flow, long cost) { this.from = from; this.to = to; this.cap = cap; this.flow = flow; this.cost = cost; } @Override public boolean equals(Object o) { if (o instanceof WeightedCapEdge) { WeightedCapEdge e = (WeightedCapEdge) o; return from == e.from && to == e.to && cap == e.cap && flow == e.flow && cost == e.cost; } return false; } } private static final class IntPair { final int first, second; IntPair(int first, int second) { this.first = first; this.second = second; } } public static final class FlowAndCost { public final long flow, cost; FlowAndCost(long flow, long cost) { this.flow = flow; this.cost = cost; } @Override public boolean equals(Object o) { if (o instanceof FlowAndCost) { FlowAndCost c = (FlowAndCost) o; return flow == c.flow && cost == c.cost; } return false; } } static final long INF = Long.MAX_VALUE; private final int n; private final java.util.ArrayList<IntPair> pos; public final java.util.ArrayList<InternalWeightedCapEdge>[] g; @SuppressWarnings("unchecked") public MinCostFlow(int n) { this.n = n; this.pos = new java.util.ArrayList<>(); this.g = new java.util.ArrayList[n]; for (int i = 0; i < n; i++) { this.g[i] = new java.util.ArrayList<>(); } } public int addEdge(int from, int to, long cap, long cost) { rangeCheck(from, 0, n); rangeCheck(to, 0, n); nonNegativeCheck(cap, "Capacity"); nonNegativeCheck(cost, "Cost"); int m = pos.size(); pos.add(new IntPair(from, g[from].size())); int fromId = g[from].size(); int toId = g[to].size(); if (from == to) toId++; g[from].add(new InternalWeightedCapEdge(to, toId, cap, cost)); g[to].add(new InternalWeightedCapEdge(from, fromId, 0L, -cost)); return m; } private InternalWeightedCapEdge getInternalEdge(int i) { return g[pos.get(i).first].get(pos.get(i).second); } private InternalWeightedCapEdge getInternalEdgeReversed(InternalWeightedCapEdge e) { return g[e.to].get(e.rev); } public WeightedCapEdge getEdge(int i) { int m = pos.size(); rangeCheck(i, 0, m); InternalWeightedCapEdge e = getInternalEdge(i); InternalWeightedCapEdge re = getInternalEdgeReversed(e); return new WeightedCapEdge(re.to, e.to, e.cap + re.cap, re.cap, e.cost); } public WeightedCapEdge[] getEdges() { WeightedCapEdge[] res = new WeightedCapEdge[pos.size()]; java.util.Arrays.setAll(res, this::getEdge); return res; } public FlowAndCost minCostMaxFlow(int s, int t) { return minCostFlow(s, t, INF); } public FlowAndCost minCostFlow(int s, int t, long flowLimit) { return minCostSlope(s, t, flowLimit).getLast(); } java.util.LinkedList<FlowAndCost> minCostSlope(int s, int t) { return minCostSlope(s, t, INF); } public java.util.LinkedList<FlowAndCost> minCostSlope(int s, int t, long flowLimit) { rangeCheck(s, 0, n); rangeCheck(t, 0, n); if (s == t) { throw new IllegalArgumentException( String.format("%d and %d is the same vertex.", s, t) ); } long[] dual = new long[n]; long[] dist = new long[n]; int[] pv = new int[n]; int[] pe = new int[n]; boolean[] vis = new boolean[n]; long flow = 0; long cost = 0, prev_cost = -1; java.util.LinkedList<FlowAndCost> result = new java.util.LinkedList<>(); result.addLast(new FlowAndCost(flow, cost)); while (flow < flowLimit) { if (!dualRef(s, t, dual, dist, pv, pe, vis)) break; long c = flowLimit - flow; for (int v = t; v != s; v = pv[v]) { c = Math.min(c, g[pv[v]].get(pe[v]).cap); } for (int v = t; v != s; v = pv[v]) { InternalWeightedCapEdge e = g[pv[v]].get(pe[v]); e.cap -= c; g[v].get(e.rev).cap += c; } long d = -dual[s]; flow += c; cost += c * d; if (prev_cost == d) { result.removeLast(); } result.addLast(new FlowAndCost(flow, cost)); prev_cost = cost; } return result; } private boolean dualRef(int s, int t, long[] dual, long[] dist, int[] pv, int[] pe, boolean[] vis) { java.util.Arrays.fill(dist, INF); java.util.Arrays.fill(pv, -1); java.util.Arrays.fill(pe, -1); java.util.Arrays.fill(vis, false); class State implements Comparable<State> { final long key; final int to; State(long key, int to) { this.key = key; this.to = to; } public int compareTo(State q) { return key > q.key ? 1 : -1; } }; java.util.PriorityQueue<State> pq = new java.util.PriorityQueue<>(); dist[s] = 0; pq.add(new State(0L, s)); while (pq.size() > 0) { int v = pq.poll().to; if (vis[v]) continue; vis[v] = true; if (v == t) break; for (int i = 0, deg = g[v].size(); i < deg; i++) { InternalWeightedCapEdge e = g[v].get(i); if (vis[e.to] || e.cap == 0) continue; long cost = e.cost - dual[e.to] + dual[v]; if (dist[e.to] - dist[v] > cost) { dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; pq.add(new State(dist[e.to], e.to)); } } } if (!vis[t]) { return false; } for (int v = 0; v < n; v++) { if (!vis[v]) continue; dual[v] -= dist[t] - dist[v]; } return true; } private void rangeCheck(int i, int minInlusive, int maxExclusive) { if (i < 0 || i >= maxExclusive) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, maxExclusive) ); } } private void nonNegativeCheck(long cap, java.lang.String attribute) { if (cap < 0) { throw new IllegalArgumentException( String.format("%s %d is negative.", attribute, cap) ); } } } class LazySegTree<S, F> { final int MAX; final int N; final int Log; final java.util.function.BinaryOperator<S> Op; final S E; final java.util.function.BiFunction<F, S, S> Mapping; final java.util.function.BinaryOperator<F> Composition; final F Id; final S[] Dat; final F[] Laz; @SuppressWarnings("unchecked") public LazySegTree(int n, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.Log = Integer.numberOfTrailingZeros(N); this.Op = op; this.E = e; this.Mapping = mapping; this.Composition = composition; this.Id = id; this.Dat = (S[]) new Object[N << 1]; this.Laz = (F[]) new Object[N]; java.util.Arrays.fill(Dat, E); java.util.Arrays.fill(Laz, Id); } public LazySegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this(dat.length, op, e, mapping, composition, id); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, Dat, N, l); for (int i = N - 1; i > 0; i--) { Dat[i] = Op.apply(Dat[i << 1 | 0], Dat[i << 1 | 1]); } } private void push(int k) { if (Laz[k] == Id) return; int lk = k << 1 | 0, rk = k << 1 | 1; Dat[lk] = Mapping.apply(Laz[k], Dat[lk]); Dat[rk] = Mapping.apply(Laz[k], Dat[rk]); if (lk < N) Laz[lk] = Composition.apply(Laz[k], Laz[lk]); if (rk < N) Laz[rk] = Composition.apply(Laz[k], Laz[rk]); Laz[k] = Id; } private void pushTo(int k) { for (int i = Log; i > 0; i--) push(k >> i); } private void pushTo(int lk, int rk) { for (int i = Log; i > 0; i--) { if (((lk >> i) << i) != lk) push(lk >> i); if (((rk >> i) << i) != rk) push(rk >> i); } } private void updateFrom(int k) { k >>= 1; while (k > 0) { Dat[k] = Op.apply(Dat[k << 1 | 0], Dat[k << 1 | 1]); k >>= 1; } } private void updateFrom(int lk, int rk) { for (int i = 1; i <= Log; i++) { if (((lk >> i) << i) != lk) { int lki = lk >> i; Dat[lki] = Op.apply(Dat[lki << 1 | 0], Dat[lki << 1 | 1]); } if (((rk >> i) << i) != rk) { int rki = (rk - 1) >> i; Dat[rki] = Op.apply(Dat[rki << 1 | 0], Dat[rki << 1 | 1]); } } } public void set(int p, S x) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = x; updateFrom(p); } public S get(int p) { exclusiveRangeCheck(p); p += N; pushTo(p); return Dat[p]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return E; l += N; r += N; pushTo(l, r); S sumLeft = E, sumRight = E; while (l < r) { if ((l & 1) == 1) sumLeft = Op.apply(sumLeft, Dat[l++]); if ((r & 1) == 1) sumRight = Op.apply(Dat[--r], sumRight); l >>= 1; r >>= 1; } return Op.apply(sumLeft, sumRight); } public S allProd() { return Dat[1]; } public void apply(int p, F f) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = Mapping.apply(f, Dat[p]); updateFrom(p); } public void apply(int l, int r, F f) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return; l += N; r += N; pushTo(l, r); for (int l2 = l, r2 = r; l2 < r2;) { if ((l2 & 1) == 1) { Dat[l2] = Mapping.apply(f, Dat[l2]); if (l2 < N) Laz[l2] = Composition.apply(f, Laz[l2]); l2++; } if ((r2 & 1) == 1) { r2--; Dat[r2] = Mapping.apply(f, Dat[r2]); if (r2 < N) Laz[r2] = Composition.apply(f, Laz[r2]); } l2 >>= 1; r2 >>= 1; } updateFrom(l, r); } public int maxRight(int l, java.util.function.Predicate<S> g) { inclusiveRangeCheck(l); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; pushTo(l); S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!g.test(Op.apply(sum, Dat[l]))) { while (l < N) { push(l); l = l << 1; if (g.test(Op.apply(sum, Dat[l]))) { sum = Op.apply(sum, Dat[l]); l++; } } return l - N; } sum = Op.apply(sum, Dat[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> g) { inclusiveRangeCheck(r); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; pushTo(r - 1); S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!g.test(Op.apply(Dat[r], sum))) { while (r < N) { push(r); r = r << 1 | 1; if (g.test(Op.apply(Dat[r], sum))) { sum = Op.apply(Dat[r], sum); r--; } } return r + 1 - N; } sum = Op.apply(Dat[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d is not in [%d, %d).", p, 0, MAX) ); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d is not in [%d, %d].", p, 0, MAX) ); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } private S[] simulatePushAll() { S[] simDat = java.util.Arrays.copyOf(Dat, 2 * N); F[] simLaz = java.util.Arrays.copyOf(Laz, 2 * N); for (int k = 1; k < N; k++) { if (simLaz[k] == Id) continue; int lk = k << 1 | 0, rk = k << 1 | 1; simDat[lk] = Mapping.apply(simLaz[k], simDat[lk]); simDat[rk] = Mapping.apply(simLaz[k], simDat[rk]); if (lk < N) simLaz[lk] = Composition.apply(simLaz[k], simLaz[lk]); if (rk < N) simLaz[rk] = Composition.apply(simLaz[k], simLaz[rk]); simLaz[k] = Id; } return simDat; } public String toDetailedString() { return toDetailedString(1, 0, simulatePushAll()); } private String toDetailedString(int k, int sp, S[] dat) { if (k >= N) return indent(sp) + dat[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent, dat); s += "\n"; s += indent(sp) + dat[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent, dat); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n --> 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { S[] dat = simulatePushAll(); StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(dat[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } class FenwickTree{ private int _n; private long[] data; public FenwickTree(int n){ this._n = n; data = new long[n]; } /** * @verified https://atcoder.jp/contests/practice2/tasks/practice2_b * @submission https://atcoder.jp/contests/practice2/submissions/16580495 */ public FenwickTree(long[] data) { this(data.length); build(data); } public void set(int p, long x){ add(p, x - get(p)); } public void add(int p, long x){ assert(0<=p && p<_n); p++; while(p<=_n){ data[p-1] += x; p += p&-p; } } public long sum(int l, int r){ assert(0<=l && l<=r && r<=_n); return sum(r)-sum(l); } public long get(int p){ return sum(p, p+1); } private long sum(int r){ long s = 0; while(r>0){ s += data[r-1]; r -= r&-r; } return s; } private void build(long[] dat) { System.arraycopy(dat, 0, data, 0, _n); for (int i=1; i<=_n; i++) { int p = i+(i&-i); if(p<=_n){ data[p-1] += data[i-1]; } } } } class MaxFlow { private static final class InternalCapEdge { final int to; final int rev; long cap; InternalCapEdge(int to, int rev, long cap) { this.to = to; this.rev = rev; this.cap = cap; } } public static final class CapEdge { public final int from, to; public final long cap, flow; CapEdge(int from, int to, long cap, long flow) { this.from = from; this.to = to; this.cap = cap; this.flow = flow; } @Override public boolean equals(Object o) { if (o instanceof CapEdge) { CapEdge e = (CapEdge) o; return from == e.from && to == e.to && cap == e.cap && flow == e.flow; } return false; } } private static final class IntPair { final int first, second; IntPair(int first, int second) { this.first = first; this.second = second; } } static final long INF = Long.MAX_VALUE; private final int n; private final java.util.ArrayList<IntPair> pos; private final java.util.ArrayList<InternalCapEdge>[] g; @SuppressWarnings("unchecked") public MaxFlow(int n) { this.n = n; this.pos = new java.util.ArrayList<>(); this.g = new java.util.ArrayList[n]; for (int i = 0; i < n; i++) { this.g[i] = new java.util.ArrayList<>(); } } public int addEdge(int from, int to, long cap) { rangeCheck(from, 0, n); rangeCheck(to, 0, n); nonNegativeCheck(cap, "Capacity"); int m = pos.size(); pos.add(new IntPair(from, g[from].size())); int fromId = g[from].size(); int toId = g[to].size(); if (from == to) toId++; g[from].add(new InternalCapEdge(to, toId, cap)); g[to].add(new InternalCapEdge(from, fromId, 0L)); return m; } private InternalCapEdge getInternalEdge(int i) { return g[pos.get(i).first].get(pos.get(i).second); } private InternalCapEdge getInternalEdgeReversed(InternalCapEdge e) { return g[e.to].get(e.rev); } public CapEdge getEdge(int i) { int m = pos.size(); rangeCheck(i, 0, m); InternalCapEdge e = getInternalEdge(i); InternalCapEdge re = getInternalEdgeReversed(e); return new CapEdge(re.to, e.to, e.cap + re.cap, re.cap); } public CapEdge[] getEdges() { CapEdge[] res = new CapEdge[pos.size()]; java.util.Arrays.setAll(res, this::getEdge); return res; } public void changeEdge(int i, long newCap, long newFlow) { int m = pos.size(); rangeCheck(i, 0, m); nonNegativeCheck(newCap, "Capacity"); if (newFlow > newCap) { throw new IllegalArgumentException( String.format("Flow %d is greater than the capacity %d.", newCap, newFlow) ); } InternalCapEdge e = getInternalEdge(i); InternalCapEdge re = getInternalEdgeReversed(e); e.cap = newCap - newFlow; re.cap = newFlow; } public long maxFlow(int s, int t) { return flow(s, t, INF); } public long flow(int s, int t, long flowLimit) { rangeCheck(s, 0, n); rangeCheck(t, 0, n); long flow = 0L; int[] level = new int[n]; int[] que = new int[n]; int[] iter = new int[n]; while (flow < flowLimit) { bfs(s, t, level, que); if (level[t] < 0) break; java.util.Arrays.fill(iter, 0); while (flow < flowLimit) { long d = dfs(t, s, flowLimit - flow, iter, level); if (d == 0) break; flow += d; } } return flow; } private void bfs(int s, int t, int[] level, int[] que) { java.util.Arrays.fill(level, -1); int hd = 0, tl = 0; que[tl++] = s; level[s] = 0; while (hd < tl) { int u = que[hd++]; for (InternalCapEdge e : g[u]) { int v = e.to; if (e.cap == 0 || level[v] >= 0) continue; level[v] = level[u] + 1; if (v == t) return; que[tl++] = v; } } } private long dfs(int cur, int s, long flowLimit, int[] iter, int[] level) { if (cur == s) return flowLimit; long res = 0; int curLevel = level[cur]; for (int itMax = g[cur].size(); iter[cur] < itMax; iter[cur]++) { int i = iter[cur]; InternalCapEdge e = g[cur].get(i); InternalCapEdge re = getInternalEdgeReversed(e); if (curLevel <= level[e.to] || re.cap == 0) continue; long d = dfs(e.to, s, Math.min(flowLimit - res, re.cap), iter, level); if (d <= 0) continue; e.cap += d; re.cap -= d; res += d; if (res == flowLimit) break; } return res; } public boolean[] minCut(int s) { rangeCheck(s, 0, n); boolean[] visited = new boolean[n]; int[] stack = new int[n]; int ptr = 0; stack[ptr++] = s; visited[s] = true; while (ptr > 0) { int u = stack[--ptr]; for (InternalCapEdge e : g[u]) { int v = e.to; if (e.cap > 0 && !visited[v]) { visited[v] = true; stack[ptr++] = v; } } } return visited; } private void rangeCheck(int i, int minInclusive, int maxExclusive) { if (i < 0 || i >= maxExclusive) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, maxExclusive) ); } } private void nonNegativeCheck(long cap, String attribute) { if (cap < 0) { throw new IllegalArgumentException( String.format("%s %d is negative.", attribute, cap) ); } } } class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next());} }
ConDefects/ConDefects/Code/arc167_b/Java/46635866
condefects-java_data_467
import java.util.*; public class Main { public static long MOD = 998244353; public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ Scanner sc = new Scanner(System.in); long a = sc.nextLong(); long b = sc.nextLong(); long div = 2; long tmp = a; Map<Long,Long> map = new HashMap<>(); while(tmp != 1 && div <= Math.sqrt(a)) { if(tmp % div == (long)0) { map.put(div,(long)0); while(tmp % div == (long)0) { map.put(div, map.get(div) + (long)1); tmp /= div; } }div++; }if(tmp > 1) { map.put(tmp, (long)1); }long all = b % MOD; boolean checkOdd = true; if(b % 2 == 0) { checkOdd = false; } for(long s:map.keySet()) { all *= (map.get(s) * b + 1) %MOD; all %= MOD; //System.out.println(all); if(map.get(s) % (long)2 != 0) { checkOdd = false; } }if(checkOdd) { all -= 1; if(all < 0) { all += MOD; } } all *= pow(2,MOD - 2); all %= MOD; System.out.print(all); } public static long pow(long a,long b) { String bs = Long.toBinaryString(b); long[] pownum = new long[bs.length() + 1]; long ret = 1; pownum[bs.length()] = a; for(int i = bs.length() - 1;i >= 0;i--) { if(bs.charAt(i) == '1') { ret =ret * pownum[i + 1] % MOD; }pownum[i] = pownum[i + 1] * pownum[i + 1] % MOD; } return ret; } } import java.util.*; public class Main { public static long MOD = 998244353; public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ Scanner sc = new Scanner(System.in); long a = sc.nextLong(); long b = sc.nextLong(); long div = 2; long tmp = a; Map<Long,Long> map = new HashMap<>(); while(tmp != 1 && div <= Math.sqrt(a)) { if(tmp % div == (long)0) { map.put(div,(long)0); while(tmp % div == (long)0) { map.put(div, map.get(div) + (long)1); tmp /= div; } }div++; }if(tmp > 1) { map.put(tmp, (long)1); }long all = b % MOD; boolean checkOdd = true; if(b % 2 == 0) { checkOdd = false; } for(long s:map.keySet()) { all *= (map.get(s) * (b %MOD) + 1) %MOD; all %= MOD; //System.out.println(all); if(map.get(s) % (long)2 != 0) { checkOdd = false; } }if(checkOdd) { all -= 1; if(all < 0) { all += MOD; } } all *= pow(2,MOD - 2); all %= MOD; System.out.print(all); } public static long pow(long a,long b) { String bs = Long.toBinaryString(b); long[] pownum = new long[bs.length() + 1]; long ret = 1; pownum[bs.length()] = a; for(int i = bs.length() - 1;i >= 0;i--) { if(bs.charAt(i) == '1') { ret =ret * pownum[i + 1] % MOD; }pownum[i] = pownum[i + 1] * pownum[i + 1] % MOD; } return ret; } }
ConDefects/ConDefects/Code/arc167_b/Java/46651120
condefects-java_data_468
import java.lang.*; import java.util.*; import java.io.*; import java.math.*; class Main { static long c(int n,int k,long[] inv,long mod) { long t = 1; for(int i=1;i<k;i++) { t = t*(n+i) % mod; } t = t*inv[k-1] % mod; return t; } static long quickM(long d,long m,long mod) { long res = 1L; long q = 1L; long t = d; while(q<=m) { if((m&q)>0) { res = res * t % mod; } q = q<<1; t = t * t % mod; } return res; } static void deal(int n,int k,int[] arr) { int sum = arr[0]; for(int i=1;i<n;i++) { sum -= arr[i]; if(sum<k) { out.println(0); return; } } long res = 1; long mod = 998244353; long[] inv = new long[k]; long t = 1; for(int i=1;i<k;i++) { t = t * i % mod; inv[i] = quickM(t, mod-2, mod); } for(int i=1;i<n;i++) { res = res * c(arr[i],k,inv,mod) % mod; } res = res*c(sum-k,k,inv,mod) % mod; out.println(res); } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); } deal(n,k,arr); out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } import java.lang.*; import java.util.*; import java.io.*; import java.math.*; class Main { static long c(int n,int k,long[] inv,long mod) { long t = 1; for(int i=1;i<k;i++) { t = t*(n+i) % mod; } if(k>1) t = t*inv[k-1] % mod; return t; } static long quickM(long d,long m,long mod) { long res = 1L; long q = 1L; long t = d; while(q<=m) { if((m&q)>0) { res = res * t % mod; } q = q<<1; t = t * t % mod; } return res; } static void deal(int n,int k,int[] arr) { int sum = arr[0]; for(int i=1;i<n;i++) { sum -= arr[i]; if(sum<k) { out.println(0); return; } } long res = 1; long mod = 998244353; long[] inv = new long[k]; long t = 1; for(int i=1;i<k;i++) { t = t * i % mod; inv[i] = quickM(t, mod-2, mod); } for(int i=1;i<n;i++) { res = res * c(arr[i],k,inv,mod) % mod; } res = res*c(sum-k,k,inv,mod) % mod; out.println(res); } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); } deal(n,k,arr); out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
ConDefects/ConDefects/Code/arc134_c/Java/28866950
condefects-java_data_469
public class Main { public static void main(final String[] args) { System.out.println(27); for (int i = 1; i < 100; i++) { System.out.print(i + " "); System.out.print(i * 100 + " "); System.out.print(i * 10000 + " "); } } } public class Main { public static void main(final String[] args) { System.out.println(297); for (int i = 1; i < 100; i++) { System.out.print(i + " "); System.out.print(i * 100 + " "); System.out.print(i * 10000 + " "); } } }
ConDefects/ConDefects/Code/abc251_d/Java/45746906
condefects-java_data_470
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(System.out); InputReader in = new InputReader(System.in); Task solver = new Task(); solver.solve(in, out); out.flush(); out.close(); } } class Task { static final long mod = 998244353; long powmod(long a, long b) { long ans = 1, d = a; while (b > 0) { if (b % 2 == 1) ans = ans * d % mod; b >>= 1; d = d * d % mod; } return ans; } public void solve(InputReader in, PrintWriter out) throws Exception { // int T = in.nextInt(); int T = 1; for (int i = 0; i < T; i++) { solveOne(in, out); } } int[] p; long[][][] dp; private void solveOne(InputReader in, PrintWriter out) { int n = in.nextInt(); p = new int[n]; for (int i = 0; i < n; i++) { p[i] = in.nextInt(); } dp = new long[2][n + 1][n]; out.println(dfs(0, 0, n - 1)); } private long dfs(int c, int i, int j) { if (dp[c][i][j] != 0) { return dp[c][i][j]; } if (i >= j) { return dp[c][i][j] = 1; } if (c == 0) { return dp[c][i][j] = dfs(1, i + 1, j); } long ans = 0; for (int k = i; k <= j; k++) { if (p[k] >= p[i]) { ans += dfs(0, i, k) * dfs(1, k + 1, j); ans %= mod; } } return dp[c][i][j] = ans; } } class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(System.out); InputReader in = new InputReader(System.in); Task solver = new Task(); solver.solve(in, out); out.flush(); out.close(); } } class Task { static final long mod = 998244353; long powmod(long a, long b) { long ans = 1, d = a; while (b > 0) { if (b % 2 == 1) ans = ans * d % mod; b >>= 1; d = d * d % mod; } return ans; } public void solve(InputReader in, PrintWriter out) throws Exception { // int T = in.nextInt(); int T = 1; for (int i = 0; i < T; i++) { solveOne(in, out); } } int[] p; long[][][] dp; private void solveOne(InputReader in, PrintWriter out) { int n = in.nextInt(); p = new int[n]; for (int i = 0; i < n; i++) { p[i] = in.nextInt(); } dp = new long[2][n + 1][n]; out.println(dfs(0, 0, n - 1)); } private long dfs(int c, int i, int j) { if (dp[c][i][j] != 0) { return dp[c][i][j]; } if (i >= j) { return dp[c][i][j] = 1; } if (c == 0) { return dp[c][i][j] = dfs(1, i + 1, j); } long ans = 0; for (int k = i; k <= j; k++) { if (k == j || p[k + 1] >= p[i]) { ans += dfs(0, i, k) * dfs(1, k + 1, j); ans %= mod; } } return dp[c][i][j] = ans; } } class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } }
ConDefects/ConDefects/Code/abc252_g/Java/36996765
condefects-java_data_471
import java.util.Scanner; public class Main { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { int height = sc.nextInt(); int width = sc.nextInt(); Board board = new Board(width, height); int number = sc.nextInt(); Point now = new Point(0, 0); for (int i = 0; i < number; i++) { if (board.isTileCovered(now.getX(), now.getY())) { board.tileUncovering(now.getX(), now.getY()); now.setRadius(now.getRadius() + 90); } else { board.tileCovering(now.getX(), now.getY()); now.setRadius(now.getRadius() - 90); } now.walkRotate(); board.print(); System.err.println(); } board.print(); } } static class Point { private int y; private int x; private int radius; // 反時計回りの回転角度、x軸の右側を0とおく Point(int x, int y) { this.x = x; this.y = y; this.radius = 90; } void walkRotate() { while (radius < 0) radius += 360; while (radius >= 360) radius -= 360; switch (radius) { case 0: x += 1; break; case 90: y -= 1; break; case 180: x -= 1; break; case 270: y += 1; } } void setRadius(int radius) { this.radius = radius; } int getRadius() { return radius; } int getX() { return x; } int getY() { return y; } } static class Board { private boolean[][] isCovered; private int width; private int height; Board(int width, int height) { isCovered = new boolean[width][height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { isCovered[i][j] = false; } } this.width = width; this.height = height; } int getValidWidth(int i) { int result = i; while (result < 0) result += width; while (result >= width) result -= width; return result; } int getValidHeight(int j) { int result = j; while (result < 0) result += height; while (result >= height) result -= height; return result; } boolean isTileCovered(int i, int j) { return isCovered[getValidWidth(i)][getValidHeight(j)]; } void tileCovering(int i, int j) { isCovered[getValidWidth(i)][getValidHeight(j)] = true; } void tileUncovering(int i, int j) { isCovered[getValidWidth(i)][getValidHeight(j)] = false; } void print() { for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { String print = isTileCovered(i, j) ? "#" : "."; System.out.print(print); } System.out.println(); } } } } import java.util.Scanner; public class Main { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { int height = sc.nextInt(); int width = sc.nextInt(); Board board = new Board(width, height); int number = sc.nextInt(); Point now = new Point(0, 0); for (int i = 0; i < number; i++) { if (board.isTileCovered(now.getX(), now.getY())) { board.tileUncovering(now.getX(), now.getY()); now.setRadius(now.getRadius() + 90); } else { board.tileCovering(now.getX(), now.getY()); now.setRadius(now.getRadius() - 90); } now.walkRotate(); } board.print(); } } static class Point { private int y; private int x; private int radius; // 反時計回りの回転角度、x軸の右側を0とおく Point(int x, int y) { this.x = x; this.y = y; this.radius = 90; } void walkRotate() { while (radius < 0) radius += 360; while (radius >= 360) radius -= 360; switch (radius) { case 0: x += 1; break; case 90: y -= 1; break; case 180: x -= 1; break; case 270: y += 1; } } void setRadius(int radius) { this.radius = radius; } int getRadius() { return radius; } int getX() { return x; } int getY() { return y; } } static class Board { private boolean[][] isCovered; private int width; private int height; Board(int width, int height) { isCovered = new boolean[width][height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { isCovered[i][j] = false; } } this.width = width; this.height = height; } int getValidWidth(int i) { int result = i; while (result < 0) result += width; while (result >= width) result -= width; return result; } int getValidHeight(int j) { int result = j; while (result < 0) result += height; while (result >= height) result -= height; return result; } boolean isTileCovered(int i, int j) { return isCovered[getValidWidth(i)][getValidHeight(j)]; } void tileCovering(int i, int j) { isCovered[getValidWidth(i)][getValidHeight(j)] = true; } void tileUncovering(int i, int j) { isCovered[getValidWidth(i)][getValidHeight(j)] = false; } void print() { for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { String print = isTileCovered(i, j) ? "#" : "."; System.out.print(print); } System.out.println(); } } } }
ConDefects/ConDefects/Code/abc339_b/Java/51440047
condefects-java_data_472
import java.util.Scanner; public class Main { static int torus(int a, int max, int houkou){ if(houkou>0 && 1<=a && a<max)a+=houkou; else if(houkou>0 && a==max)a=1; else if(houkou<0 && a>1 && a<=max)a+=houkou; else if(houkou<0 && a==1)a=max; return a; } public static void main(String[]srgs) { Scanner sc = new Scanner(System.in); int h = sc.nextInt(); int w = sc.nextInt(); int n = sc.nextInt(); String[][] masu = new String[h + 1][w + 1]; //白にする for (int i = 0; i <= h; i++) for (int j = 0; j <= w; j++) masu[i][j] = "."; int tate = 1; int yoko = 1; String[] muki = {"", "ue", "migi", "sita", "hidari"}; int mukiNo = 1; for (int i = 1; i <= n; i++) { //System.out.println("(" + tate + ", " + yoko + ")から始まる"); if (masu[tate][yoko].equals(".")) { //System.out.println("白だ!"); masu[tate][yoko] = "#"; //System.out.println(torus(mukiNo, 4, 1)); mukiNo = torus(mukiNo, 4, 1); //System.out.println(muki[mukiNo]+"に進む"); if (muki[mukiNo] == "ue") { tate = torus(tate, h, -1); } else if (muki[mukiNo].equals("migi")) { yoko = torus(yoko, w, 1); } else if (muki[mukiNo].equals("sita")) { tate = torus(tate, h, 1); } else if (muki[mukiNo].equals("hidari")) { yoko = torus(yoko, w, -1); } } else if (masu[tate][yoko].equals("#")) { //System.out.println("黒だ!"); masu[tate][yoko] = "."; mukiNo = torus(mukiNo, 4, -1); if (muki[mukiNo] == "ue") { tate = torus(tate, h, -1); } else if (muki[mukiNo] == "migi") { yoko = torus(yoko, w, 1); } else if (muki[mukiNo] == "sita") { tate = torus(tate, h, 1); } else if (muki[mukiNo] == "hidari") { yoko = torus(yoko, w, -1); } } } for (int i = 1; i <= h; i++) { for (int j = 1; j <= w; j++) { System.out.print(masu[i][j]+" "); } System.out.println(); } } } import java.util.Scanner; public class Main { static int torus(int a, int max, int houkou){ if(houkou>0 && 1<=a && a<max)a+=houkou; else if(houkou>0 && a==max)a=1; else if(houkou<0 && a>1 && a<=max)a+=houkou; else if(houkou<0 && a==1)a=max; return a; } public static void main(String[]srgs) { Scanner sc = new Scanner(System.in); int h = sc.nextInt(); int w = sc.nextInt(); int n = sc.nextInt(); String[][] masu = new String[h + 1][w + 1]; //白にする for (int i = 0; i <= h; i++) for (int j = 0; j <= w; j++) masu[i][j] = "."; int tate = 1; int yoko = 1; String[] muki = {"", "ue", "migi", "sita", "hidari"}; int mukiNo = 1; for (int i = 1; i <= n; i++) { //System.out.println("(" + tate + ", " + yoko + ")から始まる"); if (masu[tate][yoko].equals(".")) { //System.out.println("白だ!"); masu[tate][yoko] = "#"; //System.out.println(torus(mukiNo, 4, 1)); mukiNo = torus(mukiNo, 4, 1); //System.out.println(muki[mukiNo]+"に進む"); if (muki[mukiNo] == "ue") { tate = torus(tate, h, -1); } else if (muki[mukiNo].equals("migi")) { yoko = torus(yoko, w, 1); } else if (muki[mukiNo].equals("sita")) { tate = torus(tate, h, 1); } else if (muki[mukiNo].equals("hidari")) { yoko = torus(yoko, w, -1); } } else if (masu[tate][yoko].equals("#")) { //System.out.println("黒だ!"); masu[tate][yoko] = "."; mukiNo = torus(mukiNo, 4, -1); if (muki[mukiNo] == "ue") { tate = torus(tate, h, -1); } else if (muki[mukiNo] == "migi") { yoko = torus(yoko, w, 1); } else if (muki[mukiNo] == "sita") { tate = torus(tate, h, 1); } else if (muki[mukiNo] == "hidari") { yoko = torus(yoko, w, -1); } } } for (int i = 1; i <= h; i++) { for (int j = 1; j <= w; j++) { System.out.print(masu[i][j]); } System.out.println(); } } }
ConDefects/ConDefects/Code/abc339_b/Java/50000223
condefects-java_data_473
import java.util.Scanner; public class Main { public static void main(String[] args) { int mod = 998244353; Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(); int[][][][] dp = new int[n + 1][11][11][11]; dp[0][m][m][m] = 1; for(int i = 1; i <= n; i++){ for(int x = 0; x <= m; x++){ for(int y = x; y <= m; y++){ for(int z = y; z <= m; z++){ for(int j = 0; j < m; j++){ int val = dp[i - 1][x][y][z]; if(j <= x){ dp[i][j][y][z] = (dp[i][j][y][z] + val) % mod; }else if(j <= y){ dp[i][x][j][z] = (dp[i][x][j][z] + val) % mod; }else if(j <= z){ dp[i][x][y][j] = (dp[i][x][y][j] + val) % mod; } } } } } } int ans = 0; for(int x = 0; x < m; x++){ for(int y = x + 1; y < m; y++){ for(int z = y + 1; z < m; z++){ ans += dp[n][x][y][z]; } } } System.out.println(ans % mod); } } import java.util.Scanner; public class Main { public static void main(String[] args) { int mod = 998244353; Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(); int[][][][] dp = new int[n + 1][11][11][11]; dp[0][m][m][m] = 1; for(int i = 1; i <= n; i++){ for(int x = 0; x <= m; x++){ for(int y = x; y <= m; y++){ for(int z = y; z <= m; z++){ for(int j = 0; j < m; j++){ int val = dp[i - 1][x][y][z]; if(j <= x){ dp[i][j][y][z] = (dp[i][j][y][z] + val) % mod; }else if(j <= y){ dp[i][x][j][z] = (dp[i][x][j][z] + val) % mod; }else if(j <= z){ dp[i][x][y][j] = (dp[i][x][y][j] + val) % mod; } } } } } } int ans = 0; for(int x = 0; x < m; x++){ for(int y = x + 1; y < m; y++){ for(int z = y + 1; z < m; z++){ ans = (ans + dp[n][x][y][z]) % mod; } } } System.out.println(ans % mod); } }
ConDefects/ConDefects/Code/abc237_f/Java/35932051
condefects-java_data_474
import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; @SuppressWarnings("unused") public class Main { static InputStream is; static PrintWriter out; static String INPUT = ""; //global static void solve() { int X = readInt(); X += (X<42) ? 0:1; StringBuilder sb = new StringBuilder(); for (int i=0;i<3;i++) { sb.append(X%10); X/=10; } sb.append("CBA"); sb.reverse(); out.println(sb.toString()); } public static void main(String[] args) throws Exception { long S = System.currentTimeMillis(); if (INPUT=="") { is = System.in; } else { File file = new File(INPUT); is = new FileInputStream(file); } out = new PrintWriter(System.out); solve(); out.flush(); long G = System.currentTimeMillis(); } private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> { public ListComparator() {} @Override public int compare(List<T> o1, List<T> o2) { for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { int c = o1.get(i).compareTo(o2.get(i)); if (c != 0) { return c; } } return Integer.compare(o1.size(), o2.size()); } } private static boolean eof() { if(lenbuf == -1)return true; int lptr = ptrbuf; while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false; try { is.mark(1000); while(true){ int b = is.read(); if(b == -1){ is.reset(); return true; }else if(!isSpaceChar(b)){ is.reset(); return false; } } } catch (IOException e) { return true; } } private static byte[] inbuf = new byte[1024]; static int lenbuf = 0, ptrbuf = 0; private static int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } // private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double readDouble() { return Double.parseDouble(readString()); } private static char readChar() { return (char)skip(); } private static String readString() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static char[] readChar(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private static char[][] readTable(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = readChar(m); return map; } private static int[] readIntArray(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = readInt(); return a; } private static long[] readLongArray(int n) { long[] a = new long[n]; for (int i=0;i<n;i++) a[i] = readLong(); return a; } private static int readInt() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static long readLong() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); } } import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; @SuppressWarnings("unused") public class Main { static InputStream is; static PrintWriter out; static String INPUT = ""; //global static void solve() { int X = readInt(); X += (X<42) ? 0:1; StringBuilder sb = new StringBuilder(); for (int i=0;i<3;i++) { sb.append(X%10); X/=10; } sb.append("CGA"); sb.reverse(); out.println(sb.toString()); } public static void main(String[] args) throws Exception { long S = System.currentTimeMillis(); if (INPUT=="") { is = System.in; } else { File file = new File(INPUT); is = new FileInputStream(file); } out = new PrintWriter(System.out); solve(); out.flush(); long G = System.currentTimeMillis(); } private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> { public ListComparator() {} @Override public int compare(List<T> o1, List<T> o2) { for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { int c = o1.get(i).compareTo(o2.get(i)); if (c != 0) { return c; } } return Integer.compare(o1.size(), o2.size()); } } private static boolean eof() { if(lenbuf == -1)return true; int lptr = ptrbuf; while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false; try { is.mark(1000); while(true){ int b = is.read(); if(b == -1){ is.reset(); return true; }else if(!isSpaceChar(b)){ is.reset(); return false; } } } catch (IOException e) { return true; } } private static byte[] inbuf = new byte[1024]; static int lenbuf = 0, ptrbuf = 0; private static int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } // private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double readDouble() { return Double.parseDouble(readString()); } private static char readChar() { return (char)skip(); } private static String readString() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static char[] readChar(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private static char[][] readTable(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = readChar(m); return map; } private static int[] readIntArray(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = readInt(); return a; } private static long[] readLongArray(int n) { long[] a = new long[n]; for (int i=0;i<n;i++) a[i] = readLong(); return a; } private static int readInt() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static long readLong() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); } }
ConDefects/ConDefects/Code/abc230_a/Java/31370501
condefects-java_data_475
import java.util.Scanner; public class Main { public static void main(String[] args) { //整数の入力を受け付ける Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); //42を超える数字であった場合は+1する if(num>42) { num = num+1; } //数字を0埋めして表示する String formatStr = String.format("AGC%03d", num); System.out.println(formatStr); } } import java.util.Scanner; public class Main { public static void main(String[] args) { //整数の入力を受け付ける Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); //42を超える数字であった場合は+1する if(num>=42) { num = num+1; } //数字を0埋めして表示する String formatStr = String.format("AGC%03d", num); System.out.println(formatStr); } }
ConDefects/ConDefects/Code/abc230_a/Java/35820796
condefects-java_data_476
import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.Set; import java.math.BigInteger; import java.util.Comparator; class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int a = sc.nextInt(); if(a > 42){ a++; } String ans = "AGC0" + String.format("%02d", a); System.out.println(ans); } } import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.Set; import java.math.BigInteger; import java.util.Comparator; class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int a = sc.nextInt(); if(a >= 42){ a++; } String ans = "AGC0" + String.format("%02d", a); System.out.println(ans); } }
ConDefects/ConDefects/Code/abc230_a/Java/43395406
condefects-java_data_477
class Main{ public static void main(String[] args){ int N = new java.util.Scanner(System.in).nextInt(); System.out.println(N>41?N+1:N); } } class Main{ public static void main(String[] args){ int N = new java.util.Scanner(System.in).nextInt(); System.out.println("AGC0"+(N>41?N+1:(N>9?N:"0"+N))); } }
ConDefects/ConDefects/Code/abc230_a/Java/34682793
condefects-java_data_478
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int num = scan.nextInt(); if(num > 42) num += 1; System.out.printf("AGC%03d", num); } } import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int num = scan.nextInt(); if(num >= 42) num += 1; System.out.printf("AGC%03d", num); } }
ConDefects/ConDefects/Code/abc230_a/Java/35821843
condefects-java_data_479
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); String[] arr = {"A", "G", "C", "0", null, null}; for(int i = 1; i <= 54; i++) { String i1 = String.valueOf(x); if(x < 10) { arr[4] = "0"; arr[5] = i1; } else { arr[4] = i1.split("")[0]; arr[5] = i1.split("")[1]; if(x > 42) { String i2 = String.valueOf(x + 1); arr[4] = i2.split("")[0]; arr[5] = i2.split("")[1]; } } } String result = ""; for(String s : arr) { result += s; } System.out.println(result); } } import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); String[] arr = {"A", "G", "C", "0", null, null}; for(int i = 1; i <= 54; i++) { String i1 = String.valueOf(x); if(x < 10) { arr[4] = "0"; arr[5] = i1; } else { arr[4] = i1.split("")[0]; arr[5] = i1.split("")[1]; if(x >= 42) { String i2 = String.valueOf(x + 1); arr[4] = i2.split("")[0]; arr[5] = i2.split("")[1]; } } } String result = ""; for(String s : arr) { result += s; } System.out.println(result); } }
ConDefects/ConDefects/Code/abc230_a/Java/35821976
condefects-java_data_480
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.close(); if( n >= 42) { System.out.println("AGC0"+ (n+1)); }else { System.out.println("AGC0"+ n); } } } import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.close(); if( n >= 42) { System.out.println("AGC0"+ (n+1)); }else if(1<= n && n<=9){ System.out.println("AGC00"+ n); }else { System.out.println("AGC0"+ n); } } }
ConDefects/ConDefects/Code/abc230_a/Java/35822468
condefects-java_data_481
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int n=scanner.nextInt(); if(n<=41){ System.out.printf("AGC0"+ "%02d\n",n); } else{ System.out.printf("AGC0"+"%02d\n",n); } } } import java.util.Scanner; class Main { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int n=scanner.nextInt(); if(n<=41){ System.out.printf("AGC0"+ "%02d\n",n); } else{ System.out.printf("AGC0"+"%02d\n",n+1); } } }
ConDefects/ConDefects/Code/abc230_a/Java/41493929
condefects-java_data_482
import java.util.*; public class Main { public static void main(String[] args){ Scanner abc = new Scanner(System.in); int red = abc.nextInt(); if(red>=42){ System.out.println("AGC0"+red); }else{ if(red>=9){ System.out.println("AGC0"+red); }else{ System.out.println("AGC00"+red); } } } } import java.util.*; public class Main { public static void main(String[] args){ Scanner abc = new Scanner(System.in); int red = abc.nextInt(); if(red>=42){ System.out.println("AGC0"+(red+1)); }else{ if(red>=9){ System.out.println("AGC0"+red); }else{ System.out.println("AGC00"+red); } } } }
ConDefects/ConDefects/Code/abc230_a/Java/41798416
condefects-java_data_483
import java.util.*; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); scan.close(); int a = 0; String s = ""; if(n >= 42) { a = n + 1; } else { a = n; } if(a <= 99) { // s = "0" + String.valueOf(a); System.out.println("AGC0" + a); } else { // s = String.valueOf(a); System.out.println("AGC" + a); } } } import java.util.*; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); scan.close(); int a = 0; String s = ""; if(n >= 42) { a = n + 1; } else { a = n; } if(a <= 99) { // s = "0" + String.valueOf(a); System.out.println("AGC" + String.format("%03d", a)); } else { // s = String.valueOf(a); System.out.println("AGC" + a); } } }
ConDefects/ConDefects/Code/abc230_a/Java/35822273
condefects-java_data_484
import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); if(N > 41){ N ++; } System.out.println("AGC0" + N); } } import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); if(N > 41){ N ++; } System.out.println("AGC0" + String.format("%02d", N)); } }
ConDefects/ConDefects/Code/abc230_a/Java/32625539
condefects-java_data_485
import java.util.*; class Main { public static void main(String[] args)throws Exception { Scanner scanner = new Scanner(System.in); int n=scanner.nextInt(); int ans=0; for(int i=1;i<n;i++){ int X=0; int Y=n-i; int x=0; int y=0; for(int j=1;j*j<=X;j++){ if(X%j==0){ x++; if(X!=j*j)x++; } } for(int j=1;j*j<=Y;j++){ if(Y%j==0){ y++; if(Y!=j*j)y++; } } ans+=x*y; } System.out.println(ans); } } import java.util.*; class Main { public static void main(String[] args)throws Exception { Scanner scanner = new Scanner(System.in); int n=scanner.nextInt(); int ans=0; for(int i=1;i<n;i++){ int X=i; int Y=n-i; int x=0; int y=0; for(int j=1;j*j<=X;j++){ if(X%j==0){ x++; if(X!=j*j)x++; } } for(int j=1;j*j<=Y;j++){ if(Y%j==0){ y++; if(Y!=j*j)y++; } } ans+=x*y; } System.out.println(ans); } }
ConDefects/ConDefects/Code/abc292_c/Java/41894327
condefects-java_data_486
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // 数 long n = sc.nextLong(); // a~d long a = 0; long b = 0; long c = 0; long d = 0; // カウント long count = 0; // テスト用 結果をすべて格納する // ArrayList<String> test = new ArrayList<>(); // a*aがnの半分未満の間、aを総当たりする for (a=1; a*a < n/2; a++) { // bはa以上かつabがnの半分未満 for (b=a; a*b <= n/2; b++) { // cはc*cがn-ab未満 for (c=1; c*c <= n-a*b; c++) { // System.out.println(a+" "+b+" "+c); // 条件を満たすdが存在するか if ((n-a*b)%c == 0) { // 存在した場合 d = (n-a*b)/c; // 並び替えのパターン long inc = 1; // boolean c1=false,c2=false,c3=false; //test if (a != b) { inc*= 2; // c1 = true; // test } if (c != d) { inc*= 2; // c2 = true; // test } if (a != c || b != d) { inc*= 2; // c3 = true; // test } // test // if (c1&&c2&&c3) // { // if (test.contains(d+" "+c+" "+b+" "+a)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(d+" "+c+" "+b+" "+a); // } // } // if (c1&&c2) // { // if (test.contains(b+" "+a+" "+d+" "+c)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(b+" "+a+" "+d+" "+c); // } // } // if (c1&&c3) // { // if (test.contains(c+" "+d+" "+b+" "+a)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(c+" "+d+" "+b+" "+a); // } // } // if (c1) // { // if (test.contains(b+" "+a+" "+c+" "+d)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(b+" "+a+" "+c+" "+d); // } // } // if (c2&&c3) // { // if (test.contains(d+" "+c+" "+a+" "+b)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(d+" "+c+" "+a+" "+b); // } // } // if (c2) // { // if (test.contains(a+" "+b+" "+d+" "+c)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(a+" "+b+" "+d+" "+c); // } // } // if (c3) // { // if (test.contains(c+" "+d+" "+a+" "+b)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(c+" "+d+" "+a+" "+b); // } // } // if (test.contains(a+" "+b+" "+c+" "+d)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(a+" "+b+" "+c+" "+d); // } if (!(a*b == c*d && a < c)) { // カウントを増やす count += inc; } // System.out.println(inc+"x"+a+" "+b+" "+c+" "+d); } } } } // 出力 System.out.println(count); // System.out.println(test.size()); // for (String s:test) // { // System.out.println(s); // } } } import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // 数 long n = sc.nextLong(); // a~d long a = 0; long b = 0; long c = 0; long d = 0; // カウント long count = 0; // テスト用 結果をすべて格納する // ArrayList<String> test = new ArrayList<>(); // a*aがnの半分未満の間、aを総当たりする for (a=1; a*a <= n/2; a++) { // bはa以上かつabがnの半分未満 for (b=a; a*b <= n/2; b++) { // cはc*cがn-ab未満 for (c=1; c*c <= n-a*b; c++) { // System.out.println(a+" "+b+" "+c); // 条件を満たすdが存在するか if ((n-a*b)%c == 0) { // 存在した場合 d = (n-a*b)/c; // 並び替えのパターン long inc = 1; // boolean c1=false,c2=false,c3=false; //test if (a != b) { inc*= 2; // c1 = true; // test } if (c != d) { inc*= 2; // c2 = true; // test } if (a != c || b != d) { inc*= 2; // c3 = true; // test } // test // if (c1&&c2&&c3) // { // if (test.contains(d+" "+c+" "+b+" "+a)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(d+" "+c+" "+b+" "+a); // } // } // if (c1&&c2) // { // if (test.contains(b+" "+a+" "+d+" "+c)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(b+" "+a+" "+d+" "+c); // } // } // if (c1&&c3) // { // if (test.contains(c+" "+d+" "+b+" "+a)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(c+" "+d+" "+b+" "+a); // } // } // if (c1) // { // if (test.contains(b+" "+a+" "+c+" "+d)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(b+" "+a+" "+c+" "+d); // } // } // if (c2&&c3) // { // if (test.contains(d+" "+c+" "+a+" "+b)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(d+" "+c+" "+a+" "+b); // } // } // if (c2) // { // if (test.contains(a+" "+b+" "+d+" "+c)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(a+" "+b+" "+d+" "+c); // } // } // if (c3) // { // if (test.contains(c+" "+d+" "+a+" "+b)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(c+" "+d+" "+a+" "+b); // } // } // if (test.contains(a+" "+b+" "+c+" "+d)) // { // System.out.println(a+" "+b+" "+c+" "+d); // } // else // { // test.add(a+" "+b+" "+c+" "+d); // } if (!(a*b == c*d && a < c)) { // カウントを増やす count += inc; } // System.out.println(inc+"x"+a+" "+b+" "+c+" "+d); } } } } // 出力 System.out.println(count); // System.out.println(test.size()); // for (String s:test) // { // System.out.println(s); // } } }
ConDefects/ConDefects/Code/abc292_c/Java/45533539
condefects-java_data_487
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; class Main { static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static final PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static List<Long> factorize(long n) { List<Long> res = new ArrayList<>(); for (long i = 1; i * i <= n; ++i) { if (n % i == 0) { res.add(i); if (i * i != n) { res.add(n / i); } } } return res; } static void solve() throws IOException { /* Observations: 1. If g | a, b, then g | a - g, b - g 2. For any g' | a, b, we must have g' | a - b. Notably, a - b remains constant 3. g cannot decrease because of (1). However, g can increase to a multiple of g Try: - Start with a, b - Find all g', k such that g' | a - kg, b - kg - Do this by taking all g' such that g | g', g' | a - b. Calculate a / g' * g', b / g' * g'. a - kg, b - kg must reach this for some k. - Find the minimum a / g' * g', b / g' * g'. This will be the next g' */ StringTokenizer input = new StringTokenizer(br.readLine()); long a = Long.parseLong(input.nextToken()); long b = Long.parseLong(input.nextToken()); if (a > b) { long temp = a; a = b; b = temp; } long g = gcd(a, b); final List<Long> aMinusBFactors = factorize(b - a); int res = 0; while (a != 0 && b != 0) { // System.out.println(a + " " + b); long maxNextA = 0; long minStep = a; long gPrime = g; for (long factor : aMinusBFactors) { if (factor > g && factor % g == 0) { long step = a % factor; if ((b - step) % factor == 0) { if (a - step > maxNextA) { maxNextA = a - step; minStep = step; gPrime = factor; } } } } res += (a - maxNextA) / g; a = maxNextA; b = b - minStep; g = gPrime; } pw.println(res); } public static void main(String[] args) throws IOException { solve(); br.close(); pw.close(); } } import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; class Main { static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static final PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static List<Long> factorize(long n) { List<Long> res = new ArrayList<>(); for (long i = 1; i * i <= n; ++i) { if (n % i == 0) { res.add(i); if (i * i != n) { res.add(n / i); } } } return res; } static void solve() throws IOException { /* Observations: 1. If g | a, b, then g | a - g, b - g 2. For any g' | a, b, we must have g' | a - b. Notably, a - b remains constant 3. g cannot decrease because of (1). However, g can increase to a multiple of g Try: - Start with a, b - Find all g', k such that g' | a - kg, b - kg - Do this by taking all g' such that g | g', g' | a - b. Calculate a / g' * g', b / g' * g'. a - kg, b - kg must reach this for some k. - Find the minimum a / g' * g', b / g' * g'. This will be the next g' */ StringTokenizer input = new StringTokenizer(br.readLine()); long a = Long.parseLong(input.nextToken()); long b = Long.parseLong(input.nextToken()); if (a > b) { long temp = a; a = b; b = temp; } long g = gcd(a, b); final List<Long> aMinusBFactors = factorize(b - a); long res = 0; while (a != 0 && b != 0) { // System.out.println(a + " " + b); long maxNextA = 0; long minStep = a; long gPrime = g; for (long factor : aMinusBFactors) { if (factor > g && factor % g == 0) { long step = a % factor; if ((b - step) % factor == 0) { if (a - step > maxNextA) { maxNextA = a - step; minStep = step; gPrime = factor; } } } } res += (a - maxNextA) / g; a = maxNextA; b = b - minStep; g = gPrime; } pw.println(res); } public static void main(String[] args) throws IOException { solve(); br.close(); pw.close(); } }
ConDefects/ConDefects/Code/arc159_b/Java/40437071
condefects-java_data_488
import java.util.*; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String S = sc.next(); String T = sc.next(); if (S.equals("AtCoder") && T.equals("AtCoder")) { System.out.println("Yes"); }else { System.out.println("No"); } } } import java.util.*; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String S = sc.next(); String T = sc.next(); if (S.equals("AtCoder") && T.equals("Land")) { System.out.println("Yes"); }else { System.out.println("No"); } } }
ConDefects/ConDefects/Code/abc358_a/Java/55115238
condefects-java_data_489
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ Scanner scan = new Scanner(System.in); String s = scan.next(); String t = scan.next(); if (s.equals("AtCoder") && t.equals("Lnad")) { System.out.println("Yes"); } else { System.out.println("No"); } scan.close(); } } import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ Scanner scan = new Scanner(System.in); String s = scan.next(); String t = scan.next(); if (s.equals("AtCoder") && t.equals("Land")) { System.out.println("Yes"); } else { System.out.println("No"); } scan.close(); } }
ConDefects/ConDefects/Code/abc358_a/Java/54952099
condefects-java_data_490
import java.util.*; import java.io.*; class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } // for each token String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } // Scanner parseInt int nextInt() { return Integer.parseInt(next()); } // Scanner parseLong long nextLong() { return Long.parseLong(next()); } // Scanner double double nextDouble() { return Double.parseDouble(next()); } // Scanner string String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static String solve(String s, String t){ return s.equals("Atcoder") && t.equals("Land")? "Yes": "No"; } public static void main(String agrgs[]){ FastReader sc = new FastReader(); int test = 1; //sc.nextInt(); StringBuilder sb = new StringBuilder(); while(test --> 0){ // int n = sc.nextInt(); // int arr[] = new int[n]; // for(int i=0; i<n; i++) // arr[i] = sc.nextInt(); String s = sc.next(); String t = sc.next(); String res = solve(s, t); sb.append(res+"\n"); } System.out.println(sb.toString()); } } import java.util.*; import java.io.*; class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } // for each token String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } // Scanner parseInt int nextInt() { return Integer.parseInt(next()); } // Scanner parseLong long nextLong() { return Long.parseLong(next()); } // Scanner double double nextDouble() { return Double.parseDouble(next()); } // Scanner string String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static String solve(String s, String t){ return s.equals("AtCoder") && t.equals("Land")? "Yes": "No"; } public static void main(String agrgs[]){ FastReader sc = new FastReader(); int test = 1; //sc.nextInt(); StringBuilder sb = new StringBuilder(); while(test --> 0){ // int n = sc.nextInt(); // int arr[] = new int[n]; // for(int i=0; i<n; i++) // arr[i] = sc.nextInt(); String s = sc.next(); String t = sc.next(); String res = solve(s, t); sb.append(res+"\n"); } System.out.println(sb.toString()); } }
ConDefects/ConDefects/Code/abc358_a/Java/54908407
condefects-java_data_491
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String word1 = sc.next(); String word2 = sc.next(); if(word1 == "AtCoder" && word2 == "Land") { System.out.println("Yes"); }else { System.out.println("No"); } sc.close(); } } import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String word1 = sc.next(); String word2 = sc.next(); if(word1.equals("AtCoder") && word2.equals("Land")) { System.out.println("Yes"); }else { System.out.println("No"); } sc.close(); } }
ConDefects/ConDefects/Code/abc358_a/Java/55153416
condefects-java_data_492
import java.util.Scanner; class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); // String n = sc.next(); // String[] arr = new String[]; // int cnt =0; for(int i = 0;i<1;i++){ String a = sc.next(); if(a.equals("Atcoder")){ String b = sc.next(); if(b.equals("Land")){ System.out.println("Yes"); } else{ System.out.println("No"); } } else{ System.out.println("No"); } } } } import java.util.Scanner; class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); // String n = sc.next(); // String[] arr = new String[]; // int cnt =0; for(int i = 0;i<1;i++){ String a = sc.next(); if(a.equals("AtCoder")){ String b = sc.next(); if(b.equals("Land")){ System.out.println("Yes"); } else{ System.out.println("No"); } } else{ System.out.println("No"); } } } }
ConDefects/ConDefects/Code/abc358_a/Java/54960635
condefects-java_data_493
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; public class Main { static final long MOD=1000000007; static final long MOD1=998244353; static int size = 0; static long MAX = 1000000000000000000l; static long M; public static void main(String[] args){ PrintWriter out = new PrintWriter(System.out); InputReader sc=new InputReader(System.in); int n = sc.nextInt(); graph G = new graph(n); for (int i = 0; i < n-1; i++) { int a = sc.nextInt()-1; int b = sc.nextInt()-1; long w = sc.nextLong(); G.addEdge(a, b, w); G.addEdge(b, a, w); } long[] D = sc.nextLongArray(n); Rerooting rerooting = new Rerooting(n, 0l, G, D); long[] ans = new long[n]; rerooting.calc(0, -1, ans); for (int i = 0; i < ans.length; i++) { out.println(ans[i]); } out.flush(); } //全方位木dp, 更新するものが1つver //関数merge, f, gを変えて使う //注)fとgのindexは適切なものを使う static class Rerooting { long E; long[] dp1; long[] dp2; graph G; long[] D; public Rerooting(int n, long E, graph G, long[] D){ this.E = E; this.dp1 = new long[n]; this.dp2 = new long[n]; this.G = G; this.D = Arrays.copyOf(D, n); dfs1(0, -1); dfs2(0, -1); } //dp_v = g(merge(f(dp_ch1,c), f(dp_ch2,c), ..)) long f(long dp, int index, long v) { return Math.max(dp, D[index]) + v; } long g(long x, int index) { return x; } long merge(long x, long y) { return Math.max(x, y); } void dfs1(int v, int p) { long res = E; for (Edge e: G.list[v]) { if (e.to == p) continue; dfs1(e.to, v); res = merge(res, f(dp1[e.to], e.to, e.v)); } dp1[v] = g(res, v); } void dfs2(int v, int p) { if (p==-1) dp2[v] = E; int size = G.list[v].size(); long[] dp_l = new long[size+1]; long[] dp_r = new long[size+1]; dp_l[0] = E; dp_r[size] = E; long par_w = 0; for (int i = 1; i < size; i++) { int to = G.list[v].get(i-1).to; long w = G.list[v].get(i-1).v; if (to == p) { par_w = w; dp_l[i] = dp_l[i-1]; continue; } dp_l[i] = merge(dp_l[i-1], f(dp1[to], to, w)); } for (int i = size-1; i >= 0; i--) { int to = G.list[v].get(i).to; long w = G.list[v].get(i).v; if (to == p) { par_w = w; dp_r[i] = dp_r[i+1]; continue; } dp_r[i] = merge(dp_r[i+1], f(dp1[to], to, w)); } for (int i = 0; i < size; i++) { int to = G.list[v].get(i).to; if (to == p) continue; dp2[to] = merge(dp_l[i], dp_r[i+1]); if(v!=0) dp2[to] = merge(dp2[to], f(dp2[v], p, par_w)); dp2[to] = g(dp2[to], v); dfs2(to, v); } } void calc(int v, int p, long[] ans) { ans[v] = E; for (Edge e: G.list[v]) { if (e.to == p) { ans[v] = f(dp2[v], p, e.v); continue; } ans[v] = merge(ans[v], f(dp1[e.to], e.to, e.v)); calc(e.to, v, ans); } ans[v] = g(ans[v], v); } } static class Edge implements Comparable<Edge>{ int to; long v; public Edge(int to,long v) { this.to=to; this.v=v; } @Override public boolean equals(Object obj){ if(obj instanceof Edge) { Edge other = (Edge) obj; return other.to==this.to && other.v==this.v; } return false; }//同値の定義 @Override public int hashCode() { return Objects.hash(this.to,this.v); } @Override public int compareTo( Edge p2 ){ if (this.v>p2.v) { return 1; } else if (this.v<p2.v) { return -1; } else { return 0; } } } static class graph{ ArrayList<Edge>[] list; int size; long INF=Long.MAX_VALUE/2; int[] color; @SuppressWarnings("unchecked") public graph(int n) { size = n; list = new ArrayList[n]; color =new int[n]; for(int i=0;i<n;i++){ list[i] = new ArrayList<Edge>(); } } void addEdge(int from,int to,long w) { list[from].add(new Edge(to,w)); } } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } } import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; public class Main { static final long MOD=1000000007; static final long MOD1=998244353; static int size = 0; static long MAX = 1000000000000000000l; static long M; public static void main(String[] args){ PrintWriter out = new PrintWriter(System.out); InputReader sc=new InputReader(System.in); int n = sc.nextInt(); graph G = new graph(n); for (int i = 0; i < n-1; i++) { int a = sc.nextInt()-1; int b = sc.nextInt()-1; long w = sc.nextLong(); G.addEdge(a, b, w); G.addEdge(b, a, w); } long[] D = sc.nextLongArray(n); Rerooting rerooting = new Rerooting(n, 0l, G, D); long[] ans = new long[n]; rerooting.calc(0, -1, ans); for (int i = 0; i < ans.length; i++) { out.println(ans[i]); } out.flush(); } //全方位木dp, 更新するものが1つver //関数merge, f, gを変えて使う //注)fとgのindexは適切なものを使う static class Rerooting { long E; long[] dp1; long[] dp2; graph G; long[] D; public Rerooting(int n, long E, graph G, long[] D){ this.E = E; this.dp1 = new long[n]; this.dp2 = new long[n]; this.G = G; this.D = Arrays.copyOf(D, n); dfs1(0, -1); dfs2(0, -1); } //dp_v = g(merge(f(dp_ch1,c), f(dp_ch2,c), ..)) long f(long dp, int index, long v) { return Math.max(dp, D[index]) + v; } long g(long x, int index) { return x; } long merge(long x, long y) { return Math.max(x, y); } void dfs1(int v, int p) { long res = E; for (Edge e: G.list[v]) { if (e.to == p) continue; dfs1(e.to, v); res = merge(res, f(dp1[e.to], e.to, e.v)); } dp1[v] = g(res, v); } void dfs2(int v, int p) { if (p==-1) dp2[v] = E; int size = G.list[v].size(); long[] dp_l = new long[size+1]; long[] dp_r = new long[size+1]; dp_l[0] = E; dp_r[size] = E; long par_w = 0; for (int i = 1; i < size; i++) { int to = G.list[v].get(i-1).to; long w = G.list[v].get(i-1).v; if (to == p) { par_w = w; dp_l[i] = dp_l[i-1]; continue; } dp_l[i] = merge(dp_l[i-1], f(dp1[to], to, w)); } for (int i = size-1; i >= 0; i--) { int to = G.list[v].get(i).to; long w = G.list[v].get(i).v; if (to == p) { par_w = w; dp_r[i] = dp_r[i+1]; continue; } dp_r[i] = merge(dp_r[i+1], f(dp1[to], to, w)); } for (int i = 0; i < size; i++) { int to = G.list[v].get(i).to; if (to == p) continue; dp2[to] = merge(dp_l[i], dp_r[i+1]); if(v!=0) dp2[to] = merge(dp2[to], f(dp2[v], p, par_w)); dp2[to] = g(dp2[to], v); dfs2(to, v); } } void calc(int v, int p, long[] ans) { ans[v] = E; for (Edge e: G.list[v]) { if (e.to == p) { ans[v] = merge(ans[v], f(dp2[v], p, e.v)); continue; } ans[v] = merge(ans[v], f(dp1[e.to], e.to, e.v)); calc(e.to, v, ans); } ans[v] = g(ans[v], v); } } static class Edge implements Comparable<Edge>{ int to; long v; public Edge(int to,long v) { this.to=to; this.v=v; } @Override public boolean equals(Object obj){ if(obj instanceof Edge) { Edge other = (Edge) obj; return other.to==this.to && other.v==this.v; } return false; }//同値の定義 @Override public int hashCode() { return Objects.hash(this.to,this.v); } @Override public int compareTo( Edge p2 ){ if (this.v>p2.v) { return 1; } else if (this.v<p2.v) { return -1; } else { return 0; } } } static class graph{ ArrayList<Edge>[] list; int size; long INF=Long.MAX_VALUE/2; int[] color; @SuppressWarnings("unchecked") public graph(int n) { size = n; list = new ArrayList[n]; color =new int[n]; for(int i=0;i<n;i++){ list[i] = new ArrayList<Edge>(); } } void addEdge(int from,int to,long w) { list[from].add(new Edge(to,w)); } } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } }
ConDefects/ConDefects/Code/abc222_f/Java/31441839
condefects-java_data_494
import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f, mod = 1000000007, mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = false; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static void solve(PrintWriter o) { try { int n = fReader.nextInt(), m = fReader.nextInt(); List<Integer> li1 = new ArrayList<>(); List<Integer> li2 = new ArrayList<>(); List<int[]> li12 = new ArrayList<>(); List<Integer> li3 = new ArrayList<>(); for(int i=0;i<n;i++) { int t = fReader.nextInt(), x = fReader.nextInt(); if(t == 0) { li1.add(x); li12.add(new int[]{x, 0}); } else if(t == 1) { li2.add(x); li12.add(new int[]{x, 1}); } else li3.add(x); } Collections.sort(li1, (x,y)->y-x); Collections.sort(li2, (x,y)->y-x); Collections.sort(li12, (x,y)->y[0] == x[0] ? x[1]-y[1] : y[0]-x[0]); Collections.sort(li3, (x,y)->y-x); long[] preSum1 = new long[li1.size()+1]; for(int i=0;i<li1.size();i++) preSum1[i+1] = preSum1[i] + li1.get(i); long[] preSum2 = new long[li2.size()+1]; for(int i=0;i<li2.size();i++) preSum2[i+1] = preSum2[i] + li2.get(i); long[] preSum12 = new long[li12.size()+1]; int[] preSumCnt = new int[li12.size()+1]; for(int i=0;i<li12.size();i++) { preSum12[i+1] = preSum12[i] + li12.get(i)[0]; preSumCnt[i+1] = preSumCnt[i] + li12.get(i)[1]; } long[] preSum3 = new long[li3.size()+1]; for(int i=0;i<li3.size();i++) preSum3[i+1] = preSum3[i] + li3.get(i); long res = preSum1[Math.min(m, li1.size())]; for(int i=1;i<=Math.min(m, li3.size());i++) { long k = preSum3[i]; int num = Math.min(li12.size(), m-i); int t = preSumCnt[num]; if(k >= t) res = Math.max(res, preSum12[num]); else res = Math.max(res, preSum2[(int)Math.min(li2.size(), k)] + preSum1[Math.min(li1.size(), (int)Math.min(li1.size(), (t-k)))]); } o.println(res); } catch (Exception e) { e.printStackTrace(); } } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } public static long lcm(long a, long b){ return a / gcd(a,b)*b; } public static long qpow(long a, long n, int md){ a %= md; long ret = 1l; while(n > 0){ if((n & 1) == 1){ ret = ret * a % md; } n >>= 1; a = a * a % md; } return ret; } public static class DSU { int[] parent; int[] size; int n; public DSU(int n){ this.n = n; parent = new int[n]; size = new int[n]; for(int i=0;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int p){ while(parent[p] != p){ parent[p] = parent[parent[p]]; p = parent[p]; } return p; } public void union(int p, int q){ int root_p = find(p); int root_q = find(q); if(root_p == root_q) return; if(size[root_p] >= size[root_q]){ parent[root_q] = root_p; size[root_p] += size[root_q]; size[root_q] = 0; } else{ parent[root_p] = root_q; size[root_q] += size[root_p]; size[root_p] = 0; } n--; } public int getTotalComNum(){ return n; } public int getSize(int i){ return size[find(i)]; } } public static class FenWick { int n; long[] a; long[] tree; public FenWick(int n){ this.n = n; a = new long[n+1]; tree = new long[n+1]; } private void add(int x, long val){ while(x <= n){ tree[x] += val; x += x&-x; } } private void addMx(int x, long val) { a[x] += val; tree[x] = a[x]; while(x <= n) { for(int i=1;i<(x&-x);i<<=1) { tree[x] = Math.max(tree[x], tree[x-i]); } x += x&-x; } } private long query(int x){ long ret = 0l; while(x > 0){ ret += tree[x]; x -= x&-x; } return ret; } private long queryMx(int l, int r) { long res = 0l; while(l <= r) { if(r-(r&-r) >= l) { res = Math.max(res, tree[r]); r -= r&-r; } else { res = Math.max(res, a[r]); r--; } } return res; } } public static class Pair{ Integer c1; Integer c2; Integer c3; Integer c4; public Pair(Integer c1, Integer c2, Integer c3, Integer c4) { this.c1 = c1; this.c2 = c2; this.c3 = c3; this.c4 = c4; } @Override public int hashCode() { int prime = 31, ret = 1; ret = ret*prime + c1.hashCode(); ret = ret*prime + c2.hashCode(); ret = ret*prime + c3.hashCode(); ret = ret*prime + c4.hashCode(); return ret; } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { return c1.equals(((Pair) obj).c1) && c2.equals(((Pair) obj).c2) && c3.equals(((Pair) obj).c3) && c4.equals(((Pair) obj).c4); } return false; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } } import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f, mod = 1000000007, mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = false; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static void solve(PrintWriter o) { try { int n = fReader.nextInt(), m = fReader.nextInt(); List<Integer> li1 = new ArrayList<>(); List<Integer> li2 = new ArrayList<>(); List<int[]> li12 = new ArrayList<>(); List<Integer> li3 = new ArrayList<>(); for(int i=0;i<n;i++) { int t = fReader.nextInt(), x = fReader.nextInt(); if(t == 0) { li1.add(x); li12.add(new int[]{x, 0}); } else if(t == 1) { li2.add(x); li12.add(new int[]{x, 1}); } else li3.add(x); } Collections.sort(li1, (x,y)->y-x); Collections.sort(li2, (x,y)->y-x); Collections.sort(li12, (x,y)->y[0] == x[0] ? x[1]-y[1] : y[0]-x[0]); Collections.sort(li3, (x,y)->y-x); long[] preSum1 = new long[li1.size()+1]; for(int i=0;i<li1.size();i++) preSum1[i+1] = preSum1[i] + li1.get(i); long[] preSum2 = new long[li2.size()+1]; for(int i=0;i<li2.size();i++) preSum2[i+1] = preSum2[i] + li2.get(i); long[] preSum12 = new long[li12.size()+1]; int[] preSumCnt = new int[li12.size()+1]; for(int i=0;i<li12.size();i++) { preSum12[i+1] = preSum12[i] + li12.get(i)[0]; preSumCnt[i+1] = preSumCnt[i] + li12.get(i)[1]; } long[] preSum3 = new long[li3.size()+1]; for(int i=0;i<li3.size();i++) preSum3[i+1] = preSum3[i] + li3.get(i); long res = preSum1[Math.min(m, li1.size())]; for(int i=1;i<=Math.min(m, li3.size());i++) { long k = preSum3[i]; int num = Math.min(li12.size(), m-i); int t = preSumCnt[num]; if(k >= t) res = Math.max(res, preSum12[num]); else res = Math.max(res, preSum2[(int)k] + preSum1[Math.min(li1.size(), (int)(num-k))]); } o.println(res); } catch (Exception e) { e.printStackTrace(); } } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } public static long lcm(long a, long b){ return a / gcd(a,b)*b; } public static long qpow(long a, long n, int md){ a %= md; long ret = 1l; while(n > 0){ if((n & 1) == 1){ ret = ret * a % md; } n >>= 1; a = a * a % md; } return ret; } public static class DSU { int[] parent; int[] size; int n; public DSU(int n){ this.n = n; parent = new int[n]; size = new int[n]; for(int i=0;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int p){ while(parent[p] != p){ parent[p] = parent[parent[p]]; p = parent[p]; } return p; } public void union(int p, int q){ int root_p = find(p); int root_q = find(q); if(root_p == root_q) return; if(size[root_p] >= size[root_q]){ parent[root_q] = root_p; size[root_p] += size[root_q]; size[root_q] = 0; } else{ parent[root_p] = root_q; size[root_q] += size[root_p]; size[root_p] = 0; } n--; } public int getTotalComNum(){ return n; } public int getSize(int i){ return size[find(i)]; } } public static class FenWick { int n; long[] a; long[] tree; public FenWick(int n){ this.n = n; a = new long[n+1]; tree = new long[n+1]; } private void add(int x, long val){ while(x <= n){ tree[x] += val; x += x&-x; } } private void addMx(int x, long val) { a[x] += val; tree[x] = a[x]; while(x <= n) { for(int i=1;i<(x&-x);i<<=1) { tree[x] = Math.max(tree[x], tree[x-i]); } x += x&-x; } } private long query(int x){ long ret = 0l; while(x > 0){ ret += tree[x]; x -= x&-x; } return ret; } private long queryMx(int l, int r) { long res = 0l; while(l <= r) { if(r-(r&-r) >= l) { res = Math.max(res, tree[r]); r -= r&-r; } else { res = Math.max(res, a[r]); r--; } } return res; } } public static class Pair{ Integer c1; Integer c2; Integer c3; Integer c4; public Pair(Integer c1, Integer c2, Integer c3, Integer c4) { this.c1 = c1; this.c2 = c2; this.c3 = c3; this.c4 = c4; } @Override public int hashCode() { int prime = 31, ret = 1; ret = ret*prime + c1.hashCode(); ret = ret*prime + c2.hashCode(); ret = ret*prime + c3.hashCode(); ret = ret*prime + c4.hashCode(); return ret; } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { return c1.equals(((Pair) obj).c1) && c2.equals(((Pair) obj).c2) && c3.equals(((Pair) obj).c3) && c4.equals(((Pair) obj).c4); } return false; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } }
ConDefects/ConDefects/Code/abc312_f/Java/45299433
condefects-java_data_495
import java.io.*; import java.math.*; import java.time.*; import java.util.*; import java.util.Map.Entry; class Main implements Runnable { public static void solve () { n = nextInt(); m = nextInt(); s = new String[n]; for (int i=0; i<n; i++) { s[i] = next(); underbarLimit -= s[i].length(); } for (int i=0; i<m; i++) { String s = next(); set.add(s); } int[] p = new int[n]; Arrays.setAll(p, i -> i); do { rec(p, 1, s[p[0]], s[p[0]].length(), 0); } while (nextPermutation(p)); println(ans); } public static int n, m; public static String[] s; public static HashSet<String> set = new HashSet<>(); public static int underbarLimit = 16; public static String ans = "-1"; public static void rec (int[] p, int i, String now, int nowLength, int nowUnderbarNum) { if (i == n) { if (set.contains(now) == false && 3 <= now.length() && now.length() <= 16) { ans = now; } return; } for (int j=1; j<underbarLimit-nowUnderbarNum; j++) { StringBuilder sb = new StringBuilder(now); for (int k=0; k<j; k++) { sb.append("_"); } rec(p, i+1, sb.append(s[p[i]]).toString(), now.length()+s[p[i]].length(), nowUnderbarNum + j); } } public static boolean nextPermutation(int[] a) { int len = a.length; int l = len-2; while(l >= 0 && a[l] >= a[l+1]) l--; if(l < 0) return false; int r = len-1; while(a[l] >= a[r]) r--; {int t = a[l]; a[l] = a[r]; a[r] = t;} l++; r = len - 1; while (l < r) { {int t = a[l]; a[l] = a[r]; a[r] = t;} l++; r--; } return true; } /* * ############################################################################################ * # useful fields, useful methods, useful class * ############################################################################################## */ // fields public static final int infi = (int)1e9; public static final long infl = (long)1e18; public static final int modi = (int)1e9 + 7; public static final long modl = (long)1e18 + 7; public static int[] dy = {-1, 0, 1, 0}; public static int[] dx = {0, 1, 0, -1}; // public static int[] dy = {-1, 0, -1, 1, 0, 1}; // public static int[] dx = {-1, -1, 0, 0, 1, 1}; // public static int[] dy = {-1, -1, -1, 0, 1, 1, 1, 0}; // public static int[] dx = {-1, 0, 1, 1, 1, 0, -1, -1}; // methods public static int min (int... a) {Arrays.sort(a); return a[0];} public static int max (int... a) {Arrays.sort(a); return a[a.length-1];} public static long min (long... a) {Arrays.sort(a); return a[0];} public static long max (long... a) {Arrays.sort(a); return a[a.length-1];} public static long pow (long c, long b) { long res = 1; for (int i=0; i<b; i++) { res *= c; } return res; } // class public static class Edge implements Comparable<Edge> { int id, from, to, cost; Edge(int to, int cost) { //基本コレ this.to = to; this.cost = cost; } Edge(int from, int to, int cost) { this.from = from; this.to = to; this.cost = cost; } Edge(int id, int from, int to, int cost) { this.id = id; this.from = from; this.to = to; this.cost = cost; } @Override public int compareTo (Edge e) { return this.cost - e.cost; } } public static class Point implements Comparable<Point> { int x, y; Point (int x, int y) { this.x = x; this.y = y; } @Override public int compareTo (Point p) { return this.y - p.y; } } /* * ############################################################################################## * # input * ############################################################################################## */ // input - fields public static final InputStream in = System.in; public static final byte[] buffer = new byte[1024]; public static int ptr = 0; public static int bufferLength = 0; // input - basic methods public static boolean hasNextByte() { if (ptr < bufferLength) { return true; } else { ptr = 0; try { bufferLength = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (bufferLength <= 0) { return false; } } return true; } public static int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } public static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public static void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } public static boolean hasNext() { skipUnprintable(); return hasNextByte(); } // input - single public static String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public static int nextInt() { return (int) nextLong(); } public static long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public static double nextDouble() { return Double.parseDouble(next()); } // input - array public static String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) array[i] = next(); return array; } public static int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = nextInt(); return array; } public static long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) array[i] = nextLong(); return array; } public static double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } // input - table public static char[][] nextCharTable(int h, int w) { char[][] array = new char[h][w]; for (int i = 0; i < h; i++) array[i] = next().toCharArray(); return array; } public static int[][] nextIntMap(int h, int w) { int[][] a = new int[h][]; for (int i=0; i<h; i++) { for (int j=0; j<w; j++) a[i][j] = nextInt(); } return a; } /* * ############################################################################################## * # output * ############################################################################################## */ // output - fields static PrintWriter out = new PrintWriter(System.out); //output - single public static void print(Object o) {out.print(o);} public static void println(Object o) {out.println(o);} //output - array public static void printStringArray(String[] a) { for (int i=0; i<a.length; i++) { if (i != 0) print(" "); print(a[i]); } println(""); } public static void printIntArray(int[] a) { for (int i=0; i<a.length; i++) { if (i != 0) print(" "); print(a[i]); } println(""); } public static void printLongArray(long[] a) { for (int i=0; i<a.length; i++) { if (i != 0) print(" "); print(a[i]); } println(""); } public static void printBooleanArray (boolean[] a) { for (int i=0; i<a.length; i++) { char c = a[i]==true? 'o' : 'x'; print(c); } println(""); } public static void printCharTable(char[][] a) { for (int i=0; i<a.length; i++) { for (int j=0; j<a[0].length; j++) { print(a[i][j]); } println(""); } } public static void printIntTable(int[][] a) { for (int i=0; i<a.length; i++) { for (int j=0; j<a[0].length; j++) { if (j != 0) print(" "); print(a[i][j]); } println(""); } } public static void printBooleanTable(boolean[][] b) { for (int i=0; i<b.length; i++) { for (int j=0; j<b[0].length; j++) { print(b[i][j]? "o" : "x"); } println(""); } } public static void printLongTable(long[][] a) { for (int i=0; i<a.length; i++) { for (int j=0; j<a[0].length; j++) { if (j != 0) print(" "); print(a[i][j]); } println(""); } } /* * ############################################################################################## * # main * ############################################################################################## */ public static void main(String[] args) { new Thread(null, new Main(), "", 64 * 1024 * 1024).start(); } public void run() { solve(); out.close(); } } import java.io.*; import java.math.*; import java.time.*; import java.util.*; import java.util.Map.Entry; class Main implements Runnable { public static void solve () { n = nextInt(); m = nextInt(); s = new String[n]; for (int i=0; i<n; i++) { s[i] = next(); underbarLimit -= s[i].length(); } for (int i=0; i<m; i++) { String s = next(); set.add(s); } int[] p = new int[n]; Arrays.setAll(p, i -> i); do { rec(p, 1, s[p[0]], s[p[0]].length(), 0); } while (nextPermutation(p)); println(ans); } public static int n, m; public static String[] s; public static HashSet<String> set = new HashSet<>(); public static int underbarLimit = 16; public static String ans = "-1"; public static void rec (int[] p, int i, String now, int nowLength, int nowUnderbarNum) { if (i == n) { if (set.contains(now) == false && 3 <= now.length() && now.length() <= 16) { ans = now; } return; } for (int j=1; j<underbarLimit-nowUnderbarNum+1; j++) { StringBuilder sb = new StringBuilder(now); for (int k=0; k<j; k++) { sb.append("_"); } rec(p, i+1, sb.append(s[p[i]]).toString(), now.length()+s[p[i]].length(), nowUnderbarNum + j); } } public static boolean nextPermutation(int[] a) { int len = a.length; int l = len-2; while(l >= 0 && a[l] >= a[l+1]) l--; if(l < 0) return false; int r = len-1; while(a[l] >= a[r]) r--; {int t = a[l]; a[l] = a[r]; a[r] = t;} l++; r = len - 1; while (l < r) { {int t = a[l]; a[l] = a[r]; a[r] = t;} l++; r--; } return true; } /* * ############################################################################################ * # useful fields, useful methods, useful class * ############################################################################################## */ // fields public static final int infi = (int)1e9; public static final long infl = (long)1e18; public static final int modi = (int)1e9 + 7; public static final long modl = (long)1e18 + 7; public static int[] dy = {-1, 0, 1, 0}; public static int[] dx = {0, 1, 0, -1}; // public static int[] dy = {-1, 0, -1, 1, 0, 1}; // public static int[] dx = {-1, -1, 0, 0, 1, 1}; // public static int[] dy = {-1, -1, -1, 0, 1, 1, 1, 0}; // public static int[] dx = {-1, 0, 1, 1, 1, 0, -1, -1}; // methods public static int min (int... a) {Arrays.sort(a); return a[0];} public static int max (int... a) {Arrays.sort(a); return a[a.length-1];} public static long min (long... a) {Arrays.sort(a); return a[0];} public static long max (long... a) {Arrays.sort(a); return a[a.length-1];} public static long pow (long c, long b) { long res = 1; for (int i=0; i<b; i++) { res *= c; } return res; } // class public static class Edge implements Comparable<Edge> { int id, from, to, cost; Edge(int to, int cost) { //基本コレ this.to = to; this.cost = cost; } Edge(int from, int to, int cost) { this.from = from; this.to = to; this.cost = cost; } Edge(int id, int from, int to, int cost) { this.id = id; this.from = from; this.to = to; this.cost = cost; } @Override public int compareTo (Edge e) { return this.cost - e.cost; } } public static class Point implements Comparable<Point> { int x, y; Point (int x, int y) { this.x = x; this.y = y; } @Override public int compareTo (Point p) { return this.y - p.y; } } /* * ############################################################################################## * # input * ############################################################################################## */ // input - fields public static final InputStream in = System.in; public static final byte[] buffer = new byte[1024]; public static int ptr = 0; public static int bufferLength = 0; // input - basic methods public static boolean hasNextByte() { if (ptr < bufferLength) { return true; } else { ptr = 0; try { bufferLength = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (bufferLength <= 0) { return false; } } return true; } public static int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } public static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public static void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } public static boolean hasNext() { skipUnprintable(); return hasNextByte(); } // input - single public static String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public static int nextInt() { return (int) nextLong(); } public static long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public static double nextDouble() { return Double.parseDouble(next()); } // input - array public static String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) array[i] = next(); return array; } public static int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = nextInt(); return array; } public static long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) array[i] = nextLong(); return array; } public static double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } // input - table public static char[][] nextCharTable(int h, int w) { char[][] array = new char[h][w]; for (int i = 0; i < h; i++) array[i] = next().toCharArray(); return array; } public static int[][] nextIntMap(int h, int w) { int[][] a = new int[h][]; for (int i=0; i<h; i++) { for (int j=0; j<w; j++) a[i][j] = nextInt(); } return a; } /* * ############################################################################################## * # output * ############################################################################################## */ // output - fields static PrintWriter out = new PrintWriter(System.out); //output - single public static void print(Object o) {out.print(o);} public static void println(Object o) {out.println(o);} //output - array public static void printStringArray(String[] a) { for (int i=0; i<a.length; i++) { if (i != 0) print(" "); print(a[i]); } println(""); } public static void printIntArray(int[] a) { for (int i=0; i<a.length; i++) { if (i != 0) print(" "); print(a[i]); } println(""); } public static void printLongArray(long[] a) { for (int i=0; i<a.length; i++) { if (i != 0) print(" "); print(a[i]); } println(""); } public static void printBooleanArray (boolean[] a) { for (int i=0; i<a.length; i++) { char c = a[i]==true? 'o' : 'x'; print(c); } println(""); } public static void printCharTable(char[][] a) { for (int i=0; i<a.length; i++) { for (int j=0; j<a[0].length; j++) { print(a[i][j]); } println(""); } } public static void printIntTable(int[][] a) { for (int i=0; i<a.length; i++) { for (int j=0; j<a[0].length; j++) { if (j != 0) print(" "); print(a[i][j]); } println(""); } } public static void printBooleanTable(boolean[][] b) { for (int i=0; i<b.length; i++) { for (int j=0; j<b[0].length; j++) { print(b[i][j]? "o" : "x"); } println(""); } } public static void printLongTable(long[][] a) { for (int i=0; i<a.length; i++) { for (int j=0; j<a[0].length; j++) { if (j != 0) print(" "); print(a[i][j]); } println(""); } } /* * ############################################################################################## * # main * ############################################################################################## */ public static void main(String[] args) { new Thread(null, new Main(), "", 64 * 1024 * 1024).start(); } public void run() { solve(); out.close(); } }
ConDefects/ConDefects/Code/abc268_d/Java/39924937
condefects-java_data_496
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Stack; public class Main { static int len = 0; static int N; static HashSet<String> T; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); N = sc.nextInt(); int M = sc.nextInt(); String[] S = new String[N+1]; for(int i=1; i<=N; i++ ) { S[i] = sc.next(); len += S[i].length(); } T = new HashSet<>(M); for(int i=1; i<=M; i++ ) { T.add(sc.next()); } Stack<Select> queue = new Stack<>(); var select = new Select(); for(int i=1; i<=N; i++) { select.unused.add(S[i]); } queue.add(select); while(!queue.isEmpty()) { var c = queue.pop(); if(c.unused.size()==0) { String r = create(c); if(r != null) { System.out.println(r); return; } continue; } for(var s : c.unused) { queue.add(new Select(c,s)); } } System.out.println(-1); } static String create(Select s) { int delimitorLen = 16 - len; int maxAdditional = delimitorLen - (N-1); for(int i=0; i<=maxAdditional; i++) { String r = create(s,new int[N-1],i); if(r != null) { return r; } } return null; } static String create(Select select, int[] dels, int additional) { if(additional==0) { int i=0; StringBuilder buf = new StringBuilder(); while(select.s != null) { buf.append(select.s); if(i < N-1) { buf.append("_".repeat(dels[i++]+1)); } select = select.par; } String r = buf.toString(); if(T.contains(r)) { return null; } return r; } for(int i=0; i<N-1; i++) { int[] ndels = dels.clone(); ndels[i]++; String r = create(select,ndels,additional-1); if(r!=null) { return r; } } return null; } } class Select { Set<String> unused; String s; Select par; Select() { unused = new HashSet<>(); } Select(Select par, String s) { this.par = par; unused = new HashSet<>(par.unused); unused.remove(s); this.s = s; } } class FastScanner { public static final String LINE_SEPARATOR = System.getProperty("line.separator"); InputStream in; FastScanner(InputStream in) { this.in = in; } String next() { try { char ch; do { ch = (char)in.read(); } while(isDelimiter(ch)); StringBuilder buf = new StringBuilder(); do { buf.append(ch); ch = (char)in.read(); } while(!isDelimiter(ch)); return buf.toString(); } catch (IOException e) { throw new IllegalStateException(e); } } boolean isDelimiter(char ch) { return ch==' ' || ch=='\r' || ch=='\n'; } int nextInt() { return (int) nextLong(); } long nextLong() { try { long result = 0; int flag = 1; int ch; do { ch = in.read(); if(ch=='-') { flag = -1; } } while(!Character.isDigit(ch)); do { result *= 10; result += ch - '0'; ch = in.read(); } while(Character.isDigit(ch)); return result * flag; } catch (IOException e) { throw new IllegalStateException(e); } } } import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Stack; public class Main { static int len = 0; static int N; static HashSet<String> T; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); N = sc.nextInt(); int M = sc.nextInt(); String[] S = new String[N+1]; for(int i=1; i<=N; i++ ) { S[i] = sc.next(); len += S[i].length(); } T = new HashSet<>(M); for(int i=1; i<=M; i++ ) { T.add(sc.next()); } Stack<Select> queue = new Stack<>(); var select = new Select(); for(int i=1; i<=N; i++) { select.unused.add(S[i]); } queue.add(select); while(!queue.isEmpty()) { var c = queue.pop(); if(c.unused.size()==0) { String r = create(c); if(r != null) { System.out.println(r); return; } continue; } for(var s : c.unused) { queue.add(new Select(c,s)); } } System.out.println(-1); } static String create(Select s) { int delimitorLen = 16 - len; int maxAdditional = delimitorLen - (N-1); for(int i=0; i<=maxAdditional; i++) { String r = create(s,new int[N-1],i); if(r != null) { return r; } } return null; } static String create(Select select, int[] dels, int additional) { if(additional==0) { int i=0; StringBuilder buf = new StringBuilder(); while(select.s != null) { buf.append(select.s); if(i < N-1) { buf.append("_".repeat(dels[i++]+1)); } select = select.par; } String r = buf.toString(); if(T.contains(r) || r.length()>16 || r.length()<3) { return null; } return r; } for(int i=0; i<N-1; i++) { int[] ndels = dels.clone(); ndels[i]++; String r = create(select,ndels,additional-1); if(r!=null) { return r; } } return null; } } class Select { Set<String> unused; String s; Select par; Select() { unused = new HashSet<>(); } Select(Select par, String s) { this.par = par; unused = new HashSet<>(par.unused); unused.remove(s); this.s = s; } } class FastScanner { public static final String LINE_SEPARATOR = System.getProperty("line.separator"); InputStream in; FastScanner(InputStream in) { this.in = in; } String next() { try { char ch; do { ch = (char)in.read(); } while(isDelimiter(ch)); StringBuilder buf = new StringBuilder(); do { buf.append(ch); ch = (char)in.read(); } while(!isDelimiter(ch)); return buf.toString(); } catch (IOException e) { throw new IllegalStateException(e); } } boolean isDelimiter(char ch) { return ch==' ' || ch=='\r' || ch=='\n'; } int nextInt() { return (int) nextLong(); } long nextLong() { try { long result = 0; int flag = 1; int ch; do { ch = in.read(); if(ch=='-') { flag = -1; } } while(!Character.isDigit(ch)); do { result *= 10; result += ch - '0'; ch = in.read(); } while(Character.isDigit(ch)); return result * flag; } catch (IOException e) { throw new IllegalStateException(e); } } }
ConDefects/ConDefects/Code/abc268_d/Java/40984264
condefects-java_data_497
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.function.*; import java.util.stream.*; import java.awt.Point; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.util.Comparator.*; class Solver{ static int infI = (int) 1e9; static long infL = (long) 1e18; static long mod = (int) 1e9 +7; // static long mod = 998244353; static String yes = "Yes"; static String no = "No"; Util util = new Util(); Random rd = ThreadLocalRandom.current(); MyReader in = new MyReader(System.in); MyWriter out = new MyWriter(System.out); MyWriter log = new MyWriter(System.err){ @Override protected void ln(){ super.ln(); flush(); }; }; int N = in.it(); int M = in.it(); String[] S = in.str(N); String[] T = in.str(M); Set<String> ngs = new HashSet<>(); Object solve(){ Collections.addAll(ngs,T); int n = 16 -(N -1); for (var s:S) n -= s.length(); var pm = new Permutation(N); do { String ans = dfs(1,S[pm.arr[0]],pm,n); if (ans != null) return ans; } while (pm.increment()); return -1; } private String dfs(int i,String str,Permutation pm,int n){ if (i == N) return ngs.contains(str) || str.length() < 3 ? null : str; for (int k = 0;k <= n;k++) { var tmp = dfs(i +1,str +"_" +"".repeat(k) +S[pm.arr[i]],pm,n -k); if (tmp != null) return tmp; } return null; } boolean valid(int i,int N){ return 0 <= i && i < N; } int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; } class Permutation{ int n; int[] arr; int[] fac; Permutation(int n){ this.n = n; arr = new int[n]; Arrays.setAll(arr,i -> i); fac = new int[n]; fac[0] = 1; for (int i = 1;i < n;i++) fac[i] = i *fac[i -1]; } boolean increment(){ int l = n -2; while (0 <= l && arr[l] > arr[l +1]) l--; if (l < 0) return false; int r = n -1; while (arr[l] > arr[r]) r--; swap(l,r); l++; r = n -1; while (l < r) swap(l++,r--); return true; } void swap(int l,int r){ arr[l] ^= arr[r]; arr[r] ^= arr[l]; arr[l] ^= arr[r]; } } class Edge{ int id; int u; int v; long l; Edge rev; Edge(int id,int u,int v){ this.id = id; this.u = u; this.v = v; } void rev(Edge rev){ rev.l = l; } } class Util{ long st = System.currentTimeMillis(); long elapsed(){ return System.currentTimeMillis() -st; } static void reverse(Object arr){ if (!arr.getClass().isArray()) throw new UnsupportedOperationException("reverse"); int l = 0; int r = Array.getLength(arr) -1; while (l < r) { Object t = Array.get(arr,l); Array.set(arr,l,Array.get(arr,r)); Array.set(arr,r,t); l++; r--; } } static int[][] trans(int[]... T){ return arr(new int[T[0].length][],i -> arrI(T.length,j -> T[j][i])); } static int[][] addId(int[][] T){ return arr(new int[T.length][],i -> { int[] t = copyOf(T[i],T[i].length +1); t[t.length -1] = i; return t; }); } static long[][] trans(long[]... T){ return arr(new long[T[0].length][],i -> arrL(T.length,j -> T[j][i])); } static double[][] trans(double[]... T){ return arr(new double[T[0].length][],i -> arrD(T.length,j -> T[j][i])); } static int[] arrI(int N,IntUnaryOperator f){ int[] ret = new int[N]; setAll(ret,f); return ret; } static long[] arrL(int N,IntToLongFunction f){ long[] ret = new long[N]; setAll(ret,f); return ret; } static double[] arrD(int N,IntToDoubleFunction f){ double[] ret = new double[N]; setAll(ret,f); return ret; } static <T> T[] arr(T[] arr,IntFunction<T> f){ setAll(arr,f); return arr; } } class MyReader{ byte[] buf = new byte[1 <<16]; int ptr = 0; int tail = 0; InputStream in; MyReader(InputStream in){ this.in = in; } byte read(){ if (ptr == tail) try { tail = in.read(buf); ptr = 0; } catch (IOException e) {} return buf[ptr++]; } boolean isPrintable(byte c){ return 32 < c && c < 127; } boolean isNum(byte c){ return 47 < c && c < 58; } byte nextPrintable(){ byte ret = read(); while (!isPrintable(ret)) ret = read(); return ret; } int it(){ return Math.toIntExact(lg()); } int[] it(int N){ return Util.arrI(N,i -> it()); } int[][] it(int H,int W){ return Util.arr(new int[H][],i -> it(W)); } int idx(){ return it() -1; } int[] idx(int N){ return Util.arrI(N,i -> idx()); } int[][] idx(int H,int W){ return Util.arr(new int[H][],i -> idx(W)); } int[][] qry(int Q){ return Util.arr(new int[Q][],i -> new int[]{idx(), idx(), i}); } long lg(){ byte i = nextPrintable(); boolean negative = i == 45; long n = negative ? 0 : i -'0'; while (isPrintable(i = read())) n = 10 *n +i -'0'; return negative ? -n : n; } long[] lg(int N){ return Util.arrL(N,i -> lg()); } long[][] lg(int H,int W){ return Util.arr(new long[H][],i -> lg(W)); } double dbl(){ return Double.parseDouble(str()); } double[] dbl(int N){ return Util.arrD(N,i -> dbl()); } double[][] dbl(int H,int W){ return Util.arr(new double[H][],i -> dbl(W)); } char[] ch(){ return str().toCharArray(); } char[][] ch(int H){ return Util.arr(new char[H][],i -> ch()); } String line(){ StringBuilder sb = new StringBuilder(); for (byte c;(c = read()) != '\n';) sb.append((char) c); return sb.toString(); } String str(){ StringBuilder sb = new StringBuilder(); sb.append((char) nextPrintable()); for (byte c;isPrintable(c = read());) sb.append((char) c); return sb.toString(); } String[] str(int N){ return Util.arr(new String[N],i -> str()); } Edge[] e(int N,int M){ return e(N,M,e -> e.l = 1); } Edge[] e(int N,int M,Consumer<Edge> f){ return Util.arr(new Edge[M],i -> { Edge e = new Edge(i,idx(),idx()); f.accept(e); return e; }); } Edge[][] g(int N,int M,boolean b){ return g(N,b,e(N,M)); } Edge[][] g(int N,int M,boolean b,Consumer<Edge> f){ return g(N,b,e(N,M,f)); } Edge[][] g(int N,boolean b,Edge[] E){ int[] c = new int[N]; for (Edge e:E) { c[e.u]++; if (!b) c[e.v]++; } Edge[][] g = Util.arr(new Edge[N][],i -> new Edge[c[i]]); for (Edge e:E) { g[e.u][--c[e.u]] = e; if (!b) { Edge rev = new Edge(e.id,e.v,e.u); e.rev(rev); g[e.v][--c[e.v]] = e.rev = rev; } } return g; } } class MyWriter{ OutputStream out; byte[] buf = new byte[1 <<16]; byte[] ibuf = new byte[20]; int tail = 0; MyWriter(OutputStream out){ this.out = out; } void flush(){ try { out.write(buf,0,tail); tail = 0; } catch (IOException e) { e.printStackTrace(); } } protected void ln(){ write((byte) '\n'); } private void write(byte b){ buf[tail++] = b; if (tail == buf.length) flush(); } private void write(byte[] b,int off,int len){ for (int i = off;i < off +len;i++) write(b[i]); } private void write(long n){ if (n < 0) { n = -n; write((byte) '-'); } int i = ibuf.length; do { ibuf[--i] = (byte) (n %10 +'0'); n /= 10; } while (n > 0); write(ibuf,i,ibuf.length -i); } private void print(Object obj){ if (obj instanceof Boolean) print((boolean) obj ? Solver.yes : Solver.no); else if (obj instanceof Character) write((byte) (char) obj); else if (obj instanceof Integer) write((int) obj); else if (obj instanceof Long) write((long) obj); else if (obj instanceof char[]) for (char b:(char[]) obj) write((byte) b); else if (obj instanceof Collection<?>) { Iterator<?> itr = ((Collection<?>) obj).iterator(); while (itr.hasNext()) { print(itr.next()); if (itr.hasNext()) ln(); } } else if (obj.getClass().isArray()) { int l = Array.getLength(obj); boolean ln = false; if (0 < l) { Object a = Array.get(obj,0); ln = !(a instanceof char[]) && a.getClass().isArray(); } for (int i = 0;i +1 < l;i++) { print(Array.get(obj,i)); write((byte) (ln ? '\n' : ' ')); } print(Array.get(obj,l -1)); } else for (char b:Objects.toString(obj).toCharArray()) write((byte) b); } void println(Object obj){ if (obj == null) return; print(obj); ln(); } } class Main{ public static void main(String[] args) throws Exception{ Solver solver = new Solver(); Optional.ofNullable(solver.solve()).ifPresent(solver.out::println); solver.out.flush(); solver.log.println(solver.util.elapsed()); } } import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.function.*; import java.util.stream.*; import java.awt.Point; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.util.Comparator.*; class Solver{ static int infI = (int) 1e9; static long infL = (long) 1e18; static long mod = (int) 1e9 +7; // static long mod = 998244353; static String yes = "Yes"; static String no = "No"; Util util = new Util(); Random rd = ThreadLocalRandom.current(); MyReader in = new MyReader(System.in); MyWriter out = new MyWriter(System.out); MyWriter log = new MyWriter(System.err){ @Override protected void ln(){ super.ln(); flush(); }; }; int N = in.it(); int M = in.it(); String[] S = in.str(N); String[] T = in.str(M); Set<String> ngs = new HashSet<>(); Object solve(){ Collections.addAll(ngs,T); int n = 16 -(N -1); for (var s:S) n -= s.length(); var pm = new Permutation(N); do { String ans = dfs(1,S[pm.arr[0]],pm,n); if (ans != null) return ans; } while (pm.increment()); return -1; } private String dfs(int i,String str,Permutation pm,int n){ if (i == N) return ngs.contains(str) || str.length() < 3 ? null : str; for (int k = 0;k <= n;k++) { var tmp = dfs(i +1,str +"_" +"_".repeat(k) +S[pm.arr[i]],pm,n -k); if (tmp != null) return tmp; } return null; } boolean valid(int i,int N){ return 0 <= i && i < N; } int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; } class Permutation{ int n; int[] arr; int[] fac; Permutation(int n){ this.n = n; arr = new int[n]; Arrays.setAll(arr,i -> i); fac = new int[n]; fac[0] = 1; for (int i = 1;i < n;i++) fac[i] = i *fac[i -1]; } boolean increment(){ int l = n -2; while (0 <= l && arr[l] > arr[l +1]) l--; if (l < 0) return false; int r = n -1; while (arr[l] > arr[r]) r--; swap(l,r); l++; r = n -1; while (l < r) swap(l++,r--); return true; } void swap(int l,int r){ arr[l] ^= arr[r]; arr[r] ^= arr[l]; arr[l] ^= arr[r]; } } class Edge{ int id; int u; int v; long l; Edge rev; Edge(int id,int u,int v){ this.id = id; this.u = u; this.v = v; } void rev(Edge rev){ rev.l = l; } } class Util{ long st = System.currentTimeMillis(); long elapsed(){ return System.currentTimeMillis() -st; } static void reverse(Object arr){ if (!arr.getClass().isArray()) throw new UnsupportedOperationException("reverse"); int l = 0; int r = Array.getLength(arr) -1; while (l < r) { Object t = Array.get(arr,l); Array.set(arr,l,Array.get(arr,r)); Array.set(arr,r,t); l++; r--; } } static int[][] trans(int[]... T){ return arr(new int[T[0].length][],i -> arrI(T.length,j -> T[j][i])); } static int[][] addId(int[][] T){ return arr(new int[T.length][],i -> { int[] t = copyOf(T[i],T[i].length +1); t[t.length -1] = i; return t; }); } static long[][] trans(long[]... T){ return arr(new long[T[0].length][],i -> arrL(T.length,j -> T[j][i])); } static double[][] trans(double[]... T){ return arr(new double[T[0].length][],i -> arrD(T.length,j -> T[j][i])); } static int[] arrI(int N,IntUnaryOperator f){ int[] ret = new int[N]; setAll(ret,f); return ret; } static long[] arrL(int N,IntToLongFunction f){ long[] ret = new long[N]; setAll(ret,f); return ret; } static double[] arrD(int N,IntToDoubleFunction f){ double[] ret = new double[N]; setAll(ret,f); return ret; } static <T> T[] arr(T[] arr,IntFunction<T> f){ setAll(arr,f); return arr; } } class MyReader{ byte[] buf = new byte[1 <<16]; int ptr = 0; int tail = 0; InputStream in; MyReader(InputStream in){ this.in = in; } byte read(){ if (ptr == tail) try { tail = in.read(buf); ptr = 0; } catch (IOException e) {} return buf[ptr++]; } boolean isPrintable(byte c){ return 32 < c && c < 127; } boolean isNum(byte c){ return 47 < c && c < 58; } byte nextPrintable(){ byte ret = read(); while (!isPrintable(ret)) ret = read(); return ret; } int it(){ return Math.toIntExact(lg()); } int[] it(int N){ return Util.arrI(N,i -> it()); } int[][] it(int H,int W){ return Util.arr(new int[H][],i -> it(W)); } int idx(){ return it() -1; } int[] idx(int N){ return Util.arrI(N,i -> idx()); } int[][] idx(int H,int W){ return Util.arr(new int[H][],i -> idx(W)); } int[][] qry(int Q){ return Util.arr(new int[Q][],i -> new int[]{idx(), idx(), i}); } long lg(){ byte i = nextPrintable(); boolean negative = i == 45; long n = negative ? 0 : i -'0'; while (isPrintable(i = read())) n = 10 *n +i -'0'; return negative ? -n : n; } long[] lg(int N){ return Util.arrL(N,i -> lg()); } long[][] lg(int H,int W){ return Util.arr(new long[H][],i -> lg(W)); } double dbl(){ return Double.parseDouble(str()); } double[] dbl(int N){ return Util.arrD(N,i -> dbl()); } double[][] dbl(int H,int W){ return Util.arr(new double[H][],i -> dbl(W)); } char[] ch(){ return str().toCharArray(); } char[][] ch(int H){ return Util.arr(new char[H][],i -> ch()); } String line(){ StringBuilder sb = new StringBuilder(); for (byte c;(c = read()) != '\n';) sb.append((char) c); return sb.toString(); } String str(){ StringBuilder sb = new StringBuilder(); sb.append((char) nextPrintable()); for (byte c;isPrintable(c = read());) sb.append((char) c); return sb.toString(); } String[] str(int N){ return Util.arr(new String[N],i -> str()); } Edge[] e(int N,int M){ return e(N,M,e -> e.l = 1); } Edge[] e(int N,int M,Consumer<Edge> f){ return Util.arr(new Edge[M],i -> { Edge e = new Edge(i,idx(),idx()); f.accept(e); return e; }); } Edge[][] g(int N,int M,boolean b){ return g(N,b,e(N,M)); } Edge[][] g(int N,int M,boolean b,Consumer<Edge> f){ return g(N,b,e(N,M,f)); } Edge[][] g(int N,boolean b,Edge[] E){ int[] c = new int[N]; for (Edge e:E) { c[e.u]++; if (!b) c[e.v]++; } Edge[][] g = Util.arr(new Edge[N][],i -> new Edge[c[i]]); for (Edge e:E) { g[e.u][--c[e.u]] = e; if (!b) { Edge rev = new Edge(e.id,e.v,e.u); e.rev(rev); g[e.v][--c[e.v]] = e.rev = rev; } } return g; } } class MyWriter{ OutputStream out; byte[] buf = new byte[1 <<16]; byte[] ibuf = new byte[20]; int tail = 0; MyWriter(OutputStream out){ this.out = out; } void flush(){ try { out.write(buf,0,tail); tail = 0; } catch (IOException e) { e.printStackTrace(); } } protected void ln(){ write((byte) '\n'); } private void write(byte b){ buf[tail++] = b; if (tail == buf.length) flush(); } private void write(byte[] b,int off,int len){ for (int i = off;i < off +len;i++) write(b[i]); } private void write(long n){ if (n < 0) { n = -n; write((byte) '-'); } int i = ibuf.length; do { ibuf[--i] = (byte) (n %10 +'0'); n /= 10; } while (n > 0); write(ibuf,i,ibuf.length -i); } private void print(Object obj){ if (obj instanceof Boolean) print((boolean) obj ? Solver.yes : Solver.no); else if (obj instanceof Character) write((byte) (char) obj); else if (obj instanceof Integer) write((int) obj); else if (obj instanceof Long) write((long) obj); else if (obj instanceof char[]) for (char b:(char[]) obj) write((byte) b); else if (obj instanceof Collection<?>) { Iterator<?> itr = ((Collection<?>) obj).iterator(); while (itr.hasNext()) { print(itr.next()); if (itr.hasNext()) ln(); } } else if (obj.getClass().isArray()) { int l = Array.getLength(obj); boolean ln = false; if (0 < l) { Object a = Array.get(obj,0); ln = !(a instanceof char[]) && a.getClass().isArray(); } for (int i = 0;i +1 < l;i++) { print(Array.get(obj,i)); write((byte) (ln ? '\n' : ' ')); } print(Array.get(obj,l -1)); } else for (char b:Objects.toString(obj).toCharArray()) write((byte) b); } void println(Object obj){ if (obj == null) return; print(obj); ln(); } } class Main{ public static void main(String[] args) throws Exception{ Solver solver = new Solver(); Optional.ofNullable(solver.solve()).ifPresent(solver.out::println); solver.out.flush(); solver.log.println(solver.util.elapsed()); } }
ConDefects/ConDefects/Code/abc268_d/Java/42086420
condefects-java_data_498
import java.util.*; import java.io.*; class Solver { Set<String> T; void solve(FScanner sc, FWriter out) { int n = sc.nextInt(), m = sc.nextInt(); String[] S = new String[n]; for (var i = 0; i < n; i++) { S[i] = sc.next(); } T = new HashSet<>(); for (var i = 0; i < m; i++) { T.add(sc.next()); } int yoyuu = 16; for (int i = 0; i < n; i++) yoyuu -= S[i].length(); yoyuu -= n - 1; Permutation<String> permutation = new Permutation<>(S); while (true) { dfs(1, permutation.array, yoyuu, permutation.array[0]); if (!permutation.nextPermutation()) { System.out.println(-1); return; } } } void dfs(int cur, String[] S, int yoyuu, String ans) { if (cur == S.length) { if (!T.contains(ans)) { System.out.println(ans); System.exit(0); } return; } if (ans.length() > 0 && !ans.endsWith("_")) { dfs(cur, S, yoyuu, ans + "_"); } else { dfs(cur + 1, S, yoyuu, ans + S[cur]); if (ans.length() > 0 && yoyuu - 1 >= 0) { dfs(cur, S, yoyuu - 1, ans + "_"); } } } } class Permutation<T extends Comparable<T>> { T[] array; public Permutation(T[] array) { this.array = array; reset(); } private void reset() { Arrays.sort(array); } boolean nextPermutation() { for (int i = array.length - 1; i > 0; i--) { if (array[i - 1].compareTo(array[i]) < 0) { int j = find(array[i - 1], i, array.length - 1); T temp = array[j]; array[j] = array[i - 1]; array[i - 1] = temp; Arrays.sort(array, i, array.length); return true; } } return false; } int find(T dest, int f, int l) { if (f == l) { return f; } int m = (f + l + 1) / 2; return (array[m].compareTo(dest) <= 0) ? find(dest, f, m - 1) : find(dest, m, l); } } // common public class Main { public static void main(String[] args) { FScanner sc = new FScanner(System.in); FWriter out = new FWriter(System.out); try { (new Solver()).solve(sc, out); } catch (Throwable e) { out.println(e); out.flush(); System.exit(1); } out.flush(); sc.close(); } } class TwoKeyMap<K, V> { Map<K, Map<K, V>> map = new HashMap<>(); Set<K> _key2Set = new HashSet<>(); TwoKeyMap<K, V> put(K key1, K key2, V value) { _key2Set.add(key2); map.computeIfAbsent(key1, (f) -> new HashMap<K, V>()).put(key2, value); return this; } TwoKeyMap<K, V> put(K[] key, V value) { return put(key[0], key[1], value); } TwoKeyMap<K, V> merge(K key1, K key2, V value, java.util.function.BiFunction<? super V, ? super V, ? extends V> remappingFunction) { _key2Set.add(key2); map.computeIfAbsent(key1, (f) -> new HashMap<K, V>()).merge(key2, value, remappingFunction); return this; } TwoKeyMap<K, V> merge(K[] key, V value, java.util.function.BiFunction<? super V, ? super V, ? extends V> remappingFunction) { return merge(key[0], key[1], value, remappingFunction); } V get(K key1, K key2) { var m1 = map.get(key1); if (m1 == null) return null; return m1.get(key2); } Map<K, V> get(K key1) { return map.get(key1); } V get(K[] key) { return get(key[0], key[1]); } V computeIfAbsent(K key1, K key2, java.util.function.Function<? super K, ? extends V> mappingFunction) { return map.computeIfAbsent(key1, (f) -> new HashMap<K, V>()).computeIfAbsent(key2, mappingFunction); } boolean containsKey(K key1, K key2) { return get(key1, key2) != null; } Set<K> key1Set() { return map.keySet(); } Set<K> key2Set() { // 本来はインスタンス作るべきだが、競技プログラミング向けなのでパフォーマンス優先 return _key2Set; } } class FScanner { private InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; FScanner(InputStream in) { this.in = in; } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } public boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { return nextSB().toString(); } public char[] nextCharArray() { StringBuilder sb = nextSB(); char[] c = new char[sb.length()]; sb.getChars(0, sb.length(), c, 0); return c; } public StringBuilder nextSB() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb; } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (b != -1 && isPrintableChar(b)) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else { throw new NumberFormatException(); } b = readByte(); } return minus ? -n : n; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (b != -1 && isPrintableChar(b)) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else { throw new NumberFormatException(); } b = readByte(); } return minus ? -n : n; } public double nextDouble() { return Double.parseDouble(next()); } public java.math.BigDecimal nextDecimal() { return new java.math.BigDecimal(next()); } public java.util.stream.IntStream nextIntStream(int n) { return java.util.stream.IntStream.range(0, n).map(i -> nextInt()); } public java.util.stream.LongStream nextLongStream(int n) { return java.util.stream.LongStream.range(0L, (long) n).map(i -> nextLong()); } public java.util.stream.Stream<String> nextStream(int n) { return java.util.stream.IntStream.range(0, n).mapToObj(i -> next()); } public int[] nextIntArray(int arraySize) { int[] ary = new int[arraySize]; for (int i = 0; i < arraySize; i++) { ary[i] = nextInt(); } return ary; } public long[] nextLongArray(int arraySize) { long[] ary = new long[arraySize]; for (int i = 0; i < arraySize; i++) { ary[i] = nextLong(); } return ary; } public java.util.stream.Stream<int[]> nextIntArrayStream(int n, int arraySize) { return java.util.stream.IntStream.range(0, n).mapToObj(_i -> { int[] ary = new int[arraySize]; for (int i = 0; i < arraySize; i++) { ary[i] = nextInt(); } return ary; }); } public java.util.stream.Stream<long[]> nextLongArrayStream(int n, int arraySize) { return java.util.stream.IntStream.range(0, n).mapToObj(_i -> { long[] ary = new long[arraySize]; for (int i = 0; i < arraySize; i++) { ary[i] = nextLong(); } return ary; }); } public boolean close() { return true; } } class FWriter { OutputStream out; byte[] buf = new byte[1 << 16]; byte[] ibuf = new byte[20]; int tail = 0; final byte SP = (byte) ' ', LF = (byte) '\n', HYPHEN = (byte) '-'; FWriter(OutputStream out) { this.out = out; } void flush() { try { out.write(buf, 0, tail); tail = 0; } catch (IOException e) { e.printStackTrace(); } } void write(byte b) { buf[tail++] = b; if (tail == buf.length) { flush(); } } void write(byte[] b, int off, int len) { for (int i = off; i < off + len; i++) { write(b[i]); } } void println() { write(LF); } FWriter print(char c) { write((byte) c); return this; } FWriter println(char c) { print(c); println(); return this; } FWriter print(int n) { if (n < 0) { n = -n; write(HYPHEN); } int i = ibuf.length; do { ibuf[--i] = (byte) (n % 10 + '0'); n /= 10; } while (n > 0); write(ibuf, i, ibuf.length - i); return this; } FWriter println(int n) { print(n); println(); return this; } FWriter print(long n) { if (n < 0) { n = -n; write(HYPHEN); } int i = ibuf.length; do { ibuf[--i] = (byte) (n % 10 + '0'); n /= 10; } while (n > 0); write(ibuf, i, ibuf.length - i); return this; } FWriter println(long n) { print(n); println(); return this; } FWriter print(String s) { if (s != null) { byte[] b = s.getBytes(); write(b, 0, b.length); } return this; } FWriter println(String s) { print(s); println(); return this; } FWriter print(int[] a) { for (int i = 0; i < a.length; i++) { if (i > 0) write(SP); print(a[i]); } return this; } FWriter println(int[] a) { print(a); println(); return this; } FWriter print(long[] a) { for (int i = 0; i < a.length; i++) { if (i > 0) write(SP); print(a[i]); } return this; } FWriter println(long[] a) { print(a); println(); return this; } FWriter print(char[] s, int from, int to) { for (int i = from; i < to && s[i] != '\0'; i++) { print(s[i]); } return this; } FWriter print(char[] s) { print(s, 0, s.length); return this; } FWriter println(char[] s, int from, int to) { print(s, from, to); println(); return this; } FWriter println(char[] s) { println(s, 0, s.length); return this; } FWriter print(double n, int accuracy) { long longN = (long) n; print(longN); n -= (long) n; write((byte) '.'); for (int j = 0; j < accuracy; j++) { n *= 10; int digit = (int) n; write((byte) (digit + '0')); n -= digit; } return this; } FWriter print(double n) { print(n, 10); return this; } FWriter println(double n) { print(n); println(); return this; } FWriter println(double n, int accuracy) { print(n, accuracy); println(); return this; } FWriter print(Object o) { if (o != null) { print(o.toString()); } return this; } FWriter println(Object o) { print(o); println(); return this; } FWriter println(Throwable e) { println(e.toString()); for (StackTraceElement el : e.getStackTrace()) { print(" ").println(el.toString()); } if (e.getCause() != null) { println(e.getCause()); } return this; } private void _debug(Object o, int indent) { if (o == null) { for (var i = 0; i < indent; i++) print(' '); print("null"); } else if (o.getClass().isArray()) { for (int i = 0; i < java.lang.reflect.Array.getLength(o); i++) { println(); _debug(java.lang.reflect.Array.get(o, i), indent + 2); } return; } else if (o instanceof Collection) { for (var item : (Collection<?>) o) { println(); _debug(item, indent + 2); } } else if (o instanceof Map) { for (var i = 0; i < indent; i++) print(' '); println('{'); for (var entry : ((Map<?, ?>) o).entrySet()) { for (var i = 0; i < indent + 2; i++) print(' '); _debug(entry.getKey(), 0); _debug(" ", 0); _debug(entry.getValue(), 0); println(); } for (var i = 0; i < indent; i++) print(' '); println('}'); return; } for (var i = 0; i < indent; i++) print(' '); print(o); } FWriter debug(Object... os) { print("[DEBUG:").print(Thread.currentThread().getStackTrace()[2].getLineNumber()).print("]: "); for (var o : os) { _debug(o, 0); print(' '); } print(" :[DEBUG:").print(Thread.currentThread().getStackTrace()[2].getLineNumber()).println("]"); return this; } } import java.util.*; import java.io.*; class Solver { Set<String> T; void solve(FScanner sc, FWriter out) { int n = sc.nextInt(), m = sc.nextInt(); String[] S = new String[n]; for (var i = 0; i < n; i++) { S[i] = sc.next(); } T = new HashSet<>(); for (var i = 0; i < m; i++) { T.add(sc.next()); } int yoyuu = 16; for (int i = 0; i < n; i++) yoyuu -= S[i].length(); yoyuu -= n - 1; Permutation<String> permutation = new Permutation<>(S); while (true) { dfs(1, permutation.array, yoyuu, permutation.array[0]); if (!permutation.nextPermutation()) { System.out.println(-1); return; } } } void dfs(int cur, String[] S, int yoyuu, String ans) { if (cur == S.length) { if (ans.length() >= 3 && ans.length() <= 16 && !T.contains(ans)) { System.out.println(ans); System.exit(0); } return; } if (ans.length() > 0 && !ans.endsWith("_")) { dfs(cur, S, yoyuu, ans + "_"); } else { dfs(cur + 1, S, yoyuu, ans + S[cur]); if (ans.length() > 0 && yoyuu - 1 >= 0) { dfs(cur, S, yoyuu - 1, ans + "_"); } } } } class Permutation<T extends Comparable<T>> { T[] array; public Permutation(T[] array) { this.array = array; reset(); } private void reset() { Arrays.sort(array); } boolean nextPermutation() { for (int i = array.length - 1; i > 0; i--) { if (array[i - 1].compareTo(array[i]) < 0) { int j = find(array[i - 1], i, array.length - 1); T temp = array[j]; array[j] = array[i - 1]; array[i - 1] = temp; Arrays.sort(array, i, array.length); return true; } } return false; } int find(T dest, int f, int l) { if (f == l) { return f; } int m = (f + l + 1) / 2; return (array[m].compareTo(dest) <= 0) ? find(dest, f, m - 1) : find(dest, m, l); } } // common public class Main { public static void main(String[] args) { FScanner sc = new FScanner(System.in); FWriter out = new FWriter(System.out); try { (new Solver()).solve(sc, out); } catch (Throwable e) { out.println(e); out.flush(); System.exit(1); } out.flush(); sc.close(); } } class TwoKeyMap<K, V> { Map<K, Map<K, V>> map = new HashMap<>(); Set<K> _key2Set = new HashSet<>(); TwoKeyMap<K, V> put(K key1, K key2, V value) { _key2Set.add(key2); map.computeIfAbsent(key1, (f) -> new HashMap<K, V>()).put(key2, value); return this; } TwoKeyMap<K, V> put(K[] key, V value) { return put(key[0], key[1], value); } TwoKeyMap<K, V> merge(K key1, K key2, V value, java.util.function.BiFunction<? super V, ? super V, ? extends V> remappingFunction) { _key2Set.add(key2); map.computeIfAbsent(key1, (f) -> new HashMap<K, V>()).merge(key2, value, remappingFunction); return this; } TwoKeyMap<K, V> merge(K[] key, V value, java.util.function.BiFunction<? super V, ? super V, ? extends V> remappingFunction) { return merge(key[0], key[1], value, remappingFunction); } V get(K key1, K key2) { var m1 = map.get(key1); if (m1 == null) return null; return m1.get(key2); } Map<K, V> get(K key1) { return map.get(key1); } V get(K[] key) { return get(key[0], key[1]); } V computeIfAbsent(K key1, K key2, java.util.function.Function<? super K, ? extends V> mappingFunction) { return map.computeIfAbsent(key1, (f) -> new HashMap<K, V>()).computeIfAbsent(key2, mappingFunction); } boolean containsKey(K key1, K key2) { return get(key1, key2) != null; } Set<K> key1Set() { return map.keySet(); } Set<K> key2Set() { // 本来はインスタンス作るべきだが、競技プログラミング向けなのでパフォーマンス優先 return _key2Set; } } class FScanner { private InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; FScanner(InputStream in) { this.in = in; } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } public boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { return nextSB().toString(); } public char[] nextCharArray() { StringBuilder sb = nextSB(); char[] c = new char[sb.length()]; sb.getChars(0, sb.length(), c, 0); return c; } public StringBuilder nextSB() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb; } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (b != -1 && isPrintableChar(b)) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else { throw new NumberFormatException(); } b = readByte(); } return minus ? -n : n; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (b != -1 && isPrintableChar(b)) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else { throw new NumberFormatException(); } b = readByte(); } return minus ? -n : n; } public double nextDouble() { return Double.parseDouble(next()); } public java.math.BigDecimal nextDecimal() { return new java.math.BigDecimal(next()); } public java.util.stream.IntStream nextIntStream(int n) { return java.util.stream.IntStream.range(0, n).map(i -> nextInt()); } public java.util.stream.LongStream nextLongStream(int n) { return java.util.stream.LongStream.range(0L, (long) n).map(i -> nextLong()); } public java.util.stream.Stream<String> nextStream(int n) { return java.util.stream.IntStream.range(0, n).mapToObj(i -> next()); } public int[] nextIntArray(int arraySize) { int[] ary = new int[arraySize]; for (int i = 0; i < arraySize; i++) { ary[i] = nextInt(); } return ary; } public long[] nextLongArray(int arraySize) { long[] ary = new long[arraySize]; for (int i = 0; i < arraySize; i++) { ary[i] = nextLong(); } return ary; } public java.util.stream.Stream<int[]> nextIntArrayStream(int n, int arraySize) { return java.util.stream.IntStream.range(0, n).mapToObj(_i -> { int[] ary = new int[arraySize]; for (int i = 0; i < arraySize; i++) { ary[i] = nextInt(); } return ary; }); } public java.util.stream.Stream<long[]> nextLongArrayStream(int n, int arraySize) { return java.util.stream.IntStream.range(0, n).mapToObj(_i -> { long[] ary = new long[arraySize]; for (int i = 0; i < arraySize; i++) { ary[i] = nextLong(); } return ary; }); } public boolean close() { return true; } } class FWriter { OutputStream out; byte[] buf = new byte[1 << 16]; byte[] ibuf = new byte[20]; int tail = 0; final byte SP = (byte) ' ', LF = (byte) '\n', HYPHEN = (byte) '-'; FWriter(OutputStream out) { this.out = out; } void flush() { try { out.write(buf, 0, tail); tail = 0; } catch (IOException e) { e.printStackTrace(); } } void write(byte b) { buf[tail++] = b; if (tail == buf.length) { flush(); } } void write(byte[] b, int off, int len) { for (int i = off; i < off + len; i++) { write(b[i]); } } void println() { write(LF); } FWriter print(char c) { write((byte) c); return this; } FWriter println(char c) { print(c); println(); return this; } FWriter print(int n) { if (n < 0) { n = -n; write(HYPHEN); } int i = ibuf.length; do { ibuf[--i] = (byte) (n % 10 + '0'); n /= 10; } while (n > 0); write(ibuf, i, ibuf.length - i); return this; } FWriter println(int n) { print(n); println(); return this; } FWriter print(long n) { if (n < 0) { n = -n; write(HYPHEN); } int i = ibuf.length; do { ibuf[--i] = (byte) (n % 10 + '0'); n /= 10; } while (n > 0); write(ibuf, i, ibuf.length - i); return this; } FWriter println(long n) { print(n); println(); return this; } FWriter print(String s) { if (s != null) { byte[] b = s.getBytes(); write(b, 0, b.length); } return this; } FWriter println(String s) { print(s); println(); return this; } FWriter print(int[] a) { for (int i = 0; i < a.length; i++) { if (i > 0) write(SP); print(a[i]); } return this; } FWriter println(int[] a) { print(a); println(); return this; } FWriter print(long[] a) { for (int i = 0; i < a.length; i++) { if (i > 0) write(SP); print(a[i]); } return this; } FWriter println(long[] a) { print(a); println(); return this; } FWriter print(char[] s, int from, int to) { for (int i = from; i < to && s[i] != '\0'; i++) { print(s[i]); } return this; } FWriter print(char[] s) { print(s, 0, s.length); return this; } FWriter println(char[] s, int from, int to) { print(s, from, to); println(); return this; } FWriter println(char[] s) { println(s, 0, s.length); return this; } FWriter print(double n, int accuracy) { long longN = (long) n; print(longN); n -= (long) n; write((byte) '.'); for (int j = 0; j < accuracy; j++) { n *= 10; int digit = (int) n; write((byte) (digit + '0')); n -= digit; } return this; } FWriter print(double n) { print(n, 10); return this; } FWriter println(double n) { print(n); println(); return this; } FWriter println(double n, int accuracy) { print(n, accuracy); println(); return this; } FWriter print(Object o) { if (o != null) { print(o.toString()); } return this; } FWriter println(Object o) { print(o); println(); return this; } FWriter println(Throwable e) { println(e.toString()); for (StackTraceElement el : e.getStackTrace()) { print(" ").println(el.toString()); } if (e.getCause() != null) { println(e.getCause()); } return this; } private void _debug(Object o, int indent) { if (o == null) { for (var i = 0; i < indent; i++) print(' '); print("null"); } else if (o.getClass().isArray()) { for (int i = 0; i < java.lang.reflect.Array.getLength(o); i++) { println(); _debug(java.lang.reflect.Array.get(o, i), indent + 2); } return; } else if (o instanceof Collection) { for (var item : (Collection<?>) o) { println(); _debug(item, indent + 2); } } else if (o instanceof Map) { for (var i = 0; i < indent; i++) print(' '); println('{'); for (var entry : ((Map<?, ?>) o).entrySet()) { for (var i = 0; i < indent + 2; i++) print(' '); _debug(entry.getKey(), 0); _debug(" ", 0); _debug(entry.getValue(), 0); println(); } for (var i = 0; i < indent; i++) print(' '); println('}'); return; } for (var i = 0; i < indent; i++) print(' '); print(o); } FWriter debug(Object... os) { print("[DEBUG:").print(Thread.currentThread().getStackTrace()[2].getLineNumber()).print("]: "); for (var o : os) { _debug(o, 0); print(' '); } print(" :[DEBUG:").print(Thread.currentThread().getStackTrace()[2].getLineNumber()).println("]"); return this; } }
ConDefects/ConDefects/Code/abc268_d/Java/35831926
condefects-java_data_499
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); InputReader in = new InputReader(inputStream); // for(int i=4;i<=4;i++) { // InputStream uinputStream = new FileInputStream("timeline.in"); //String f = i+".in"; //InputStream uinputStream = new FileInputStream(f); // InputReader in = new InputReader(uinputStream); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("timeline.out"))); // } Task t = new Task(); t.solve(in, out); out.close(); } static class Task{ public void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int m = in.nextInt(); int l = 0; String[] arr = new String[n]; for(int i=0;i<n;i++) { arr[i] = in.next(); l+=arr[i].length(); } HashSet<String> s = new HashSet<String>(); for(int i=0;i<m;i++) s.add(in.next()); int left = 16-l-n+1; int[] tmp = new int[n-1]; ArrayList<int[]> underscore = new ArrayList<int[]>(); dfs(left,0,n-1,tmp,underscore); ArrayList<int[]> arrange = new ArrayList<int[]>(); dfs2(0,n,new int[n],new boolean[n],arrange); boolean can = false; for(int i=0;i<arrange.size();i++) {//0,2,1,3 for(int p=0;p<underscore.size();p++) {//[1,0,0] StringBuilder sb = new StringBuilder(); for(int j=0;j<n;j++) { sb.append(arr[arrange.get(i)[j]]); if(j<n-1) { sb.append("_"); for(int k=0;k<underscore.get(p)[j];k++) { sb.append("_"); } } } if(!s.contains(sb.toString())) { out.println(sb.toString()); can = true; break; } } if(can) break; } if(!can) out.println(-1); } void dfs(int left, int cur, int m, int[] arr, ArrayList<int[]> ret){ if(cur==m) { ret.add(arr.clone()); return; } for(int i=0;i<=left;i++) { arr[cur] = i; dfs(left-i,cur+1,m,arr,ret); } } void dfs2(int cur, int m, int[] arr, boolean[] vis, ArrayList<int[]> ret) { if(cur==m) { ret.add(arr.clone()); return; } for(int i=0;i<m;i++) { if(!vis[i]) { vis[i] = true; arr[cur] = i; dfs2(cur+1,m,arr,vis,ret); vis[i] = false; } } } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } long work(long a, long b, long c, long d, int m, int f) { long col = (d-b)/2+1; long row = (c-a)/2+1; long diff_row = 2*m%f*col%f; long a1_col = ((a-1)*m%f+b)%f; long an_col = ((a-1)*m%f+d)%f; //long sum_col = (a1_col+an_col)*col/2%f; long sum_col = ((a-1)*m%f + (b+d)/2)%f*col%f; long a1_row = sum_col; long an_row = (row-1)*diff_row%f+a1_row; an_row%=f; //long sum_row = (a1_row+an_row)*row/2%f; long sum_row = (a1_row+(row-1)*m%f*col%f)%f*row%f; return sum_row; } private static long qpow(long a, long p, long MOD) { long m = Long.highestOneBit(p); long ans = 1; for (; m > 0; m >>>= 1) { ans = ans * ans %MOD; if ((p & m) > 0) ans = ans * a %MOD; } return ans; } public int cnr(int n, int r, int mod) { if(r==0||n==r) return 1; long x = cnr(n-1,r,mod); x%=mod; x+=cnr(n-1,r-1,mod); x%=mod; return (int) x; } public long fmi(long base, long exp, long fa) { if(exp==1) return base; else if(exp%2==0) { long tmp = fmi(base, exp/2, fa); return tmp*tmp%fa; }else { long tmp = fmi(base,exp-1,fa); return base*tmp%fa; } } public class edge implements Comparable<edge>{ int f, t, len; public edge(int a, int b, int c) { f = a; t = b; len = c; } @Override public int compareTo(Main.Task.edge o) { // TODO Auto-generated method stub return this.len - o.len; } } public Set<Integer> get_factor(int number) { int n = number; Set<Integer> primeFactors = new HashSet<Integer>(); for (int i = 2; i <= n/i; i++) { while (n % i == 0) { primeFactors.add(i); n /= i; } } if(n>1) primeFactors.add(n); return primeFactors; } private static int combx(int n, int k) { int comb[][] = new int[n+1][n+1]; for(int i = 0; i <=n; i ++){ comb[i][0] = comb[i][i] = 1; for(int j = 1; j < i; j++){ comb[i][j] = comb[i-1][j] + comb[i-1][j-1]; comb[i][j] %= 1000000007; } } return comb[n][k]; } class trie_node{ boolean end; int val; int lvl; trie_node zero; trie_node one; public trie_node() { zero = null; one = null; end = false; val = -1; lvl = -1; } } class trie{ trie_node root = new trie_node(); public void build(int x, int sz) { trie_node cur = root; for(int i=sz;i>=0;i--) { int v = (x&(1<<i))==0?0:1; if(v==0&&cur.zero==null) { cur.zero = new trie_node(); } if(v==1&&cur.one==null) { cur.one = new trie_node(); } cur.lvl = i; if(i==0) { cur.end = true; cur.val = x; }else { if(v==0) cur = cur.zero; else cur = cur.one; cur.val = v; cur.lvl = i; } } } int search(int num, int limit, trie_node r, int lvl) { if(r==null) return -1; if(r.end) return r.val; int f = -1; int num_val = (num&1<<lvl)==0?0:1; int limit_val = (limit&1<<lvl)==0?0:1; if(limit_val==1) { if(num_val==0) { int t = search(num,limit,r.one,lvl-1); if(t>f) return t; t = search(num,limit,r.zero,lvl-1); if(t>f) return t; }else { int t = search(num,limit,r.zero,lvl-1); if(t>f) return t; t = search(num,limit,r.one,lvl-1); if(t>f) return t; } }else { int t = search(num,limit,r.zero,lvl-1); if(t>f) return t; } return f; } } public int[] maximizeXor(int[] nums, int[][] queries) { int m = queries.length; int ret[] = new int[m]; trie t = new trie(); int sz = 5; for(int i:nums) t.build(i,sz); int p = 0; for(int x[]:queries) { if(p==1) { Dumper.print("here"); } ret[p++] = t.search(x[0], x[1], t.root, sz); } return ret; } /* * class edge implements Comparable<edge>{ int id,f,t; int len;int short_len; * public edge(int a, int b, int c, int d, int e) { f=a;t=b;len=c;id=d;short_len * = e; } * * @Override public int compareTo(edge t) { if(this.len-t.len>0) return 1; else * if(this.len-t.len<0) return -1; return 0; } } */ static class lca_naive{ int n; ArrayList<edge>[] g; int lvl[]; int pare[]; int dist[]; public lca_naive(int t, ArrayList<edge>[] x) { n=t; g=x; lvl = new int[n]; pare = new int[n]; dist = new int[n]; } void pre_process() { dfs(0,-1,g,lvl,pare,dist); } void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[]) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; pare[nxt_edge.t] = cur; dfs(nxt_edge.t,cur,g,lvl,pare,dist); } } } public int work(int p, int q) { int a = p; int b = q; while(lvl[p]<lvl[q]) q = pare[q]; while(lvl[p]>lvl[q]) p = pare[p]; while(p!=q){p = pare[p]; q = pare[q];} int c = p; return dist[a]+dist[b]-dist[c]*2; } } static class lca_binary_lifting{ int n; ArrayList<edge>[] g; int lvl[]; int pare[]; int dist[]; int table[][]; public lca_binary_lifting(int a, ArrayList<edge>[] t) { n = a; g = t; lvl = new int[n]; pare = new int[n]; dist = new int[n]; table = new int[20][n]; } void pre_process() { dfs(0,-1,g,lvl,pare,dist); for(int i=0;i<20;i++) { for(int j=0;j<n;j++) { if(i==0) table[0][j] = pare[j]; else table[i][j] = table[i-1][table[i-1][j]]; } } } void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[]) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; pare[nxt_edge.t] = cur; dfs(nxt_edge.t,cur,g,lvl,pare,dist); } } } public int work(int p, int q) { int a = p; int b = q; if(lvl[p]>lvl[q]) { int tmp = p; p=q; q=tmp; } for(int i=19;i>=0;i--) { if(lvl[table[i][q]]>=lvl[p]) q=table[i][q]; } if(p==q) return p;// return dist[a]+dist[b]-dist[p]*2; for(int i=19;i>=0;i--) { if(table[i][p]!=table[i][q]) { p = table[i][p]; q = table[i][q]; } } return table[0][p]; //return dist[a]+dist[b]-dist[table[0][p]]*2; } } static class lca_sqrt_root{ int n; ArrayList<edge>[] g; int lvl[]; int pare[]; int dist[]; int jump[]; int sz; public lca_sqrt_root(int a, ArrayList<edge>[] b) { n=a; g=b; lvl = new int[n]; pare = new int[n]; dist = new int[n]; jump = new int[n]; sz = (int) Math.sqrt(n); } void pre_process() { dfs(0,-1,g,lvl,pare,dist,jump); } void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[], int[] jump) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; pare[nxt_edge.t] = cur; if(lvl[nxt_edge.t]%sz==0) { jump[nxt_edge.t] = cur; }else { jump[nxt_edge.t] = jump[cur]; } dfs(nxt_edge.t,cur,g,lvl,pare,dist,jump); } } } int work(int p, int q) { int a = p; int b = q; if(lvl[p]>lvl[q]) { int tmp = p; p=q; q=tmp; } while(jump[p]!=jump[q]) { if(lvl[p]>lvl[q]) p = jump[p]; else q = jump[q]; } while(p!=q) { if(lvl[p]>lvl[q]) p = pare[p]; else q = pare[q]; } return dist[a]+dist[b]-dist[p]*2; } } // class edge implements Comparable<edge>{ // int f,t,len; // public edge(int a, int b, int c) { // f=a;t=b;len=c; // } // @Override // public int compareTo(edge t) { // return t.len-this.len; // } // } class pair implements Comparable<pair>{ int idx,lvl; public pair(int a, int b) { idx = a; lvl = b; } @Override public int compareTo(pair t) { return t.lvl-this.lvl; } } static class lca_RMQ{ int n; ArrayList<edge>[] g; int lvl[]; int dist[]; int tour[]; int tour_rank[]; int first_occ[]; int c; sgt s; public lca_RMQ(int a, ArrayList<edge>[] b) { n=a; g=b; c=0; lvl = new int[n]; dist = new int[n]; tour = new int[2*n]; tour_rank = new int[2*n]; first_occ = new int[n]; Arrays.fill(first_occ, -1); } void pre_process() { tour[c++] = 0; dfs(0,-1); for(int i=0;i<2*n;i++) { tour_rank[i] = lvl[tour[i]]; if(first_occ[tour[i]]==-1) first_occ[tour[i]] = i; } s = new sgt(0,2*n,tour_rank); } void dfs(int cur, int pre) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; tour[c++] = nxt_edge.t; dfs(nxt_edge.t,cur); tour[c++] = cur; } } } int work(int p,int q) { int a = Math.max(first_occ[p], first_occ[q]); int b = Math.min(first_occ[p], first_occ[q]); int idx = s.query_min_idx(b, a+1); //Dumper.print(a+" "+b+" "+idx); int c = tour[idx]; return dist[p]+dist[q]-dist[c]*2; } } static class sgt{ sgt lt; sgt rt; int l,r; int sum, max, min, lazy; int min_idx; public sgt(int L, int R, int arr[]) { l=L;r=R; if(l==r-1) { sum = max = min = arr[l]; lazy = 0; min_idx = l; return; } lt = new sgt(l, l+r>>1, arr); rt = new sgt(l+r>>1, r, arr); pop_up(); } void pop_up() { this.sum = lt.sum + rt.sum; this.max = Math.max(lt.max, rt.max); this.min = Math.min(lt.min, rt.min); if(lt.min<rt.min) this.min_idx = lt.min_idx; else if(lt.min>rt.min) this.min_idx = rt.min_idx; else this.min = Math.min(lt.min_idx, rt.min_idx); } void push_down() { if(this.lazy!=0) { lt.sum+=lazy; rt.sum+=lazy; lt.max+=lazy; lt.min+=lazy; rt.max+=lazy; rt.min+=lazy; lt.lazy+=this.lazy; rt.lazy+=this.lazy; this.lazy = 0; } } void change(int L, int R, int v) { if(R<=l||r<=L) return; if(L<=l&&r<=R) { this.max+=v; this.min+=v; this.sum+=v*(r-l); this.lazy+=v; return; } push_down(); lt.change(L, R, v); rt.change(L, R, v); pop_up(); } int query_max(int L, int R) { if(L<=l&&r<=R) return this.max; if(r<=L||R<=l) return Integer.MIN_VALUE; push_down(); return Math.max(lt.query_max(L, R), rt.query_max(L, R)); } int query_min(int L, int R) { if(L<=l&&r<=R) return this.min; if(r<=L||R<=l) return Integer.MAX_VALUE; push_down(); return Math.min(lt.query_min(L, R), rt.query_min(L, R)); } int query_sum(int L, int R) { if(L<=l&&r<=R) return this.sum; if(r<=L||R<=l) return 0; push_down(); return lt.query_sum(L, R) + rt.query_sum(L, R); } int query_min_idx(int L, int R) { if(L<=l&&r<=R) return this.min_idx; if(r<=L||R<=l) return Integer.MAX_VALUE; int a = lt.query_min_idx(L, R); int b = rt.query_min_idx(L, R); int aa = lt.query_min(L, R); int bb = rt.query_min(L, R); if(aa<bb) return a; else if(aa>bb) return b; return Math.min(a,b); } } List<List<Integer>> convert(int arr[][]){ int n = arr.length; List<List<Integer>> ret = new ArrayList<>(); for(int i=0;i<n;i++) { ArrayList<Integer> tmp = new ArrayList<Integer>(); for(int j=0;j<arr[i].length;j++) tmp.add(arr[i][j]); ret.add(tmp); } return ret; } public int GCD(int a, int b) { if (b==0) return a; return GCD(b,a%b); } public long GCD(long a, long b) { if (b==0) return a; return GCD(b,a%b); } } static class ArrayUtils { static final long seed = System.nanoTime(); static final Random rand = new Random(seed); public static void sort(int[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(int[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); int t = a[i]; a[i] = a[j]; a[j] = t; } } public static void sort(long[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(long[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); long t = a[i]; a[i] = a[j]; a[j] = t; } } } static class BIT{ int arr[]; int n; public BIT(int a) { n=a; arr = new int[n]; } int sum(int p) { int s=0; while(p>0) { s+=arr[p]; p-=p&(-p); } return s; } void add(int p, int v) { while(p<n) { arr[p]+=v; p+=p&(-p); } } } static class DSU{ int[] arr; int[] sz; public DSU(int n) { arr = new int[n]; sz = new int[n]; for(int i=0;i<n;i++) arr[i] = i; Arrays.fill(sz, 1); } public int find(int a) { if(arr[a]!=a) arr[a] = find(arr[a]); return arr[a]; } public void union(int a, int b) { int x = find(a); int y = find(b); if(x==y) return; arr[y] = x; sz[x] += sz[y]; } public int size(int x) { return sz[find(x)]; } } static class MinHeap<Key> implements Iterable<Key> { private int maxN; private int n; private int[] pq; private int[] qp; private Key[] keys; private Comparator<Key> comparator; public MinHeap(int capacity){ if (capacity < 0) throw new IllegalArgumentException(); this.maxN = capacity; n=0; pq = new int[maxN+1]; qp = new int[maxN+1]; keys = (Key[]) new Object[capacity+1]; Arrays.fill(qp, -1); } public MinHeap(int capacity, Comparator<Key> c){ if (capacity < 0) throw new IllegalArgumentException(); this.maxN = capacity; n=0; pq = new int[maxN+1]; qp = new int[maxN+1]; keys = (Key[]) new Object[capacity+1]; Arrays.fill(qp, -1); comparator = c; } public boolean isEmpty() { return n==0; } public int size() { return n; } public boolean contains(int i) { if (i < 0 || i >= maxN) throw new IllegalArgumentException(); return qp[i] != -1; } public int peekIdx() { if (n == 0) throw new NoSuchElementException("Priority queue underflow"); return pq[1]; } public Key peek(){ if(isEmpty()) throw new NoSuchElementException("Priority queue underflow"); return keys[pq[1]]; } public int poll(){ if(isEmpty()) throw new NoSuchElementException("Priority queue underflow"); int min = pq[1]; exch(1,n--); down(1); assert min==pq[n+1]; qp[min] = -1; keys[min] = null; pq[n+1] = -1; return min; } public void update(int i, Key key) { if (i < 0 || i >= maxN) throw new IllegalArgumentException(); if (!contains(i)) { this.add(i, key); }else { keys[i] = key; up(qp[i]); down(qp[i]); } } private void add(int i, Key x){ if (i < 0 || i >= maxN) throw new IllegalArgumentException(); if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue"); n++; qp[i] = n; pq[n] = i; keys[i] = x; up(n); } private void up(int k){ while(k>1&&less(k,k/2)){ exch(k,k/2); k/=2; } } private void down(int k){ while(2*k<=n){ int j=2*k; if(j<n&&less(j+1,j)) j++; if(less(k,j)) break; exch(k,j); k=j; } } public boolean less(int i, int j){ if (comparator == null) { return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0; } else { return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0; } } public void exch(int i, int j){ int swap = pq[i]; pq[i] = pq[j]; pq[j] = swap; qp[pq[i]] = i; qp[pq[j]] = j; } @Override public Iterator<Key> iterator() { // TODO Auto-generated method stub return null; } } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int zcurChar; private int znumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (znumChars == -1) throw new InputMismatchException(); if (zcurChar >= znumChars) { zcurChar = 0; try { znumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (znumChars <= 0) return -1; } return buf[zcurChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] readIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } static class Dumper { static void print_int_arr(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_char_arr(char[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_double_arr(double[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_2d_arr(int[][] arr, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); System.out.println("---------------------"); } static void print_2d_arr(boolean[][] arr, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); System.out.println("---------------------"); } static void print(Object o) { System.out.println(o.toString()); } static void getc() { System.out.println("here"); } } } import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); InputReader in = new InputReader(inputStream); // for(int i=4;i<=4;i++) { // InputStream uinputStream = new FileInputStream("timeline.in"); //String f = i+".in"; //InputStream uinputStream = new FileInputStream(f); // InputReader in = new InputReader(uinputStream); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("timeline.out"))); // } Task t = new Task(); t.solve(in, out); out.close(); } static class Task{ public void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int m = in.nextInt(); int l = 0; String[] arr = new String[n]; for(int i=0;i<n;i++) { arr[i] = in.next(); l+=arr[i].length(); } HashSet<String> s = new HashSet<String>(); for(int i=0;i<m;i++) s.add(in.next()); int left = 16-l-n+1; int[] tmp = new int[n-1]; ArrayList<int[]> underscore = new ArrayList<int[]>(); dfs(left,0,n-1,tmp,underscore); ArrayList<int[]> arrange = new ArrayList<int[]>(); dfs2(0,n,new int[n],new boolean[n],arrange); boolean can = false; for(int i=0;i<arrange.size();i++) {//0,2,1,3 for(int p=0;p<underscore.size();p++) {//[1,0,0] StringBuilder sb = new StringBuilder(); for(int j=0;j<n;j++) { sb.append(arr[arrange.get(i)[j]]); if(j<n-1) { sb.append("_"); for(int k=0;k<underscore.get(p)[j];k++) { sb.append("_"); } } } if(sb.length()>=3&&!s.contains(sb.toString())) { out.println(sb.toString()); can = true; break; } } if(can) break; } if(!can) out.println(-1); } void dfs(int left, int cur, int m, int[] arr, ArrayList<int[]> ret){ if(cur==m) { ret.add(arr.clone()); return; } for(int i=0;i<=left;i++) { arr[cur] = i; dfs(left-i,cur+1,m,arr,ret); } } void dfs2(int cur, int m, int[] arr, boolean[] vis, ArrayList<int[]> ret) { if(cur==m) { ret.add(arr.clone()); return; } for(int i=0;i<m;i++) { if(!vis[i]) { vis[i] = true; arr[cur] = i; dfs2(cur+1,m,arr,vis,ret); vis[i] = false; } } } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } long work(long a, long b, long c, long d, int m, int f) { long col = (d-b)/2+1; long row = (c-a)/2+1; long diff_row = 2*m%f*col%f; long a1_col = ((a-1)*m%f+b)%f; long an_col = ((a-1)*m%f+d)%f; //long sum_col = (a1_col+an_col)*col/2%f; long sum_col = ((a-1)*m%f + (b+d)/2)%f*col%f; long a1_row = sum_col; long an_row = (row-1)*diff_row%f+a1_row; an_row%=f; //long sum_row = (a1_row+an_row)*row/2%f; long sum_row = (a1_row+(row-1)*m%f*col%f)%f*row%f; return sum_row; } private static long qpow(long a, long p, long MOD) { long m = Long.highestOneBit(p); long ans = 1; for (; m > 0; m >>>= 1) { ans = ans * ans %MOD; if ((p & m) > 0) ans = ans * a %MOD; } return ans; } public int cnr(int n, int r, int mod) { if(r==0||n==r) return 1; long x = cnr(n-1,r,mod); x%=mod; x+=cnr(n-1,r-1,mod); x%=mod; return (int) x; } public long fmi(long base, long exp, long fa) { if(exp==1) return base; else if(exp%2==0) { long tmp = fmi(base, exp/2, fa); return tmp*tmp%fa; }else { long tmp = fmi(base,exp-1,fa); return base*tmp%fa; } } public class edge implements Comparable<edge>{ int f, t, len; public edge(int a, int b, int c) { f = a; t = b; len = c; } @Override public int compareTo(Main.Task.edge o) { // TODO Auto-generated method stub return this.len - o.len; } } public Set<Integer> get_factor(int number) { int n = number; Set<Integer> primeFactors = new HashSet<Integer>(); for (int i = 2; i <= n/i; i++) { while (n % i == 0) { primeFactors.add(i); n /= i; } } if(n>1) primeFactors.add(n); return primeFactors; } private static int combx(int n, int k) { int comb[][] = new int[n+1][n+1]; for(int i = 0; i <=n; i ++){ comb[i][0] = comb[i][i] = 1; for(int j = 1; j < i; j++){ comb[i][j] = comb[i-1][j] + comb[i-1][j-1]; comb[i][j] %= 1000000007; } } return comb[n][k]; } class trie_node{ boolean end; int val; int lvl; trie_node zero; trie_node one; public trie_node() { zero = null; one = null; end = false; val = -1; lvl = -1; } } class trie{ trie_node root = new trie_node(); public void build(int x, int sz) { trie_node cur = root; for(int i=sz;i>=0;i--) { int v = (x&(1<<i))==0?0:1; if(v==0&&cur.zero==null) { cur.zero = new trie_node(); } if(v==1&&cur.one==null) { cur.one = new trie_node(); } cur.lvl = i; if(i==0) { cur.end = true; cur.val = x; }else { if(v==0) cur = cur.zero; else cur = cur.one; cur.val = v; cur.lvl = i; } } } int search(int num, int limit, trie_node r, int lvl) { if(r==null) return -1; if(r.end) return r.val; int f = -1; int num_val = (num&1<<lvl)==0?0:1; int limit_val = (limit&1<<lvl)==0?0:1; if(limit_val==1) { if(num_val==0) { int t = search(num,limit,r.one,lvl-1); if(t>f) return t; t = search(num,limit,r.zero,lvl-1); if(t>f) return t; }else { int t = search(num,limit,r.zero,lvl-1); if(t>f) return t; t = search(num,limit,r.one,lvl-1); if(t>f) return t; } }else { int t = search(num,limit,r.zero,lvl-1); if(t>f) return t; } return f; } } public int[] maximizeXor(int[] nums, int[][] queries) { int m = queries.length; int ret[] = new int[m]; trie t = new trie(); int sz = 5; for(int i:nums) t.build(i,sz); int p = 0; for(int x[]:queries) { if(p==1) { Dumper.print("here"); } ret[p++] = t.search(x[0], x[1], t.root, sz); } return ret; } /* * class edge implements Comparable<edge>{ int id,f,t; int len;int short_len; * public edge(int a, int b, int c, int d, int e) { f=a;t=b;len=c;id=d;short_len * = e; } * * @Override public int compareTo(edge t) { if(this.len-t.len>0) return 1; else * if(this.len-t.len<0) return -1; return 0; } } */ static class lca_naive{ int n; ArrayList<edge>[] g; int lvl[]; int pare[]; int dist[]; public lca_naive(int t, ArrayList<edge>[] x) { n=t; g=x; lvl = new int[n]; pare = new int[n]; dist = new int[n]; } void pre_process() { dfs(0,-1,g,lvl,pare,dist); } void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[]) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; pare[nxt_edge.t] = cur; dfs(nxt_edge.t,cur,g,lvl,pare,dist); } } } public int work(int p, int q) { int a = p; int b = q; while(lvl[p]<lvl[q]) q = pare[q]; while(lvl[p]>lvl[q]) p = pare[p]; while(p!=q){p = pare[p]; q = pare[q];} int c = p; return dist[a]+dist[b]-dist[c]*2; } } static class lca_binary_lifting{ int n; ArrayList<edge>[] g; int lvl[]; int pare[]; int dist[]; int table[][]; public lca_binary_lifting(int a, ArrayList<edge>[] t) { n = a; g = t; lvl = new int[n]; pare = new int[n]; dist = new int[n]; table = new int[20][n]; } void pre_process() { dfs(0,-1,g,lvl,pare,dist); for(int i=0;i<20;i++) { for(int j=0;j<n;j++) { if(i==0) table[0][j] = pare[j]; else table[i][j] = table[i-1][table[i-1][j]]; } } } void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[]) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; pare[nxt_edge.t] = cur; dfs(nxt_edge.t,cur,g,lvl,pare,dist); } } } public int work(int p, int q) { int a = p; int b = q; if(lvl[p]>lvl[q]) { int tmp = p; p=q; q=tmp; } for(int i=19;i>=0;i--) { if(lvl[table[i][q]]>=lvl[p]) q=table[i][q]; } if(p==q) return p;// return dist[a]+dist[b]-dist[p]*2; for(int i=19;i>=0;i--) { if(table[i][p]!=table[i][q]) { p = table[i][p]; q = table[i][q]; } } return table[0][p]; //return dist[a]+dist[b]-dist[table[0][p]]*2; } } static class lca_sqrt_root{ int n; ArrayList<edge>[] g; int lvl[]; int pare[]; int dist[]; int jump[]; int sz; public lca_sqrt_root(int a, ArrayList<edge>[] b) { n=a; g=b; lvl = new int[n]; pare = new int[n]; dist = new int[n]; jump = new int[n]; sz = (int) Math.sqrt(n); } void pre_process() { dfs(0,-1,g,lvl,pare,dist,jump); } void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[], int[] jump) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; pare[nxt_edge.t] = cur; if(lvl[nxt_edge.t]%sz==0) { jump[nxt_edge.t] = cur; }else { jump[nxt_edge.t] = jump[cur]; } dfs(nxt_edge.t,cur,g,lvl,pare,dist,jump); } } } int work(int p, int q) { int a = p; int b = q; if(lvl[p]>lvl[q]) { int tmp = p; p=q; q=tmp; } while(jump[p]!=jump[q]) { if(lvl[p]>lvl[q]) p = jump[p]; else q = jump[q]; } while(p!=q) { if(lvl[p]>lvl[q]) p = pare[p]; else q = pare[q]; } return dist[a]+dist[b]-dist[p]*2; } } // class edge implements Comparable<edge>{ // int f,t,len; // public edge(int a, int b, int c) { // f=a;t=b;len=c; // } // @Override // public int compareTo(edge t) { // return t.len-this.len; // } // } class pair implements Comparable<pair>{ int idx,lvl; public pair(int a, int b) { idx = a; lvl = b; } @Override public int compareTo(pair t) { return t.lvl-this.lvl; } } static class lca_RMQ{ int n; ArrayList<edge>[] g; int lvl[]; int dist[]; int tour[]; int tour_rank[]; int first_occ[]; int c; sgt s; public lca_RMQ(int a, ArrayList<edge>[] b) { n=a; g=b; c=0; lvl = new int[n]; dist = new int[n]; tour = new int[2*n]; tour_rank = new int[2*n]; first_occ = new int[n]; Arrays.fill(first_occ, -1); } void pre_process() { tour[c++] = 0; dfs(0,-1); for(int i=0;i<2*n;i++) { tour_rank[i] = lvl[tour[i]]; if(first_occ[tour[i]]==-1) first_occ[tour[i]] = i; } s = new sgt(0,2*n,tour_rank); } void dfs(int cur, int pre) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; tour[c++] = nxt_edge.t; dfs(nxt_edge.t,cur); tour[c++] = cur; } } } int work(int p,int q) { int a = Math.max(first_occ[p], first_occ[q]); int b = Math.min(first_occ[p], first_occ[q]); int idx = s.query_min_idx(b, a+1); //Dumper.print(a+" "+b+" "+idx); int c = tour[idx]; return dist[p]+dist[q]-dist[c]*2; } } static class sgt{ sgt lt; sgt rt; int l,r; int sum, max, min, lazy; int min_idx; public sgt(int L, int R, int arr[]) { l=L;r=R; if(l==r-1) { sum = max = min = arr[l]; lazy = 0; min_idx = l; return; } lt = new sgt(l, l+r>>1, arr); rt = new sgt(l+r>>1, r, arr); pop_up(); } void pop_up() { this.sum = lt.sum + rt.sum; this.max = Math.max(lt.max, rt.max); this.min = Math.min(lt.min, rt.min); if(lt.min<rt.min) this.min_idx = lt.min_idx; else if(lt.min>rt.min) this.min_idx = rt.min_idx; else this.min = Math.min(lt.min_idx, rt.min_idx); } void push_down() { if(this.lazy!=0) { lt.sum+=lazy; rt.sum+=lazy; lt.max+=lazy; lt.min+=lazy; rt.max+=lazy; rt.min+=lazy; lt.lazy+=this.lazy; rt.lazy+=this.lazy; this.lazy = 0; } } void change(int L, int R, int v) { if(R<=l||r<=L) return; if(L<=l&&r<=R) { this.max+=v; this.min+=v; this.sum+=v*(r-l); this.lazy+=v; return; } push_down(); lt.change(L, R, v); rt.change(L, R, v); pop_up(); } int query_max(int L, int R) { if(L<=l&&r<=R) return this.max; if(r<=L||R<=l) return Integer.MIN_VALUE; push_down(); return Math.max(lt.query_max(L, R), rt.query_max(L, R)); } int query_min(int L, int R) { if(L<=l&&r<=R) return this.min; if(r<=L||R<=l) return Integer.MAX_VALUE; push_down(); return Math.min(lt.query_min(L, R), rt.query_min(L, R)); } int query_sum(int L, int R) { if(L<=l&&r<=R) return this.sum; if(r<=L||R<=l) return 0; push_down(); return lt.query_sum(L, R) + rt.query_sum(L, R); } int query_min_idx(int L, int R) { if(L<=l&&r<=R) return this.min_idx; if(r<=L||R<=l) return Integer.MAX_VALUE; int a = lt.query_min_idx(L, R); int b = rt.query_min_idx(L, R); int aa = lt.query_min(L, R); int bb = rt.query_min(L, R); if(aa<bb) return a; else if(aa>bb) return b; return Math.min(a,b); } } List<List<Integer>> convert(int arr[][]){ int n = arr.length; List<List<Integer>> ret = new ArrayList<>(); for(int i=0;i<n;i++) { ArrayList<Integer> tmp = new ArrayList<Integer>(); for(int j=0;j<arr[i].length;j++) tmp.add(arr[i][j]); ret.add(tmp); } return ret; } public int GCD(int a, int b) { if (b==0) return a; return GCD(b,a%b); } public long GCD(long a, long b) { if (b==0) return a; return GCD(b,a%b); } } static class ArrayUtils { static final long seed = System.nanoTime(); static final Random rand = new Random(seed); public static void sort(int[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(int[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); int t = a[i]; a[i] = a[j]; a[j] = t; } } public static void sort(long[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(long[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); long t = a[i]; a[i] = a[j]; a[j] = t; } } } static class BIT{ int arr[]; int n; public BIT(int a) { n=a; arr = new int[n]; } int sum(int p) { int s=0; while(p>0) { s+=arr[p]; p-=p&(-p); } return s; } void add(int p, int v) { while(p<n) { arr[p]+=v; p+=p&(-p); } } } static class DSU{ int[] arr; int[] sz; public DSU(int n) { arr = new int[n]; sz = new int[n]; for(int i=0;i<n;i++) arr[i] = i; Arrays.fill(sz, 1); } public int find(int a) { if(arr[a]!=a) arr[a] = find(arr[a]); return arr[a]; } public void union(int a, int b) { int x = find(a); int y = find(b); if(x==y) return; arr[y] = x; sz[x] += sz[y]; } public int size(int x) { return sz[find(x)]; } } static class MinHeap<Key> implements Iterable<Key> { private int maxN; private int n; private int[] pq; private int[] qp; private Key[] keys; private Comparator<Key> comparator; public MinHeap(int capacity){ if (capacity < 0) throw new IllegalArgumentException(); this.maxN = capacity; n=0; pq = new int[maxN+1]; qp = new int[maxN+1]; keys = (Key[]) new Object[capacity+1]; Arrays.fill(qp, -1); } public MinHeap(int capacity, Comparator<Key> c){ if (capacity < 0) throw new IllegalArgumentException(); this.maxN = capacity; n=0; pq = new int[maxN+1]; qp = new int[maxN+1]; keys = (Key[]) new Object[capacity+1]; Arrays.fill(qp, -1); comparator = c; } public boolean isEmpty() { return n==0; } public int size() { return n; } public boolean contains(int i) { if (i < 0 || i >= maxN) throw new IllegalArgumentException(); return qp[i] != -1; } public int peekIdx() { if (n == 0) throw new NoSuchElementException("Priority queue underflow"); return pq[1]; } public Key peek(){ if(isEmpty()) throw new NoSuchElementException("Priority queue underflow"); return keys[pq[1]]; } public int poll(){ if(isEmpty()) throw new NoSuchElementException("Priority queue underflow"); int min = pq[1]; exch(1,n--); down(1); assert min==pq[n+1]; qp[min] = -1; keys[min] = null; pq[n+1] = -1; return min; } public void update(int i, Key key) { if (i < 0 || i >= maxN) throw new IllegalArgumentException(); if (!contains(i)) { this.add(i, key); }else { keys[i] = key; up(qp[i]); down(qp[i]); } } private void add(int i, Key x){ if (i < 0 || i >= maxN) throw new IllegalArgumentException(); if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue"); n++; qp[i] = n; pq[n] = i; keys[i] = x; up(n); } private void up(int k){ while(k>1&&less(k,k/2)){ exch(k,k/2); k/=2; } } private void down(int k){ while(2*k<=n){ int j=2*k; if(j<n&&less(j+1,j)) j++; if(less(k,j)) break; exch(k,j); k=j; } } public boolean less(int i, int j){ if (comparator == null) { return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0; } else { return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0; } } public void exch(int i, int j){ int swap = pq[i]; pq[i] = pq[j]; pq[j] = swap; qp[pq[i]] = i; qp[pq[j]] = j; } @Override public Iterator<Key> iterator() { // TODO Auto-generated method stub return null; } } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int zcurChar; private int znumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (znumChars == -1) throw new InputMismatchException(); if (zcurChar >= znumChars) { zcurChar = 0; try { znumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (znumChars <= 0) return -1; } return buf[zcurChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] readIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } static class Dumper { static void print_int_arr(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_char_arr(char[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_double_arr(double[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_2d_arr(int[][] arr, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); System.out.println("---------------------"); } static void print_2d_arr(boolean[][] arr, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); System.out.println("---------------------"); } static void print(Object o) { System.out.println(o.toString()); } static void getc() { System.out.println("here"); } } }
ConDefects/ConDefects/Code/abc268_d/Java/36342960
condefects-java_data_500
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class Main { static class Solution { int sz = 0; String[] ws; Set<String> dict; public Solution(String[] ws, Set<String> dict) { this.ws = ws; this.dict = dict; for (String w: ws) { sz += w.length(); } } // String dfs2(int[] arr, int id, int ) // 写个互递归 String dfs2(int[] arr, boolean[] used, int id, int[] bx, int total) { if (id == arr.length) { // *) 16 StringBuilder sb = new StringBuilder(); sb.append(ws[arr[0]]); for (int i = 1; i < arr.length; i++) { for (int j = 0; j < bx[i]; j++) { sb.append('_'); } sb.append(ws[arr[i]]); } String expr = sb.toString(); if (!dict.contains(expr)) { return expr; } return null; } int left = arr.length - id; if (total < left) return null; for (int i = 1; i <= total; i++) { if (total - i < arr.length - id - 1) break; bx[id] = i; String res = dfs(arr, used, id, bx, total - i); if (res != null) return res; } return null; } // *) 只能暴力搞了 String dfs(int[] arr, boolean[] used, int id, int[] bx, int total) { // if (id == arr.length) { // // *) 16 // StringBuilder sb = new StringBuilder(); // sb.append(ws[arr[0]]); // for (int i = 1; i < arr.length; i++) { // for (int j = 0; j < bx[i]; j++) { // sb.append(' '); // } // sb.append(ws[arr[i]]); // } // String expr = sb.toString(); // if (!dict.contains(expr)) { // return expr; // } // // return null; // } for (int i = 0; i < arr.length; i++) { if (!used[i]) { used[i] = true; arr[id] = i; String r = dfs2(arr, used, id + 1, bx, total); if (r != null) return r; used[i] = false; } } return null; } // *) String solve() { int n = ws.length; String r = dfs(new int[n], new boolean[n], 0, new int[n], 16 - sz); return r == null ? "-1" : r; } } public static void main(String[] args) { AReader sc = new AReader(); int n = sc.nextInt(); int m = sc.nextInt(); String[] ws = new String[n]; for (int i = 0; i < n; i++) { ws[i] = sc.next(); } Set<String> sets = new HashSet<>(); for (int i = 0; i < m; i++) { sets.add(sc.next()); } Solution solution = new Solution(ws, sets); System.out.println(solution.solve()); } static class AReader { private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer tokenizer = new StringTokenizer(""); private String innerNextLine() { try { return reader.readLine(); } catch (IOException ex) { return null; } } public boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String nextLine = innerNextLine(); if (nextLine == null) { return false; } tokenizer = new StringTokenizer(nextLine); } return true; } public String nextLine() { tokenizer = new StringTokenizer(""); return innerNextLine(); } public String next() { hasNext(); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } // public BigInteger nextBigInt() { // return new BigInteger(next()); // } // 若需要nextDouble等方法,请自行调用Double.parseDouble包装 } } import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class Main { static class Solution { int sz = 0; String[] ws; Set<String> dict; public Solution(String[] ws, Set<String> dict) { this.ws = ws; this.dict = dict; for (String w: ws) { sz += w.length(); } } // String dfs2(int[] arr, int id, int ) // 写个互递归 String dfs2(int[] arr, boolean[] used, int id, int[] bx, int total) { if (id == arr.length) { // *) 16 StringBuilder sb = new StringBuilder(); sb.append(ws[arr[0]]); for (int i = 1; i < arr.length; i++) { for (int j = 0; j < bx[i]; j++) { sb.append('_'); } sb.append(ws[arr[i]]); } String expr = sb.toString(); if (!dict.contains(expr) && expr.length() >= 3 && expr.length() <= 16) { return expr; } return null; } int left = arr.length - id; if (total < left) return null; for (int i = 1; i <= total; i++) { if (total - i < arr.length - id - 1) break; bx[id] = i; String res = dfs(arr, used, id, bx, total - i); if (res != null) return res; } return null; } // *) 只能暴力搞了 String dfs(int[] arr, boolean[] used, int id, int[] bx, int total) { // if (id == arr.length) { // // *) 16 // StringBuilder sb = new StringBuilder(); // sb.append(ws[arr[0]]); // for (int i = 1; i < arr.length; i++) { // for (int j = 0; j < bx[i]; j++) { // sb.append(' '); // } // sb.append(ws[arr[i]]); // } // String expr = sb.toString(); // if (!dict.contains(expr)) { // return expr; // } // // return null; // } for (int i = 0; i < arr.length; i++) { if (!used[i]) { used[i] = true; arr[id] = i; String r = dfs2(arr, used, id + 1, bx, total); if (r != null) return r; used[i] = false; } } return null; } // *) String solve() { int n = ws.length; String r = dfs(new int[n], new boolean[n], 0, new int[n], 16 - sz); return r == null ? "-1" : r; } } public static void main(String[] args) { AReader sc = new AReader(); int n = sc.nextInt(); int m = sc.nextInt(); String[] ws = new String[n]; for (int i = 0; i < n; i++) { ws[i] = sc.next(); } Set<String> sets = new HashSet<>(); for (int i = 0; i < m; i++) { sets.add(sc.next()); } Solution solution = new Solution(ws, sets); System.out.println(solution.solve()); } static class AReader { private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer tokenizer = new StringTokenizer(""); private String innerNextLine() { try { return reader.readLine(); } catch (IOException ex) { return null; } } public boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String nextLine = innerNextLine(); if (nextLine == null) { return false; } tokenizer = new StringTokenizer(nextLine); } return true; } public String nextLine() { tokenizer = new StringTokenizer(""); return innerNextLine(); } public String next() { hasNext(); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } // public BigInteger nextBigInt() { // return new BigInteger(next()); // } // 若需要nextDouble等方法,请自行调用Double.parseDouble包装 } }
ConDefects/ConDefects/Code/abc268_d/Java/37622371