exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
sequencelengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
8dafa6c3aa5b01b56ab1de46cabf9c1d
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class C { static BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(""); public static void main(String[] args) throws Exception { int n = readInt(); TreeMap<Integer, Integer> tm = new TreeMap<>(); int temp; for (int i = 0; i < n * n; i++) { temp = readInt(); if (tm.containsKey(temp)) { tm.put(temp, tm.get(temp) + 1); } else { tm.put(temp, 1); } } List<Integer> answers = new ArrayList<>(); for (int i = 0; i < n; i++) { int highest = tm.lastKey(); int hvalue = tm.get(highest); if (hvalue == 1) { tm.remove(highest); } else { tm.put(highest, hvalue-1); } answers.add(highest); for (int j = 0; j < i; j++) { int gecede = gcd(highest, answers.get(j)); int value = tm.get(gecede); if (value == 2) { tm.remove(gecede); } else { tm.put(gecede, value - 2); } } } String out = Arrays.toString(answers.toArray()); System.out.println(out.substring(1, out.length()-1).replaceAll(",", "")); } public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static String readString() throws Exception { while (!st.hasMoreTokens()) { st = new StringTokenizer(stdin.readLine()); } return st.nextToken(); } static int readInt() throws Exception { return Integer.parseInt(readString()); } static double readDouble() throws Exception { return Double.parseDouble(readString()); } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
f82c3d8006d12bfaf67ffcf16a2b2a15
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.util.ArrayList; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class Main { public void solve() { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); TreeMap<Integer, Integer> cnt = new TreeMap<>(); for (int i = 0; i < n * n; ++i) { int x = -scanner.nextInt(); Integer value = cnt.get(x); if (value == null) { cnt.put(x, 1); } else { cnt.put(x, value + 1); } } scanner.close(); ArrayList<Integer> ans = new ArrayList<>(); for (Map.Entry<Integer, Integer> entry : cnt.entrySet()) { int top = -entry.getKey(); while (entry.getValue() > 0) { for (int a : ans) { int gcd = -gcd(top, a); cnt.put(gcd, cnt.get(gcd) - 2); } ans.add(top); cnt.put(-top, cnt.get(-top) - 1); } } for (int i = 0; i < n; ++i) { System.out.print(ans.get(i) + " "); } } public static void main(String[] args) { new Main().solve(); } // 最大公約数 private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
43ec39533e6a1722ded36097d10d0d7b
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.util.Map.Entry; import java.util.Scanner; import java.util.TreeMap; public class C { /* 4 2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2 2 1 1 1 1 4 3 3 3 3 2 2 2 2 1 1 1 1 1 1 1 1 */ public static void main(String[] args) { Scanner reader = new Scanner(System.in); int n = reader.nextInt(); /* int[][] gcd = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { gcd[i][j] = reader.nextInt(); } } */ int[] g = new int[n * n]; for(int i = 0; i < n * n; i++) { g[i] = reader.nextInt(); } TreeMap<Integer, Integer> M = new TreeMap<>(); for(int x : g) { if(M.containsKey(x)) { M.put(x, M.get(x) + 1); } else { M.put(x, 1); } } int[][] S = new int[n][n]; int k = 0; while(M.size() > 0) { addNumber(M, S, k); k++; } for(int i = 0; i < n; i++) { System.out.print(S[i][i]); if(i < n - 1) System.out.print(" "); } System.out.println(); reader.close(); } static void addNumber(TreeMap<Integer, Integer> M, int[][] S, int k) { int x = -1; for(Entry<Integer, Integer> e : M.entrySet()) { if(e.getValue() % 2 == 1) { x = e.getKey(); break; } } if(x != -1) { decrement(M, x); S[k][k] = x; for(int i = 0; i < k; i++) { int d = gcd(x, S[i][i]); S[i][k] = d; decrement(M, d); } for(int j = 0; j < k; j++) { int d = gcd(x, S[j][j]); S[k][j] = d; decrement(M, d); } } else { x = -1; for(Entry<Integer, Integer> e : M.entrySet()) { x = Math.max(x, e.getKey()); } decrement(M, x); S[k][k] = x; for(int i = 0; i < k; i++) { int d = gcd(x, S[i][i]); S[i][k] = d; decrement(M, d); } for(int j = 0; j < k; j++) { int d = gcd(x, S[j][j]); S[k][j] = d; decrement(M, d); } } } static void decrement(TreeMap<Integer, Integer> M, int x) { int val = M.get(x); if(val == 1) M.remove(x); else M.put(x, val - 1); } static int gcd(int a, int b) { if(b == 0) return a; return gcd(b, a % b); } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
b04901f69532bc2729df26c71f701aac
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; /** * @author Don Li */ public class GCDTable { void solve() { int n = in.nextInt(); Map<Integer, Integer> map = new TreeMap<>((x, y) -> y - x); for (int i = 0; i < n * n; i++) { int x = in.nextInt(); if (map.containsKey(x)) map.put(x, map.get(x) + 1); else map.put(x, 1); } Map<Integer, Integer> collect = new TreeMap<>(); for (int i = 0; i < n; i++) { int k = map.keySet().iterator().next(); int v = map.get(k); if (v == 1) map.remove(k); else map.put(k, v - 1); for (int kk : collect.keySet()) { int vv = collect.get(kk); int g = gcd(k, kk); int t = map.get(g); if (t == 2 * vv) map.remove(g); else map.put(g, t - 2 * vv); } if (!collect.containsKey(k)) collect.put(k, 1); else collect.put(k, collect.get(k) + 1); } for (int k : collect.keySet()) { int v = collect.get(k); for (int i = 0; i < v; i++) { out.print(k + " "); } } out.println(); } private int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new GCDTable().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
279bb5d94272958d66030b83d41e1c56
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.util.*; public class Main { public static int gcd(int a,int b) { return b == 0 ? a : gcd(b, a % b); } private static class St { int number, count; public St(int number, int count) { this.number = number; this.count = count; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] numbers = new int[n * n]; for (int i = 0; i < n * n; i++) { numbers[i] = scanner.nextInt(); } if (n == 1) { System.out.println(numbers[0]); return; } Arrays.sort(numbers); int currentN = numbers[n * n - 1]; int currentC = 1; int[] result = new int[n]; int resultPos = 0; List<St> counts = new ArrayList<>(n * n); Map<Integer, St> map = new TreeMap<>(); for (int i = n * n - 2; i >= 0; i--) { if (numbers[i] != currentN) { St st = new St(currentN, currentC); counts.add(st); map.put(currentN, st); currentN = numbers[i]; currentC = 1; } else { currentC++; } } St st = new St(currentN, currentC); counts.add(st); map.put(currentN, st); cc: for (St c : counts) { if (c.count == 1) { for (int i = 0; i < resultPos; i++) { map.get(gcd(result[i], c.number)).count -= 2; } result[resultPos++] = c.number; continue; } int found = 0; for (int i = 0; i < resultPos; i++) { if (gcd(result[i], c.number) == c.number) { found++; } } int toAdd; for (toAdd = 1; toAdd * toAdd + 2 * found * toAdd < c.count; toAdd++) { } if (toAdd * toAdd + 2 * found * toAdd > c.count) { continue; } for (int i = 0; i < resultPos; i++) { try { map.get(gcd(result[i], c.number)).count -= 2 * toAdd; } catch (NullPointerException e) { continue cc; } } for (int i = 0; i < toAdd; i++) { result[resultPos++] = c.number; } } for (int i = 0; i < n; i++) { System.out.print(result[i] + " "); } } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
84f38f6fa38e9535b910c73d28361bd5
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
//package com.codeforces.competitions.year2015.octobertodecember.round323div2; import java.io.*; import java.util.*; public final class Third { static int n, arr[]; static InputReader in; static OutputWriter out; public static void main(String[] args) { Third third = new Third(); in = third.new InputReader(System.in); out = third.new OutputWriter(System.out); getAttributes(); out.flush(); in.close(); out.close(); } static void getAttributes() { n = in.nextInt(); int total = n * n; arr = new int[total]; // Map<Integer, Integer> map = new HashMap<>(); TreeMap<Integer, Integer> map = new TreeMap<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(o2, o1); } }); for (int i = 0; i < total; i++) { arr[i] = in.nextInt(); Integer count = map.get(arr[i]); if (count == null) map.put(arr[i], 1); else map.put(arr[i], count + 1); } List<Integer> removed = new ArrayList<>(); for (int i = 0; i < n; i++) { // int max = set.pollFirst(); Map.Entry<Integer, Integer> max = map.firstEntry(); if (max.getValue() > 1) map.put(max.getKey(), max.getValue() - 1); else map.remove(max.getKey()); int size = removed.size(); for (int j = 0; j < size; j++) { int gcd = CMath.gcd(max.getKey(), removed.get(j)); Integer count = map.get(gcd); /* System.out.println("j : " + j + ", removed : " + removed.toString() + ", map : " + map.toString() + ", max : " + max + ", gcd : " + gcd);*/ if (count > 2) map.put(gcd, count - 2); else map.remove(gcd); } removed.add(max.getKey()); out.print(max.getKey() + " "); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } 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 & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int arraySize) { int array[] = new int[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextInt(); return array; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } long result = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); result *= 10; result += c & 15; c = read(); } while (!isSpaceChar(c)); return result * sign; } public long[] nextLongArray(int arraySize) { long array[] = new long[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextLong(); return array; } public float nextFloat() // problematic { float result, div; byte c; result = 0; div = 1; c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean isNegative = (c == '-'); if (isNegative) c = (byte) read(); do { result = result * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') result += (c - '0') / (div *= 10); if (isNegative) return -result; return result; } public double nextDouble() // not completely accurate { double ret = 0, div = 1; byte c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean neg = (c == '-'); if (neg) c = (byte) read(); do { ret = ret * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } public String next() { 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String nextLine() { int c = read(); StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (!isNewLine(c)); return result.toString(); } public boolean isNewLine(int c) { return c == '\n'; } public void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(int x) { writer.println(x); } public void print(int x) { writer.print(x); } public void println(int array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(int array[], int size) { for (int i = 0; i < size; i++) print(array[i] + " "); } public void println(long x) { writer.println(x); } public void print(long x) { writer.print(x); } public void println(long array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(long array[], int size) { for (int i = 0; i < size; i++) print(array[i]); } public void println(float num) { writer.println(num); } public void print(float num) { writer.print(num); } public void println(double num) { writer.println(num); } public void print(double num) { writer.print(num); } public void println(String s) { writer.println(s); } public void print(String s) { writer.print(s); } public void println() { writer.println(); } public void printSpace() { writer.print(" "); } public void flush() { writer.flush(); } public void close() { writer.close(); } } static class CMath { static long power(long number, long power) { if (number == 1 || number == 0 || power == 0) return 1; if (power == 1) return number; if (power % 2 == 0) return power(number * number, power / 2); else return power(number * number, power / 2) * number; } static long modPower(long number, long power, long mod) { if (number == 1 || number == 0 || power == 0) return 1; number = mod(number, mod); if (power == 1) return number; long square = mod(number * number, mod); if (power % 2 == 0) return modPower(square, power / 2, mod); else return mod(modPower(square, power / 2, mod) * number, mod); } static long moduloInverse(long number, long mod) { return modPower(number, mod - 2, mod); } static long mod(long number, long mod) { return number - (number / mod) * mod; } static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } } } /* 4 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 */
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
cc56621eeb860dbcda76592907441372
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; import java.util.TreeSet; /** * * @author sarthak */ public class rnd323_C { public static long gcd(long a, long b) { if (b == 0) { return a; } if (b > a) { return gcd(b, a); } else { return gcd(b, a % b); } } public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); ArrayList<Long> bl = new ArrayList<>(); HashMap<Long, Integer> m = new HashMap<>(); for (int i = 0; i < n * n; i++) { long l = s.nextLong(); if (m.containsKey(l)) { int c = m.get(l); ++c; m.put(l, c); } else { m.put(l, 1); } bl.add(l); } // if(bl.size()==1) // { // for(int i=1;i<=n;i++) // System.out.print(bl.get(0) + " "); // System.out.println(); // return; // } Collections.sort(bl); int i = bl.size() - 1; ArrayList<Long> al = new ArrayList(); al.add(bl.get(i)); int lc=m.get(bl.get(i)); lc--; m.put(bl.get(i), lc); i--; while (i >= 0) { long l = bl.get(i); if (m.get(l) > 0) { int c = 0; for (long ll : al) { long g1 = gcd(ll, l); long g2 = gcd(l, ll); c = m.get(g1); c--; m.put(g1, c); c = m.get(g2); c--; m.put(g2, c); } long g3 = l; c = m.get(g3); c--; m.put(g3, c); al.add(l); } i--; } for (long l : al) { System.out.print(l + " "); } System.out.println(); } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
8c89b686a5d282f10782731532f907d4
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.util.*; public class Main{ public static void main(String args[]){ Scanner in = new Scanner(System.in); Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); int n = in.nextInt(); int[] a = new int[n*n]; for(int i=0;i<n*n;i++){ a[i] = in.nextInt(); if(mp.get(a[i]) == null) mp.put(a[i], 1); else mp.put(a[i], mp.get(a[i])+1); } Arrays.sort(a); int[] ans = new int[n]; int cur = 0; for(int i=n*n-1;i>=0;i--) if(mp.get(a[i]) > 0){ int num = 0; int cnt = 0; for(int j=0;j<cur;j++) if(ans[j]%a[i] == 0) cnt ++; for(int j=0;j <= mp.get(a[i]);j++) if(2*cnt*j + j*j == mp.get(a[i])){ num = j; break; } mp.put(a[i], 0); for(int j=0;j<cur;j++){ int gcd = GCD(a[i], ans[j]); mp.put(gcd, mp.get(gcd)-2*num); } for(int j=0;j<num;j++) ans[cur++] = a[i]; } for(int i=0;i<cur;i++) System.out.print(ans[i] + " "); } static int GCD(int a, int b){ if(b == 0) return a; else return GCD(b, a%b); } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
d8a1ef522bf8371c284b5a7d19a2df98
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.io.*; import java.util.*; public class CF583C { static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static void remove(TreeMap<Integer, Integer> map, int v) { int cnt = map.get(v); if (cnt == 1) map.remove(v); else map.put(v, cnt - 1); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] aa = new int[n * n]; StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 0; i < n * n; i++) aa[i] = Integer.parseInt(st.nextToken()); TreeMap<Integer, Integer> map = new TreeMap<>(); for (int i = 0; i < n * n; i++) map.put(aa[i], map.containsKey(aa[i]) ? map.get(aa[i]) + 1 : 1); int[] a = new int[n]; for (int k = 0; k < n; k++) { int v = map.lastKey(); remove(map, v); a[k] = v; for (int i = 0; i < k; i++) { int g = gcd(a[i], a[k]); remove(map, g); remove(map, g); } } StringBuilder sb = new StringBuilder(); sb.append(a[0]); for (int i = 1; i < n; i++) sb.append(" " + a[i]); System.out.println(sb); } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
3baed3a04dab68df6b68fdffcc6d655f
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.io.*; import java.util.*; public class C { int[] v, c, a; int k, r; int gcd(int a, int b) { return a == 0 ? b : gcd(b % a, a); } void add(int e) { for (int i = 0; i < r; ++i) { int g = gcd(e, a[i]); int t = 0; while (t < k && g != v[t]) ++t; if (t == k || c[t] < 2) { throw new RuntimeException(); } c[t] -= 2; } a[r++] = e; } void solve() throws IOException { in = new InputReader("__std"); out = new OutputWriter("__std"); int n = in.readInt(); int l = n * n; v = new int[l]; c = new int[l]; k = 0; for (int i = 0; i < l; ++i) { int g = in.readInt(); int j = 0; while (j < k && g != v[j]) ++j; if (j == k) { v[k] = g; c[k] = 1; ++k; } else { ++c[j]; } } if (k == 1) { for (int i = 0; i < n; ++i) { out.print(v[0] + " "); } exit(); } a = new int[n]; r = 0; while (r < n) { // find max int j = -1; for (int i = 0; i < k; ++i) { if (c[i] > 0 && (j == -1 || v[i] > v[j])) { j = i; } } --c[j]; add(v[j]); // find odd do { j = -1; for (int i = 0; i < k; ++i) { if (c[i] > 0 && c[i] % 2 > 0) { j = i; break; } } if (j != -1) { --c[j]; add(v[j]); } } while (r < n && j != -1); } Arrays.sort(a); for (int i = 0; i < r; ++i) { out.print(a[i] + " "); } exit(); } void exit() { //System.err.println((System.currentTimeMillis() - startTime) + " ms"); out.close(); System.exit(0); } InputReader in; OutputWriter out; //long startTime = System.currentTimeMillis(); public static void main(String[] args) throws IOException { new C().solve(); } class InputReader { private InputStream stream; private byte[] buffer = new byte[1024]; private int pos, len; private int cur; private StringBuilder sb = new StringBuilder(32); InputReader(String name) throws IOException { if (name.equals("__std")) { stream = System.in; } else { stream = new FileInputStream(name); } cur = read(); } private int read() throws IOException { if (len == -1) { throw new EOFException(); } if (pos >= len) { pos = 0; len = stream.read(buffer); if (len == -1) return -1; } return buffer[pos++]; } private boolean whitespace() { return cur == ' ' || cur == '\t' || cur == '\r' || cur == '\n' || cur == -1; } char readChar() throws IOException { if (cur == -1) { throw new EOFException(); } char res = (char) cur; cur = read(); return res; } int readInt() throws IOException { if (cur == -1) { throw new EOFException(); } while (whitespace()) { cur = read(); } if (cur == -1) { throw new EOFException(); } int sign = 1; if (cur == '-') { sign = -1; cur = read(); } int res = 0; while (!whitespace()) { if (cur < '0' || cur > '9') { throw new NumberFormatException(); } res *= 10; res += cur - '0'; cur = read(); } return res * sign; } long readLong() throws IOException { if (cur == -1) { throw new EOFException(); } return Long.parseLong(readToken()); } double readDouble() throws IOException { if (cur == -1) { throw new EOFException(); } return Double.parseDouble(readToken()); } String readLine() throws IOException { if (cur == -1) { throw new EOFException(); } sb.setLength(0); while (cur != -1 && cur != '\r' && cur != '\n') { sb.append((char) cur); cur = read(); } if (cur == '\r') { cur = read(); } if (cur == '\n') { cur = read(); } return sb.toString(); } String readToken() throws IOException { if (cur == -1) { throw new EOFException(); } while (whitespace()) { cur = read(); } if (cur == -1) { throw new EOFException(); } sb.setLength(0); while (!whitespace()) { sb.append((char) cur); cur = read(); } return sb.toString(); } boolean eof() { return cur == -1; } } class OutputWriter { private PrintWriter writer; OutputWriter(String name) throws IOException { if (name.equals("__std")) { writer = new PrintWriter(System.out); } else { writer = new PrintWriter(name); } } void print(String format, Object ... args) { writer.print(new Formatter(Locale.US).format(format, args)); } void println(String format, Object ... args) { writer.println(new Formatter(Locale.US).format(format, args)); } void print(Object value) { writer.print(value); } void println(Object value) { writer.println(value); } void println() { writer.println(); } void close() { writer.close(); } } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
61ac026c3a1cfee1c75a19e4b448f86f
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class Codeforces { private static BufferedReader br; private static StringTokenizer st; private static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } private static int nextInt() throws IOException { return Integer.parseInt(st.nextToken()); } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); int n = nextInt(); st = new StringTokenizer(br.readLine()); HashMap<Integer, Integer> hm = new HashMap<>(); for (int i = 0; i < n * n; i++) { int value = nextInt(); if (hm.containsKey(value)) { hm.put(value, hm.get(value) + 1); } else { hm.put(value, 1); } } Integer[] keys = hm.keySet().toArray(new Integer[hm.size()]); Arrays.sort(keys); ArrayList<Integer> answer = new ArrayList<>(); for (int i = keys.length - 1; i >= 0; i--) { while (hm.get(keys[i]) > 0) { answer.add(keys[i]); for (Integer key : answer) { int temp = gcd(key, keys[i]); hm.put(temp, hm.get(temp) - 2); } hm.put(keys[i], hm.get(keys[i]) + 1); } } String result = answer.toString().replace(", ", " "); System.out.println(result.substring(1, result.length() - 1)); System.out.close(); } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
f708997d78591afbae4b406ee87b01c2
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; /** * * @author ploskov */ public class Codeforces { private static StreamTokenizer st; private static PrintWriter out; private static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } private static int nextInt() throws IOException { st.nextToken(); return (int) st.nval; } /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); int n = nextInt(); HashMap<Integer, Integer> hm = new HashMap<>(); for (int i = 0; i < n * n; i++) { int value = nextInt(); if (hm.containsKey(value)) { hm.put(value, hm.get(value) + 1); } else { hm.put(value, 1); } } Integer[] keys = hm.keySet().toArray(new Integer[hm.size()]); Arrays.sort(keys); ArrayList<Integer> answer = new ArrayList<>(); for (int i = keys.length - 1; i >= 0; i--) { while (hm.get(keys[i]) > 0) { answer.add(keys[i]); for (Integer key : answer) { int temp = gcd(key, keys[i]); hm.put(temp, hm.get(temp) - 2); } hm.put(keys[i], hm.get(keys[i]) + 1); } } String result = answer.toString().replace(", ", " "); out.println(result.substring(1, result.length() - 1)); out.close(); } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
9b4aeb737c0c18b21ac8c878633fff0c
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.util.ArrayList; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.TreeMap; public class CF583C { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; PrintWriter out; long timeBegin, timeEnd; public static void main(String[] args) throws IOException { new CF583C().runIO(); } public void runIO() throws IOException { timeBegin = System.currentTimeMillis(); InputStream inputStream; OutputStream outputStream; if (ONLINE_JUDGE) { inputStream = System.in; Reader.init(inputStream); outputStream = System.out; out = new PrintWriter(outputStream); } else { inputStream = new FileInputStream("input.txt"); Reader.init(inputStream); out = new PrintWriter("output.txt"); } solve(); // Start Main Problem Solving out.flush(); out.close(); timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } private int gcd(int a, int b) { if(b > a) return gcd(b, a); return b == 0? a : gcd(b, a % b); } private void solve() throws IOException { int n = Reader.nextInt(); int N = n * n; TreeMap<Integer, Integer> table = new TreeMap<>(); ArrayList<Integer> answer = new ArrayList<>(); while(N-- > 0) { int val = Reader.nextInt(); if(table.containsKey(val)) { table.put(val, table.get(val) + 1); } else { table.put(val, 1); } } int val = table.lastKey(); answer.add(val); table.put(val, table.get(val) - 1); if(table.get(val) == 0) { table.remove(val); } while(table.isEmpty() == false) { val = table.lastKey(); table.put(val, table.get(val) - 1); if(table.get(val) == 0) { table.remove(val); } for(int i = 0; i < answer.size(); i++) { int g = gcd(val, answer.get(i)); if(table.containsKey(g)) { int t = table.get(g); table.put(g, t - 2); if(t - 2 == 0 || t == 0) table.remove(g); } } answer.add(val); } for (int i = 0; i < n; i++) { out.print(answer.get(i) + " "); } } static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** * get next word */ static String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
1cdf38055ecc2ba1af38337cef89d5fc
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Contest { public static void main(String[] args) { Map<Integer, Integer> map = new HashMap<>(); List<Integer> result = new ArrayList<>(); Scanner sc = new Scanner(System.in); int size = sc.nextInt(); int totalNum = size * size; while(totalNum > 0) { totalNum--; increase(map, sc.nextInt()); } sc.close(); result.add(maxKey(map)); //the max int next, gcd; for(int ll = 1; ll < size; ++ll) { next = maxKey(map); for(int i = 0; i < result.size(); i++) { gcd = getGCD(result.get(i), next); remove(map, gcd, 2); } result.add(next); } StringBuilder sb = new StringBuilder(); for(int i : result) { sb.append(i).append(" "); } System.out.println(sb.substring(0, sb.length() - 1)); } static void increase(Map<Integer, Integer> map, int key) { if (map.containsKey(key)) { map.put(key, map.get(key) + 1); } else map.put(key, 1); } static Integer maxKey(Map<Integer, Integer> map) { Integer maximal = Collections.max(map.keySet()); remove(map, maximal, 1); return maximal; } static void remove(Map<Integer, Integer> map, Integer key, Integer value) { int result = map.get(key) - value; if (result > 0) map.put(key, result); else map.remove(key); } public static int getGCD(int a, int b) { if (b == 0) return a; return getGCD(b, a % b); } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
9eeb78771e1ab750ffe07b5b09895309
train_000.jsonl
1443890700
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Contest { public static void main(String[] args) { List<Integer> divisors = new ArrayList<>(); Map<Integer, Integer> map = new HashMap<>(); List<Integer> result = new ArrayList<>(); Scanner sc = new Scanner(System.in); int size = sc.nextInt(); int totalNum = size * size; while(totalNum > 0) { totalNum--; int input = sc.nextInt(); divisors.add(input); if (map.containsKey(input)) { map.put(input, map.get(input) + 1); } else map.put(input, 1); } sc.close(); Collections.sort(divisors); Collections.reverse(divisors); result.add(divisors.get(0)); //the max map.put(divisors.get(0), map.get(divisors.get(0)) - 1); int nextIdx = 1; int next, gcd; for(int ll = 1; ll < size; ++ll) { while (nextIdx < divisors.size() && map.get(divisors.get(nextIdx)) <= 0) ++nextIdx; next = divisors.get(nextIdx++); map.put(next, map.get(next) - 1); for(int i = 0; i < result.size(); i++) { gcd = getGCD(result.get(i), next); map.put(gcd, map.get(gcd) - 2); } result.add(next); } StringBuilder sb = new StringBuilder(); for(int i : result) { sb.append(i).append(" "); } System.out.println(sb.substring(0, sb.length() - 1)); } public static int getGCD(int a, int b) { if (b > a) return getGCD(b, a); if (b == 0) return a; return getGCD(b, a % b); } }
Java
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
2 seconds
["4 3 6 2", "42", "1 1"]
null
Java 8
standard input
[ "constructive algorithms", "number theory" ]
71dc07f0ea8962f23457af1d6509aeee
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
1,700
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
standard output
PASSED
cee32aad2fd8c07090c2bf69e31ad687
train_000.jsonl
1397977200
The R2 company has n employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke.R2 has m Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges messages daily. An employee can simultaneously talk in multiple chats. If some employee is in the k-th chat, he can write messages to this chat and receive notifications about messages from this chat. If an employee writes a message in the chat, all other participants of the chat receive a message notification.The R2 company is conducting an audit. Now the specialists study effective communication between the employees. For this purpose, they have a chat log and the description of chat structure. You, as one of audit specialists, are commissioned to write a program that will use this data to determine the total number of message notifications received by each employee.
256 megabytes
import java.io.*; import java.util.*; public final class Template { public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int employeeDetails[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) employeeDetails[i][j] = sc.nextInt(); } int receivedNotifications[] = new int[n]; int writtenToChat[] = new int[m]; for (int i = 0; i < k; i++) { int x = sc.nextInt(); int y = sc.nextInt(); receivedNotifications[x-1] += -1; writtenToChat[y-1] += 1; } for (int i = 0; i < m; i++) { if (writtenToChat[i] != 0) for (int j = 0; j < n; j++) { receivedNotifications[j] += writtenToChat[i] * employeeDetails[j][i]; } } for (int i = 0; i < n; i++) { System.out.print(receivedNotifications[i] + " "); } } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3 4 5\n1 1 1 1\n1 0 1 1\n1 1 0 0\n1 1\n3 1\n1 3\n2 4\n3 2", "4 3 4\n0 1 1\n1 0 1\n1 1 1\n0 0 0\n1 2\n2 1\n3 1\n1 3"]
1 second
["3 3 1", "0 2 3 0"]
null
Java 11
standard input
[ "implementation" ]
fad203b52e11706d70e9b2954c295f70
The first line contains three space-separated integers n, m and k (2 ≤ n ≤ 2·104; 1 ≤ m ≤ 10; 1 ≤ k ≤ 2·105) — the number of the employees, the number of chats and the number of events in the log, correspondingly. Next n lines contain matrix a of size n × m, consisting of numbers zero and one. The element of this matrix, recorded in the j-th column of the i-th line, (let's denote it as aij) equals 1, if the i-th employee is the participant of the j-th chat, otherwise the element equals 0. Assume that the employees are numbered from 1 to n and the chats are numbered from 1 to m. Next k lines contain the description of the log events. The i-th line contains two space-separated integers xi and yi (1 ≤ xi ≤ n; 1 ≤ yi ≤ m) which mean that the employee number xi sent one message to chat number yi. It is guaranteed that employee number xi is a participant of chat yi. It is guaranteed that each chat contains at least two employees.
1,300
Print in the single line n space-separated integers, where the i-th integer shows the number of message notifications the i-th employee receives.
standard output
PASSED
17322687a5131755f0c05a10a8194616
train_000.jsonl
1397977200
The R2 company has n employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke.R2 has m Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges messages daily. An employee can simultaneously talk in multiple chats. If some employee is in the k-th chat, he can write messages to this chat and receive notifications about messages from this chat. If an employee writes a message in the chat, all other participants of the chat receive a message notification.The R2 company is conducting an audit. Now the specialists study effective communication between the employees. For this purpose, they have a chat log and the description of chat structure. You, as one of audit specialists, are commissioned to write a program that will use this data to determine the total number of message notifications received by each employee.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class SpykeChatting { public static void main(String[] args) { int n = fs.nextInt(), m = fs.nextInt(), k = fs.nextInt(); int[][] employeeToChat = new int[n][]; for (int i = 0; i < n; i++) { employeeToChat[i] = fs.readArray(m); } int []employeeNotifications = new int[n]; int []chatNotifications = new int[m]; for (int i = 0; i < k; i++) { int employee = fs.nextInt(); int chat = fs.nextInt(); employeeNotifications[employee-1]--; chatNotifications[chat-1]++; } StringBuilder output = new StringBuilder(""); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (employeeToChat[i][j] == 1) { employeeNotifications[i] += chatNotifications[j]; } } output.append(employeeNotifications[i] + " "); } System.out.println(output); } 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()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } static FastScanner fs = new FastScanner(); }
Java
["3 4 5\n1 1 1 1\n1 0 1 1\n1 1 0 0\n1 1\n3 1\n1 3\n2 4\n3 2", "4 3 4\n0 1 1\n1 0 1\n1 1 1\n0 0 0\n1 2\n2 1\n3 1\n1 3"]
1 second
["3 3 1", "0 2 3 0"]
null
Java 11
standard input
[ "implementation" ]
fad203b52e11706d70e9b2954c295f70
The first line contains three space-separated integers n, m and k (2 ≤ n ≤ 2·104; 1 ≤ m ≤ 10; 1 ≤ k ≤ 2·105) — the number of the employees, the number of chats and the number of events in the log, correspondingly. Next n lines contain matrix a of size n × m, consisting of numbers zero and one. The element of this matrix, recorded in the j-th column of the i-th line, (let's denote it as aij) equals 1, if the i-th employee is the participant of the j-th chat, otherwise the element equals 0. Assume that the employees are numbered from 1 to n and the chats are numbered from 1 to m. Next k lines contain the description of the log events. The i-th line contains two space-separated integers xi and yi (1 ≤ xi ≤ n; 1 ≤ yi ≤ m) which mean that the employee number xi sent one message to chat number yi. It is guaranteed that employee number xi is a participant of chat yi. It is guaranteed that each chat contains at least two employees.
1,300
Print in the single line n space-separated integers, where the i-th integer shows the number of message notifications the i-th employee receives.
standard output
PASSED
e6092062d04df2f5d889af6cd8cd4ace
train_000.jsonl
1289646000
Vasya has gotten interested in programming contests in TCMCF+++ rules. On the contest n problems were suggested and every problem had a cost — a certain integral number of points (perhaps, negative or even equal to zero). According to TCMCF+++ rules, only accepted problems can earn points and the overall number of points of a contestant was equal to the product of the costs of all the problems he/she had completed. If a person didn't solve anything, then he/she didn't even appear in final standings and wasn't considered as participant. Vasya understood that to get the maximal number of points it is not always useful to solve all the problems. Unfortunately, he understood it only after the contest was finished. Now he asks you to help him: find out what problems he had to solve to earn the maximal number of points.
256 megabytes
import java.lang.*; import java.util.*; public class Cost{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] arr=new int[n]; int negCount=0; int negMax=-100; int posCount=0; for(int i=0; i<n; i++){ arr[i]=sc.nextInt(); if(arr[i]>0) posCount++; if(arr[i]<0){ negCount++; if(arr[i]>=negMax){ negMax=arr[i]; } } } for(int i=0; i<n; i++){ if(arr.length==1){ System.out.print(arr[0]); return; } if(negCount%2==1 && arr[i]==negMax){ negMax=-101; continue; } else{ if(arr[i]!=0){ System.out.print(arr[i]+" "); } else{ if(posCount==0 && (negCount==0 || negCount==1)){ System.out.print(0); return; } } } } } }
Java
["5\n1 2 -3 3 3", "13\n100 100 100 100 100 100 100 100 100 100 100 100 100", "4\n-2 -2 -2 -2"]
2 seconds
["3 1 2 3", "100 100 100 100 100 100 100 100 100 100 100 100 100", "-2 -2 -2 -2"]
null
Java 11
standard input
[ "greedy" ]
b11644953bdd1b92eb1b18c339a268a1
The first line contains an integer n (1 ≤ n ≤ 100) — the number of the suggested problems. The next line contains n space-separated integers ci ( - 100 ≤ ci ≤ 100) — the cost of the i-th task. The tasks' costs may coinсide.
1,400
Print space-separated the costs of the problems that needed to be solved to get the maximal possible number of points. Do not forget, please, that it was necessary to solve at least one problem. If there are several solutions to that problem, print any of them.
standard output
PASSED
1649622eeaca5833de2fad776cab143b
train_000.jsonl
1289646000
Vasya has gotten interested in programming contests in TCMCF+++ rules. On the contest n problems were suggested and every problem had a cost — a certain integral number of points (perhaps, negative or even equal to zero). According to TCMCF+++ rules, only accepted problems can earn points and the overall number of points of a contestant was equal to the product of the costs of all the problems he/she had completed. If a person didn't solve anything, then he/she didn't even appear in final standings and wasn't considered as participant. Vasya understood that to get the maximal number of points it is not always useful to solve all the problems. Unfortunately, he understood it only after the contest was finished. Now he asks you to help him: find out what problems he had to solve to earn the maximal number of points.
256 megabytes
import java.lang.*; import java.util.*; public class Cost{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] arr=new int[n]; int negCount=0; int negMax=-100; int posCount=0; for(int i=0; i<n; i++){ arr[i]=sc.nextInt(); if(arr[i]>0) posCount++; if(arr[i]<0){ negCount++; if(arr[i]>=negMax){ negMax=arr[i]; } } } for(int i=0; i<n; i++){ if(arr.length==1){ System.out.print(arr[0]); return; } if(negCount%2==1 && arr[i]==negMax){ negMax=-101; continue; } else{ if(arr[i]!=0){ System.out.print(arr[i]+" "); } else{ if(posCount==0 && (negCount==0 || negCount==1)){ System.out.print(0); return; } } } } } }
Java
["5\n1 2 -3 3 3", "13\n100 100 100 100 100 100 100 100 100 100 100 100 100", "4\n-2 -2 -2 -2"]
2 seconds
["3 1 2 3", "100 100 100 100 100 100 100 100 100 100 100 100 100", "-2 -2 -2 -2"]
null
Java 11
standard input
[ "greedy" ]
b11644953bdd1b92eb1b18c339a268a1
The first line contains an integer n (1 ≤ n ≤ 100) — the number of the suggested problems. The next line contains n space-separated integers ci ( - 100 ≤ ci ≤ 100) — the cost of the i-th task. The tasks' costs may coinсide.
1,400
Print space-separated the costs of the problems that needed to be solved to get the maximal possible number of points. Do not forget, please, that it was necessary to solve at least one problem. If there are several solutions to that problem, print any of them.
standard output
PASSED
63d8fb2722dc8e48d2109b3035d5b240
train_000.jsonl
1289646000
Vasya has gotten interested in programming contests in TCMCF+++ rules. On the contest n problems were suggested and every problem had a cost — a certain integral number of points (perhaps, negative or even equal to zero). According to TCMCF+++ rules, only accepted problems can earn points and the overall number of points of a contestant was equal to the product of the costs of all the problems he/she had completed. If a person didn't solve anything, then he/she didn't even appear in final standings and wasn't considered as participant. Vasya understood that to get the maximal number of points it is not always useful to solve all the problems. Unfortunately, he understood it only after the contest was finished. Now he asks you to help him: find out what problems he had to solve to earn the maximal number of points.
256 megabytes
import java.io.*; import java.util.*; public class MyClass { 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; } } public static void main(String args[]) { FastReader fr = new FastReader(); int n = fr.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i += 1) nums[i] = fr.nextInt(); if (n == 1) { System.out.println(nums[0]); return; } List<String> res = new ArrayList<>(); List<Integer> neg = new ArrayList<>(); for (int i = 0; i < n; i += 1) { if (nums[i] > 0) res.add("" + nums[i]); else if (nums[i] < 0) neg.add(nums[i]); } Collections.sort(neg, (e1, e2) -> Integer.compare(e1, e2)); int neg_size = neg.size() % 2 == 0 ? neg.size() : neg.size() - 1; for (int i = 0; i < neg_size; i += 1) res.add("" + neg.get(i)); if (res.size() == 0) System.out.println("0"); else System.out.println(String.join(" ", res)); } }
Java
["5\n1 2 -3 3 3", "13\n100 100 100 100 100 100 100 100 100 100 100 100 100", "4\n-2 -2 -2 -2"]
2 seconds
["3 1 2 3", "100 100 100 100 100 100 100 100 100 100 100 100 100", "-2 -2 -2 -2"]
null
Java 11
standard input
[ "greedy" ]
b11644953bdd1b92eb1b18c339a268a1
The first line contains an integer n (1 ≤ n ≤ 100) — the number of the suggested problems. The next line contains n space-separated integers ci ( - 100 ≤ ci ≤ 100) — the cost of the i-th task. The tasks' costs may coinсide.
1,400
Print space-separated the costs of the problems that needed to be solved to get the maximal possible number of points. Do not forget, please, that it was necessary to solve at least one problem. If there are several solutions to that problem, print any of them.
standard output
PASSED
241a0d31706e8ccfaa346484eef130b9
train_000.jsonl
1289646000
Vasya has gotten interested in programming contests in TCMCF+++ rules. On the contest n problems were suggested and every problem had a cost — a certain integral number of points (perhaps, negative or even equal to zero). According to TCMCF+++ rules, only accepted problems can earn points and the overall number of points of a contestant was equal to the product of the costs of all the problems he/she had completed. If a person didn't solve anything, then he/she didn't even appear in final standings and wasn't considered as participant. Vasya understood that to get the maximal number of points it is not always useful to solve all the problems. Unfortunately, he understood it only after the contest was finished. Now he asks you to help him: find out what problems he had to solve to earn the maximal number of points.
256 megabytes
import java.io.*; import java.util.*; //import java.math.*; // for bigInteger public class Main { public static void main(String args[]) throws Exception { InputReader sc = new InputReader(); PrintWriter out = new PrintWriter(System.out); int t=1; //t = sc.nextInt(); for(int tt=1;tt<=t;++tt) solve(tt,sc,out); out.close(); } static void solve(int t, InputReader sc, PrintWriter out) { int n = sc.nextInt(); int total = 0; int zeroCount = 0; List<Integer> negatives = new ArrayList<>(); for(int i=0;i<n;++i) { int x = sc.nextInt(); if(x>0) { out.print(x+" "); ++total; } else if(x==0) { ++zeroCount; } else { negatives.add(x); } } Collections.sort(negatives); int size = negatives.size(); if(size%2==0 && size!=0) { ++total; out.print(negatives.get(size-1)+" "); } for(int i=0;i<size-1;++i) { ++total; out.print(negatives.get(i)+" "); } if(total==0) { if(zeroCount!=0) { out.println(0); } else { out.println(negatives.get(0)); } } } public static class InputReader{ BufferedReader br; StringTokenizer st; InputReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){} } return st.nextToken(); } } /*private final static int m =(int)1e9+7; private static class Pair<T,V> { T first; V second; Pair(final T first, final V second) { this.first = first; this.second = second; } public boolean equals(Object o) { Pair given = (Pair)o; if(given.first == first && given.second == second) return true; return false; } public int hashCode() { long temp = (long)(first.hashCode())*31; temp = (temp+(long)second.hashCode())%m; return (int)temp; } }*/ public static void debug(final int[] ...var) { for(final int[] row : var) { debug(row); } } public static void debug(final long[] ...var) { for(final long[] row : var) { debug(row); } } public static void debug(final String[] ...var) { for(final String[] row : var) { debug(row); } } public static void debug(final double[] ...var) { for(final double[] row : var) { debug(row); } } public static void debug(final char[] ...var) { for(final char[] row : var) { debug(row); } } public static void debug(final int ...var) { for(final int i:var) System.err.print(i+" "); System.err.println(); } public static void debug(final String ...var) { for(final String i:var) System.err.print(i+" "); System.err.println(); } public static void debug(final double ...var) { for(final double i:var) System.err.print(i+" "); System.err.println(); } public static void debug(final long ...var) { for(final long i:var) System.err.print(i+" "); System.err.println(); } public static void debug(final char ...var) { for(final char c:var) System.err.print(c+" "); System.err.println(); } /* public static <T> void debug(T ...varargs) { // Warning // Heap Pollution might occur // this overrides even 1d and 2d array methods as it is an object... // + i am not using object based array like Integer[] // I am using int[] so that is a problem as i need Wrapper class as an argument for(T val:varargs) System.err.printf("%s ",val); System.err.println(); } */ }
Java
["5\n1 2 -3 3 3", "13\n100 100 100 100 100 100 100 100 100 100 100 100 100", "4\n-2 -2 -2 -2"]
2 seconds
["3 1 2 3", "100 100 100 100 100 100 100 100 100 100 100 100 100", "-2 -2 -2 -2"]
null
Java 11
standard input
[ "greedy" ]
b11644953bdd1b92eb1b18c339a268a1
The first line contains an integer n (1 ≤ n ≤ 100) — the number of the suggested problems. The next line contains n space-separated integers ci ( - 100 ≤ ci ≤ 100) — the cost of the i-th task. The tasks' costs may coinсide.
1,400
Print space-separated the costs of the problems that needed to be solved to get the maximal possible number of points. Do not forget, please, that it was necessary to solve at least one problem. If there are several solutions to that problem, print any of them.
standard output
PASSED
d1295423254d16fbd71a35f6f5a5aa06
train_000.jsonl
1549208100
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintStream out = System.out; TaskC taskC = new TaskC(); taskC.solve(in, out); } static class TaskC { int N, K, A, B; int[] positions; int lower(long x) { int l = 0, h = K-1; while (l <= h) { int mid = (l + h) / 2; if (positions[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } int upper(long x) { int l = 0, h = K-1; while (l <= h) { int mid = (l + h) / 2; if (positions[mid] <= x) l = mid + 1; else h = mid - 1; } return h; } long getMin(long start, long end) { long len = end - start + 1; int l = lower(start), h = upper(end); int count = h - l + 1; long pow = count == 0 ? A : B * count * len; if (start == end || count == 0) return pow; long mid = start + len / 2 - 1; long min = getMin(start, mid) + getMin(mid+1, end); return Math.min(min, pow); } void solve(InputReader in, PrintStream out) { N = in.nextInt(); K = in.nextInt(); A = in.nextInt(); B = in.nextInt(); positions = new int[K]; int bound = (int)Math.pow(2, N) - 1; for (int i = 0; i < K; i++) positions[i] = in.nextInt() - 1; Arrays.sort(positions); out.println(getMin(0, bound)); } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() {return Double.parseDouble(next());} } }
Java
["2 2 1 2\n1 3", "3 2 1 2\n1 7"]
1 second
["6", "8"]
NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.
Java 8
standard input
[ "binary search", "divide and conquer", "brute force", "math" ]
4695aa2b3590a0734ef2c6c580e471a9
The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.
1,700
Output one integer — the minimum power needed to destroy the avengers base.
standard output
PASSED
5ba433092447af00290ddc33f1241edc
train_000.jsonl
1549208100
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class p1111C { static int A; static int B; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] arr = new int[k]; for (int i = 0; i < k; i++) { arr[i] = Integer.parseInt(st.nextToken()); } out.println(solve(n, k,arr)); out.flush(); out.close(); } private static long solve(int n, int k, int[] arr) { Arrays.sort(arr); return rec(1, (1 << n)+1, 0, k, arr); } private static long rec(int from, int to, int pFrom, int pTo, int[] arr) { if(pFrom == pTo) return A; if(to - from == 1) return B * (pTo - pFrom); long res = (long)B * (pTo - pFrom) * (to - from); int mid = (to + from)/2; int pp = pFrom; while(pp < pTo && arr[pp] < mid) pp++; return Math.min(res, rec(from, mid, pFrom, pp, arr) + rec(mid, to, pp, pTo, arr)); } }
Java
["2 2 1 2\n1 3", "3 2 1 2\n1 7"]
1 second
["6", "8"]
NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.
Java 8
standard input
[ "binary search", "divide and conquer", "brute force", "math" ]
4695aa2b3590a0734ef2c6c580e471a9
The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.
1,700
Output one integer — the minimum power needed to destroy the avengers base.
standard output
PASSED
f28825224701e3e36cde47f6bb210961
train_000.jsonl
1549208100
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.stream.IntStream; public class C { public static void main(String[] args) throws IOException { try (Input input = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) { int n = input.nextInt(), k = input.nextInt(), a = input.nextInt(), b = input.nextInt(); int[] p = new int[k]; for (int i = 0; i < k; i++) { p[i] = input.nextInt(); } Arrays.sort(p); class Helper { private long rec(int from, int to, int pFrom, int pTo) { if (pTo - pFrom == 0) { return a; } if (to - from == 1) { return b * (pTo - pFrom); } long result = (long)b * (pTo - pFrom) * (to - from); int med = (from + to) / 2; int pp = pFrom; while (pp < pTo && p[pp] < med) { pp++; } result = Math.min(result, rec(from, med, pFrom, pp) + rec(med, to, pp, pTo)); return result; } } Helper helper = new Helper(); writer.println(helper.rec(1, (1 << n) + 1, 0, k)); } } interface Input extends Closeable { String next() throws IOException; default int nextInt() throws IOException { return Integer.parseInt(next()); } default long nextLong() throws IOException { return Long.parseLong(next()); } } private static class StandardInput implements Input { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer stringTokenizer; @Override public void close() throws IOException { reader.close(); } @Override public String next() throws IOException { if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } } }
Java
["2 2 1 2\n1 3", "3 2 1 2\n1 7"]
1 second
["6", "8"]
NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.
Java 8
standard input
[ "binary search", "divide and conquer", "brute force", "math" ]
4695aa2b3590a0734ef2c6c580e471a9
The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.
1,700
Output one integer — the minimum power needed to destroy the avengers base.
standard output
PASSED
4d898554b31175b0da53b3d8ec92e40b
train_000.jsonl
1549208100
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
256 megabytes
import java.util.Scanner; import java.util.TreeMap; public class C { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int k = s.nextInt(); int A = s.nextInt(); int B = s.nextInt(); TreeMap<Integer, Integer> positions = new TreeMap<>(); for (int i = 0; i < k; i++) { int x = s.nextInt() - 1; positions.put(x, positions.getOrDefault(x, 0) + 1); } TreeMap<Integer, Integer> acc = new TreeMap<>(); acc.put(-1, 0); int total = 0; for (Integer p : positions.keySet()) { total += positions.get(p); acc.put(p, total); } System.out.println(best(A, B, 0, (1 << n)-1, acc)); } private static long best(int A, int B, int l, int r, TreeMap<Integer, Integer> acc) { long a = acc.floorEntry(r).getValue() - acc.floorEntry(l-1).getValue(); if (a == 0) return A; if (r - l == 0) return B * a; int m = (l + r) / 2; return Math.min(B * a * (r - l + 1), best(A, B, l, m, acc) + best(A, B, m + 1, r, acc)); } }
Java
["2 2 1 2\n1 3", "3 2 1 2\n1 7"]
1 second
["6", "8"]
NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.
Java 8
standard input
[ "binary search", "divide and conquer", "brute force", "math" ]
4695aa2b3590a0734ef2c6c580e471a9
The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.
1,700
Output one integer — the minimum power needed to destroy the avengers base.
standard output
PASSED
5fd4707a802f8e8452ff9be1589e1a68
train_000.jsonl
1549208100
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.TreeSet; @SuppressWarnings("Duplicates") public class ProblemCnorm { public static long n, numAvengers, Acon, Bcon; public static ArrayList<Integer> pos; public static int numAv = 0; public static int cont = 0; public static Avenger low = new Avenger(0,-100); public static Avenger high = new Avenger(0,-100); public static TreeSet<Avenger> aveng; public static void main(String[] args) throws IOException{ Reader sc = new Reader(); PrintWriter pw = new PrintWriter(System.out); //Scanner sc = new Scanner(System.in); //BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); n = sc.nextInt(); numAvengers = sc.nextInt(); Acon = sc.nextInt(); Bcon = sc.nextInt(); //pos = new ArrayList<>((int)numAvengers); aveng = new TreeSet<>(); for (int i = 0; i < numAvengers; i++) { //pos.add(sc.nextInt()-1); aveng.add(new Avenger(sc.nextInt()-1,cont++)); } //Collections.sort(pos,Collections.reverseOrder()); long sol = solve(0,(int) Math.pow(2,n)); pw.print(sol+"\n"); pw.flush(); } public static int avengersIn(int start, int end){ low.pos = start; high.pos = end; return aveng.subSet(low,high).size(); } public static long solve(int start, int end){ if (start == end-1){ int numaven = avengersIn(start,end); if(numaven != 0){ return Bcon*numaven; }else { return Acon; } } int mid = start+(end-start)/2; long s1 = 0; int s1av = avengersIn(start,mid); if (s1av !=0){ s1 = solve(start, mid); } else { s1 = Acon; } long s2 = 0; int s2av = avengersIn(mid,end); if (s2av !=0){ s2 = solve(mid,end); } else { s2 = Acon; } long snapCost; if (s1av+s2av == 0){ snapCost = Acon; }else { snapCost=(s1av+s2av)*Bcon*(end-start); } snapCost = Math.min(snapCost,s1+s2); return snapCost; } static class Avenger implements Comparable<Avenger>{ int pos,id; public Avenger(int pos, int id) { this.pos = pos; this.id = id; } @Override public boolean equals(Object o) { Avenger avenger = (Avenger) o; if (pos != avenger.pos) return false; return id == avenger.id; } @Override public int hashCode() { int result = pos; result = 31 * result + id; return result; } @Override public int compareTo(Avenger o) { if (this.pos == o.pos) return Integer.compare(this.id,o.id); return Integer.compare(this.pos,o.pos); } } static class State { public long numAv, minCost; public State(long numAv, long minCost) { this.numAv = numAv; this.minCost = minCost; } } 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') break; 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(); } } }
Java
["2 2 1 2\n1 3", "3 2 1 2\n1 7"]
1 second
["6", "8"]
NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.
Java 8
standard input
[ "binary search", "divide and conquer", "brute force", "math" ]
4695aa2b3590a0734ef2c6c580e471a9
The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.
1,700
Output one integer — the minimum power needed to destroy the avengers base.
standard output
PASSED
5a691ad4fb1381cde5f65bae14626e95
train_000.jsonl
1549208100
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Scanner; public class CreativeSnap { static int N; static int A; static int B; static int[] POS; static int[] SUM; static Map<Integer, Integer> COUNT; public static void main(String[] args) { Locale.setDefault(Locale.US); final Scanner scanner = new Scanner(System.in); N = 1 << scanner.nextInt(); final int k = scanner.nextInt(); A = scanner.nextInt(); B = scanner.nextInt(); COUNT = new HashMap<>(); for (int i = 0; i < k; i++) { int pos = scanner.nextInt(); COUNT.compute(pos, (key, old) -> old != null ? 1 + old : 1); } POS = new int[COUNT.size()]; SUM = new int[COUNT.size() + 1]; int i = 0; for (int pos : COUNT.keySet()) POS[i++] = pos; Arrays.sort(POS); for (int j = 0; j < POS.length; j++) SUM[j + 1] = SUM[j] + COUNT.get(POS[j]); System.out.println(solve()); } static long solve() { return min(1, N); } static long min(int from, int to) { final int avgs = avgs(from, to); if (avgs == 0) return A; if (from == to) return cost(from, to, avgs); final int mid = (from + to) >> 1; return Math.min(cost(from, to, avgs), min(from, mid) + min(mid + 1, to)); } static long cost(int from, int to, int avgs) { return ((long) B) * avgs * (to - from + 1); } static int avgs(int from, int to) { int i = Arrays.binarySearch(POS, from); if (i < 0) i = -i - 1; int j = Arrays.binarySearch(POS, to); if (j < 0) j = -j - 2; return SUM[j + 1] - SUM[i]; } }
Java
["2 2 1 2\n1 3", "3 2 1 2\n1 7"]
1 second
["6", "8"]
NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.
Java 8
standard input
[ "binary search", "divide and conquer", "brute force", "math" ]
4695aa2b3590a0734ef2c6c580e471a9
The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.
1,700
Output one integer — the minimum power needed to destroy the avengers base.
standard output
PASSED
b5e6668263d0f2087e7979761991d82a
train_000.jsonl
1549208100
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Solution{ static int A; static int B; public static int bSearch(int[] a, int low, int high,int val){ int ans = high+1; while(low <= high){ int mid = (low+high)/2; if(a[mid] >= val){ ans = mid; high = mid-1; } else low = mid+1; } return ans; } public static long divideAndCon(int[] a, int low, int high, int l, int h){ if(l > h) return A; else if(low == high) return B*(h-l+1); int mid = (low+high)/2+1; int ind = bSearch(a,l,h,mid); long left = divideAndCon(a,low,mid-1,l,ind-1); long right = divideAndCon(a,mid,high,ind,h); return Math.min((long)B*(long)(h-l+1L)*(long)(high-low+1),left+right); } public static void main(String[] args)throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); int[] a = new int[k]; st = new StringTokenizer(br.readLine()); for(int i=0; i<k; i++) a[i] = Integer.parseInt(st.nextToken()); Arrays.sort(a); out.println(divideAndCon(a,1,(1<<n),0,k-1)); out.close(); } }
Java
["2 2 1 2\n1 3", "3 2 1 2\n1 7"]
1 second
["6", "8"]
NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.
Java 8
standard input
[ "binary search", "divide and conquer", "brute force", "math" ]
4695aa2b3590a0734ef2c6c580e471a9
The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.
1,700
Output one integer — the minimum power needed to destroy the avengers base.
standard output
PASSED
4f1b55b638cc26e5a76bc15f8f0c6464
train_000.jsonl
1549208100
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ static long A; static long B; public static int bSearch(int[] a, int low, int high,int val){ int ans = high+1; while(low <= high){ int mid = (low+high)/2; if(a[mid] >= val){ ans = mid; high = mid-1; } else low = mid+1; } return ans; } public static long divideAndCon(int[] a, int low, int high, int l, int h){ if(l > h) return A; else if(low == high) return B*(h-l+1); int mid = (low+high)/2+1; int ind = bSearch(a,l,h,mid); long left = divideAndCon(a,low,mid-1,l,ind-1); long right = divideAndCon(a,mid,high,ind,h); return Math.min(B*(h-l+1)*(high-low+1),left+right); } public static void main(String[] args)throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); A = Long.parseLong(st.nextToken()); B = Long.parseLong(st.nextToken()); int[] a = new int[k]; st = new StringTokenizer(br.readLine()); for(int i=0; i<k; i++) a[i] = Integer.parseInt(st.nextToken()); Arrays.sort(a); out.println(divideAndCon(a,1,(1<<n),0,k-1)); out.close(); } }
Java
["2 2 1 2\n1 3", "3 2 1 2\n1 7"]
1 second
["6", "8"]
NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.
Java 8
standard input
[ "binary search", "divide and conquer", "brute force", "math" ]
4695aa2b3590a0734ef2c6c580e471a9
The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.
1,700
Output one integer — the minimum power needed to destroy the avengers base.
standard output
PASSED
cb514b4423b83143c45b29c395e83058
train_000.jsonl
1549208100
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.TreeMap; import java.util.TreeSet; public class Solution2 implements Runnable { static final long MAX = 464897L; static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } 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 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 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 String readString() { 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 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 readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Solution2(),"Solution2",1<<26).start(); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long lcm(long a,long b) { return (a*b)/gcd(a,b); } int maxn = 1000005; long MOD = 10000000007L; long prime = 29; Long[] arr; public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); a= sc.nextLong(); b = sc.nextLong(); arr = new Long[k]; for(int i = 0;i < k;i++) { arr[i] = sc.nextLong(); } Arrays.sort(arr); int one = (int)power(2,n,MOD); long fans = rec(1,one); w.println(fans); w.close(); } long a; long b; long rec(int l,int r) { if(l == r) { long count = count(l,r); long ans1 = b * count * (1); if(ans1 == 0) { return a; } return ans1; } long count = count(l,r); long ans1 = b * count * (r - l + 1); if(ans1 == 0) { return a; } int mid = (l + r)/2; long ans2 = rec(l,mid); long ans3 = rec(mid+1,r); long ans4 = ans2 + ans3; if(ans1 <= ans4) { return ans1; }else { return ans4; } } long count(int start,int end) { int l = 0; int r = arr.length-1; int ans1 = -1; while(l <= r) { int mid = (l + r)/2; if(arr[mid] <= end) { ans1 = mid; l = mid + 1; }else { r = mid - 1; } } l = 0; r = arr.length-1; int ans2 = -1; while(l <= r) { int mid = (l + r)/2; if(arr[mid] >= start) { ans2 = mid; r = mid - 1; }else { l = mid + 1; } } if(ans1 == -1 || ans2 == -1 || ans2 > ans1) { return 0; } int tans = ans1 - ans2 + 1; if(tans <= 0) { return 0; } return tans; } static long power(long a,long b,long mod) { long ans = 1; a = a % mod; while(b != 0) { if(b % 2 == 1) { ans = (ans * a) % mod; } a = (a * a) % mod; b = b/2; } return ans; } class Pair implements Comparable<Pair>{ int a; int b; int c; Pair(int a,int b,int c){ this.b = b; this.a = a; this.c = c; } public boolean equals(Object o) { Pair p = (Pair)o; return this.a == p.a && this.b == this.b; } public int hashCode(){ return Long.hashCode(a)*27 + Long.hashCode(b)*31; } public int compareTo(Pair p) { return Long.compare(this.a,p.a); } } }
Java
["2 2 1 2\n1 3", "3 2 1 2\n1 7"]
1 second
["6", "8"]
NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.
Java 8
standard input
[ "binary search", "divide and conquer", "brute force", "math" ]
4695aa2b3590a0734ef2c6c580e471a9
The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.
1,700
Output one integer — the minimum power needed to destroy the avengers base.
standard output
PASSED
1d6545123f4b49c83746d911189981c0
train_000.jsonl
1549208100
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class C1111 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int k = scanner.nextInt(); int A = scanner.nextInt(); int B = scanner.nextInt(); int[] arr = new int[k]; for(int i=0;i<k;i++){ int a = scanner.nextInt(); arr[i] = a; } //位置排序 Arrays.sort(arr); //总长度 long length = 1; while (n-->=1){ length *= 2; } long power = getPower(arr,k,1,length,A,B); System.out.println(power); } //递归切开 private static long getPower(int[] arr,int k, long l, long r, int A, int B){ long result = 0; //计算一段区间内的复仇者 long count = upperBound(arr,0,k,r)-lowerBound(arr,0,k,l); if(count < 0){ count = 0; } if(count == 0){ return A; } else{ result = B*count*(r-l+1); } if(r - l >= 1){ long m = l+(r-l+1)/2; result = Math.min(result, getPower(arr,k,l,m-1,A,B)+getPower(arr,k,m,r,A,B)); } return result; } private static int lowerBound(int [] arr,int l,int r,long target){ while(l<r){ int m = l + (r - l) / 2; if(arr[m]>=target){ r = m; } else{ l = m +1; } } return l; } private static int upperBound(int [] arr,int l,int r,long target){ while(l<r){ int m = l + (r - l) / 2; if(arr[m]<=target) { l = m+1; } else { r = m; } } return l; } }
Java
["2 2 1 2\n1 3", "3 2 1 2\n1 7"]
1 second
["6", "8"]
NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.
Java 8
standard input
[ "binary search", "divide and conquer", "brute force", "math" ]
4695aa2b3590a0734ef2c6c580e471a9
The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.
1,700
Output one integer — the minimum power needed to destroy the avengers base.
standard output
PASSED
221545a1968d4b8cc70718b5d51f354d
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.io.*; import java.util.*; public class R150qB { @SuppressWarnings("unchecked") public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int h = in.nextInt(); int t = in.nextInt(); HashSet<Integer> set[] = new HashSet[n + 1]; for (int i = 1; i <= n; i++) set[i] = new HashSet<Integer>(); int a[] = new int[m + 1]; int b[] = new int[m + 1]; for (int i = 1; i <= m; i++) { a[i] = in.nextInt(); b[i] = in.nextInt(); set[a[i]].add(b[i]); set[b[i]].add(a[i]); } boolean f = false; int u = -1, v = -1; for (int i = 1; i <= m; i++) { if(set[a[i]].size() > set[b[i]].size()) { int temp = a[i]; a[i] = b[i]; b[i] = temp; } int x = set[a[i]].size() - 1; int y = set[b[i]].size() - 1; int c = 0; boolean canSearch = (x >= t && y >= h) || (x >= h && y >= t); if(canSearch) { for (int neigh : set[a[i]]) { if(neigh == b[i]) continue; if(set[b[i]].contains(neigh)) { x--; y--; c++; } } } if(Math.max(0, h - x) + Math.max(0, t - y) <= c) { f = true; u = a[i]; v = b[i]; break; } if(Math.max(0, t - x) + Math.max(0, h - y) <= c) { f = true; u = b[i]; v = a[i]; break; } } if(!f) w.println("NO"); else { w.println("YES"); w.println(u + " " + v); List<Integer> A = new ArrayList<Integer>(); List<Integer> B = new ArrayList<Integer>(); List<Integer> C = new ArrayList<Integer>(); for (int neigh : set[u]) { if (neigh != v) { if (set[v].contains(neigh)) C.add(neigh); else A.add(neigh); } } for (int neigh : set[v]) { if (neigh != u) { if (!set[u].contains(neigh)) B.add(neigh); } } int extraCnt = 0; for (int j = 0; j < Math.min(A.size(), h); j++) w.print(A.get(j) + " "); for (int j = 0; j < h - A.size(); j++) w.print(C.get(extraCnt++) + " "); w.println(); for (int j = 0; j < Math.min(B.size(), t); j++) w.print(B.get(j) + " "); for (int j = 0; j < t - B.size(); j++) w.print(C.get(extraCnt++) + " "); w.println(); } w.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 8
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
566e3aaf62fa56620b382c97cd6c3969
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.io.*; import java.util.*; public class Main { void solve() { int n = in.nextInt(); int m = in.nextInt(); int h = in.nextInt(); int t = in.nextInt(); ArrayList<Integer>[] g = new ArrayList[n]; for (int i = 0; i < n; ++i) { g[i] = new ArrayList<>(); } for (int i = 0; i < m; ++i) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; g[x].add(y); g[y].add(x); } int[] p = new int[n]; Arrays.fill(p, -1); for (int x = 0; x < n; ++x) { int degX = g[x].size(); for (int y : g[x]) { p[y] = x; } for (int y : g[x]) { int degY = g[y].size(); int both = 0, good = 0; for (int i = 0; i < g[y].size() && i <= h + t + 1; ++i) { int z = g[y].get(i); if (z == x) { continue; } if (p[z] == x) { ++both; } else { ++good; } } int curT = t; curT = Math.max(0, curT - good); int by = Math.min(both, curT); curT -= by; both -= by; if (curT == 0) { if (degX - 1 - by >= h) { out.println("YES"); out.println((x + 1) + " " + (y + 1)); ArrayList<Integer> ansT = new ArrayList<>(); ArrayList<Integer> ansH = new ArrayList<>(); boolean[] used = new boolean[n]; Arrays.fill(used, false); for (int z : g[y]) { if (z == x || p[z] == x) { continue; } if (t > 0) { ansT.add(z + 1); --t; } } for (int z : g[y]) { if (z == x || p[z] != x) { continue; } if (t > 0) { ansT.add(z + 1); used[z] = true; --t; } } for (int z : g[x]) { if (z == y || used[z]) { continue; } if (h > 0) { ansH.add(z + 1); --h; } } for (int i = 0; i < ansH.size(); ++i) { out.print(ansH.get(i) + " "); } out.println(); for (int i = 0; i < ansT.size(); ++i) { out.print(ansT.get(i) + " "); } return; } } } for (int y : g[x]) { p[y] = -1; } } out.println("NO"); } void run() { in = new InputReader(System.in); out = new PrintWriter(System.out); solve(); out.close(); } InputReader in; PrintWriter out; class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); st = null; } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } } public static void main(String[] args) { new Main().run(); } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 8
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
3fc68888663032eb8ea86bd1d7d33165
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class test{ // ArrayList<Integer> lis = new ArrayList<Integer>(); // ArrayList<String> lis = new ArrayList<String>(); // PriorityQueue<Integer> que = new PriorityQueue<Integer>(); // Stack<Integer> que = new Stack<Integer>(); // static long sum=0; // int a,b,c; // 1000000007 (10^9+7) //static int mod = 1000000007; static int mod = 1000000009,r=0,k; // static int dx[]={1,-1,0,0}; // static int dy[]={0,0,1,-1}; // static int dx[]={1,-1,0,0,1,1,-1,-1}; // static int dy[]={0,0,1,-1,1,-1,1,-1}; //static long H,L; //static Set<Integer> set = new HashSet<Integer>(); public static void main(String[] args) throws Exception, IOException{ //String line=""; throws Exception, IOException //(line=br.readLine())!=null //Scanner sc =new Scanner(System.in); // !!caution!! int long // Reader sc = new Reader(System.in); // while( ){ // int n=sc.nextInt(),m=sc.nextInt();//a[]=new int[n],b[]=new int[n]; int n=sc.nextInt(),m=sc.nextInt(),h=sc.nextInt(),t=sc.nextInt(); int d[]=new int[n],f[][]=new int[m][3]; ArrayList<Integer> e[] = new ArrayList [n]; for(int i=0; i<n ;i++)e[i]=new ArrayList<Integer>(); for(int i=0; i<m ;i++){ int a=sc.nextInt()-1; int b=sc.nextInt()-1; f[i][0]=a;f[i][1]=b; d[a]++; d[b]++; e[a].add(b); e[b].add(a);} for(int i=0; i<m ;i++){ f[i][2]=d[f[i][0]]+d[f[i][1]]; } sort(f,new TheComparator()); //for(int i=0; i<m ;i++)db(f[i][2]); int re=-1; for(int i=0; i<m ;i++){ if( d[f[i][0]]+d[f[i][1]]<h+t )break; if( h+t+1<=d[f[i][0]] && h+t+1<=d[f[i][1]]){ re=i;break; } if( h+t+1<=d[f[i][0]] && min(h,t)+1<=d[f[i][1]] ){ re=i;break; } if( h+t+1<=d[f[i][1]] && min(h,t)+1<=d[f[i][0]] ){ re=i;break; } if( h+t+1<=d[f[i][0]] && d[f[i][1]]<min(h,t)+1 ){ continue; } if( h+t+1<=d[f[i][1]] && d[f[i][0]]<min(h,t)+1 ){ continue; } boolean b[]=new boolean[100001]; int c=0; for(int s=0; s<e[f[i][0]].size(); s++){ b[ e[f[i][0]].get(s) ]=true; } for(int s=0; s<e[f[i][1]].size(); s++){ boolean k=b[ e[f[i][1]].get(s) ]; if(k)c++;} int ca=max(h,t)-max(d[f[i][1]],d[f[i][0]]) +c+1; int cb=min(h,t)-min(d[f[i][1]],d[f[i][0]]) +c+1; if( 0<ca ){ c-=ca; } if( 0<cb ){ c-=cb; } if(0<=c){ re=i;break; } } if(re<0){ System.out.println("NO"); } else{ ArrayList<Integer> lis = new ArrayList<Integer>(); int a=f[re][0],b=f[re][1]; if(t<=h){ if( d[a]<d[b] ){ int k=a; a=b; b=k; } } else if( d[b]<=d[a] ){ int k=a; a=b; b=k; } boolean bb[]=new boolean[100001]; boolean x[]=new boolean[100001]; for(int s=0; s<e[a].size(); s++){ bb[ e[a].get(s) ]=true; } for(int s=0; s<e[b].size(); s++){ boolean k=bb[ e[b].get(s) ]; if(k){lis.add(e[b].get(s)); x[e[b].get(s)]=true;} } x[b]=x[a]=true; // if(n==5687){ System.out.println(d[a]+" "+d[b]+" "+c); } System.out.println("YES"); System.out.println(1+a+" "+(1+b)); String q=""; for(int s=0; s<e[a].size() && 0<h; s++){ if( !x[e[a].get(s)] ){System.out.print(q+(e[a].get(s)+1)); q=" "; h--; } } int p=0; while(0<h){ System.out.print(q+(lis.get(p)+1));h--; q=" "; p++; } System.out.println(); q=""; for(int s=0; s<e[b].size()&& 0<t; s++){ if( !x[e[b].get(s)] ){System.out.print(q+(e[b].get(s)+1));q=" "; t--; } } while(0<t){ System.out.print(q+(lis.get(p)+1));t--; q=" "; p++; } } } static void db(Object... os){ System.err.println(Arrays.deepToString(os)); } } class Reader { private BufferedReader x; private StringTokenizer st; public Reader(InputStream in) { x = new BufferedReader(new InputStreamReader(in)); st = null; } public String nextString() throws IOException { while( st==null || !st.hasMoreTokens() ) st = new StringTokenizer(x.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextString()); } public long nextLong() throws IOException { return Long.parseLong(nextString()); } public double nextDouble() throws IOException { return Double.parseDouble(nextString()); } } class TheComparator implements Comparator<Object> { public int compare( Object a, Object b ) { int[] strA = ( int[] ) a; int[] strB = ( int[] ) b; return ( strB[ 2 ]-strA[ 2 ] ); } } /*class P implements Comparable<P>{ // implements Comparable<P> int a,b,c; P(int a,int b,int c){ this.a=a; this.b=b; this.c=c; } public int compareTo(P x){ return b-x.b; } } */
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 6
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
1af8d6866e6bc32df38bc67e25f251ac
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeSet; public class BB { public static void main(String[] args) { HashSet<Point> se=new HashSet<Point>(); Random rand=new Random(); InputReader r = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = r.nextInt(); int m = r.nextInt(); int h = r.nextInt(); int t = r.nextInt(); // int n=100000; // int m=100000; // int h=20; // int t=20; HashSet<Integer>[] adj = new HashSet[n]; for (int i = 0; i < adj.length; i++) { adj[i] = new HashSet<Integer>(); } Point[] arr = new Point[m]; for (int i = 0; i < m; i++) { // if(i==m-1){ // int from =0; // int to = 1; // adj[from].add(to); // adj[to].add(from); // continue; // } int from = r.nextInt() - 1; int to = r.nextInt() - 1; // int from =0; // int to = rand.nextInt(100000); // if(i<m/2){ // from =1; // to = rand.nextInt(100000); // } arr[i] = new Point(from, to); adj[from].add(to); adj[to].add(from); // Point p=new Point(from,to); // if(from==to||se.contains(p)){ // i--; // continue; // } // se.add(p); } // for(int i=0;i<m;i++){ // int index = rand.nextInt(m); // Point temp = arr[index]; // arr[index]=arr[i]; // arr[i]=temp; // } TreeSet<Integer> set = new TreeSet<Integer>(); int max=t+h+20; // int[] set=new int[n+10]; int index=0; for (int i = m-1; i >=0; i--) { // System.out.println(i); // System.out.println(arr[i]); // index=0; set.clear(); int u = arr[i].x; int v = arr[i].y; int uniqueU = 0, uniqueV = 0, common = 0; for (int x : adj[u]) { if (!adj[v].contains(x) && x != v) { uniqueU++; } else if (adj[v].contains(x) && x != v) { set.add(x); if (set.size() == h + t + 20) { break; } } if(uniqueU==max){ break; } } for (int x : adj[v]) { if (!adj[u].contains(x) && x != u) { uniqueV++; }else if (adj[u].contains(x) && x != u) { set.add(x); if (set.size() == h + t + 20) { break; } } if(uniqueV==max){ break; } } common = set.size(); int remH = Math.max(0, h - uniqueU); int remT = Math.max(0, t - uniqueV); if (common >= remH + remT) { out.println("YES"); out.println((u + 1) + " " + (v + 1)); uniqueU = 0; uniqueV = 0; for (int x : adj[u]) { if (!adj[v].contains(x) && x != v) { out.print((x + 1) + " "); uniqueU++; } if (uniqueU == h) { break; } } while (uniqueU < h) { out.print((set.pollFirst() + 1) + " "); uniqueU++; } out.println(); for (int x : adj[v]) { if (!adj[u].contains(x) && x != u) { out.print((x + 1) + " "); uniqueV++; } if (uniqueV == t) { break; } } while (uniqueV < t) { out.print((set.pollFirst() + 1) + " "); uniqueV++; } out.println(); out.close(); return; } remH = Math.max(0, h - uniqueV); remT = Math.max(0, t - uniqueU); if (common >= remH + remT) { out.println("YES"); out.println((v + 1) + " " + (u + 1)); uniqueU = 0; uniqueV = 0; for (int x : adj[v]) { if (!adj[u].contains(x) && x != u) { out.print((x + 1) + " "); uniqueU++; } if (uniqueU == h) { break; } } while (uniqueU < h) { out.print((set.pollFirst() + 1) + " "); uniqueU++; } out.println(); for (int x : adj[u]) { if (!adj[v].contains(x) && x != v) { out.print((x + 1) + " "); uniqueV++; } if (uniqueV == t) { break; } } while (uniqueV < t) { out.print((set.pollFirst() + 1) + " "); uniqueV++; } out.println(); out.close(); return; } } out.println("NO"); out.close(); } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 6
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
9d95b0a61e563506b8504f9db772d1a6
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeSet; public class Hydra { public static void main(String[] args) { Random rand = new Random(); InputReader r = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = r.nextInt(); int m = r.nextInt(); int h = r.nextInt(); int t = r.nextInt(); HashSet<Integer>[] adj = new HashSet[n]; for (int i = 0; i < adj.length; i++) { adj[i] = new HashSet<Integer>(); } Point[] arr = new Point[m]; for (int i = 0; i < m; i++) { int from = r.nextInt() - 1; int to = r.nextInt() - 1; if(rand.nextDouble()<0.5) arr[i] = new Point(to, from); else arr[i] = new Point(from,to); } // for (int i = 0; i < m; i++) { // int index = rand.nextInt(m - i) + i; // Point temp = arr[index]; // arr[index] = arr[i]; // arr[i] = temp; // } for (int i = 0; i < m; i++) { int from = arr[i].x; int to = arr[i].y; adj[from].add(to); adj[to].add(from); } TreeSet<Integer> set = new TreeSet<Integer>(); int max = Math.max(t, h) + 1; for (int i = m - 1; i >= 0; i--) { int u = arr[i].x; int v = arr[i].y; set.clear(); int uniqueU = 0, uniqueV = 0, common = 0; for (int x : adj[u]) { if (!adj[v].contains(x) && x != v) { uniqueU++; } else if (adj[v].contains(x) && x != v) { set.add(x); } if (set.size() == h + t + 2) { break; } if (uniqueU == max) { break; } } for (int x : adj[v]) { if (!adj[u].contains(x) && x != u) { uniqueV++; } else if (adj[u].contains(x) && x != u) { set.add(x); } if (set.size() == h + t + 2) { break; } if (uniqueV == max) { break; } } common = set.size(); int remH = Math.max(0, h - uniqueU); int remT = Math.max(0, t - uniqueV); if (common >= remH + remT) { out.println("YES"); out.println((u + 1) + " " + (v + 1)); uniqueU = 0; uniqueV = 0; for (int x : adj[u]) { if (!adj[v].contains(x) && x != v) { out.print((x + 1) + " "); uniqueU++; } if (uniqueU == h) { break; } } while (uniqueU < h) { out.print((set.pollFirst() + 1) + " "); uniqueU++; } out.println(); for (int x : adj[v]) { if (!adj[u].contains(x) && x != u) { out.print((x + 1) + " "); uniqueV++; } if (uniqueV == t) { break; } } while (uniqueV < t) { out.print((set.pollFirst() + 1) + " "); uniqueV++; } out.println(); out.close(); return; } remH = Math.max(0, h - uniqueV); remT = Math.max(0, t - uniqueU); if (common >= remH + remT) { out.println("YES"); out.println((v + 1) + " " + (u + 1)); uniqueU = 0; uniqueV = 0; for (int x : adj[v]) { if (!adj[u].contains(x) && x != u) { out.print((x + 1) + " "); uniqueU++; } if (uniqueU == h) { break; } } while (uniqueU < h) { out.print((set.pollFirst() + 1) + " "); uniqueU++; } out.println(); for (int x : adj[u]) { if (!adj[v].contains(x) && x != v) { out.print((x + 1) + " "); uniqueV++; } if (uniqueV == t) { break; } } while (uniqueV < t) { out.print((set.pollFirst() + 1) + " "); uniqueV++; } out.println(); out.close(); return; } } out.println("NO"); out.close(); } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 6
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
57afa970a0a03b5b59927045e5eaf3e6
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out)); StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int n = Integer.parseInt(tokenizer.nextToken())+1; int m = Integer.parseInt(tokenizer.nextToken()); int h = Integer.parseInt(tokenizer.nextToken()); int t = Integer.parseInt(tokenizer.nextToken()); int[] degrees = new int[n]; int[][] edges = readEdges(n, m, reader, degrees); int foundX = -1, foundY = -1; for(int i = 0;i < n && foundX == -1;i++) if(degrees[i] >= h+1 || degrees[i] >= t+1) for(int j : edges[i]) if(degrees[j] >= h+1 || degrees[j] >= t+1) if(degrees[i] >= h+t+1 || degrees[j] >= h+t+1) { foundX = i; foundY = j; break; } for(int i = 0;i < n && foundX == -1;i++) if(degrees[i] >= h+1 || degrees[i] >= t+1) if(degrees[i] < h+t+1) for(int j : edges[i]) if(degrees[j] >= h+1 && degrees[i] >= t+1 || degrees[j] >= t+1 && degrees[i] >= h+1) if(degrees[j] < h+t+1) { int common = 0; int atX = 0; int atY = 0; while (atX < edges[i].length && atY < edges[j].length) { if(edges[i][atX] == edges[j][atY]) { common++; atX++; } else if(edges[i][atX] < edges[j][atY]) atX++; else atY++; } if(degrees[i]+degrees[j]-2-common >= h+t) { foundX = i; foundY = j; break; } } if(foundX == -1) { writer.println("NO"); } else { writer.println("YES"); if(degrees[foundX] < h+1 || degrees[foundY] < t+1) { int tmp = foundX; foundX = foundY; foundY = tmp; } writer.println(foundX + " " + foundY); boolean[] common = new boolean[n]; int atX = 0; int atY = 0; while (atX < edges[foundX].length && atY < edges[foundY].length) { if(edges[foundX][atX] == edges[foundY][atY]) { common[edges[foundX][atX]] = true; atX++; } else if(edges[foundX][atX] < edges[foundY][atY]) atX++; else atY++; } boolean[] used = new boolean[n]; boolean first = true; int rem = h; for(int i : edges[foundX]) if(i != foundY) if(!common[i]) { if(!first) writer.print(" "); first = false; rem--; writer.print(i); if(rem == 0) break; } if(rem > 0) for(int i : edges[foundX]) if(common[i]) { if(!first) writer.print(" "); first = false; rem--; writer.print(i); used[i] = true; if(rem == 0) break; } writer.println(); first = true; rem = t; for(int i : edges[foundY]) if(i != foundX) if(!common[i]) { if(!first) writer.print(" "); first = false; rem--; writer.print(i); if(rem == 0) break; } if(rem > 0) for(int i : edges[foundY]) if(common[i] && !used[i]) { if(!first) writer.print(" "); first = false; rem--; writer.print(i); if(rem == 0) break; } writer.println(); } writer.flush(); writer.close(); } private static int[][] readEdges(int n, int m, BufferedReader reader, int[] degrees) throws Exception { ArrayList<Integer>[] edges = new ArrayList[n]; for(int i = 0;i < n;i++) edges[i] = new ArrayList<Integer>(); for(int i = 0;i < m;i++) { StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int a = Integer.parseInt(tokenizer.nextToken()); int b = Integer.parseInt(tokenizer.nextToken()); edges[a].add(b); edges[b].add(a); degrees[a]++; degrees[b]++; } int[][] res = new int[n][]; for(int i = 0;i < n;i++) { res[i] = new int[edges[i].size()]; for(int j = 0;j < res[i].length;j++) res[i][j] = edges[i].get(j); Arrays.sort(res[i]); } return res; } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 6
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
f0e81b594628c094bd938a7a618484de
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.StringTokenizer; public class B { static StringTokenizer st; static BufferedReader in; public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int m = nextInt(); int h = nextInt(); int t = nextInt(); ArrayList<Integer>[]ages = new ArrayList[n+1]; Set<Integer>[]set = new HashSet[n+1]; int[]v1 = new int[2*m+1], v2 = new int[2*m+1]; for (int i = 1; i <= n; i++) { ages[i] = new ArrayList<Integer>(); set[i] = new HashSet<Integer>(); } long s1 = System.currentTimeMillis(); for (int i = 1; i <= m; i++) { v1[i] = nextInt(); v2[i] = nextInt(); v1[i+m] = v2[i]; v2[i+m] = v1[i]; ages[v1[i]].add(v2[i]); ages[v2[i]].add(v1[i]); set[v1[i]].add(v2[i]); set[v2[i]].add(v1[i]); } for (int i = 1; i <= 2*m; i++) { int tem_size = 0; if (set[v1[i]].size() > set[v2[i]].size()) { for (Integer v : set[v2[i]]) { if (set[v1[i]].contains(v)) tem_size++; } } else { for (Integer v : set[v1[i]]) { if (set[v2[i]].contains(v)) tem_size++; } } int hh = ages[v1[i]].size()-1-tem_size, tt = ages[v2[i]].size()-1-tem_size; if (tem_size >= h-hh+t-tt && tem_size >= h-hh && tem_size >= t-tt) { pw.println("YES"); pw.println(v1[i]+" "+v2[i]); Set<Integer> temp = new HashSet<Integer>(); temp.addAll(set[v1[i]]); temp.retainAll(set[v2[i]]); for (int v : ages[v1[i]]) { if (h==0) break; if (v==v2[i] || temp.contains(v)) continue; h--; pw.print(v+" "); } boolean[]used = new boolean[n+1]; for (int v : temp) { if (h==0) break; h--; used[v] = true; pw.print(v+" "); } pw.println(); for (int v : ages[v2[i]]) { if (t==0) break; if (v==v1[i] || temp.contains(v)) continue; t--; pw.print(v+" "); } for (int v : temp) { if (t==0) break; if (used[v]) continue; t--; used[v] = true; pw.print(v+" "); } long s2 = System.currentTimeMillis(); // pw.println((s2-s1)/1000.0); pw.close(); return; } } long s2 = System.currentTimeMillis(); // System.out.println((s2-s1)/1000.0); pw.println("NO"); pw.close(); } private static int nextInt() throws IOException{ return Integer.parseInt(next()); } private static long nextLong() throws IOException{ return Long.parseLong(next()); } private static double nextDouble() throws IOException{ return Double.parseDouble(next()); } private static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 6
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
81a596f8e67de7b03c3c497e3ed08d86
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.io.* ; import java.util.*; import static java.lang.Math.* ; import static java.util.Arrays.* ; public class B { public static void main(String[] args) throws IOException { // out.println("300 597 100 100"); // for( int i = 2; i < 300; i++){ // out.println(1 + " " + (1+i)); // out.println(2 + " " + (1+i)); // // } // out.println("1 2"); new B().solveProblem(); out.close(); } static Input in = new Input() ; static PrintStream out = new PrintStream(new BufferedOutputStream(System.out)); static Output out2 = new Output(out) ; ArrayList<Integer>[] b ; int n,h,t; Random rr = new Random(); int[] used ; int[] used2 ; public void solveProblem() throws IOException { n = in.nextInt(); int m = in.nextInt(); h = in.nextInt(); t = in.nextInt(); used = new int[n]; used2 = new int[n]; fill(used,-1); fill(used2,-1); b = new ArrayList[n]; for( int i = 0; i < n ; i++) b[i] = new ArrayList<Integer>(); for( int i = 0; i < m ; i++){ int u = in.nextInt()-1; int v = in.nextInt()-1; // int u = rr.nextInt(10000); // int v = rr.nextInt(10000); b[u].add(v); b[v].add(u); } int t = 0; for( int u = 0; u < n ; u++){ for( int v : b[u]){ if( ok(t,u,v) ){ maak(t,u,v); return; } t++; } } out.println("NO"); } private void maak(int ind, int head, int tail) { int[] a = new int[n]; for( int u : b[head]) a[u]++; for( int u : b[tail]) a[u]++; ArrayList<Integer> heads = new ArrayList<Integer>(); ArrayList<Integer> tails = new ArrayList<Integer>(); for( int i = 0; i < b[head].size() && heads.size() < h; i++){ int v = b[head].get(i); if( v != tail && a[v] < 2 ) heads.add(v+1); } for( int i = 0; i < b[tail].size() && tails.size() < t ; i++){ int v = b[tail].get(i); if( v != head && a[v] < 2 ) tails.add(v+1); } for( int i = 0; i < n ; i++){ if( a[i] == 2){ if( heads.size() < h) heads.add(i+1); else if( tails.size() < t) tails.add(i+1); } } head++;tail++; out.println("YES\n" + head + " " + tail); for( int i = 0; i < h - 1; i++){ out.print(heads.get(i)+ " "); } out.println(heads.get(h-1)); for( int i = 0; i < t - 1; i++){ out.print(tails.get(i)+ " "); } out.println(tails.get(t-1)); } boolean ok( int ind, int head, int tail){ for( int i = 0; i < b[head].size() && i < t + h + 1; i++){ int v = b[head].get(i); if( v != tail) used[v] = ind; } int gem = 0; for( int i = 0; i < b[tail].size() && i < t + h + 1; i++){ int v = b[tail].get(i); if( v != head && used[v] == ind){ gem++; used2[v] = ind; } } int vangem = max(0,h-(b[head].size()-1-gem)); int vangem2 = max(0,t-(b[tail].size()-1-gem)); return vangem + vangem2 <= gem; } static void p( Object ...p){ System.out.println(Arrays.deepToString(p)); } static class Input { BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokens ; public int nextInt(){ return Integer.parseInt(next()) ; } public int[] nextInt(int n ){ int[] res = new int[n] ; for( int i = 0 ; i < n ; i++ ) res[i] = nextInt() ; return res ; } public long nextLong(){ return Long.parseLong(next()) ; } public long[] nextLong(int n ){ long[] res = new long[n] ; for( int i = 0 ; i < n ; i++ ) res[i] = nextLong() ; return res ; } public double nextDouble(){ return Double.parseDouble(next()) ; } public String next(){ try{ while( tokens == null || !tokens.hasMoreTokens() ) tokens = new StringTokenizer(buf.readLine()) ; }catch( Exception e ){ e.printStackTrace() ; } return tokens.nextToken() ; } public String nextLine(){ try { return buf.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } } static class Output { PrintStream out ; public Output(PrintStream out) { this.out = out; } void wr( int[] rij ){ for( int i = 0 ; i < rij.length - 1 ; i++ ) out.print(rij[i] + " ") ; out.println(rij[rij.length-1]); } void wr( long[] rij ){ for( int i = 0 ; i < rij.length - 1 ; i++ ) out.print(rij[i] + " ") ; out.println(rij[rij.length-1]); } void wr( char[] rij){ out.println(new String(rij)) ; } } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 6
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
88aeba51515173af8b625530dd1d4098
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Comparator; import java.io.OutputStream; import java.util.RandomAccess; import java.io.PrintWriter; import java.util.AbstractList; import java.io.Writer; import java.util.List; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.util.ArrayList; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov ([email protected]) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int count = in.readInt(); int edgeCount = in.readInt(); int headCount = in.readInt(); int tailCount = in.readInt(); int[] from = new int[edgeCount]; int[] to = new int[edgeCount]; IOUtils.readIntArrays(in, from, to); MiscUtils.decreaseByOne(from, to); int[][] graph = GraphUtils.buildSimpleGraph(count, from, to); for (int[] vertex : graph) ArrayUtils.sort(vertex, IntComparator.DEFAULT); for (int i = 0; i < count; i++) { for (int j : graph[i]) { if (i < j) break; if (Math.max(graph[i].length, graph[j].length) <= Math.max(headCount, tailCount) || Math.min(graph[i].length, graph[j].length) <= Math.min(headCount, tailCount)) continue; int total = graph[i].length - 1 + graph[j].length - 1; int[] sample = (graph[i].length < graph[j].length) ? graph[i] : graph[j]; int[] target = (graph[i].length < graph[j].length) ? graph[j] : graph[i]; for (int k : sample) { if (Arrays.binarySearch(target, k) >= 0) total--; } if (total < headCount + tailCount) continue; if (graph[i].length > graph[j].length ^ headCount > tailCount) { int temp = i; i = j; j = temp; } out.printLine("YES"); out.printLine(i + 1, j + 1); boolean[] used = new boolean[count]; int[] head = new int[headCount]; int l = 0; for (int k : graph[i]) { if (k != j && Arrays.binarySearch(graph[j], k) < 0) { head[l++] = k + 1; used[k] = true; } if (l == headCount) break; } if (l != headCount) { for (int k : graph[i]) { if (k != j && !used[k]) { head[l++] = k + 1; used[k] = true; } if (l == headCount) break; } } int[] tail = new int[tailCount]; l = 0; for (int k : graph[j]) { if (k != i && !used[k]) tail[l++] = k + 1; if (l == tailCount) break; } out.printLine(Array.wrap(head).toArray()); out.printLine(Array.wrap(tail).toArray()); return; } } out.printLine("NO"); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { 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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IOUtils { public static void readIntArrays(InputReader in, int[]... arrays) { for (int i = 0; i < arrays[0].length; i++) { for (int j = 0; j < arrays.length; j++) arrays[j][i] = in.readInt(); } } } class MiscUtils { public static void decreaseByOne(int[]...arrays) { for (int[] array : arrays) { for (int i = 0; i < array.length; i++) array[i]--; } } } class GraphUtils { public static int[][] buildGraph(int vertexCount, int[] from, int[] to) { int edgeCount = from.length; int[] degree = new int[vertexCount]; for (int i = 0; i < edgeCount; i++) { degree[from[i]]++; degree[to[i]]++; } int[][] graph = new int[vertexCount][]; for (int i = 0; i < vertexCount; i++) graph[i] = new int[degree[i]]; for (int i = 0; i < edgeCount; i++) { graph[from[i]][--degree[from[i]]] = i; graph[to[i]][--degree[to[i]]] = i; } return graph; } public static int otherVertex(int vertex, int from, int to) { return from + to - vertex; } public static int[][] buildSimpleGraph(int vertexCount, int[] from, int[] to) { int[][] graph = buildGraph(vertexCount, from, to); simplifyGraph(from, to, graph); return graph; } private static void simplifyGraph(int[] from, int[] to, int[][] graph) { for (int i = 0; i < graph.length; i++) { for (int j = 0; j < graph[i].length; j++) { graph[i][j] = otherVertex(i, from[graph[i][j]], to[graph[i][j]]); } } } } class ArrayUtils { private static int[] tempInt = new int[0]; public static int[] sort(int[] array, IntComparator comparator) { return sort(array, 0, array.length, comparator); } public static int[] sort(int[] array, int from, int to, IntComparator comparator) { ensureCapacityInt(to - from); System.arraycopy(array, from, tempInt, 0, to - from); sortImpl(array, from, to, tempInt, 0, to - from, comparator); return array; } private static void ensureCapacityInt(int size) { if (tempInt.length >= size) return; size = Math.max(size, tempInt.length << 1); tempInt = new int[size]; } private static void sortImpl(int[] array, int from, int to, int[] temp, int fromTemp, int toTemp, IntComparator comparator) { if (to - from <= 1) return; int middle = (to - from) >> 1; int tempMiddle = fromTemp + middle; sortImpl(temp, fromTemp, tempMiddle, array, from, from + middle, comparator); sortImpl(temp, tempMiddle, toTemp, array, from + middle, to, comparator); int index = from; int index1 = fromTemp; int index2 = tempMiddle; while (index1 < tempMiddle && index2 < toTemp) { if (comparator.compare(temp[index1], temp[index2]) <= 0) array[index++] = temp[index1++]; else array[index++] = temp[index2++]; } if (index1 != tempMiddle) System.arraycopy(temp, index1, array, index, tempMiddle - index1); if (index2 != toTemp) System.arraycopy(temp, index2, array, index, toTemp - index2); } } interface IntComparator { public static final IntComparator DEFAULT = new IntComparator() { public int compare(int first, int second) { if (first < second) return -1; if (first > second) return 1; return 0; } }; public int compare(int first, int second); } abstract class Array<T> extends AbstractList<T> implements RandomAccess { public static List<Integer> wrap(int...array) { return new IntArray(array); } protected static class IntArray extends Array<Integer> { protected final int[] array; protected IntArray(int[] array) { this.array = array; } public int size() { return array.length; } public Integer get(int index) { return array[index]; } public Integer set(int index, Integer value) { int result = array[index]; array[index] = value; return result; } } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 6
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
01330411300f520703c90efdb7b14410
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.io.*; import java.util.*; public class Solution { private StringTokenizer st; private BufferedReader in; private PrintWriter out; private long[][] nsBig; private int[][] nsLst; public void solve() throws IOException { int n = nextInt(); int m = nextInt(); int u = nextInt(); int v = nextInt(); int[] a = new int[m]; int[] b = new int[m]; int[] l = new int[n]; for (int i = 0; i < m; ++i) { a[i] = nextInt() - 1; b[i] = nextInt() - 1; l[a[i]]++; l[b[i]]++; } final int thr = 2000; nsBig = new long[n][]; nsLst = new int[n][]; for (int i = 0; i < n; ++i) { if (l[i] > thr) { nsBig[i] = new long[(n + 63) / 64]; } else { nsLst[i] = new int[l[i]]; } l[i] = 0; } for (int i = 0; i < m; ++i) { if (nsBig[a[i]] != null) { nsBig[a[i]][b[i] / 64] |= 1L << (b[i] % 64); } else { nsLst[a[i]][l[a[i]]] = b[i]; } if (nsBig[b[i]] != null) { nsBig[b[i]][a[i] / 64] |= 1L << (a[i] % 64); } else { nsLst[b[i]][l[b[i]]] = a[i]; } l[a[i]]++; l[b[i]]++; } for (int i = 0; i < n; ++i) { if (nsLst[i] != null) { Arrays.sort(nsLst[i]); } } col = new boolean[n]; for (int i = 0; i < m; ++i) { int common = 0; if (nsBig[a[i]] != null && nsBig[b[i]] != null) { for (int j = 0; j < nsBig[a[i]].length; ++j) { common += Long.bitCount(nsBig[a[i]][j] & nsBig[b[i]][j]); } } else if (nsBig[a[i]] != null) { for (int j : nsLst[b[i]]) { if (contains(a[i], j)) { common++; } } } else if (nsBig[b[i]] != null) { for (int j : nsLst[a[i]]) { if (contains(b[i], j)) { common++; } } } else { for (int j1 = 0, j2 = 0; j1 < nsLst[a[i]].length && j2 < nsLst[b[i]].length; ) { int cmp = nsLst[a[i]][j1] - nsLst[b[i]][j2]; if (cmp == 0) { j1++; j2++; common++; } else if (cmp < 0) { j1++; } else { j2++; } } } if (Math.max(0, u - (l[a[i]] - common - 1)) + Math.max(0, v - (l[b[i]] - common - 1)) <= common) { printAns(a[i], b[i], u, v, Math.max(0, u - (l[a[i]] - common - 1)), Math.max(0, v - (l[b[i]] - common - 1))); return; } if (Math.max(0, u - (l[b[i]] - common - 1)) + Math.max(0, v - (l[a[i]] - common - 1)) <= common) { printAns(b[i], a[i], u, v, Math.max(0, u - (l[b[i]] - common - 1)), Math.max(0, v - (l[a[i]] - common - 1))); return; } } out.println("NO"); } private void printAns(int i, int j, int u, int v, int uc, int vc) { out.println("YES"); out.println((i + 1) + " " + (j + 1)); printNs(i, j, u, uc); printNs(j, i, v, vc); } boolean[] col; private void printNs(int i, int j, int u, int uc) { for (int t = 0; u > 0; ++t) { if (contains(i, t) && j != t) { if (contains(j, t)) { if (!col[t] && uc > 0) { out.print((t + 1) + " "); --u; --uc; col[t] = true; } } else { if (u > 0) { out.print((t + 1) + " "); --u; } } } } out.println(); } private boolean contains(int i, int j) { if (nsBig[i] != null) { return (nsBig[i][j / 64] & (1L << (j % 64))) != 0; } return Arrays.binarySearch(nsLst[i], j) >= 0; } public void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); solve(); out.close(); } void eat(String s) { st = new StringTokenizer(s); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Solution().run(); } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 6
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
479be76c7e452235eefd71cc9ba15d1e
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.InputMismatchException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author niyaznigmatul */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int m = in.nextInt(); int heads = in.nextInt(); int tails = in.nextInt(); int[][] edges = new int[n][]; int[] deg = new int[n]; int[] from = new int[m]; int[] to = new int[m]; for (int i = 0; i < m; i++) { from[i] = in.nextInt() - 1; to[i] = in.nextInt() - 1; deg[from[i]]++; deg[to[i]]++; } for (int i = 0; i < n; i++) { edges[i] = new int[deg[i]]; } for (int i = 0; i < m; i++) { edges[from[i]][--deg[from[i]]] = to[i]; edges[to[i]][--deg[to[i]]] = from[i]; } int[] version = new int[n]; int[] h = new int[n]; int[] t = new int[n]; int tim = 0; for (int i = 0; i < m; i++) { int v = from[i]; int u = to[i]; for (int it = 0; it < 2; it++) { int temp = u; u = v; v = temp; ++tim; int degV = edges[v].length - 1; int degU = edges[u].length - 1; if (degV >= heads && degU >= tails) { int headsLeft = heads; int tailsLeft = tails; int hNumber = 0; int tNumber = 0; boolean ok; if (degV >= heads + tails) { ok = true; for (int j : edges[u]) { if (tailsLeft <= 0) { break; } if (j == v) { continue; } version[j] = tim; --tailsLeft; t[tNumber++] = j; } for (int j : edges[v]) { if (headsLeft <= 0) { break; } if (j == u || version[j] == tim) { continue; } --headsLeft; h[hNumber++] = j; } } else if (degU >= heads + tails) { ok = true; for (int j : edges[v]) { if (headsLeft <= 0) { break; } if (j == u) { continue; } version[j] = tim; --headsLeft; h[hNumber++] = j; } for (int j : edges[u]) { if (tailsLeft <= 0) { break; } if (j == v || version[j] == tim) { continue; } --tailsLeft; t[tNumber++] = j; } } else { ok = true; for (int j : edges[v]) { if (j == u) { continue; } version[j] = tim; } ++tim; int common = 0; for (int j : edges[u]) { if (j == v) { continue; } if (version[j] == tim - 1) { version[j] = tim; ++common; } } if (degU + degV - common < heads + tails) { continue; } for (int j : edges[v]) { if (headsLeft <= 0) { break; } if (j == u || version[j] == tim) { continue; } --headsLeft; h[hNumber++] = j; } for (int j : edges[u]) { if (tailsLeft <= 0) { break; } if (j == v || version[j] == tim) { continue; } --tailsLeft; t[tNumber++] = j; } int oldTim = tim; ++tim; for (int j : edges[v]) { if (headsLeft <= 0) { break; } if (j == u || version[j] != oldTim) { continue; } --headsLeft; version[j] = tim; h[hNumber++] = j; } for (int j : edges[u]) { if (tailsLeft <= 0) { break; } if (j == v || version[j] != oldTim) { continue; } --tailsLeft; version[j] = tim; t[tNumber++] = j; } } // if (headsLeft > 0 || tailsLeft > 0) { // throw new AssertionError(); // } // if (tails != tNumber) { // throw new AssertionError(); // } // if (heads != hNumber) { // throw new AssertionError(); // } if (ok) { out.println("YES"); out.println((v + 1) + " " + (u + 1)); for (int z = 0; z < hNumber; z++) { out.print(h[z] + 1 + " "); } out.println(); for (int z = 0; z < tNumber; z++) { out.print(t[z] + 1 + " "); } out.println(); return; } } } } out.println("NO"); } } class FastScanner extends BufferedReader { boolean isEOF; public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); if (isEOF && ret < 0) { throw new InputMismatchException(); } isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } static boolean isWhiteSpace(int c) { return c >= -1 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (!isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 6
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
7834ae1c854a029909171cff0b579717
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String[] args) throws IOException{ BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(rd.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); H = Integer.parseInt(st.nextToken()); T = Integer.parseInt(st.nextToken()); G = new ArrayList[N+1]; for(int i=0; i<G.length; i++) G[i] = new ArrayList<Integer>(); set = new HashSet[N+1]; for(int i=0; i<=N; i++) set[i] = new HashSet<Integer>(); for(int i=0; i<M; i++){ st = new StringTokenizer(rd.readLine()); int a = Integer.parseInt(st.nextToken()), b = Integer.parseInt(st.nextToken()); G[a].add(b); G[b].add(a); set[a].add(b); set[b].add(a); } ArrayList<Integer> Hs = new ArrayList<Integer>(), Ts = new ArrayList<Integer>(); boolean[] isNeigOfH = new boolean[N+1]; boolean[] isNeigOfT = new boolean[N+1]; for(int i=1; i<=N; i++){ if(G[i].size()>=H+1) Hs.add(i); if(G[i].size()>=T+1) Ts.add(i); } Pair[] p = new Pair[Hs.size()]; for(int i=0; i<Hs.size(); i++) p[i] = new Pair(Hs.get(i), G[Hs.get(i)].size()); Arrays.sort(p, new cmp()); for(int i=0; i<Hs.size(); i++){ int cur = p[i].x; for(int j=0; j<G[cur].size(); j++){ int to = G[cur].get(j); if(G[to].size()<=T) continue; check(cur, to); } } System.out.println("NO"); } static void check(int h, int t){ int inter = 0; for(int i=0; i<G[h].size(); i++){ int to = G[h].get(i); if(set[t].contains(to)) inter++; } // int dif = G[h].size()-1-inter, dif1 = G[t].size()-1-inter; if(G[h].size()-1>=H && G[t].size()-1>=T && H+T<=G[h].size()-1+G[t].size()-1-inter){ // if(dif>=H && dif1>=T){ output(h, t, inter); System.exit(0); } } static HashSet<Integer>[] set; static void output(int h, int t, int inter){ PrintWriter pw = new PrintWriter(System.out); pw.println("YES"); pw.println(h+" "+t); boolean[] used = new boolean[N+1]; ArrayList<Integer> x = new ArrayList<Integer>(), y = new ArrayList<Integer>(); for(int i=0; i<G[h].size(); i++){ int to = G[h].get(i); if(set[t].contains(to) || to==t) continue; if(x.size()>=H) break; x.add(to); used[to] = true; } for(int i=0; i<G[t].size(); i++){ int to = G[t].get(i); if(set[h].contains(to) || to==h) continue; if(y.size()>=T) break; y.add(to); used[to] = true; } for(int i=0; i<G[h].size(); i++){ int to = G[h].get(i); if(used[to] || to==t) continue; if(x.size()>=H) break; used[to] = true; x.add(to); } for(int i=0; i<G[t].size(); i++){ int to = G[t].get(i); if(used[to] || to==h) continue; if(y.size()>=T) break; used[to] = true; y.add(to); } if(x.size()>H || y.size()>T) System.out.println("TY"); for(int i=0; i<x.size(); i++) pw.print(x.get(i)+" "); pw.println(); for(int i=0; i<y.size(); i++) pw.print(y.get(i)+" "); pw.println(); pw.flush(); System.exit(0); } static ArrayList<Integer>[] G; static int N, M, H, T; } class Pair{ public int x, y; public Pair(int a, int b){ x = a; y = b; } } class cmp implements Comparator{ @Override public int compare(Object o1, Object o2) { // TODO Auto-generated method stub return ((Pair)o2).y-((Pair)o1).y; } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 6
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
ebed7120411cd929def2e55dfaec7af5
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class ProblemB { static int[][] graph; static int[] deg; static int H, T, N; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] nmht = in.readLine().split(" "); int n = Integer.valueOf(nmht[0]); int m = Integer.valueOf(nmht[1]); H = Integer.valueOf(nmht[2]); T = Integer.valueOf(nmht[3]); N = n; deg = new int[n]; int[] idx = new int[n]; int[][] edge = new int[m][2]; graph = new int[n][]; for (int i = 0 ; i < m ; i++) { String[] uv = in.readLine().split(" "); int u = Integer.valueOf(uv[0])-1; int v = Integer.valueOf(uv[1])-1; edge[i][0] = u; edge[i][1] = v; deg[u]++; deg[v]++; } for (int i = 0 ; i < n ; i++) { graph[i] = new int[deg[i]]; } for (int i = 0 ; i < m ; i++) { int u = edge[i][0]; int v = edge[i][1]; graph[u][idx[u]++] = v; graph[v][idx[v]++] = u; } int[] mark = new int[N]; Arrays.fill(mark, -1); int[] dbl = new int[n]; Arrays.fill(dbl, -1); boolean done = false; int didx = 0; int[] order = new int[n]; for (int i = 0 ; i < n ; i++) { order[i] = i; } for (int i = 0 ; i < n ; i++) { int t = (int)(Math.random() * n); int tmp = order[t]; order[t] = order[i]; order[i] = tmp; } sch: for (int i : order) { if (deg[i] < H + 1) { continue; } for (int j : graph[i]) { mark[j] = i; } for (int j : graph[i]) { if (deg[j] < T + 1) { continue; } int cover = 0; for (int k : graph[j]) { if (mark[k] == i) { cover++; dbl[k] = didx; } } if (doit(i, j, cover, dbl, didx)) { done = true; break sch; } didx++; } } if (!done) { out.println("NO"); } else { out.println("YES"); out.println(ret); } out.flush(); } static String ret = ""; private static boolean doit(int a, int b, int cover, int[] dbl, int idx) { int diff = ((deg[a] - 1) - H) + ((deg[b] - 1) - T); if (cover > diff) { return false; } int needH = H; StringBuffer headRet = new StringBuffer(); boolean[] done = new boolean[N]; for (int h : graph[a]) { if (h != b && !done[h] && dbl[h] != idx) { headRet.append(" ").append(h+1); done[h] = true; needH--; if (needH == 0) { break; } } } if (needH >= 1) { for (int h : graph[a]) { if (h != b && !done[h]) { headRet.append(" ").append(h+1); done[h] = true; needH--; if (needH == 0) { break; } } } } int needT = T; StringBuffer tailRet = new StringBuffer(); for (int h : graph[b]) { if (h != a && !done[h]) { tailRet.append(" ").append(h+1); done[h] = true; needT--; if (needT == 0) { break; } } } // debug(a,b,ad,diff); // debug(headRet); // debug(tailRet); ret = (a+1) + " " + (b+1) + "\n" + headRet.substring(1) + "\n" + tailRet.substring(1); return true; } public static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 6
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
247e8b210200cb14da77309bdcb166b8
train_000.jsonl
1353079800
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { (new Main()).solve(); } void solve() { Scanner cin = new Scanner(System.in); MAIN: while( cin.hasNextInt() ) { int N = cin.nextInt(); int M = cin.nextInt(); int H = cin.nextInt(); int T = cin.nextInt(); List<List<Integer>> next = new ArrayList<List<Integer>>(); for(int i=0; i<N; ++i) { next.add(new ArrayList<Integer>()); } int arr[][] = new int[M][2]; for(int i=0; i<M; ++i) { int a = cin.nextInt() - 1; int b = cin.nextInt() - 1; arr[i][0] = a; arr[i][1] = b; next.get(a).add(b); next.get(b).add(a); } for(int i=0; i<N; ++i) { Collections.sort(next.get(i)); } LOOP: for(int x=0; x<M; ++x) { int a = arr[x][0]; int b = arr[x][1]; List<Integer> set = next.get(a); List<Integer> opp = next.get(b); if( set.size() >= T + 1 && opp.size() >= H + 1 ) { List<Integer> tmp = set; set = opp; opp = tmp; int t = a; a = b; b = t; } if( set.size() >= H + 1 && opp.size() >= T + 1 ) { int head = set.size() - 1; int tail = opp.size() - 1; int p = 0; int q = 0; int over = (head - H) + (tail - T); if( over < Math.min(head, tail) ) { while( p < set.size() && q < opp.size() ) { if( set.get(p) < opp.get(q) ) { ++p; } else if( set.get(p) > opp.get(q) ) { ++q; } else { if( over-- == 0 ) { continue LOOP; } ++p; ++q; } } } System.out.println("YES"); System.out.println((a + 1) + " " + (b + 1)); List<Integer> hset = new ArrayList<Integer>(); List<Integer> tset = new ArrayList<Integer>(); List<Integer> share = new ArrayList<Integer>(); p = q = 0; while( p < set.size() || q < opp.size() ) { if( Math.max(0, H - hset.size()) + Math.max(0, T - tset.size()) <= share.size() ) { break; } if( p == set.size() ) { if( opp.get(q) == a ) { ++q; } else { tset.add(opp.get(q++)); } } else if( q == opp.size() ) { if( set.get(p) == b ) { ++p; } else { hset.add(set.get(p++)); } } else if( set.get(p) < opp.get(q) ) { if( set.get(p) == b ) { ++p; } else { hset.add(set.get(p++)); } } else if( set.get(p) > opp.get(q) ) { if( opp.get(q) == a ) { ++q; } else { tset.add(opp.get(q++)); } } else { share.add(set.get(p++)); q++; } } int su = 0; if( Math.max(0, H - hset.size()) + Math.max(0, T - tset.size()) > share.size() ) { throw new RuntimeException(hset.size() + " " + tset.size() + " " + share.size()); } for(int i=0; i<H; ++i) { if( i > 0 ) { System.out.print(" "); } if( i < hset.size() ) { System.out.print(hset.get(i) + 1); } else { System.out.print(share.get(su++) + 1); } } System.out.println(); for(int i=0; i<T; ++i) { if( i > 0 ) { System.out.print(" "); } if( i < tset.size() ) { System.out.print(tset.get(i) + 1); } else { System.out.print(share.get(su++) + 1); } } System.out.println(); continue MAIN; } } System.out.println("NO"); } } }
Java
["9 12 2 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5\n8 7\n9 1", "7 10 3 3\n1 2\n2 3\n1 3\n1 4\n2 5\n4 5\n4 6\n6 5\n6 7\n7 5"]
2 seconds
["YES\n4 1\n5 6 \n9 3 2", "NO"]
NoteThe first sample is depicted on the picture below:
Java 6
standard input
[ "sortings", "graphs" ]
2d098058a553a70f30977266059f01c2
The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.
2,000
If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them.
standard output
PASSED
babd7d59f1d6ab9a5fd4dbf6e1688989
train_000.jsonl
1442939400
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!
256 megabytes
import java.io.*; public class First { public static void main(String[] args) throws IOException { int n; int x, y; int max = 1; int count = 1; n = nextInt(); y = nextInt(); while (--n > 0) { x = y; y = nextInt(); if (y >= x) count++; else { max = Math.max(count, max); count = 1; } } if (count > max) max = count; System.out.println(max); } static InputStreamReader isr = new InputStreamReader(System.in); static BufferedReader br = new BufferedReader(isr); static StreamTokenizer in = new StreamTokenizer(br); static int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } }
Java
["6\n2 2 1 3 4 1", "3\n2 2 9"]
2 seconds
["3", "3"]
NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Java 7
standard input
[ "dp", "implementation", "brute force" ]
1312b680d43febdc7898ffb0753a9950
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1,  a2,  ...,  an (1 ≤ ai ≤ 109).
900
Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.
standard output
PASSED
31437a7c0c3dbf8ad2c3cf6f95142d1c
train_000.jsonl
1442939400
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!
256 megabytes
import java.util.Scanner; public class First { public static void main(String[] args) { int n; int x, y; int max = 1; int count = 1; Scanner sc = new Scanner(System.in); n = sc.nextInt(); y = sc.nextInt(); while (--n > 0) { x = y; y = sc.nextInt(); if (y >= x) count++; else { if (count > max) max = count; count = 1; } } if (count > max) max = count; System.out.println(max); } }
Java
["6\n2 2 1 3 4 1", "3\n2 2 9"]
2 seconds
["3", "3"]
NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Java 7
standard input
[ "dp", "implementation", "brute force" ]
1312b680d43febdc7898ffb0753a9950
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1,  a2,  ...,  an (1 ≤ ai ≤ 109).
900
Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.
standard output
PASSED
e0c597021074414d1e73b80c0b9930af
train_000.jsonl
1442939400
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!
256 megabytes
import java.util.*; public class subSequence { public static void main(String []args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int arr[] = new int[n]; for(int i=0; i<n; i++) arr[i] = s.nextInt(); int ans = segment(arr); System.out.println(ans); } static int segment(int arr[]) { int i=0; int count =1; int max = count; while(i<arr.length-1) { if(arr[i]<=arr[i+1]) { count++; if(count>= max) max = count; } else { if(count>= max) max = count; count = 1; } i++; } return max; } }
Java
["6\n2 2 1 3 4 1", "3\n2 2 9"]
2 seconds
["3", "3"]
NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Java 7
standard input
[ "dp", "implementation", "brute force" ]
1312b680d43febdc7898ffb0753a9950
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1,  a2,  ...,  an (1 ≤ ai ≤ 109).
900
Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.
standard output
PASSED
5dc1c8c6b84bc4277122264ff2779da3
train_000.jsonl
1442939400
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!
256 megabytes
import java.util.Scanner; public class Codeforces { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] a = new int[100005]; int[] b = new int[100005]; int n = sc.nextInt(); a[0]=sc.nextInt(); b[0]=1; int ans=1; for(int i=1;i<n; i++) { a[i] = sc.nextInt(); if(a[i]>=a[i-1]) { b[i] = b[i-1]+1; } else { b[i]=1; } if(b[i]>ans) { ans = b[i]; } } System.out.println(ans); sc.close(); } }
Java
["6\n2 2 1 3 4 1", "3\n2 2 9"]
2 seconds
["3", "3"]
NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Java 7
standard input
[ "dp", "implementation", "brute force" ]
1312b680d43febdc7898ffb0753a9950
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1,  a2,  ...,  an (1 ≤ ai ≤ 109).
900
Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.
standard output
PASSED
1c9d34d0542395811a7af2e773df0122
train_000.jsonl
1442939400
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!
256 megabytes
import java.util.*; public class Problem580A { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int runtime = scanner.nextInt(); int [] input = new int[runtime]; int realresult = 1; int newresult = 1; for(int i = 0; i < runtime; i++) { input[i] = scanner.nextInt(); } scanner.close(); for(int i = 0; i < runtime-1; i++) { if (input[i]<=input[i+1]) newresult++; else { if(newresult>realresult) realresult = newresult; newresult = 1; } } if(newresult>realresult) realresult = newresult; System.out.println(realresult); } }
Java
["6\n2 2 1 3 4 1", "3\n2 2 9"]
2 seconds
["3", "3"]
NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Java 7
standard input
[ "dp", "implementation", "brute force" ]
1312b680d43febdc7898ffb0753a9950
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1,  a2,  ...,  an (1 ≤ ai ≤ 109).
900
Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.
standard output
PASSED
b811577d23278340ea415c44bf668f7b
train_000.jsonl
1442939400
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!
256 megabytes
import java.util.*; public class kefa_and_first_steps { public static void main( String[] args ) { Scanner in = new Scanner( System.in ); int n = in.nextInt(), a = in.nextInt(), c = 1, m = Integer.MIN_VALUE; for ( int i = 1; i < n; i++ ) { int b = in.nextInt(); if ( b >= a ) c++; else { m = Math.max( m, c ); c = 1; } a = b; } m = Math.max( m, c ); if ( m != Integer.MIN_VALUE ) System.out.println( m ); else System.out.println( n ); in.close(); System.exit( 0 ); } }
Java
["6\n2 2 1 3 4 1", "3\n2 2 9"]
2 seconds
["3", "3"]
NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Java 7
standard input
[ "dp", "implementation", "brute force" ]
1312b680d43febdc7898ffb0753a9950
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1,  a2,  ...,  an (1 ≤ ai ≤ 109).
900
Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.
standard output
PASSED
77eadbbad0654b799f53730a5f5219e7
train_000.jsonl
1442939400
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Ideone { public static void main (String[] args) throws java.lang.Exception { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) arr[i] = s.nextInt(); int max =1; int res=1; for(int i=0;i<n-1;i++) { if(arr[i]<=arr[i+1]) max++; else { if(res<=max) res = max; max =1; } } if(res<=max){ res = max; } System.out.println(res); } }
Java
["6\n2 2 1 3 4 1", "3\n2 2 9"]
2 seconds
["3", "3"]
NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Java 7
standard input
[ "dp", "implementation", "brute force" ]
1312b680d43febdc7898ffb0753a9950
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1,  a2,  ...,  an (1 ≤ ai ≤ 109).
900
Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.
standard output
PASSED
488e0f1ef2f2112d9b6cda022f75888f
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
//package March16; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; public class Main{ public static void main(String[] args) throws java.lang.Exception{ InputStream inputstream = System.in; OutputStream outputstream = System.out; InputReader in = new InputReader(inputstream); PrintWriter out = new PrintWriter(outputstream); Call one = new Call(); one.solve(in,out); out.close(); } static class Call { public void solve(InputReader in,PrintWriter out) { long n = in.nextLong(); int count = 0; HashSet<String> list = new HashSet<>(); for(int i=0;i<n;i++) { String s = in.next(); char a[] = s.toCharArray(); int occur[] = new int[26]; for(int j=0;j<a.length;j++) { occur[a[j]-'a']++; } String x = ""; for(int j=0;j<occur.length;j++) { if(occur[j]>0)x+=j; } list.add(x); } out.println(list.size()); /*for(int i=0;i<n;i++) { String s = in.next(); char a[] = s.toCharArray(); Arrays.sort(a); s = new String(a); list.add(s); } Iterator<String> it = list.iterator(); while(it.hasNext()) { String s = it.next(); char a[] = s.toCharArray(); char occur[] = new char[26]; for(int j=0;j<a.length;j++) { occur[a[j]-'a']++; } boolean flag = true; for(int j=0;j<occur.length;j++) { if(occur[j]>1)flag = false; } if(flag)count++; } out.println(count);*/ } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader (stream),32768); tokenizer = null; } public String next() { while(tokenizer == null || !tokenizer.hasMoreElements()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch(IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
5a0a2edc1f5c5bf662d3205b46f6a940
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
// Don't place your source in a package import java.util.*; import java.lang.*; import java.io.*; // Please name your class Main public class Main { public static void main (String[] args) { Scanner in = new Scanner(System.in); HashSet<String> hs = new HashSet<String>(); int n = in.nextInt(), count = 0; boolean b[] = new boolean[1001]; for (int i = 0; i < n; i++){ char c[] = in.next().toCharArray(); Arrays.sort(c); LinkedHashSet knownChars = new LinkedHashSet(); String noDups = ""; for(Character l : c){ if(!knownChars.contains(l)){ knownChars.add(l); noDups += "" + l; } } if (!hs.contains(noDups)){ count++; hs.add(noDups); } } //System.out.println(Arrays.toString(b)); System.out.println(count); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
e021da2ab5eb04a013d7719e16ce7783
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Arrays; public class Main{ public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); String w[] = br.readLine().split(" "); HashMap<String, Integer> map = new HashMap<String,Integer>(); int p[] = new int[26]; int ans = 0; for(int i = 0; i<n;i++){ String pal = ""; char d[] = w[i].toCharArray(); Arrays.sort(d); pal+=""+d[0]; for(int j = 1;j<w[i].length();j++){ if(d[j]!=d[j-1]){ pal+=""+d[j]; } } map.put(pal,1); } out.println(map.size()); out.close(); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
5f5341141ef74c01648c85238afe9e0a
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.util.Arrays; import java.util.Scanner; import java.util.*; // http://codeforces.com/problemset/problem/975/A public class aramic{ public static void main(String...args){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); HashSet<String> wordSet = new HashSet<>(); for( int i = 0;i<n;i++){ String s1 = stripDuplicate(sc.next()); Iterator iterator = wordSet.iterator(); boolean exist = false; while (iterator.hasNext()) { if(isAnagram(s1,(String)iterator.next())) { exist = true; break; } } if(!exist){ wordSet.add(s1); } } System.out.println(wordSet.size()); return; } public static boolean isAnagram(String s1, String s2){ if(s1.length()!=s2.length()) return false; char[] c1 = s1.toCharArray(); char[] c2 = s2.toCharArray(); Arrays.sort(c1); Arrays.sort(c2); if( Arrays.equals(c1,c2)) return true; return false; } public static String stripDuplicate(String s1){ char[] c1 = s1.toCharArray(); HashSet<Character> h1 = new HashSet<Character>(); for (char c:c1){ if(!h1.contains(c)){ h1.add(c); } } char[] c2 = new char[h1.size()]; Iterator iterator = h1.iterator(); // check values int i = 0; while (iterator.hasNext()) { c2[i++] =(char)(iterator.next()); } return new String(c2); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
10aa19d7d326745dfb1619f828e633a0
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.util.HashSet; import java.util.Scanner; public class Driver { public static Scanner scanner; public static void main(String[] args) { scanner = new Scanner(System.in); int n = scanner.nextInt(); String[] st = new String[n]; for(int i=0; i<n; i++) st[i] = scanner.next(); HashSet<HashSet<Character>> hs = new HashSet<>(); for(int i=0; i<n; i++) { HashSet<Character> chs = new HashSet<>(); for(int j=0; j<st[i].length(); j++) { chs.add(st[i].charAt(j)); } hs.add(chs); } System.out.println(hs.size()); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
c19d38d587f9f4c63a7993c574b41f57
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.util.*; public class AramicScript { public static void main(String [] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); Set<Set<Character>> answer = new HashSet<>(); for(int i = 0; i < n; i++){ String string = input.next(); Set<Character> charactersSet = new HashSet<>(); for(Character character : string.toCharArray()) charactersSet.add(character); answer.add(charactersSet); } System.out.println(answer.size()); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
df56f634db4bf600692685b669366b86
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Preet */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); HashSet<String> hs = new HashSet<>(); for (int i = 0; i < n; i++) { char c[] = in.next().toCharArray(); Arrays.sort(c); StringBuilder sb = new StringBuilder(); sb.append(c[0]); for (int j = 1; j < c.length; j++) { if (c[j] != c[j - 1]) { sb.append(c[j]); } } hs.add(sb.toString()); } out.println(hs.size()); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } 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 readString() { 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 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 readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
12506ba7786083fb1a5995d9ef853187
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.util.*; public class abc { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); String[]table = new String[n]; Set<String> list = new HashSet<>(); String res = ""; for (int i = 0; i <n; i++) { table[i] = scanner.next(); res = ""; for (int j = 0; j <table[i].length(); j++) { if(res.contains(String.valueOf(table[i].charAt(j)))){ continue; } else{ res+=table[i].charAt(j); } } char[] chars = res.toCharArray(); Arrays.sort(chars); String sorted = new String(chars); list.add(sorted); } System.out.println(list.size()); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
ea67595d0693717469e3508ad63bc58b
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; /** * * @author moham */ public class NewMain17 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); ArrayList<String> ar = new ArrayList<>(); for(int i=0;i<n;i++){ String temp = input.next(); ArrayList <Character> arr = new ArrayList<>(); String root = ""; for(int j=0;j<temp.length();j++){ if(!arr.contains(temp.charAt(j))){ arr.add(temp.charAt(j)); root+=temp.charAt(j); } } char a[] = root.toCharArray(); Arrays.sort(a); String ans = String.copyValueOf(a); if(!ar.contains(ans)){ ar.add(ans); } } System.out.println(ar.size()); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
dc548af63b342f1344f35a192d0be019
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.regex.Pattern; import javafx.scene.shape.Line; public class Main{ private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; private static long count = 0,mod=(long)1e9+7; // private static TreeSet<Integer> ts=new TreeSet[200000]; public final static int INF = (int) 1E9; public static void main(String args[]) { InputReader(System.in); pw = new PrintWriter(System.out); new Thread(null ,new Runnable(){ public void run(){ try{ test(); pw.close(); } catch(Exception e){ e.printStackTrace(); } } },"1",1<<26).start(); } static StringBuilder sb; public static void test() throws IOException{ sb=new StringBuilder(); int t=1; while(t-->0){ solve(); //pw.println(); //sb.append("\n"); } //pw.println(sb); } public static long pow(long n, long p,long mod) { if(p==0) return 1; if(p==1) return n%mod; if(p%2==0){ long temp=pow(n, p/2,mod); return (temp*temp)%mod; }else{ long temp=pow(n,p/2,mod); temp=(temp*temp)%mod; return(temp*n)%mod; } } public static long pow(long n, long p) { if(p==0) return 1; if(p==1) return n; if(p%2==0){ long temp=pow(n, p/2); return (temp*temp); }else{ long temp=pow(n,p/2); temp=(temp*temp); return(temp*n); } } public static void Merge(long a[],int p,int r){ if(p<r){ int q = (p+r)/2; Merge(a,p,q); Merge(a,q+1,r); Merge_Array(a,p,q,r); } } public static void Merge_Array(long a[],int p,int q,int r){ long b[] = new long[q-p+1]; long c[] = new long[r-q]; for(int i=0;i<b.length;i++) b[i] = a[p+i]; for(int i=0;i<c.length;i++) c[i] = a[q+i+1]; int i = 0,j = 0; for(int k=p;k<=r;k++){ if(i==b.length){ a[k] = c[j]; j++; } else if(j==c.length){ a[k] = b[i]; i++; } else if(b[i]<c[j]){ a[k] = b[i]; i++; } else{ a[k] = c[j]; j++; } } } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd( y % x,x); } 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; } static LinkedList<Integer> adj[],adj2[]; static boolean Visited[]; static HashSet<Integer> exc; static long oddsum[]=new long[1000001]; static long co=0; static int indeg[],outdeg[]; private static void buildgraph(int n){ adj=new LinkedList[n+1]; adj2=new LinkedList[n+1]; Visited=new boolean[n+1]; levl=new int[n+1]; indeg=new int[n+1]; outdeg=new int[n+1]; for(int i=0;i<=n;i++){ adj[i]=new LinkedList<Integer>(); adj2[i]=new LinkedList<Integer>(); } } static int[] levl; static int[] eat; static int n,m; static int price[]; //ind frog crab static long d,x,y; static long modInverse(long A, long M) { extendedEuclid(A,M); return (x%M+M)%M; //x may be negative } static void extendedEuclid(long A, long B) { if(B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A%B); long temp = x; x = y; y = temp - (A/B)*y; } } static double distance(int x1,int y1,int x2,int y2){ return Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); } static double area(int x1, int y1, int x2, int y2, int x3, int y3) { return Math.abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0); } static boolean isInside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y) { double A = area (x1, y1, x2, y2, x3, y3); double A1 = area (x, y, x2, y2, x3, y3); double A2 = area (x1, y1, x, y, x3, y3); double A3 = area (x1, y1, x2, y2, x, y); return (A == A1 + A2 + A3); } static int col[]; public static boolean isVowel(char c){ if(c=='a' || c=='e'||c=='i' || c=='o' || c=='u') return true; return false; } static long arr[], lazy[],ans[]; static int c[],nodes[]; static int dp[][]; static long a[][]; private static boolean isPrim(long n,int p){ for (long i = 2; i * i <= n; i++) { if (n % i == 0 && i <= p) return false; } return true; } //price - starting index of string with given hash //rating-count of number of time of a hash static ArrayList<String> all_perm; static boolean[][] visited1; static boolean won; static boolean containsCycle; static ArrayList<Integer> anss; private static int size = 0; public static void solve() throws IOException{ int n=nextInt(); int freq[]=new int[26]; int cnt=0; String t[]=nextLine().split(" "); HashSet<String> g=new HashSet<String>(); for(int i=0;i<n;i++){ String s=t[i]; TreeSet<Character> hs=new TreeSet<Character>(); for(int j=0;j<s.length();j++) hs.add(s.charAt(j)); boolean b=true; String fin=""; for(char c:hs){ fin+=c; } g.add(fin); } pw.println(g.size()); } private static int mySoln(int n,int a,int b){ int tempa=Math.min(a, b); int tempb=Math.max(a, b); ArrayList<Integer> list = new ArrayList<Integer>(); for(int i=1;i<=n;i++){ list.add(i); } int round=1; while(true){ ArrayList<Integer> temp = new ArrayList<Integer>(); for(int i=0;i<list.size();i+=2){ if(list.get(i)==tempa && list.get(i+1)==tempb){ return round; } if(list.get(i)==tempa || list.get(i)==tempb){ temp.add(list.get(i)); }else if(list.get(i+1)==tempa || list.get(i+1)==tempb){ temp.add(list.get(i+1)); }else{ temp.add(list.get(i)); } } list.clear(); for(int i:temp){ list.add(i); } round++; } } private static int othersoln(int n,int a,int b){ for(int i=16;i>=0;i--){ if(BB(a,i) ^ BB(b,i)){ int m=i+1; return m; } } return 0; } private static boolean BB(int n,int i){ return (n & (1<<i)) >0; } private static boolean check(int x,int y,int n,int m){ if(x>=0 && x<n && y>=0 && y<m) return true; return false; } private static void dfs(int curr,int par){ Visited[curr]=true; for(int i:adj[curr]){ if(!Visited[i]){ dfs(i,curr); } } dp[curr][nodes[curr]]++; for(int i=0;i<26;i++){ dp[par][i]+=dp[curr][i]; } } private static boolean Check(int x,int y,int n){ if(x>=0 && x<n && y>=0 && y<n) return true; return false; } public static String reverseString(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return (sb.toString()); } /* private static void BFS(int sou){ Queue<Integer> q=new LinkedList<Integer>(); q.add(sou); Visited[sou]=true; levl[sou]=0; while(!q.isEmpty()){ int top=q.poll(); for(int i:adj[top]){ //pw.println(i+" "+top); if(!Visited[i]) { q.add(i); levl[i]=levl[top]+1; } Visited[i]=true; } } }*/ /* private static void kahn(int n){ PriorityQueue<Integer> q=new PriorityQueue<Integer>(); for(int i=1;i<=n;i++){ if(indeg[i]==0){ q.add(i); } } while(!q.isEmpty()){ int top=q.poll(); st.push(top); for(Node i:adj[top]){ indeg[i.to]--; if(indeg[i.to]==0){ q.add(i.to); } } } } static int state=1; static long no_exc=0,no_vert=0; static Stack<Integer> st; static HashSet<Integer> inset; /* private static void topo(int curr){ Visited[curr]=true; inset.add(curr); for(int x:adj[curr]){ if(adj[x].contains(curr) || inset.contains(x)){ state=0; return; } if(state==0) return; } st.push(curr); inset.remove(curr); }*/ static HashSet<Integer> hs; static boolean prime[]; static int spf[]; public static void sieve(int n){ prime=new boolean[n+1]; spf=new int[n+1]; Arrays.fill(spf, 1); Arrays.fill(prime, true); prime[1]=false; spf[2]=2; for(int i=4;i<=n;i+=2){ spf[i]=2; } for(int i=3;i<=n;i+=2){ if(prime[i]){ spf[i]=i; for(int j=2*i;j<=n;j+=i){ prime[j]=false; if(spf[j]==1){ spf[j]=i; } } } } } // To Get Input // Some Buffer Methods public static void sort(long a[]){ Merge(a, 0, a.length-1); } public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } private static 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; } private static 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; } private static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } private static int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private static long[][] next2dArray(int n, int m) { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nextLong(); } } return arr; } private static char[][] nextCharArray(int n,int m){ char [][]c=new char[n][m]; for(int i=0;i<n;i++){ String s=nextLine(); for(int j=0;j<s.length();j++){ c[i][j]=s.charAt(j); } } return c; } private static long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private static void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pArray(boolean[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class Node{ int to; long dist; Node(int to,long dist){ this.to=to; this.dist=dist; } } class Qu{ long a0,a1,a2,a3; public Qu(long a0,long a1,long a2,long a3) { this.a0=a0; this.a1=a1; this.a2=a2; this.a3=a3; } } class Dsu{ private int rank[], parent[] ,n; long str[],si[],larg[]; long max=0; int cnt=0; private static int[] parent1; Dsu(int size){ this.n=size+1; rank=new int[n]; cnt=n-1; //parent=new int[n]; parent=new int[n]; str=new long[n]; si=new long[n]; larg=new long[n]; makeSet(); } void makeSet(){ for(int i=0;i<n;i++){ parent[i]=i; si[i]=1; } } int find(int x){ if(parent[x]!=x){ parent[x]=find(parent[x]); } return parent[x]; } void join(int ind,long val){ if(str[ind]==0){ str[ind]=val; larg[ind]=val; max=Math.max(max, str[ind]); } int prev_ind=(ind-1); int next_ind=(ind+1); if(prev_ind>0 && larg[prev_ind]!=0){ union(prev_ind,ind); } if(next_ind<n && larg[next_ind]!=0){ union(next_ind,ind); } } boolean union(int x,int y){ int xRoot=find(x); int yRoot=find(y); if(xRoot==yRoot) return false; if(rank[xRoot]<rank[yRoot]){ parent[xRoot]=yRoot; larg[yRoot]=Math.max(larg[xRoot], larg[yRoot]); si[yRoot]+=si[xRoot]; str[yRoot]=larg[yRoot]*si[yRoot]; max=Math.max(str[yRoot], max); }else if(rank[yRoot]<rank[xRoot]){ parent[yRoot]=xRoot; larg[xRoot]=Math.max(larg[xRoot], larg[yRoot]); si[xRoot]+=si[yRoot]; str[xRoot]=larg[xRoot]*si[xRoot]; max=Math.max(str[xRoot], max); }else{ parent[yRoot]=xRoot; rank[xRoot]++; larg[xRoot]=Math.max(larg[xRoot], larg[yRoot]); si[xRoot]+=si[yRoot]; str[xRoot]=larg[xRoot]*si[xRoot]; max=Math.max(str[xRoot], max); } cnt--; return true; } } class Pair1 implements Comparable<Pair1>{ long price,rating; Pair1(long a,long b){ this.price=a; this.rating=b; } @Override public int compareTo(Pair1 arg0) { return (int)(price-arg0.price); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
40f538cbbcb5f5f3e785e607fcc6c3d3
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; public class A { static String removeDuplicate(String s) { char [] c = s.toCharArray(); TreeMap<Character, Integer> h = new TreeMap(); for(int i = 0 ; i<c.length ;i++) if(!h.containsKey(c[i])) h.put(c[i], 0); s = ""; for(Map.Entry<Character, Integer>e :h.entrySet()) s+=e.getKey()+""; return s; } public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String [] s = new String [n]; HashSet<String> hs = new HashSet<>(); for(int i = 0 ; i< n ;i++) hs.add(removeDuplicate(sc.next())); System.out.println(hs.size()); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
b43d451fbf22a02baa7e4ff17d076cdf
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class B { public static void main(String args[]) throws IOException { Scanner sc=new Scanner (System.in); int n=sc.nextInt(); String arr[]=sc.nextLine().split(" "); StringBuilder res=new StringBuilder(); ArrayList<String> list=new ArrayList<>(); int tmp[]=new int [26]; for(int i=0;i<n;i++) { tmp=new int[26]; for(int j=0;j<arr[i].length();j++) { tmp[arr[i].charAt(j)-'a']++; } for(int j=0;j<26;j++) { if(tmp[j]>=1)res.append((char)(j+'a')); } if (!list.contains(res.toString()))list.add(res.toString()); res=new StringBuilder(); } // System.out.println(Arrays.toString(list.toArray())); System.out.println(list.size()); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine(), ",| "); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } }}
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
fe5eb151f51cf026a7d786cf058e3de0
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.util.*; import java.io.*; // Main public class Main { public static void main (String[] argv) { new Main(); } public Main() { FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); //FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in"))); int n = in.nextInt(); Set<String> set = new HashSet<String>(); final int R = 26; boolean[] r = new boolean[R]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { String s = in.next(); for (int j = 0; j < s.length(); j++) r[s.charAt(j) - 'a'] = true; for (int j = 0; j < R; j++) { if (r[j]) { sb.append((char)(j + 'a')); r[j] = false; //reset for latter use } } set.add(sb.toString()); sb.setLength(0); } System.out.println(set.size()); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(BufferedReader in) { br = in; } String next() { while (st == null || !st.hasMoreElements()) { try { String line = br.readLine(); if (line == null || line.length() == 0) return ""; st = new StringTokenizer(line); } catch (IOException e) { return ""; //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) { return ""; //e.printStackTrace(); } return str; } } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
58e6d3fb9f1e9120ef83d65964fef972
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.util.*; import java.io.*; // Main public class Main { public static void main (String[] argv) { new Main(); } public Main() { FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); //FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in"))); int n = in.nextInt(); Set<Integer> set = new HashSet<Integer>(); final int R = 26; for (int i = 0; i < n; i++) { String s = in.next(); int root = 0; for (int j = 0; j < s.length(); j++) root |= 1 << (s.charAt(j) - 'a'); set.add(root); } System.out.println(set.size()); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(BufferedReader in) { br = in; } String next() { while (st == null || !st.hasMoreElements()) { try { String line = br.readLine(); if (line == null || line.length() == 0) return ""; st = new StringTokenizer(line); } catch (IOException e) { return ""; //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) { return ""; //e.printStackTrace(); } return str; } } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
731d20679e74b6aaee9bd08593cdbf7c
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; public class A_GENERAL { public static void main(String[] args) { MyScanner sc = new MyScanner(); int n = sc.nextInt(); Set<Character> charset; Set<String> finalset = new HashSet<>(); for(int i = 0; i < n; i++) { char[] ch = sc.next().toCharArray(); charset = new HashSet<>(); for(char c : ch) { charset.add(c); } char[] t = new char[charset.size()]; int j = 0; for(char c : charset) { t[j++] = c; } Arrays.sort(t); // System.out.println(String.valueOf(t)); finalset.add(String.valueOf(t)); } System.out.println(finalset.size()); } 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;} } } //727 //baabbabbbababbbbaaaabaabbaabababaaababaaababbbbababbbbbbbbbbaaabaabbbbbbbbaaaabaabbaaabaabbabaa //ddcdcccccccdccdcdccdddcddcddcddddcdddcdcdccddcdddddccddcccdcdddcdcccdccccccdcdcdccccccdccccccdc //fffeefeffeefeeeeffefffeeefffeefffefeefefeeeffefefefefefefffffffeeeeeffffeefeeeeffffeeeeeefeffef //60 //ddcZYXYbZbcXYcZdYbddaddYaZYZdaZdZZdXaaYdaZZZaXZXXaaZbb //dcdXcYbcaXYaXYcacYabYcbZYdacaYbYdXaccYXZZZdYbbYdcZZZbY //XaZXbbdcXaadcYdYYcbZdcaXaYZabbXZZYbYbcXbaXabcXbXadbZYZ
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
fa619c79e981d758fe6fcf3c544b25bd
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.util.ArrayList; import java.util.Scanner; import java.util.TreeSet; @SuppressWarnings("unused") public class B { public static Scanner scan = new Scanner(System.in); public static void solve () { int n=scan.nextInt(); String[] s= new String[n]; for(int i=0;i<n;i++) { s[i]=scan.next(); } TreeSet<String> a= new TreeSet<String>(); for(int i=0;i<n;i++) { TreeSet<Character> h= new TreeSet<Character>(); for(int j=0;j<s[i].length();j++) { h.add(s[i].charAt(j)); } String s1 = ""; for(Character c : h) s1 += c; a.add(s1); } System.out.println(a.size()); } public static void main(String[] args) { solve(); scan.close(); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
828e315a554f2700ea9999091a2fb50a
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Reader.init(System.in); int n = Reader.nextInt() ; str ar[] = new str[n] ; for(int i = 0 ; i < n ; i++) { ar[i] = new str() ; ar[i].s = Reader.next(); } int count = 0 ; Set<String> set = new TreeSet<>() ; for(int i = 0 ; i < n ; i++){ int frq[] = new int[26] ; int len = ar[i].s.length() ; boolean flag = false ; for(int j = 0 ; j < len ; j++) { if(frq[ar[i].s.charAt(j) - 'a'] == 0) { frq[ar[i].s.charAt(j) - 'a'] = 1; } } String st = "" ; for(int q = 0 ; q < frq.length ; q++) { st += (char) (frq[q]+'a') ; } set.add(st) ; } System.out.println(set.size()); } } class str implements Comparable<str>{ String s ; @Override public int compareTo(str o) { if(o.s.length() < s.length()) return 1; if(o.s.length() > s.length()) return -1 ; return 0; } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) throws Exception{ reader = new BufferedReader(new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException{ return Long.parseLong(next()) ; } static int nextShort() throws IOException { return Short.parseShort(next() ); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
92df6815042906a685ea8ca1ac3bc0c7
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.util.*; public class one{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int n=Integer.parseInt(sc.nextLine()); String[] s=sc.nextLine().split(" "); Set<Set> set=new HashSet<Set>(); for(int i=0;i<n;i++){ Set<Character> s1=new HashSet<Character>(); for(int j=0;j<s[i].length();j++){ s1.add(s[i].charAt(j)); } set.add(s1); //System.out.println(s1.toString()); } System.out.println(set.size()); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
4eaaf0799349ad522080cce45ab447ae
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.InputMismatchException; public class A975 { private static int MAX = 50; public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); Reader sc=new Reader(); int n=sc.i(); String[] input = new String[n]; for(int i=0;i<n;i++) input[i]=sc.s(); out.println(findObj(input)); out.close(); } private static int findObj(String[] input) { ArrayList<String> result = new ArrayList<>(); int[] counter; StringBuilder builder; for (String str : input) { char[] temp = str.toCharArray(); counter = new int[MAX]; for (int i = 0; i < temp.length; i++) { counter[temp[i]-'a'] = 1; } builder = new StringBuilder(); for (int i = 0; i < counter.length; i++) { if (counter[i]==1)builder.append((char) (i+'a')); } if (!result.contains(builder.toString())) result.add(builder.toString()); } return result.size(); } static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){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 long l(){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 int i(){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 double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;} } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
775b6da247a0715f66b850bdc8b6eecf
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class cp { public static void main(String args[]) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //Scanner in = new Scanner(System.in); int n = Integer.parseInt(in.readLine()), roots=0; String S[] = in.readLine().split(" "); Map<String, Integer> map1 = new HashMap<String, Integer>(); for(int i=0;i<n;++i){ Map<Character, Integer> map = new HashMap<Character, Integer>(); int j; String si=""; for(j=0;j<S[i].length();j++){ if(!map.containsKey(S[i].charAt(j))){ map.put(S[i].charAt(j), 1); si+=S[i].charAt(j); } } char k[] = si.toCharArray(); Arrays.sort(k); if(!map1.containsKey(String.valueOf(k))){ map1.put(String.valueOf(k), 1); ++roots; } } System.out.println(roots); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
7feaedbd8aa1b05160feb98ac630c9ce
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class temp { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); HashSet<Integer> obj = new HashSet<Integer>(); while (n-- > 0) { String current = sc.next(); int mask = 0; for (int i = 0; i < current.length(); i++) { int c = current.charAt(i); int idx = c - 'a'; mask |= (1 << idx); } obj.add(mask); } out.println(obj.size()); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
248532cddab331f8548d42ad5696eedf
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.util.*; import java.util.Scanner; public class index { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int n = cin.nextInt(); Set<Set> s = new HashSet<>(); for (int i = 0; i < n; i++) { String script = cin.next(); Set<Character> s1 = new HashSet<>(); for (int j = 0; j < script.length(); j++) { s1.add(script.charAt(j)); } s.add(s1); } System.out.println(s.size()); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
d49ee96a0b402ac25b12455d4d96b62e
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
//package DC; //new import java.awt.List; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; import javax.print.attribute.Size2DSyntax;; public class Main { public static void main(String[] args) { HashMap<String, ArrayList<String>> result = new HashMap<>(); Scanner s = new Scanner(System.in); ArrayList<String> roots = new ArrayList<>(); int n = s.nextInt(); String root, input; while (n > 0) { input = s.next(); root = find_root(input); if (!hasThisRoot(root, roots)) { // ArrayList<String> permutationsOfRoot = null; // result.put(root, permutationsOfRoot); roots.add(root); } n--; } System.out.println(roots.size()); } public static boolean hasThisRoot(String root1, ArrayList<String> roots) { for (String r : roots) { if (r.length() != root1.length()) continue; for (int i = 0; i < root1.length(); i++) { if (!r.contains(String.valueOf(root1.charAt(i)))) break; if (i == root1.length() - 1) return true; } // ArrayList<String> pr = map.get(r); // if (pr == null) { // pr = new ArrayList<>(); // isRoot("", r, pr); // map.put(r, pr); // } // for (String roo : pr) // if (roo.equals(root1)) // return true; } return false; } public static String find_root(String word) { String newWord = ""; for (int i = 0; i < word.length(); i++) { if (!newWord.contains(String.valueOf(word.charAt(i)))) newWord += word.charAt(i); } return newWord; } public static void isRoot(String prefix, String main, ArrayList<String> roots) { if (main.length() == 0) roots.add(prefix); for (int i = 0; i < main.length(); i++) isRoot(prefix + main.charAt(i), main.substring(0, i) + main.substring(i + 1, main.length()), roots); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
b226eeb05fc9b04d89c4676a18b14164
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.math.BigInteger; import java.util.*; import java.io.*; public class A{ public static void main(String arg[]) { FastScanner sc = new FastScanner(System.in); int n ,c=0; n = sc.nextInt(); String sums [] = new String[n]; ArrayList<String>list = new ArrayList<>(); for(int i =0;i<n;++i){ String j = sc.next() ,kkk=""; int x [] = new int[26]; int y = j.length(); for(int k= 0;k<y;++k){ if(x[j.charAt(k)-'a']==0){ x[j.charAt(k)-'a']++; } } for(int t =0;t<26;++t){ if(x[t]!=0){ kkk = kkk + String.valueOf(t);} } if(!list.contains(kkk)){ c++; list.add(kkk); } } System.out.println(c); } public int bi(long []x,int str,int end,long looking){ int o = (str+end)/2; if(x[o]>looking){ for(int i =str;i<o;++i){ if(x[i]>=looking){ return i; } } } else if (x[o]<looking){ for(int i =o;i<end;++i){ if(x[i]>=looking){ return i; } } } return o; } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } 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.valueOf(next()); } double nextd() { return Double.valueOf(next()); } } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
d7a82f215287aa30bb107856bffe5e94
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class forces{ public 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; } } /*public 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') break; 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(); } }*/ public static void main (String args[]){ FastReader in=new FastReader(); try{ int i,n=in.nextInt(); String[]s=new String[n]; for(i=0;i<n;i++){ s[i]=in.next(); } int count=0; Set<String>set=new TreeSet<String>(); for(i=0;i<n;i++){ int[]a=new int[26]; String z=s[i],result=""; int l=z.length(); for(int j=0;j<l;j++){ char c=z.charAt(j); int index=(int)c-97; if(a[index]==0){ a[index]++; } } for(int j=0;j<26;j++){ if(a[j]!=0){ result+=(char)(j+97); } } set.add(result); } System.out.println(set.size()); } catch(Exception e){ } } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
ba330f52d49cf14be80fcfa4c9f68e57
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.util.*; import java.lang.*; import java.text.DecimalFormat; import java.text.NumberFormat; import java.io.*; public class Solution { static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } static long gcd(long a, long b){ if (b == 0) return a; return gcd(b, a % b); } 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()); } public int[] readIntArray(int n) { int[] arr = new int[n]; for(int i=0; i<n; ++i) arr[i]=nextInt(); return arr; } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]) throws IOException { long start = System.currentTimeMillis(); FastReader sc = new FastReader(); int n = sc.nextInt(); Set<Integer> set = new HashSet<>(); int p = 0; for(int i = 0;i < n;i++){ char[] s = sc.next().toCharArray(); int f = 0; for(char c : s){ f |= 1<<c-'a'; } set.add(f); } System.out.println(set.size()); long end = System.currentTimeMillis(); NumberFormat formatter = new DecimalFormat("#0.00000"); //System.out.print("Execution time is " + formatter.format((end - start) / 1000d) + " seconds"); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
922e9921281a74ff07752f7d971a47fb
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.ByteArrayInputStream; import java.util.Scanner; public class Main2 { // 5 // a aa aa ab abb public static void main(String[] args) { String input = ""; ByteArrayInputStream bais = new ByteArrayInputStream(input.getBytes()); Scanner scanner = new Scanner(System.in); short numOfWords = scanner.nextShort(); int max = 0b00000011_11111111_11111111_11111111; boolean[] marks = new boolean[max+1]; int counts = 0; for (int i = 0; i < numOfWords; i++) { String word = scanner.next(); int mark = 0; for (int index = 0; index < word.length(); index++) { char c = word.charAt(index); int charIndex = c - 97; mark = mark | 1 << charIndex; } if (!marks[mark]) { marks[mark] = true; counts++; } } System.out.println(counts); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
c3e5edcd40bb5f208cac449cc699179c
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.io.*; import java.math.*; import java.util.StringTokenizer; public class Aramic { static PrintStream out = System.out; public static void main(String args[] ) throws Exception { int n = ni(); String str[] = new String[n]; for(int i=0;i<n;i++) str[i] = n(); TreeSet<String> tree = new TreeSet<String>(); for(String i:str){ tree.add(printDistinct1(i)); } out.println(tree.size()); } static String printDistinct1(String str ){ int arr1[] = new int[26]; for(int i=0;i<str.length();i++){ arr1[str.charAt(i)-'a']=1; } String str1 = ""; for(int i=0;i<26;i++){ if(arr1[i]==1 ) str1 += (char)(i+'a'); } return str1; } static final int MAX_CHAR = 256; static String printDistinct(String str){ int n = str.length(); int[] count = new int[MAX_CHAR]; int[] index = new int[MAX_CHAR]; for (int i = 0; i < MAX_CHAR; i++){ count[i] = 0; index[i] = n; } for (int i = 0; i < n; i++){ char x = str.charAt(i); ++count[x]; if (count[x] == 1 && x !=' ') index[x] = i; if (count[x] == 2) index[x] = n; } Arrays.sort(index); String str123 =""; for (int i = 0; i < MAX_CHAR && index[i] != n; i++) str123+=(str.charAt(index[i])); return str123; } //-------------------------------------------------fast Method---------------------------------------------------------------\\ static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));; static StringTokenizer st; private static int[] inta(int n){ int [] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private static long[] longa(long n){ long[] a = new long[(int)n]; for(int i = 0;i < n;i++)a[i] = nl(); return a; } private static void pla(long[] a){ for(int i = 0;i <a.length;i++) out.print(a[i]+" "); } private static void pia(int[] a){ for(int i = 0;i <a.length;i++) out.print(a[i]+" "); } private static String n(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } private static int ni(){ return Integer.parseInt(n()); } private static long nl(){ return Long.parseLong(n()); } private static double nd(){ return Double.parseDouble(n()); } private static String nli(){ String str = ""; try{ str = br.readLine(); } catch (IOException e){ e.printStackTrace(); } return str; } //-------------------------------------------------fast Method---------------------------------------------------------------\\ }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
0c0e17710ce30ef185a1edd7c0bcb325
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * * @author SNEHITH */ public class problem_A { public static void main(String[] args){ int arr[] = new int[26]; int n; String s = ""; Set< Set<Integer> > set = new HashSet<>(); // Set<Integer> set1 = new HashSet<>(); Scanner sc = new Scanner(System.in); n = sc.nextInt(); for(int i=0;i<n;i++){ s = sc.next(); Set<Integer> set1 = new HashSet<>(); for(int j=0;j<s.length();j++) set1.add(s.charAt(j) - 'a' +1); set.add(set1); } System.out.println(set.size()); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
e0546dcd00b791c421d487946b961732
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * * @author SNEHITH */ public class problem_A { public static void main(String[] args){ int arr[] = new int[26]; int n; String s = ""; Set< Set<Integer> > set = new HashSet<>(); Scanner sc = new Scanner(System.in); n = sc.nextInt(); for(int i=0;i<n;i++){ s = sc.next(); Set<Integer> set1 = new HashSet<>(); for(int j=0;j<s.length();j++) set1.add(s.charAt(j) - 'a' +1); set.add(set1); } System.out.println(set.size()); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
646cfb2173d11a25b99e44bbf5ef0529
train_000.jsonl
1525183500
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
256 megabytes
import java.util.*; public class prob1 { public static void main (String[] args) throws java.lang.Exception { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); String[] a = new String[n]; for(int i=0;i<n;i++){ a[i] = scan.next(); } for(int i=0;i<n-1;i++){ if(a[i]!=null){ int[] b = new int[26]; for(int k=0;k<a[i].length();k++){ b[a[i].charAt(k)-97] = b[a[i].charAt(k)-97] + 1; } for(int j=i+1;j<n;j++){ if(a[j]!=null){ int[] c = new int[26]; for(int k=0;k<a[j].length();k++){ c[a[j].charAt(k)-97] = c[a[j].charAt(k)-97] + 1; } boolean v = true; for(int p=0;p<26;p++){ if((b[p]!=0&&c[p]!=0)||(b[p]==0&&c[p]==0)){ } else{ v=false; break; } } if(v){ a[j] = null; } }}} } int t=0; for(int i=0;i<n;i++){ if(a[i]!=null){ t++; } } System.out.println(t); } }
Java
["5\na aa aaa ab abb", "3\namer arem mrea"]
1 second
["2", "1"]
NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Java 8
standard input
[ "implementation", "strings" ]
cf1eb164c4c970fd398ef9e98b4c07b1
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
900
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
standard output
PASSED
0253bbec7b8737d9bc00ab897c08381d
train_000.jsonl
1569143100
Marcin is a coach in his university. There are $$$n$$$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from $$$1$$$ to $$$n$$$. Each of them can be described with two integers $$$a_i$$$ and $$$b_i$$$; $$$b_i$$$ is equal to the skill level of the $$$i$$$-th student (the higher, the better). Also, there are $$$60$$$ known algorithms, which are numbered with integers from $$$0$$$ to $$$59$$$. If the $$$i$$$-th student knows the $$$j$$$-th algorithm, then the $$$j$$$-th bit ($$$2^j$$$) is set in the binary representation of $$$a_i$$$. Otherwise, this bit is not set.Student $$$x$$$ thinks that he is better than student $$$y$$$ if and only if $$$x$$$ knows some algorithm which $$$y$$$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Map; import java.util.NoSuchElementException; public class Main { static PrintWriter out; static InputReader ir; static void solve() { int n = ir.nextInt(); long[] a = ir.nextLongArray(n); long[] b = ir.nextLongArray(n); HashMap<Long, Integer> ct = new HashMap<>(); HashMap<Long, Long> mp = new HashMap<>(); ArrayList<Long> l = new ArrayList<>(); for (int i = 0; i < n; i++) { if (!ct.containsKey(a[i])) { ct.put(a[i], 1); mp.put(a[i], b[i]); } else { if (ct.get(a[i]) == 1) l.add(a[i]); ct.put(a[i], ct.get(a[i]) + 1); mp.put(a[i], mp.get(a[i]) + b[i]); } } long res = 0; for (Map.Entry<Long, Long> e : mp.entrySet()) { for (long x : l) { if (((long) e.getKey() & x) == (long) e.getKey()) { res += e.getValue(); break; } } } out.println(res); } public static void main(String[] args) { ir = new InputReader(System.in); out = new PrintWriter(System.out); solve(); out.flush(); } 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 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; } } static void tr(Object... o) { out.println(Arrays.deepToString(o)); } }
Java
["4\n3 2 3 6\n2 8 5 10", "3\n1 2 3\n1 2 3", "1\n0\n1"]
3 seconds
["15", "0", "0"]
NoteIn the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $$$b_i$$$.In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.
Java 8
standard input
[ "dfs and similar", "greedy", "graphs", "brute force" ]
9404ec14922a69082f3573bbaf78ccf0
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 7000$$$) — the number of students interested in the camp. The second line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$). The third line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).
1,700
Output one integer which denotes the maximum sum of $$$b_i$$$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.
standard output
PASSED
91eb1edc7247a0eaf92ca88b0b21310c
train_000.jsonl
1569143100
Marcin is a coach in his university. There are $$$n$$$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from $$$1$$$ to $$$n$$$. Each of them can be described with two integers $$$a_i$$$ and $$$b_i$$$; $$$b_i$$$ is equal to the skill level of the $$$i$$$-th student (the higher, the better). Also, there are $$$60$$$ known algorithms, which are numbered with integers from $$$0$$$ to $$$59$$$. If the $$$i$$$-th student knows the $$$j$$$-th algorithm, then the $$$j$$$-th bit ($$$2^j$$$) is set in the binary representation of $$$a_i$$$. Otherwise, this bit is not set.Student $$$x$$$ thinks that he is better than student $$$y$$$ if and only if $$$x$$$ knows some algorithm which $$$y$$$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author xylenox */ public class d { static int MOD = 998244353; public static void main(String[] args) { FS in = new FS(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); long[] a = new long[n]; long[] b = new long[n]; for(int i = 0; i < n; i++) { a[i] = in.nextLong(); } for(int i = 0; i < n; i++) { b[i] = in.nextInt(); } ArrayList<Long> vals = new ArrayList<>(); long tot = 0; HashMap<Long, Integer> map = new HashMap<>(); for(int i = 0; i < n; i++) { map.putIfAbsent(a[i], 0); map.put(a[i], map.get(a[i])+1); } boolean[] has = new boolean[n]; for(int i = 0; i < n; i++) { if(map.get(a[i]) > 1) { has[i] = true; vals.add(a[i]); tot += b[i]; } } for(int i = 0; i < n; i++) { if(!has[i]) { for(long j : vals) { if((a[i]^j) == j-a[i]) { tot += b[i]; break; } } } } System.out.println(tot); out.close(); } static class FS { BufferedReader in; StringTokenizer token; public FS(InputStream st) { in = new BufferedReader(new InputStreamReader(st)); } public String next() { if (token == null || !token.hasMoreElements()) { try { token = new StringTokenizer(in.readLine()); } catch (Exception e) { } return next(); } return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n3 2 3 6\n2 8 5 10", "3\n1 2 3\n1 2 3", "1\n0\n1"]
3 seconds
["15", "0", "0"]
NoteIn the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $$$b_i$$$.In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.
Java 8
standard input
[ "dfs and similar", "greedy", "graphs", "brute force" ]
9404ec14922a69082f3573bbaf78ccf0
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 7000$$$) — the number of students interested in the camp. The second line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$). The third line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).
1,700
Output one integer which denotes the maximum sum of $$$b_i$$$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.
standard output
PASSED
334c60907748e9dee6e5714c2bfbe49b
train_000.jsonl
1569143100
Marcin is a coach in his university. There are $$$n$$$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from $$$1$$$ to $$$n$$$. Each of them can be described with two integers $$$a_i$$$ and $$$b_i$$$; $$$b_i$$$ is equal to the skill level of the $$$i$$$-th student (the higher, the better). Also, there are $$$60$$$ known algorithms, which are numbered with integers from $$$0$$$ to $$$59$$$. If the $$$i$$$-th student knows the $$$j$$$-th algorithm, then the $$$j$$$-th bit ($$$2^j$$$) is set in the binary representation of $$$a_i$$$. Otherwise, this bit is not set.Student $$$x$$$ thinks that he is better than student $$$y$$$ if and only if $$$x$$$ knows some algorithm which $$$y$$$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); long[] a = new long[n]; long[] b = new long[n]; StringTokenizer st = new StringTokenizer(in.readLine()); for (int i = 0; i < n; i++) { a[i] = Long.parseLong(st.nextToken()); // System.out.println(iStr); } st = new StringTokenizer(in.readLine()); for (int i = 0; i < n; i++) { b[i] = Long.parseLong(st.nextToken()); } HashSet<Long> safe = new HashSet<>(); for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { long c = a[i] | a[j]; if (c == a[i] && c == a[j]) { safe.add(c); } } } long res = 0; long cnt = 0; boolean[] marked = new boolean[n]; for (long t : safe) { for (int i = 0; i < n; i++) { if (marked[i]) { continue; } long c = t | a[i]; if (c == t) { res += b[i]; cnt++; marked[i] = true; } } } if (cnt == 1) { System.out.println("0"); return; } System.out.println(res); } } /* 5 3 3 12 12 6 1 1 1 1 1 */
Java
["4\n3 2 3 6\n2 8 5 10", "3\n1 2 3\n1 2 3", "1\n0\n1"]
3 seconds
["15", "0", "0"]
NoteIn the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $$$b_i$$$.In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.
Java 8
standard input
[ "dfs and similar", "greedy", "graphs", "brute force" ]
9404ec14922a69082f3573bbaf78ccf0
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 7000$$$) — the number of students interested in the camp. The second line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$). The third line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).
1,700
Output one integer which denotes the maximum sum of $$$b_i$$$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.
standard output
PASSED
d0bbfc0a43ceb0c6495cc022e6326ac5
train_000.jsonl
1569143100
Marcin is a coach in his university. There are $$$n$$$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from $$$1$$$ to $$$n$$$. Each of them can be described with two integers $$$a_i$$$ and $$$b_i$$$; $$$b_i$$$ is equal to the skill level of the $$$i$$$-th student (the higher, the better). Also, there are $$$60$$$ known algorithms, which are numbered with integers from $$$0$$$ to $$$59$$$. If the $$$i$$$-th student knows the $$$j$$$-th algorithm, then the $$$j$$$-th bit ($$$2^j$$$) is set in the binary representation of $$$a_i$$$. Otherwise, this bit is not set.Student $$$x$$$ thinks that he is better than student $$$y$$$ if and only if $$$x$$$ knows some algorithm which $$$y$$$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.TreeSet; /** * Created by mostafa on 10/6/19. */ public class CF588D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); int n = sc.nextInt(); long[] a = new long[n]; int[] b = new int[n]; TreeSet<Long> dup = new TreeSet<>(); for (int i = 0; i < n; i++) { a[i] = sc.nextLong(); if (dup.contains(a[i])) continue; for (int j = 0; j < i; j++) if (a[j] == a[i]) { dup.add(a[i]); break; } } for (int i = 0; i < n; i++) { b[i] = sc.nextInt(); } long ans = 0; for (int i = 0; i < n; i++) if (dup.contains(a[i])) { ans += b[i]; } else { for (long d : dup) { if ((~d & a[i]) == 0) { ans += b[i]; break; } } } System.out.println(ans); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["4\n3 2 3 6\n2 8 5 10", "3\n1 2 3\n1 2 3", "1\n0\n1"]
3 seconds
["15", "0", "0"]
NoteIn the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $$$b_i$$$.In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.
Java 8
standard input
[ "dfs and similar", "greedy", "graphs", "brute force" ]
9404ec14922a69082f3573bbaf78ccf0
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 7000$$$) — the number of students interested in the camp. The second line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$). The third line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).
1,700
Output one integer which denotes the maximum sum of $$$b_i$$$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.
standard output
PASSED
90491e2d3604ec3b96be4f2a3120541b
train_000.jsonl
1569143100
Marcin is a coach in his university. There are $$$n$$$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from $$$1$$$ to $$$n$$$. Each of them can be described with two integers $$$a_i$$$ and $$$b_i$$$; $$$b_i$$$ is equal to the skill level of the $$$i$$$-th student (the higher, the better). Also, there are $$$60$$$ known algorithms, which are numbered with integers from $$$0$$$ to $$$59$$$. If the $$$i$$$-th student knows the $$$j$$$-th algorithm, then the $$$j$$$-th bit ($$$2^j$$$) is set in the binary representation of $$$a_i$$$. Otherwise, this bit is not set.Student $$$x$$$ thinks that he is better than student $$$y$$$ if and only if $$$x$$$ knows some algorithm which $$$y$$$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?
256 megabytes
import java.io.*; import java.util.*; public class TaskD { static class X { long bit, sum; int cnt; X(long bit, long sum, int cnt) { this.bit = bit; this.sum = sum; this.cnt = cnt; } } public static void main(String[] args) { FastReader in = new FastReader(System.in); // FastReader in = new FastReader(new FileInputStream("input.txt")); PrintWriter out = new PrintWriter(System.out); // PrintWriter out = new PrintWriter(new FileOutputStream("output.txt")); int n = in.nextInt(); long[][] a = new long[n][2]; for (int i = 0; i < n; i++) { a[i][0] = in.nextLong(); } for (int i = 0; i < n; i++) { a[i][1] = in.nextInt(); } Arrays.sort(a, (o1, o2) -> Long.compare(o2[0], o1[0])); ArrayList<X> xs = new ArrayList<>(); for (int i = 0; i < n; i++) { int j = i + 1; long sum = a[i][1]; while (j < n && a[i][0] == a[j][0]) { sum += a[j][1]; j++; } xs.add(new X(a[i][0], sum, j - i)); i = j - 1; } // // for (X x : xs) { // out.println(x.bit + " " + x.sum + " " + x.cnt); // } long ans = 0; for (int i = 0; i < xs.size(); i++) { X x = xs.get(i); if (x.cnt > 1) { ans += x.sum; } else { for (int j = 0; j < i; j++) { X x1 = xs.get(j); if (x1.cnt > 1 && (x.bit | x1.bit) == x1.bit) { ans += x.sum; break; } } } // out.println(ans); } out.println(ans); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } Integer nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } Double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["4\n3 2 3 6\n2 8 5 10", "3\n1 2 3\n1 2 3", "1\n0\n1"]
3 seconds
["15", "0", "0"]
NoteIn the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $$$b_i$$$.In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.
Java 8
standard input
[ "dfs and similar", "greedy", "graphs", "brute force" ]
9404ec14922a69082f3573bbaf78ccf0
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 7000$$$) — the number of students interested in the camp. The second line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$). The third line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).
1,700
Output one integer which denotes the maximum sum of $$$b_i$$$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.
standard output
PASSED
4c94f31bd48f5e0b5e9d7204b1c928b5
train_000.jsonl
1569143100
Marcin is a coach in his university. There are $$$n$$$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from $$$1$$$ to $$$n$$$. Each of them can be described with two integers $$$a_i$$$ and $$$b_i$$$; $$$b_i$$$ is equal to the skill level of the $$$i$$$-th student (the higher, the better). Also, there are $$$60$$$ known algorithms, which are numbered with integers from $$$0$$$ to $$$59$$$. If the $$$i$$$-th student knows the $$$j$$$-th algorithm, then the $$$j$$$-th bit ($$$2^j$$$) is set in the binary representation of $$$a_i$$$. Otherwise, this bit is not set.Student $$$x$$$ thinks that he is better than student $$$y$$$ if and only if $$$x$$$ knows some algorithm which $$$y$$$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class D { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine().trim()); HashMap<Long, Group> groups = new HashMap<>(); long[] skills = new long[n]; StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { skills[i] = Long.parseLong(st.nextToken().trim()); } st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { long cost = Long.parseLong(st.nextToken().trim()); if (!groups.containsKey(skills[i])) { groups.put(skills[i], new Group()); } groups.get(skills[i]).add(cost); } long max = 0; TreeSet<Long> set = new TreeSet<>(Collections.reverseOrder()); for (int i = 0; i < n; i++) { set.add(skills[i]); } while (!set.isEmpty()) { long root = set.pollFirst(); if (groups.get(root).count >= 2) { max += groups.get(root).cost; for (long sub : set) { if ((sub & root) == sub) { max += groups.get(sub).cost; groups.get(sub).cost=0; } } } } System.out.println(max); } static class Group { int count; long cost; public Group() { this.count = 0; this.cost = 0; } public void add(long cost) { this.count++; this.cost += cost; } } }
Java
["4\n3 2 3 6\n2 8 5 10", "3\n1 2 3\n1 2 3", "1\n0\n1"]
3 seconds
["15", "0", "0"]
NoteIn the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $$$b_i$$$.In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.
Java 8
standard input
[ "dfs and similar", "greedy", "graphs", "brute force" ]
9404ec14922a69082f3573bbaf78ccf0
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 7000$$$) — the number of students interested in the camp. The second line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$). The third line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).
1,700
Output one integer which denotes the maximum sum of $$$b_i$$$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.
standard output
PASSED
e070ccfdad3bf4d8e2afabb0a51dcbe9
train_000.jsonl
1569143100
Marcin is a coach in his university. There are $$$n$$$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from $$$1$$$ to $$$n$$$. Each of them can be described with two integers $$$a_i$$$ and $$$b_i$$$; $$$b_i$$$ is equal to the skill level of the $$$i$$$-th student (the higher, the better). Also, there are $$$60$$$ known algorithms, which are numbered with integers from $$$0$$$ to $$$59$$$. If the $$$i$$$-th student knows the $$$j$$$-th algorithm, then the $$$j$$$-th bit ($$$2^j$$$) is set in the binary representation of $$$a_i$$$. Otherwise, this bit is not set.Student $$$x$$$ thinks that he is better than student $$$y$$$ if and only if $$$x$$$ knows some algorithm which $$$y$$$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?
256 megabytes
import java.io.*; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static int oo = (int)1e9; static int mod = 1_000_000_007; static int[] di = {-1, 1, 0, 0}; static int[] dj = {0, 0, -1, 1}; public static void main(String[] args) throws IOException { int n = in.nextInt(); long[] a = new long[n]; for(int i = 0; i < n; ++i) a[i] = in.nextLong(); long[] b = new long[n]; for(int i = 0; i < n; ++i) b[i] = in.nextLong(); TreeMap<Long, Group> set = new TreeMap<>(Collections.reverseOrder()); for(int i = 0; i < n; ++i) { if(!set.containsKey(a[i])) { set.put(a[i], new Group(1, b[i])); } else { Group g = set.get(a[i]); set.put(a[i], new Group(g.cnt + 1, g.sum + b[i])); } } HashSet<Long> done = new HashSet<>(); long ans = 0; for(long k : set.keySet()) { if(done.contains(k)) continue; done.add(k); Group g = set.get(k); if(g.cnt == 1) continue; long x = g.sum; for(long k2 : set.keySet()) { if(k <= k2) continue; if(done.contains(k2)) continue; if(k - k2 == (k ^ k2)) { x += set.get(k2).sum; done.add(k2); } } ans += x; } System.out.println(ans); out.close(); } static class Group { long cnt, sum; public Group(long cnt, long sum) { super(); this.cnt = cnt; this.sum = sum; } } static class SegmentTree { int n; long[] a, seg; int DEFAULT_VALUE = 0; public SegmentTree(long[] a, int n) { super(); this.a = a; this.n = n; seg = new long[n * 4 + 1]; build(1, 0, n-1); } private long build(int node, int i, int j) { if(i == j) return seg[node] = a[i]; long first = build(node * 2, i, (i+j) / 2); long second = build(node * 2 + 1, (i+j) / 2 + 1, j); return seg[node] = combine(first, second); } long update(int k, long value) { return update(1, 0, n-1, k, value); } private long update(int node, int i, int j, int k, long value) { if(k < i || k > j) return seg[node]; if(i == j && j == k) { a[k] = value; seg[node] = value; return value; } int m = (i + j) / 2; long first = update(node * 2, i, m, k, value); long second = update(node * 2 + 1, m + 1, j, k, value); return seg[node] = combine(first, second); } long query(int l, int r) { return query(1, 0, n-1, l, r); } private long query(int node, int i, int j, int l, int r) { if(l <= i && j <= r) return seg[node]; if(j < l || i > r) return DEFAULT_VALUE; int m = (i + j) / 2; long first = query(node * 2, i, m, l, r); long second = query(node * 2 + 1, m+1, j, l, r); return combine(first, second); } private long combine(long a, long b) { return a + b; } } static class DisjointSet { int n; int[] g; int[] h; public DisjointSet(int n) { super(); this.n = n; g = new int[n]; h = new int[n]; for(int i = 0; i < n; ++i) { g[i] = i; h[i] = 1; } } int find(int x) { if(g[x] == x) return x; return g[x] = find(g[x]); } void union(int x, int y) { x = find(x); y = find(y); if(x == y) return; if(h[x] >= h[y]) { g[y] = x; if(h[x] == h[y]) h[x]++; } else { g[x] = y; } } } static int[] getPi(char[] a) { int m = a.length; int j = 0; int[] pi = new int[m]; for(int i = 1; i < m; ++i) { while(j > 0 && a[i] != a[j]) j = pi[j-1]; if(a[i] == a[j]) { pi[i] = j + 1; j++; } } return pi; } static long lcm(long a, long b) { return a * b / gcd(a, b); } static boolean nextPermutation(int[] a) { for(int i = a.length - 2; i >= 0; --i) { if(a[i] < a[i+1]) { for(int j = a.length - 1; ; --j) { if(a[i] < a[j]) { int t = a[i]; a[i] = a[j]; a[j] = t; for(i++, j = a.length - 1; i < j; ++i, --j) { t = a[i]; a[i] = a[j]; a[j] = t; } return true; } } } } return false; } static void shuffle(int[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); int t = a[si]; a[si] = a[i]; a[i] = t; } } static void shuffle(long[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); long t = a[si]; a[si] = a[i]; a[i] = t; } } static int lower_bound(int[] a, int n, int k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int lower_bound(long[] a, int n, long k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { super(); this.first = first; this.second = second; } // @Override // public int compareTo(Pair o) { // return this.first != o.first ? this.first - o.first : this.second - o.second; // } @Override public int compareTo(Pair o) { return this.first != o.first ? o.first - this.first : o.second - this.second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); 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 { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { 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 String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
Java
["4\n3 2 3 6\n2 8 5 10", "3\n1 2 3\n1 2 3", "1\n0\n1"]
3 seconds
["15", "0", "0"]
NoteIn the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $$$b_i$$$.In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.
Java 8
standard input
[ "dfs and similar", "greedy", "graphs", "brute force" ]
9404ec14922a69082f3573bbaf78ccf0
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 7000$$$) — the number of students interested in the camp. The second line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$). The third line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).
1,700
Output one integer which denotes the maximum sum of $$$b_i$$$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.
standard output
PASSED
d5e5b75f68fd0245110629b6bb4e91aa
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query.
256 megabytes
/* Author: Ronak Agarwal, reader part not written by me*/ import java.io.* ; import java.util.* ; import static java.lang.Math.min ; import static java.lang.Math.max ; import static java.lang.Math.abs ; import static java.lang.Math.log ; import static java.lang.Math.pow ; import static java.lang.Math.sqrt ; /* Thread is created here to increase the stack size of the java code so that recursive dfs can be performed */ public class F{ public static void main(String[] args) throws IOException{ new Thread(null,new Runnable(){ public void run(){ exec_Code() ;} },"Solver",1l<<27).start() ; } static void exec_Code(){ try{ Solver Machine = new Solver() ; Machine.Solve() ; Machine.Finish() ;} catch(Exception e){ e.printStackTrace() ; print_and_exit() ;} catch(Error e){ e.printStackTrace() ; print_and_exit() ; } } static void print_and_exit(){ System.out.flush() ; System.exit(-1) ;} } /* Implementation of the Reader class */ class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar,numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is;} public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();} if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine(){ int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString() ; } public String s(){ 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 long l(){ 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 int i(){ 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } /* All the useful functions,constants,renamings are here*/ class Template{ /* Constants Section */ final int INT_MIN = Integer.MIN_VALUE ; final int INT_MAX = Integer.MAX_VALUE ; final long LONG_MIN = Long.MIN_VALUE ; final long LONG_MAX = Long.MAX_VALUE ; static long MOD = 1000000007 ; static Reader ip = new Reader() ; static PrintWriter op = new PrintWriter(System.out) ; /* Methods for writing */ static void p(Object o){ op.print(o) ; } static void pln(Object o){ op.println(o) ;} static void Finish(){ op.flush(); op.close(); } /* Implementation of operations modulo MOD */ static long inv(long a){ return powM(a,MOD-2) ; } static long m(long a,long b){ return (a*b)%MOD ; } static long d(long a,long b){ return (a*inv(b))%MOD ; } static long powM(long a,long b){ if(b<0) return powM(inv(a),-b) ; long ans=1 ; for( ; b!=0 ; a=(a*a)%MOD , b/=2) if((b&1)==1) ans = (ans*a)%MOD ; return ans ; } /* Renaming of some generic utility classes */ final static class mylist extends ArrayList<Integer>{} final static class myset extends TreeSet<Integer>{} final static class mystack extends Stack<Integer>{} final static class mymap extends TreeMap<Integer,Integer>{} } /* Implementation of the pair class, useful for every other problem */ class pair implements Comparable<pair>{ int x ; int y ; pair(int _x,int _y){ x=_x ; y=_y ;} public int compareTo(pair p){ return (this.x<p.x ? -1 : (this.x>p.x ? 1 : (this.y<p.y ? -1 : (this.y>p.y ? 1 : 0)))) ; } } /* Main code starts here */ class Solver extends Template{ int MAXN = 1000000 ; int nd[] = new int[MAXN+1] ; int fac[] = new int[MAXN+1] ; void Fill(){ for(int i=1 ; i<=MAXN ; i++) fac[i] = i ; for(int i=2 ; i<=MAXN ; i++) if(fac[i]==i) for(int j=(2*i) ; j<=MAXN ; j+=i) fac[j] = i ; nd[1] = 1 ; for(int i=2 ; i<=MAXN ; i++){ int ct=1 ; int j = i ; int prm = fac[i] ; while(j%prm==0){j/=prm ; ct++ ;} nd[i] = ct*nd[j] ; } } int LM = 7 ; long seg[][] ; int lz[] ; int a[][] ; void build(int i,int s,int e){ if(s==e){ for(int j=0 ; j<=LM ; j++) seg[j][i] = a[j][s] ; return ; } int m = (s+e)/2 ; build(i+i,s,m) ; build(i+i+1,m+1,e) ; for(int j=0 ; j<=LM ; j++) seg[j][i] = seg[j][i+i]+seg[j][i+i+1] ; } void rLaz(int i,int s,int e){ if(lz[i]!=0){ int k = lz[i] ; for(int j=0 ; j<=LM ; j++){ if((j+k)<=LM) seg[j][i] = seg[j+k][i] ; else seg[j][i] = (e-s+1)*2 ; } if(s!=e){ lz[i+i]+=k ; lz[i+i+1]+=k ; } lz[i]=0 ; } } void upd(int i,int s,int e,int l,int r){ rLaz(i,s,e) ; if(r<s || e<l) return ; if(l<=s && e<=r){ lz[i]++ ; rLaz(i,s,e) ; return ; } int m = (s+e)/2 ; upd(i+i,s,m,l,r) ; upd(i+i+1,m+1,e,l,r) ; for(int j=0 ; j<=LM ; j++) seg[j][i] = seg[j][i+i]+seg[j][i+i+1] ; } long qry(int i,int s,int e,int l,int r){ rLaz(i,s,e) ; if(r<s || e<l) return 0 ; if(l<=s && e<=r) return seg[0][i] ; int m = (s+e)/2 ; return qry(i+i,s,m,l,r)+qry(i+i+1,m+1,e,l,r) ; } public void Solve() throws IOException{ Fill() ; int n = ip.i() ; int m = ip.i() ; a = new int[LM+1][n+1] ; int ct1[] = new int[n+1] ; seg = new long[LM+1][5*n] ; lz = new int[5*n] ; for(int i=1 ; i<=n ; i++) a[0][i] = ip.i() ; for(int i=1 ; i<=n ; i++) ct1[i] = ct1[i-1]+(a[0][i]==1 ? 1 : 0) ; for(int i=1 ; i<=n ; i++) if(a[0][i]==1) a[0][i] = 2 ; for(int j=1 ; j<=LM ; j++) for(int i=1 ; i<=n ; i++) a[j][i] = nd[a[j-1][i]] ; build(1,1,n) ; while(m--!=0){ int t = ip.i() ; int l = ip.i() ; int r = ip.i() ; if(t==1){ upd(1,1,n,l,r) ; }else{ pln(((qry(1,1,n,l,r)-ct1[r])+ct1[l-1])) ; } } } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
323f66ed603be019cdd5169618bc33d1
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query.
256 megabytes
/* Author: Ronak Agarwal, reader part not written by me*/ import java.io.* ; import java.util.* ; import static java.lang.Math.min ; import static java.lang.Math.max ; import static java.lang.Math.abs ; import static java.lang.Math.log ; import static java.lang.Math.pow ; import static java.lang.Math.sqrt ; /* Thread is created here to increase the stack size of the java code so that recursive dfs can be performed */ public class F{ public static void main(String[] args) throws IOException{ new Thread(null,new Runnable(){ public void run(){ exec_Code() ;} },"Solver",1l<<27).start() ; } static void exec_Code(){ try{ Solver Machine = new Solver() ; Machine.Solve() ; Machine.Finish() ;} catch(Exception e){ e.printStackTrace() ; print_and_exit() ;} catch(Error e){ e.printStackTrace() ; print_and_exit() ; } } static void print_and_exit(){ System.out.flush() ; System.exit(-1) ;} } /* Implementation of the Reader class */ class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar,numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is;} public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();} if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine(){ int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString() ; } public String s(){ 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 long l(){ 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 int i(){ 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } /* All the useful functions,constants,renamings are here*/ class Template{ /* Constants Section */ final int INT_MIN = Integer.MIN_VALUE ; final int INT_MAX = Integer.MAX_VALUE ; final long LONG_MIN = Long.MIN_VALUE ; final long LONG_MAX = Long.MAX_VALUE ; static long MOD = 1000000007 ; static Reader ip = new Reader() ; static PrintWriter op = new PrintWriter(System.out) ; /* Methods for writing */ static void p(Object o){ op.print(o) ; } static void pln(Object o){ op.println(o) ;} static void Finish(){ op.flush(); op.close(); } /* Implementation of operations modulo MOD */ static long inv(long a){ return powM(a,MOD-2) ; } static long m(long a,long b){ return (a*b)%MOD ; } static long d(long a,long b){ return (a*inv(b))%MOD ; } static long powM(long a,long b){ if(b<0) return powM(inv(a),-b) ; long ans=1 ; for( ; b!=0 ; a=(a*a)%MOD , b/=2) if((b&1)==1) ans = (ans*a)%MOD ; return ans ; } /* Renaming of some generic utility classes */ final static class mylist extends ArrayList<Integer>{} final static class myset extends TreeSet<Integer>{} final static class mystack extends Stack<Integer>{} final static class mymap extends TreeMap<Integer,Integer>{} } /* Implementation of the pair class, useful for every other problem */ class pair implements Comparable<pair>{ int x ; int y ; pair(int _x,int _y){ x=_x ; y=_y ;} public int compareTo(pair p){ return (this.x<p.x ? -1 : (this.x>p.x ? 1 : (this.y<p.y ? -1 : (this.y>p.y ? 1 : 0)))) ; } } /* Main code starts here */ class Solver extends Template{ int MAXN = 1000000 ; int nd[] = new int[MAXN+1] ; int fac[] = new int[MAXN+1] ; void Fill(){ for(int i=1 ; i<=MAXN ; i++) fac[i] = i ; for(int i=2 ; i<=MAXN ; i++) if(fac[i]==i) for(int j=(2*i) ; j<=MAXN ; j+=i) fac[j] = i ; nd[1] = 1 ; for(int i=2 ; i<=MAXN ; i++){ int ct=1 ; int j = i ; int prm = fac[i] ; while(j%prm==0){j/=prm ; ct++ ;} nd[i] = ct*nd[j] ; } } int LM = 7 ; long seg[][] ; int lz[] ; int a[][] ; void build(int i,int s,int e){ if(s==e){ for(int j=0 ; j<=LM ; j++) seg[j][i] = a[j][s] ; return ; } int m = (s+e)/2 ; build(i+i,s,m) ; build(i+i+1,m+1,e) ; for(int j=0 ; j<=LM ; j++) seg[j][i] = seg[j][i+i]+seg[j][i+i+1] ; } void rLaz(int i,int s,int e){ if(lz[i]!=0){ int k = lz[i] ; for(int j=0 ; j<=LM ; j++){ if((j+k)<=LM) seg[j][i] = seg[j+k][i] ; else seg[j][i] = (e-s+1)*2 ; } if(s!=e){ lz[i+i]+=k ; lz[i+i+1]+=k ; } lz[i]=0 ; } } void upd(int i,int s,int e,int l,int r){ rLaz(i,s,e) ; if(r<s || e<l) return ; if(l<=s && e<=r){ lz[i]++ ; rLaz(i,s,e) ; return ; } int m = (s+e)/2 ; upd(i+i,s,m,l,r) ; upd(i+i+1,m+1,e,l,r) ; for(int j=0 ; j<=LM ; j++) seg[j][i] = seg[j][i+i]+seg[j][i+i+1] ; } long qry(int i,int s,int e,int l,int r){ rLaz(i,s,e) ; if(r<s || e<l) return 0 ; if(l<=s && e<=r) return seg[0][i] ; int m = (s+e)/2 ; return qry(i+i,s,m,l,r)+qry(i+i+1,m+1,e,l,r) ; } public void Solve() throws IOException{ Fill() ; int n = ip.i() ; int m = ip.i() ; a = new int[LM+1][n+1] ; int ct1[] = new int[n+1] ; seg = new long[LM+1][5*n] ; lz = new int[5*n] ; for(int i=1 ; i<=n ; i++) a[0][i] = ip.i() ; for(int i=1 ; i<=n ; i++) ct1[i] = ct1[i-1]+(a[0][i]==1 ? 1 : 0) ; for(int i=1 ; i<=n ; i++) if(a[0][i]==1) a[0][i] = 2 ; for(int j=1 ; j<=LM ; j++) for(int i=1 ; i<=n ; i++) a[j][i] = nd[a[j-1][i]] ; build(1,1,n) ; while(m--!=0){ int t = ip.i() ; int l = ip.i() ; int r = ip.i() ; if(t==1){ upd(1,1,n,l,r) ; }else{ pln(((qry(1,1,n,l,r)-ct1[r])+ct1[l-1])) ; } } } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
8b0ab02420540b1ae469dcbcf24dec7b
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Objects; import java.util.StringTokenizer; public final class ProblemF { public static void main(String[] args) throws IOException { final FastIn in = FastIn.fromSystemIn(); final int n = in.nextInt(); final int m = in.nextInt(); long[] array = in.nextLongArray(n); // final SegmentTree st = new SegmentTree(array); final SegmentTreeEager segmentTreeEager = new SegmentTreeEager(array); final PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); for (int i = 0; i < m; i++) { final int opCode = in.nextInt(); final int l = in.nextInt(); final int r = in.nextInt(); switch (opCode) { case 1: //replace // st.replace(l, r); segmentTreeEager.replace(l, r); break; case 2: //sum // System.out.println(st.sum(l, r)); pw.println(segmentTreeEager.sum(l, r)); break; } } pw.flush(); pw.close(); } private static final int[] dArray; static { dArray = new int[1_000_001]; Arrays.fill(dArray, 2); dArray[1] = 1; for (int i = 2; i < dArray.length; i++) { for (int j = i + i; j < dArray.length; j += i) { dArray[j]++; } } } private static final class SegmentTreeEager { private final long[] sum; private final boolean[] hasOnlyFixedPoints; SegmentTreeEager(final long[] array) { final boolean isPowerOf2 = (array.length & (array.length- 1)) == 0; final int treeSize = isPowerOf2 ? array.length << 1 : Integer.highestOneBit(array.length) << 2; this.sum = new long[treeSize]; this.hasOnlyFixedPoints = new boolean[treeSize]; System.arraycopy(array, 0, sum, treeSize / 2, array.length); for (int i = treeSize / 2; i < treeSize / 2 + array.length; i++) { if (sum[i] <= 2) { hasOnlyFixedPoints[i] = true; } } for (int i = treeSize / 2 - 1; i > 0; i--) { sum[i] = sum[left(i)] + sum[right(i)]; hasOnlyFixedPoints[i] = hasOnlyFixedPoints[left(i)] && hasOnlyFixedPoints[right(i)]; } } void replace(int l, int r) { replace(1, 1, sum.length / 2, l, r); } void replace(int p, int pLeft, int pRight, int qLeft, int qRight) { if (qRight < pLeft || pRight < qLeft) { return; } else if (hasOnlyFixedPoints[p]) { return; } else if (pLeft == pRight) {//should be length 1, single element sum[p] = dArray[(int) sum[p]]; hasOnlyFixedPoints[p] = sum[p] <= 2; } else { final int lEnd = pLeft + (pRight - pLeft) / 2; replace(left(p), pLeft , lEnd , qLeft, qRight); replace(right(p), lEnd + 1, pRight, qLeft, qRight); sum[p] = sum[left(p)] + sum[right(p)]; hasOnlyFixedPoints[p] = hasOnlyFixedPoints[left(p)] && hasOnlyFixedPoints[right(p)]; } } long sum(int l, int r) { return sum(1, 1, sum.length / 2, l, r); } long sum(int p, int pLeft, int pRight, int qLeft, int qRight) { if (qRight < pLeft || pRight < qLeft) { return 0L; } else if (qLeft <= pLeft && pRight <= qRight) { return sum[p]; } else { final int lEnd = pLeft + (pRight - pLeft) / 2; return sum(left(p), pLeft, lEnd, qLeft, qRight) + sum(right(p), lEnd + 1, pRight, qLeft, qRight); } } private static int left(int p) { return p * 2; } private static int right(int p) { return p * 2 + 1; } } private static final class SegmentTree { private final long[] data; private final int[] repCount; private final boolean[] isLazy; private final int n; SegmentTree(final long[] array) { final boolean isPowerOf2 = (array.length & (array.length - 1)) == 0; final int treeSize; if (isPowerOf2) { treeSize = array.length << 1; } else { treeSize = Integer.highestOneBit(array.length) << 2; } this.data = new long[treeSize]; this.repCount = new int[treeSize]; this.isLazy = new boolean[treeSize]; this.n = array.length; System.arraycopy(array, 0, data, treeSize / 2, array.length); for (int i = treeSize / 2 - 1; i > 0; i--) { data[i] = data[left(i)] + data[right(i)]; } } private static int left(final int p) { return p * 2; } private static int right(final int p) { return p * 2 + 1; } private static int leftEnd(final int left, final int right) { return left + (right - left) / 2; } private static int rightStart(final int left, final int right) { return leftEnd(left, right) + 1; } private void replace(int left, int right) { replace(1, 1, n, left, right); } private void replace(int p, int pLeft, int pRight, int qLeft, int qRight) { if (qRight < pLeft || pRight < qLeft) { return; } else if (qLeft <= pLeft && pRight <= qRight) { repCount[p]++; isLazy[p] = true; } else { isLazy[left(p)] = true; repCount[left(p)] += repCount[p]; replace(left(p), pLeft, leftEnd(pLeft, pRight), qLeft, qRight); isLazy[right(p)] = true; repCount[right(p)] += repCount[p]; replace(right(p), rightStart(pLeft, pRight), pRight, qLeft, qRight); isLazy[p] = true; repCount[p] = 0; } } private long sum(int left, int right) { return sum(1, 1, n, left, right); } private long sum(int p, int pLeft, int pRight, int qLeft, int qRight) { if (qRight < pLeft || pRight < qLeft) { return 0; } else if (left(p) > data.length) { for (; repCount[p] > 0; repCount[p]--) { final int value = (int) data[p]; final int dValue = dArray[value]; if (value == dValue) { break; } data[p] = dValue; } isLazy[p] = false; return data[p]; } else if (qLeft <= pLeft && pRight <= qRight) { if (isLazy[p]) { isLazy[left(p)] = true; repCount[left(p)] += repCount[p]; isLazy[right(p)] = true; repCount[right(p)] += repCount[p]; isLazy[p] = false; repCount[p] = 0; data[p] = 0; data[p] += sum(left(p), pLeft, leftEnd(pLeft, pRight), qLeft, qRight); data[p] += sum(right(p), rightStart(pLeft, pRight), pRight, qLeft, qRight); } return data[p]; } else { if (isLazy[p]) { isLazy[left(p)] = true; repCount[left(p)] += repCount[p]; isLazy[right(p)] = true; repCount[right(p)] += repCount[p]; isLazy[p] = false; repCount[p] = 0; } long ret = 0; ret += sum(left(p), pLeft, leftEnd(pLeft, pRight), qLeft, qRight); ret += sum(right(p), rightStart(pLeft, pRight), pRight, qLeft, qRight); data[p] = data[left(p)] + data[right(p)]; return ret; } } } private static final class FastIn { private final BufferedReader br; private StringTokenizer tokenizer = null; private FastIn(final InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } static FastIn fromInputStream(final InputStream inputStream) { Objects.requireNonNull(inputStream); return new FastIn(inputStream); } static FastIn fromSystemIn() { return FastIn.fromInputStream(System.in); } private StringTokenizer tokenizer() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { final String nextLine = br.readLine(); tokenizer = new StringTokenizer(nextLine); } return tokenizer; } private String nextToken() throws IOException { return tokenizer().nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } int[] nextIntArray(final int size) throws IOException { final int[] array = new int[size]; for (int i = 0; i < array.length; i++) { array[i] = nextInt(); } return array; } long[] nextLongArray(final int size) throws IOException { assert size >= 0 : "size must be non-negative"; final long[] array = new long[size]; for (int i = 0; i < array.length; i++) { array[i] = nextLong(); } return array; } String nextString() throws IOException { return nextToken(); } } private static final class FastOut { private final PrintWriter pw; private FastOut(final OutputStream outputStream) { pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } static FastOut toSystemOut() { return fromOutputStream(System.out); } static FastOut fromOutputStream(final OutputStream outputStream) { Objects.requireNonNull(outputStream); return new FastOut(outputStream); } void prinltn(final String s) { pw.println(s); } void flush() { pw.flush(); } void close() { pw.close(); } } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
7bd5be4887ad746714d07f75493f816e
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query.
256 megabytes
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.util.HashMap; 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; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); SUMandREPLACE solver = new SUMandREPLACE(); solver.solve(1, in, out); out.close(); } static class SUMandREPLACE { final int MAX = (int) 1e6 + 5; int n; int m; int[] arr; int[] divisors = new int[MAX]; int[] spf = new int[MAX]; Node[] tree; void init() { spf[1] = 1; for (int i = 2; i < MAX; i++) spf[i] = (i % 2 == 0 ? 2 : i); for (int i = 3; i * i < MAX; i++) { if (spf[i] == i) { for (int j = i * i; j < MAX; j += i) { if (spf[j] == j) spf[j] = i; } } } Arrays.fill(divisors, 1); Occurrences<Integer> factors; for (int i = 2; i < MAX; i++) { factors = new Occurrences<>(); int j = i; while (j != 1) { factors.increment(spf[j]); j /= spf[j]; } for (int factor : factors.keySet()) { divisors[i] *= factors.get(factor) + 1; } } } public void solve(int testNumber, InputReader in, PrintWriter out) { init(); n = in.nextInt(); m = in.nextInt(); arr = in.nextIntArray(1, n); tree = new Node[4 * n + 5]; build(1, 1, n); for (int i = 1; i <= m; i++) { int arg1 = in.nextInt(), arg2 = in.nextInt(), arg3 = in.nextInt(); if (arg1 == 1) { update(1, 1, n, arg2, arg3); } else { out.println(query(1, 1, n, arg2, arg3)); } } } int l(int n) { return (n << 1); } int r(int n) { return (1 + (n << 1)); } int m(int l, int r) { return (l + r) >> 1; } void build(int n, int l, int r) { if (l == r) tree[n] = new Node(arr[l]); else { int m = m(l, r); build(l(n), l, m); build(r(n), m + 1, r); tree[n] = tree[l(n)].combine(tree[r(n)]); } } void update(int n, int l, int r, int a, int b) { if (l > b || r < a) return; if (tree[n].twos + tree[n].ones == (r - l + 1)) return; if (l == r) tree[n] = new Node(arr[l] = divisors[arr[l]]); else { int m = m(l, r); update(l(n), l, m, a, b); update(r(n), m + 1, r, a, b); tree[n] = tree[l(n)].combine(tree[r(n)]); } } long query(int n, int l, int r, int a, int b) { if (l > b || r < a) return 0; if (a <= l && r <= b) return tree[n].sum; return (query(l(n), l, m(l, r), a, b) + query(r(n), m(l, r) + 1, r, a, b)); } class Node { int twos; int ones; long sum; Node(long sum) { this.sum = sum; if (sum == 2) twos = 1; if (sum == 1) ones = 1; } Node(int twos, int ones, long sum) { this.twos = twos; this.ones = ones; this.sum = sum; } Node combine(Node n) { return (new Node(ones + n.ones, twos + n.twos, sum + n.sum)); } } } static class Occurrences<E> extends HashMap<E, Integer> { public void increment(E key) { Integer occ = get(key); if (occ == null) occ = 0; put(key, occ + 1); } } static class InputReader { private StringTokenizer tokenizer; private BufferedReader reader; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private void fillTokenizer() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } } public String next() { fillTokenizer(); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] nextIntArray(int offset, int length) { int[] arr = new int[offset + length]; for (int i = offset; i < offset + length; i++) { arr[i] = nextInt(); } return arr; } } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
f51498ee97a86c3b25c1c83804410d9c
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query.
256 megabytes
import java.util.*; import java.io.*; public class MainClass { static int[] div; public static void main(String[] args) throws IOException { Reader in = new Reader(); int n = in.nextInt(); int m = in.nextInt(); div = new int[1000000 + 5]; Arrays.fill(div, 1); for (int i=2;i<div.length;i++) for (int j=i;j<div.length;j+=i) if (j % i == 0) div[j]++; StringBuilder stringBuilder = new StringBuilder(); int[] A = new int[n]; BIT BIT = new BIT(n + 10); for (int i=0;i<n;i++) { A[i] = in.nextInt(); BIT.update(i + 1, A[i]); } TreeSet<Integer> h = new TreeSet<>(); for (int i=0;i<n;i++) { if (A[i] > 2) h.add(i); } while (m -- > 0) { int type = in.nextInt(); int l = in.nextInt() - 1; int r = in.nextInt() - 1; if (type == 1) { int ff = l - 1; while (h.higher(ff) != null && h.higher(ff) <= r) { ff = h.higher(ff); int oldValue = A[ff]; BIT.update(ff + 1, -oldValue); int newValue = findDiv(oldValue, 1); A[ff] = newValue; BIT.update(ff + 1, newValue); if (newValue <= 2) h.remove(ff); } } else { long sum = BIT.sum(r + 1) - BIT.sum(l); stringBuilder.append(sum).append("\n"); } } System.out.println(stringBuilder); } public static int findDiv(int n, int times) { int count = 0; while (count < times) { if (div[n] == n) break; else { n = div[n]; count++; } } return n; } } class BIT { int size; long[] table; public BIT(int size) { table = new long[size]; this.size = size; } void update(int i, long delta) { while (i < size) { table[i] += delta; i += Integer.lowestOneBit(i); } } long sum(int i) { long sum = 0L; while (i > 0) { sum += table[i]; i -= Integer.lowestOneBit(i); } return sum; } } 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') break; 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(); } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
b11676918bf84360f1ed06c7520e863b
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * @author pttrung */ public class F_Edu_Round_37 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int m = in.nextInt(); int max = 1000001; int[] dp = new int[max]; Arrays.fill(dp, 1); for (int i = 2; i < max; i++) { if (dp[i] == 1) { for (int j = i + i; j < max; j += i) { int c = 0; int st = j; while (st % i == 0) { c++; st /= i; } dp[j] *= (c + 1); } dp[i]++; } } FT tree = new FT (n + 2); int[]data = new int[n + 1]; for(int i = 1; i <= n; i++){ data[i] = in.nextInt(); tree.update(i, data[i]); } TreeSet<Integer> set = new TreeSet(); for(int i = 1; i <= n; i++){ set.add(i); } for(int i = 0; i < m; i++){ int t = in.nextInt(); int l = in.nextInt(); int r = in.nextInt(); if(t == 1){ Integer v = set.ceiling(l); while(v != null && v <= r){ int nxt = dp[data[v]]; if(nxt == data[v]){ set.remove(v); }else{ //System.out.println(v + " " + data[v] + "->" + nxt + " " + l + " " + r + " " + (nxt - data[v])); tree.update(v, nxt - data[v]); data[v] = nxt; } v = set.higher(v); } }else{ long re = tree.get(r) - (l == 1 ? 0 : tree.get(l - 1)); out.println(re); } } out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
5e653a95532abad5d2e784cd2342fdd2
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query.
256 megabytes
/* * Author: Minho Kim (ISKU) * Date: February 02, 2018 * E-mail: [email protected] * * https://github.com/ISKU/Algorithm * http://codeforces.com/problemset/problem/920/F */ import java.util.*; import java.io.*; public class F { private static int[] divisor; private static long[] tree; private static boolean[] change; private static int H; public static void main(String... args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); divisor = new int[1000001]; for (int i = 1; i <= 1000000; i++) for (int j = i; j <= 1000000; j += i) divisor[j]++; H = 1 << (int) Math.ceil(Math.log(N) / Math.log(2)); tree = new long[H * 2]; change = new boolean[H * 2]; st = new StringTokenizer(br.readLine()); for (int i = H; st.hasMoreTokens(); i++) { long element = Long.parseLong(st.nextToken()); if (element <= 2) change[i] = true; tree[i] = element; } for (int i = H - 1; i >= 1; i--) tree[i] = tree[i * 2] + tree[i * 2 + 1]; while (M-- > 0) { st = new StringTokenizer(br.readLine()); int t = Integer.parseInt(st.nextToken()); int l = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); if (t == 1) update(1, H, 1, l, r); if (t == 2) { bw.write(String.valueOf(sum(1, H, 1, l, r))); bw.newLine(); } } bw.close(); } private static long sum(int l, int r, int i, int L, int R) { if (r < L || R < l) return 0; if (L <= l && r <= R) return tree[i]; int mid = (l + r) / 2; return sum(l, mid, i * 2, L, R) + sum(mid + 1, r, i * 2 + 1, L, R); } private static void update(int l, int r, int i, int L, int R) { if (r < L || R < l) return; if (change[i]) return; if (l == r) { tree[i] = divisor[(int) tree[i]]; if (tree[i] <= 2) change[i] = true; return; } int mid = (l + r) / 2; update(l, mid, i * 2, L, R); update(mid + 1, r, i * 2 + 1, L, R); tree[i] = tree[i * 2] + tree[i * 2 + 1]; change[i] = change[i * 2] & change[i * 2 + 1]; } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
8c2be2a17b2d92337ca9df0a66d6d85c
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query.
256 megabytes
import java.util.*; import java.io.*; public class SUMandREPLACE { /************************ SOLUTION STARTS HERE ************************/ static int tau[]; static final int MAX = (int) 1e6; static { tau = new int[MAX + 1]; for(int i = 1; i <= MAX; i++) for(int j = i; j <= MAX; j+= i) tau[j]++; } static class FenwickTree { /**************** * DONT USE BIT IF YOU UPDATE INDEX 0 (causes infinite loop) ******************/ long tree[]; int len; FenwickTree(int len) { this.len = len; tree = new long[len + 10]; } void update(int idx, int val) { if (idx == 0) throw new IndexOutOfBoundsException("BIT IS NOT ZERO INDEXED"); for (; idx <= len; idx += (idx & -idx)) tree[idx] += val; } long query(int idx) { long sum = 0; for (; idx > 0; idx -= (idx & -idx)) sum += tree[idx]; return sum; } long query(int L, int R) { return query(R) - query(L - 1); } } private static void solve() { FasterScanner scan = new FasterScanner(); int n = scan.nextInt(); int m = scan.nextInt(); int a[] = new int[n + 1]; for(int i = 1; i <= n; i++) a[i] = scan.nextInt(); int ones[] = Arrays.stream(a).map(val -> val == 1 ? 1 : 0).toArray(); for(int i = 1; i <= n; i++) ones[i] += ones[i - 1]; FenwickTree twosBIT = new FenwickTree(n); for(int i = 1; i <= n; i++) if(a[i] == 2) twosBIT.update(i, 1); TreeMap<Integer, Integer> othersMap = new TreeMap<>(); for(int i = 1; i <= n; i++) if(a[i] > 2) othersMap.put(i, a[i]); FenwickTree othersBIT = new FenwickTree(n); for(int i = 1; i <= n; i++) if(a[i] > 2) othersBIT.update(i, a[i]); while(m-->0) { int type = scan.nextInt(); int L = scan.nextInt(); int R = scan.nextInt(); if(type == 1) { // replace Map.Entry<Integer, Integer> curr = othersMap.ceilingEntry(L); while(curr != null && curr.getKey() <= R) { if(tau[curr.getValue()] == 2) { othersMap.remove(curr.getKey()); twosBIT.update(curr.getKey(), 1); othersBIT.update(curr.getKey(), -curr.getValue()); } else { othersMap.replace(curr.getKey(), tau[curr.getValue()]); othersBIT.update(curr.getKey(), -curr.getValue() + tau[curr.getValue()]); } curr = othersMap.higherEntry(curr.getKey()); } } else { long sum = (ones[R] - ones[L - 1]) + 2L * twosBIT.query(L, R) + othersBIT.query(L, R); println(sum); } } } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE **********************/ public static void main(String[] args) throws IOException { // reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); st = null; solve(); // reader.close(); writer.close(); } static class FasterScanner { private byte[] buf = new byte[1024]; private int tmp_curChar; private int tmp_numChars; public int read() { if (tmp_numChars == -1) throw new InputMismatchException(); if (tmp_curChar >= tmp_numChars) { tmp_curChar = 0; try { tmp_numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (tmp_numChars <= 0) return -1; } return buf[tmp_curChar++]; } 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; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static BufferedReader reader; static PrintWriter writer; static StringTokenizer st; static String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} static String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} static int nextInt() {return Integer.parseInt(next());} static long nextLong() {return Long.parseLong(next());} static double nextDouble(){return Double.parseDouble(next());} static char nextChar() {return next().charAt(0);} static int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} static long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} static int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} static long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} static void print(Object o) { writer.print(o); } static void println(Object o){ writer.println(o);} /************************ TEMPLATE ENDS HERE ************************/ }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
1b0907f58c06dbfe39ea6ddaa5c85c28
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query.
256 megabytes
import java.awt.List; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; public class Main { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int[] spf=enumLowestPrimeFactors(1000000); int[] nd=enumNumDivisorsFast(1000000,spf); int n=ni(), Q=ni(); int[] a=na(n); long[] ft=new long[n+1]; LST lst=new LST(n); for(int i=0;i<n;i++) { addFenwick(ft,i,a[i]); if(a[i]>2) { lst.set(i); } } for(int q=0;q<Q;q++) { int t=ni(); int l=ni()-1; int r=ni()-1; if(t==1) { for(int i=lst.next(l);i!=-1&&i<=r;i=lst.next(i+1)) { addFenwick(ft,i,nd[a[i]]-a[i]); a[i]=nd[a[i]]; if(a[i]<=2) { lst.unset(i); } } } else { out.println(sumFenwick(ft,r)-sumFenwick(ft,l-1)); } } } public static long sumFenwick(long[] ft, int i) { long sum = 0; for(i++;i > 0;i -= i&-i)sum += ft[i]; return sum; } public static void addFenwick(long[] ft, int i, long v) { if(v == 0)return; int n = ft.length; for(i++;i < n;i += i&-i)ft[i] += v; } public static int[] enumNumDivisorsFast(int n, int[] lpf) { int[] nd = new int[n+1]; nd[1] = 1; for(int i = 2;i <= n;i++){ int j = i, e = 0; while(j % lpf[i] == 0){ j /= lpf[i]; e++; } nd[i] = nd[j] * (e+1); } return nd; } public static int[] enumLowestPrimeFactors(int n) { int tot = 0; int[] lpf = new int[n + 1]; int u = n + 32; double lu = Math.log(u); int[] primes = new int[(int) (u / lu + u / lu / lu * 1.5)]; for (int i = 2; i <= n; i++) lpf[i] = i; for (int p = 2; p <= n; p++) { if (lpf[p] == p) primes[tot++] = p; int tmp; for (int i = 0; i < tot && primes[i] <= lpf[p] && (tmp = primes[i] * p) <= n; i++) { lpf[tmp] = primes[i]; } } return lpf; } public static class LST { public long[][] set; public int n; // public int size; public LST(int n) { this.n = n; int d = 1; for(int m = n;m > 1;m>>>=6, d++); set = new long[d][]; for(int i = 0, m = n>>>6;i < d;i++, m>>>=6){ set[i] = new long[m+1]; } // size = 0; } // [0,r) public LST setRange(int r) { for(int i = 0;i < set.length;i++, r=r+63>>>6){ for(int j = 0;j < r>>>6;j++){ set[i][j] = -1L; } if((r&63) != 0)set[i][r>>>6] |= (1L<<r)-1; } return this; } // [0,r) public LST unsetRange(int r) { if(r >= 0){ for(int i = 0;i < set.length;i++, r=r+63>>>6){ for(int j = 0;j < r+63>>>6;j++){ set[i][j] = 0; } if((r&63) != 0)set[i][r>>>6] &= ~((1L<<r)-1); } } return this; } public LST set(int pos) { if(pos >= 0 && pos < n){ // if(!get(pos))size++; for(int i = 0;i < set.length;i++, pos>>>=6){ set[i][pos>>>6] |= 1L<<pos; } } return this; } public LST unset(int pos) { if(pos >= 0 && pos < n){ // if(get(pos))size--; for(int i = 0;i < set.length && (i == 0 || set[i-1][pos] == 0L);i++, pos>>>=6){ set[i][pos>>>6] &= ~(1L<<pos); } } return this; } public boolean get(int pos) { return pos >= 0 && pos < n && set[0][pos>>>6]<<~pos<0; } public int prev(int pos) { for(int i = 0;i < set.length && pos >= 0;i++, pos>>>=6, pos--){ int pre = prev(set[i][pos>>>6], pos&63); if(pre != -1){ pos = pos>>>6<<6|pre; while(i > 0)pos = pos<<6|63-Long.numberOfLeadingZeros(set[--i][pos]); return pos; } } return -1; } public int next(int pos) { for(int i = 0;i < set.length && pos>>>6 < set[i].length;i++, pos>>>=6, pos++){ int nex = next(set[i][pos>>>6], pos&63); if(nex != -1){ pos = pos>>>6<<6|nex; while(i > 0)pos = pos<<6|Long.numberOfTrailingZeros(set[--i][pos]); return pos; } } return -1; } private static int prev(long set, int n) { long h = Long.highestOneBit(set<<~n); if(h == 0L)return -1; return Long.numberOfTrailingZeros(h)-(63-n); } private static int next(long set, int n) { long h = Long.lowestOneBit(set>>>n); if(h == 0L)return -1; return Long.numberOfTrailingZeros(h)+n; } @Override public String toString() { ArrayList<Integer> list = new ArrayList<Integer>(); for(int pos = next(0);pos != -1;pos = next(pos+1)){ list.add(pos); } return list.toString(); } } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private 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 boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(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 char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { 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 long nl() { 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) { System.out.println(Arrays.deepToString(o)); } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
5cc4f6eef186da6d44047244cc8ac18c
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r — for every replace ai with D(ai); SUM l r — calculate . Print the answer for each SUM query.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.*; import java.text.DecimalFormat; import java.util.*; public class Main { private static final int MAX = 1000*1000,MAXP2 = 1 << 19,MAXST = MAXP2 << 1; private static int n,m; private static int [] A; private static int [] sig0; private static long [] ST = new long[MAXST]; private static boolean [] finite = new boolean[MAXST]; private static void init(){ sig0 = new int[MAX + 1]; for (int i = 1;i <= MAX;i++) for (int j = i;j <= MAX;j += i) sig0[j] ++; } private static void build(int node,int s,int e) { if (s == e) { ST[node] = A[s]; finite[node] = A[s] == sig0[A[s]]; return; } int m = (s + e) >> 1,left = node*2 + 1,right = left + 1; build(left,s,m); build(right,m+1,e); ST[node] = ST[left] + ST[right]; finite[node] = finite[left] && finite[right]; } private static void update(int node,int s,int e,int l,int r) { if (finite[node]) return; if (s == e) { A[s] = sig0[A[s]]; ST[node] = A[s]; finite[node] = A[s] == sig0[A[s]]; return; } int m = (s + e) >> 1,left = node*2 + 1,right = left + 1; if (r <= m) update(left,s,m,l,r); else if (m < l) update(right,m+1,e,l,r); else { update(left,s,m,l,m); update(right,m+1,e,m+1,r); } ST[node] = ST[left] + ST[right]; finite[node] = finite[left] && finite[right]; } private static long query(int node,int s,int e,int l,int r) { if (l <= s && e <= r) return ST[node]; int m = (s + e) >> 1,left = node*2 + 1,right = left + 1; if (r <= m) return query(left,s,m,l,r); else if (m < l) return query(right,m+1,e,l,r); else return query(left,s,m,l,m) + query(right,m+1,e,m+1,r); } public static void main(String[] args) throws Exception{ IO io = new IO(null,null); init(); n = io.getNextInt(); m = io.getNextInt(); A = new int[n + 1]; for (int i = 1;i <= n;i++) A[i] = io.getNextInt(); build(0,1,n); while (m-- > 0) { int t = io.getNextInt(),l = io.getNextInt(),r = io.getNextInt(); if (t == 1) update(0,1,n,l,r); else io.println(query(0,1,n,l,r)); } io.close(); } } class IO{ private BufferedReader br; private StringTokenizer st; private PrintWriter writer; private String inputFile,outputFile; public boolean hasMore() throws IOException{ if(st != null && st.hasMoreTokens()) return true; if(br != null && br.ready()) return true; return false; } public String getNext() throws FileNotFoundException, IOException{ while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String getNextLine() throws FileNotFoundException, IOException{ return br.readLine().trim(); } public int getNextInt() throws FileNotFoundException, IOException{ return Integer.parseInt(getNext()); } public long getNextLong() throws FileNotFoundException, IOException{ return Long.parseLong(getNext()); } public void print(double x,int num_digits) throws IOException{ writer.printf("%." + num_digits + "f" ,x); } public void println(double x,int num_digits) throws IOException{ writer.printf("%." + num_digits + "f\n" ,x); } public void print(Object o) throws IOException{ writer.print(o.toString()); } public void println(Object o) throws IOException{ writer.println(o.toString()); } public IO(String x,String y) throws FileNotFoundException, IOException{ inputFile = x; outputFile = y; if(x != null) br = new BufferedReader(new FileReader(inputFile)); else br = new BufferedReader(new InputStreamReader(System.in)); if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile))); else writer = new PrintWriter(new OutputStreamWriter(System.out)); } protected void close() throws IOException{ br.close(); writer.close(); } public void outputArr(Object [] A) throws IOException{ int L = A.length; for (int i = 0;i < L;i++) { if(i > 0) writer.print(" "); writer.print(A[i]); } writer.print("\n"); } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output