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
listlengths
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
33605368112227c9ef8fe91e9c1b7379
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k > 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x > 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
import java.io.*; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } class GraphBuilder { int n, m; int[] x, y; int index; int[] size; GraphBuilder(int n, int m) { this.n = n; this.m = m; x = new int[m]; y = new int[m]; size = new int[n]; } void add(int u, int v) { x[index] = u; y[index] = v; size[u]++; size[v]++; index++; } int[][] build() { int[][] graph = new int[n][]; for (int i = 0; i < n; i++) { graph[i] = new int[size[i]]; } for (int i = index - 1; i >= 0; i--) { int u = x[i]; int v = y[i]; graph[u][--size[u]] = v; graph[v][--size[v]] = u; } return graph; } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long[] readLongArray(int size) throws IOException { long[] res = new long[size]; for (int i = 0; i < size; i++) { res[i] = readLong(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Template().run(); // new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } HashMap<String, Integer> map = new HashMap<>(); int[] name; List<Integer>[] childs; int[] tin; int[] tout; int time; List<Integer>[] layers; int[] he; void dfs(int x, int h) { he[x] = h; layers[h].add(x); tin[x] = time++; for (int y : childs[x]) { dfs(y, h + 1); } tout[x] = time++; } class Query implements Comparable<Query> { int l, r; int index; public Query(int l, int r, int index) { this.l = l; this.r = r; this.index = index; } @Override public int compareTo(Query o) { if (l != o.l) return l - o.l; return r - o.r; } } void solve() throws IOException { int n = readInt() + 1; childs = createGraphList(n); int root = 0; name = new int[n]; tin = new int[n]; tout = new int[n]; he = new int[n]; for (int i = 0; i < n - 1; i++) { String nm = readString(); int p = readInt(); if (!map.containsKey(nm)) { map.put(nm, map.size()); } name[i + 1] = map.get(nm); childs[p].add(i + 1); } layers = createGraphList(n * 2); dfs(root, 0); int m = readInt(); List<Query>[] queries = createGraphList(n * 2); int[] answer = new int[m]; for (int i = 0; i < m; i++) { int v = readInt(); int k = readInt(); List<Integer> targetLayer = layers[he[v] + k]; int li = findLeftChild(targetLayer, v); int ri = findRightChild(targetLayer, v); if (li > ri) continue; queries[he[v] + k].add(new Query(li, ri, i)); } for (int l = 0; l < queries.length; l++) { solveForLayer(layers[l], queries[l], answer); } for (int x : answer) { out.println(x); } } void solveForLayer(List<Integer> layer, List<Query> queries, int[] ans) { HashMap<Integer, ArrayDeque<Integer>> map = new HashMap<>(); for (int i = 0; i < layer.size(); i++) { int v = layer.get(i); if (!map.containsKey(name[v])) { map.put(name[v], new ArrayDeque<>()); } map.get(name[v]).add(i); } BIT bit = new BIT(layer.size()); for (Map.Entry<Integer, ArrayDeque<Integer>> entry : map.entrySet()) { bit.update(entry.getValue().peek(), 1); } Collections.sort(queries); ArrayDeque<Query> deq = new ArrayDeque<>(); deq.addAll(queries); for (int i = 0; i < layer.size(); i++) { int v = layer.get(i); while (deq.size() > 0 && deq.peek().l == i) { Query query = deq.poll(); ans[query.index] = bit.get(query.r); } ArrayDeque<Integer> d = map.get(name[v]); d.poll(); bit.update(i, -1); if (d.size() > 0) { bit.update(d.peek(), 1); } } } int findLeftChild(List<Integer> list, int root) { int l = 0; int r = list.size() - 1; int answer = Integer.MAX_VALUE; while (l <= r) { int mid = (l + r) >> 1; int x = list.get(mid); if (tin[x] >= tin[root] && tout[x] <= tout[root]) { answer = mid; r = mid - 1; } else if (tout[x] < tin[root]) { l = mid + 1; } else { r = mid - 1; } } return answer; } int findRightChild(List<Integer> list, int root) { int l = 0; int r = list.size() - 1; int answer = Integer.MIN_VALUE; while (l <= r) { int mid = (l + r) >> 1; int x = list.get(mid); if (tin[x] >= tin[root] && tout[x] <= tout[root]) { answer = mid; l = mid + 1; } else if (tout[x] < tin[root]) { l = mid + 1; } else { r = mid - 1; } } return answer; } class BIT { int[] data; BIT(int n) { data = new int[n]; } void update(int at, int diff) { while (at < data.length) { data[at] += diff; at = at | (at + 1); } } int get(int at) { int res = 0; while (at >= 0) { res += data[at]; at = (at & (at + 1)) - 1; } return res; } } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 8
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≀ n ≀ 105) β€” the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≀ ri ≀ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≀ m ≀ 105) β€” the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≀ vi, ki ≀ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers β€” the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output
PASSED
3f7911439ea06dbfd2a744e6c9236fce
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k &gt; 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x &gt; 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
import com.sun.org.apache.bcel.internal.generic.FieldGen; import com.sun.org.apache.xpath.internal.operations.Bool; import java.io.*; import java.math.BigInteger; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } class GraphBuilder { int n, m; int[] x, y; int index; int[] size; GraphBuilder(int n, int m) { this.n = n; this.m = m; x = new int[m]; y = new int[m]; size = new int[n]; } void add(int u, int v) { x[index] = u; y[index] = v; size[u]++; size[v]++; index++; } int[][] build() { int[][] graph = new int[n][]; for (int i = 0; i < n; i++) { graph[i] = new int[size[i]]; } for (int i = index - 1; i >= 0; i--) { int u = x[i]; int v = y[i]; graph[u][--size[u]] = v; graph[v][--size[v]] = u; } return graph; } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long[] readLongArray(int size) throws IOException { long[] res = new long[size]; for (int i = 0; i < size; i++) { res[i] = readLong(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Template().run(); // new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } class Query { int depth; int index; public Query(int depth, int index) { this.depth = depth; this.index = index; } } int[] answer; int[] name; List<Integer>[] graph; List<Query>[] queries; Set<Integer> merge(Set<Integer> a, Set<Integer> b) { if (a.size() > b.size()) { a.addAll(b); return a; } else { b.addAll(a); return b; } } ArrayList<Set<Integer>> merge(ArrayList<Set<Integer>> a, ArrayList<Set<Integer>> b) { if (a.size() < b.size()) { return merge(b, a); } int count = b.size(); for (int i = 0; i < count; i++) { a.set(a.size() - 1 - i, merge(a.get(a.size() - 1 - i), b.get(b.size() - 1 - i))); } return a; } ArrayList<Set<Integer>> dfs(int x) { ArrayList<Set<Integer>> result = new ArrayList<>(); for (int y : graph[x]) { ArrayList<Set<Integer>> childAns = dfs(y); result = merge(result, childAns); } HashSet<Integer> set = new HashSet<>(); set.add(name[x]); result.add(set); for (Query query : queries[x]) { int setIndex = result.size() - 1 - query.depth; if (setIndex >= 0) { answer[query.index] = result.get(setIndex).size(); } } return result; } void solve() throws IOException { int n = readInt(); this.name = new int[n]; graph = createGraphList(n); queries = createGraphList(n); HashMap<String, Integer> nameMap = new HashMap<>(); List<Integer> roots = new ArrayList<>(); for (int i = 0; i < n; i++) { String name = readString(); int parent = readInt(); int nameIndex = nameMap.computeIfAbsent(name, k -> nameMap.size()); this.name[i] = nameIndex; if (parent == 0) { roots.add(i); } else { graph[parent - 1].add(i); } } int m = readInt(); for (int i = 0; i < m; i++) { int v = readInt() - 1; int k = readInt(); queries[v].add(new Query(k, i)); } answer = new int[m]; for (int r : roots) { dfs(r); } for (int ans : answer) { out.println(ans); } } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 8
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≀ n ≀ 105) β€” the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≀ ri ≀ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≀ m ≀ 105) β€” the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≀ vi, ki ≀ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers β€” the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output
PASSED
fb252065529371689edca5a253f01a8e
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k &gt; 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x &gt; 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
import java.io.*; import java.util.*; public class Program { static BufferedReader in; static PrintWriter out; static StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } private static String readString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tok.nextToken(); } private static int readInt() { return Integer.parseInt(readString()); } private static double readDouble() { return Double.parseDouble(readString()); } private static long readLong() { return Long.parseLong(readString()); } static int timer = 0; static int[] tin; static int[] tout; static List<Integer>[] graph; static int[] dist; static int pointer = 0; static int[] renamedNodes; private static void solve() throws IOException { int n = readInt(); String[] names = new String[n]; graph = new ArrayList[n]; for (int i = 0; i < n; i++) { graph[i] = new ArrayList<>(); } tin = new int[n]; tout = new int[n]; dist = new int[n]; renamedNodes = new int[n]; Map<String, Integer> mappedNames = new HashMap<>(); List<Integer> roots = new ArrayList<>(); for (int i = 0; i < n; i++) { names[i] = readString(); mappedNames.put(names[i], i); int parent = readInt() - 1; if (parent > -1) { graph[parent].add(i); } else { roots.add(i); } } bfs(roots); for (int v : roots) { dfs(v, 0); } int q = readInt(); Request[] requests = new Request[q]; for (int i = 0; i < q; i++) { requests[i] = new Request(readInt() - 1, readInt(), i); } Arrays.sort(requests); int[] ans = new int[q]; int[] lastSeen = new int[n]; int[] temp = new int[n]; Arrays.fill(temp, n); for (int i = n - 1; i >= 0; i--) { int oldIndex = renamedNodes[i]; int value = mappedNames.get(names[oldIndex]); lastSeen[i] = temp[value]; temp[value] = i; } SegmentTree tree = new SegmentTree(n + 1); Set<Integer> used = new HashSet<>(); for (int i = 0; i < n; i++) { int oldIndex = renamedNodes[i]; int value = mappedNames.get(names[oldIndex]); if (!used.contains(value)) { used.add(value); tree.addValue(0, 0, n + 1, i, 1); } } int pointer = 0; for (int left = 0; left < n; left++) { while (pointer < q && requests[pointer].left == left) { int sum = tree.getSum(0, 0, n + 1, left, requests[pointer].right + 1); ans[requests[pointer].index] = sum; pointer++; } tree.addValue(0, 0, n + 1, lastSeen[left], 1); } for (int i = 0; i < q; i++) { out.println(ans[i]); } } private static void bfs(List<Integer> start) { Deque<Integer> deque = new ArrayDeque<>(); deque.addAll(start); while (!deque.isEmpty()) { int v = deque.pollFirst(); renamedNodes[pointer++] = v; deque.addAll(graph[v]); } } private static void dfs(int v, int h) { tin[v] = timer++; dist[v] = h; for (int to : graph[v]) { dfs(to, h + 1); } tout[v] = timer; } static class Request implements Comparable<Request> { int v, k, index, left, right; public Request(int v, int k, int index) { this.v = v; this.k = k; this.index = index; this.left = find(v, k, true); this.right = find(v, k, false); if (left < 0 || right < 0) { left = 0; right = -1; } } @Override public int compareTo(Request o) { int t = Integer.compare(this.left, o.left); return t != 0 ? t : Integer.compare(this.right, o.right); } } static int find(int parent, int depth, boolean isLeft) { int left = 0; int right = tout.length - 1; int res = -1; while (left <= right) { int mid = (left + right) / 2; if (dist[renamedNodes[mid]] < dist[parent] + depth) { left = mid + 1; continue; } if (dist[renamedNodes[mid]] > dist[parent] + depth) { right = mid - 1; continue; } if (isUpper(parent, renamedNodes[mid])) { res = mid; if (isLeft) { right = mid - 1; } else { left = mid + 1; } } else { if (tin[parent] > tin[renamedNodes[mid]]) { left = mid + 1; } else { right = mid - 1; } } } return res; } static boolean isUpper(int a, int b) { return tin[a] < tin[b] && tout[a] >= tout[b]; } static class SegmentTree { int n; int[] t; public SegmentTree(int n) { this.n = n; this.t = new int[4 * n]; } int getSum(int idx, int l, int r, int L, int R) { if (l == L && r == R) { return t[idx]; } int mid = (l + r) / 2; int res = 0; if (L < mid) { res += getSum(idx * 2 + 1, l, mid, L, Math.min(mid, R)); } if (R > mid) { res += getSum(idx * 2 + 2, mid, r, Math.max(mid, L), R); } return res; } void addValue(int idx, int l, int r, int index, int value) { if (r - l == 1) { t[idx] = value; return; } int mid = (l + r) / 2; if (index < mid) { addValue(idx * 2 + 1, l, mid, index, value); } else { addValue(idx * 2 + 2, mid, r, index, value); } t[idx] = t[idx * 2 + 1] + t[idx * 2 + 2]; } } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 8
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≀ n ≀ 105) β€” the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≀ ri ≀ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≀ m ≀ 105) β€” the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≀ vi, ki ≀ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers β€” the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output
PASSED
295edc4b441159725c801a217fdcb647
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k &gt; 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x &gt; 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.Set; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.io.FileNotFoundException; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.io.Writer; import java.io.UnsupportedEncodingException; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author MaxHeap */ 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); EBloodCousinsReturn solver = new EBloodCousinsReturn(); solver.solve(1, in, out); out.close(); } static class EBloodCousinsReturn { int n; BiMap<String, Integer> people; List<Integer>[] g; Map<Integer, Set<String>>[] count; List<IntPair>[] queries; int[] size; int[] ans; void dfs(int u, int p) { size[u] = 1; for (int v : g[u]) { if (v != p) { dfs(v, u); size[u] += size[v]; } } } void compute(int u, int p, int depth) { int big = 0; for (int v : g[u]) { if (v != p) { compute(v, u, depth + 1); if (size[big] < size[v]) { big = v; } } } if (big > 0) { count[u] = count[big]; } Set<String> set = count[u].get(depth); if (set == null) { set = new HashSet<>(); } set.add(people.getByValue(u)); count[u].put(depth, set); for (int v : g[u]) { if (v != p && v != big) { for (Entry<Integer, Set<String>> occ : count[v].entrySet()) { Set<String> strings = count[u].get(occ.getKey()); if (strings == null) { count[u].put(occ.getKey(), new HashSet<>()); } count[u].get(occ.getKey()).addAll(occ.getValue()); } } } for (IntPair query : queries[u]) { int newDepth = depth + query.first; Set<String> val = count[u].get(newDepth); if (val != null) { ans[query.second] = val.size(); } } } public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); g = GraphUtils.generateGraph(n + 1); people = new BiMap<>(); List<Integer> roots = new ArrayList<>(); for (int i = 0; i < n; ++i) { String name = in.next(); people.put(name, i + 1); int parent = in.nextInt(); if (parent != 0) { g[i + 1].add(parent); g[parent].add(i + 1); } else { roots.add(i + 1); } } size = new int[n + 1]; count = new HashMap[n + 1]; queries = new ArrayList[n + 1]; for (int i = 0; i <= n; ++i) { count[i] = new HashMap<>(); queries[i] = new ArrayList<>(); } int q = in.nextInt(); for (int i = 0; i < q; ++i) { int u = in.nextInt(); int lev = in.nextInt(); queries[u].add(Factories.makeIntPair(lev, i)); } ans = new int[q + 1]; for (int root : roots) { dfs(root, 0); compute(root, 0, 1); } for (int i = 0; i < q; ++i) { out.println(ans[i]); } } } static interface FastIO { } static class GraphUtils { private GraphUtils() { } public static <T> List<T>[] generateGraph(int n) { List<T>[] graph = new ArrayList[n]; for (int i = 0; i < n; i++) { graph[i] = new ArrayList<>(); } return graph; } } static class BiMap<K, V> { private Map<K, V> toValue; private Map<V, K> toKey; public BiMap() { toValue = new HashMap<>(); toKey = new HashMap<>(); } public void put(K key, V value) { toValue.put(key, value); toKey.put(value, key); } public K getByValue(V value) { return toKey.get(value); } public String toString() { return "BiMap{" + "toValue=" + toValue + ", toKey=" + toKey + '}'; } } static class InputReader implements FastIO { private InputStream stream; private static final int DEFAULT_BUFFER_SIZE = 1 << 16; private static final int EOF = -1; private byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (this.numChars == EOF) { throw new UnknownError(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException ex) { throw new InputMismatchException(); } if (this.numChars <= 0) { return EOF; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public String next() { int c; while (isSpaceChar(c = this.read())) { } StringBuilder result = new StringBuilder(); result.appendCodePoint(c); while (!isSpaceChar(c = this.read())) { result.appendCodePoint(c); } return result.toString(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == EOF; } } static final class Factories { private Factories() { } public static IntPair makeIntPair(int first, int second) { return new IntPair(first, second); } } static class OutputWriter extends PrintWriter { public OutputWriter(OutputStream os, boolean autoFlush) { super(os, autoFlush); } public OutputWriter(Writer out) { super(out); } public OutputWriter(Writer out, boolean autoFlush) { super(out, autoFlush); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public OutputWriter(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException { super(fileName, csn); } public OutputWriter(File file) throws FileNotFoundException { super(file); } public OutputWriter(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException { super(file, csn); } public OutputWriter(OutputStream out) { super(out); } public void flush() { super.flush(); } public void close() { super.close(); } } static class IntPair implements Comparable<IntPair> { public int first; public int second; public IntPair() { first = second = 0; } public IntPair(int first, int second) { this.first = first; this.second = second; } public int compareTo(IntPair a) { if (first == a.first) { return Integer.compare(second, a.second); } return Integer.compare(first, a.first); } public String toString() { return "<" + first + ", " + second + ">"; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntPair a = (IntPair) o; if (first != a.first) { return false; } return second == a.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 8
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≀ n ≀ 105) β€” the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≀ ri ≀ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≀ m ≀ 105) β€” the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≀ vi, ki ≀ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers β€” the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output
PASSED
431248a5ec191b94ce0f948fc08c471a
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k &gt; 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x &gt; 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class DilworthTheorem { static String[] names; static int[][] adj; static int sz[], lvl[]; static int[] par; static boolean vis[]; static Scanner sc = new Scanner(); public static void main(String[] args) throws IOException { PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); vis = new boolean[n]; par = new int[n]; lvl = new int[n]; sz = new int[n]; names = new String[n]; int[] from = new int[n]; int[] to = new int[n]; for (int i = 0; i < n; i++) { names[i] = sc.next(); from[i] = sc.nextInt() - 1; par[i] = from[i]; to[i] = i; } adj = packD(n, from, to); for (int i = 0; i < n; i++) { if (sz[i] == 0) { size(i, -1); } } for (int i = 0; i < n; i++) { if (par[i] == -1) { bfs(i); } } int m = sc.nextInt(); set = new TreeSet[n + 1]; qu = new ArrayList[n]; ans = new int[m]; for (int i = 0; i < m; i++) { int v = sc.nextInt() - 1; int k = sc.nextInt() + lvl[v]; if(k > n){ ans[i] = 0 ; continue; } if (qu[v] == null) { qu[v] = new ArrayList<Query>(); } qu[v].add(new Query(i, k)); } for (int i = 0; i < set.length; i++) { set[i] = new TreeSet<>(); } for (int i = 0; i < n; i++) { if (lvl[i] == 0) solve(i, -1, false); } for (int i = 0; i < m; i++) { pw.println(ans[i]); } pw.flush(); pw.close(); } static int ans[]; static TreeSet<String>[] set; private static void solve(int u, int p, boolean keep) { int big = -1; int mx = -1; for (int v : adj[u]) { if (v != p && sz[v] > mx) { mx = sz[v]; big = v; } } for (int v : adj[u]) { if (v != p && v != big) { solve(v, u, false); } } if (big != -1) { solve(big, u, true); } add(u, p, big); if (qu[u] != null) { for (Query query : qu[u]) { ans[query.idx] = set[query.kth].size() ; } } if (!keep) { remove(u, p); } } private static void remove(int u, int p) { set[lvl[u]].remove(names[u]); for (int v : adj[u]) if (v != p) remove(v, u); } private static void add(int u, int p, int big) { set[lvl[u]].add(names[u]); for (int v : adj[u]) if (v != p && v != big) add(v, u, big); } static ArrayList<Query> qu[]; private static void bfs(int root) { vis[root] = true; lvl[root] = 0; Queue<Integer> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { int poll = q.poll(); for (Integer i : adj[poll]) { if (!vis[i]) { vis[i] = true; lvl[i] = lvl[poll] + 1; q.add(i); } } } } private static void size(int u, int p) { sz[u]++; for (int v : adj[u]) if (v != p) { size(v, u); sz[u] += sz[v]; } } static int[][] packD(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) if (f != -1) p[f]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) if (from[i] != -1) { g[from[i]][--p[from[i]]] = to[i]; } return g; } static class Query { int idx, kth; public Query(int idx, int kth) { this.idx = idx; this.kth = kth; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public Scanner(FileReader fileReader) throws FileNotFoundException { br = new BufferedReader(fileReader); } 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 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 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(); } } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 8
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≀ n ≀ 105) β€” the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≀ ri ≀ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≀ m ≀ 105) β€” the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≀ vi, ki ≀ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers β€” the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output
PASSED
6c9b1ac739d9532251f51f15ba8634ef
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k &gt; 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x &gt; 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
import java.io.*; import java.util.*; public final class blood_cousins_return { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); static TreeMap<String,Integer>[] tm; static int[][] al; static String[] a; static int[] parent,level,size,res; static List<Node> list=new ArrayList<Node>(); static ArrayList<Node>[] al2; static ArrayList<Integer>[] al3; static void dfs1(int u,int p,int curr) { level[u]=curr;size[u]=1; for(int x:al[u]) { if(x!=p) { dfs1(x,u,curr+1);size[u]+=size[x]; } } } static void dfs2(int u,int p,boolean keep) { int max=-1,big_child=-1; for(int x:al[u]) { if(x!=p && size[x]>max) { max=size[x];big_child=x; } } for(int x:al[u]) { if(x!=p && x!=big_child) { dfs2(x,u,false); } } if(big_child!=-1) { dfs2(big_child,u,true);al3[u]=al3[big_child]; } for(int x:al[u]) { if(x!=p && x!=big_child) { for(int y:al3[x]) { al3[u].add(y);put(level[y],a[y],1); } } } put(level[u],a[u],1);al3[u].add(u); for(Node x:al2[u]) { res[x.u]=tm[x.v].size(); } if(!keep) { for(int x:al3[u]) { put(level[x],a[x],-1); } } } static void put(int idx,String curr,int val) { if(tm[idx].get(curr)==null) { tm[idx].put(curr,val); } else { tm[idx].put(curr,tm[idx].get(curr)+val); } if(tm[idx].get(curr)==0) { tm[idx].remove(curr); } } @SuppressWarnings("unchecked") public static void main(String args[]) throws Exception { int n=sc.nextInt();a=new String[n];parent=new int[n];int[] count=new int[n]; for(int i=0;i<n;i++) { parent[i]=-1;a[i]=sc.next();int u=i,v=sc.nextInt()-1; if(v>=0) { list.add(new Node(u,v));count[u]++;count[v]++;parent[u]=v; } } al=new int[n][];al2=new ArrayList[n];al3=new ArrayList[n];tm=new TreeMap[n]; for(int i=0;i<n;i++) { al[i]=new int[count[i]];al2[i]=new ArrayList<Node>();al3[i]=new ArrayList<Integer>();tm[i]=new TreeMap<>(); } count=new int[n];level=new int[n];size=new int[n]; for(int i=0;i<list.size();i++) { int u=list.get(i).u,v=list.get(i).v; al[u][count[u]]=v;al[v][count[v]]=u;count[u]++;count[v]++; } for(int i=0;i<n;i++) { if(parent[i]==-1) { dfs1(i,-1,0); } } int q=sc.nextInt();res=new int[q]; for(int i=0;i<q;i++) { int u=sc.nextInt()-1,k=sc.nextInt(); if(level[u]+k<n) { al2[u].add(new Node(i,level[u]+k)); } } for(int i=0;i<n;i++) { if(parent[i]==-1) { dfs2(i,-1,false); } } for(int i=0;i<q;i++) { out.println(res[i]); } out.close(); } } class Node { int u,v; public Node(int u,int v) { this.u=u;this.v=v; } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 8
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≀ n ≀ 105) β€” the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≀ ri ≀ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≀ m ≀ 105) β€” the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≀ vi, ki ≀ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers β€” the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output
PASSED
ea8c5188e8d51e96bc0e3743177b6435
train_001.jsonl
1353511800
Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k &gt; 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x &gt; 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.
256 megabytes
import java.io.*; import java.lang.reflect.*; import java.util.*; public class E { final int MOD = (int)1e9 + 7; final double eps = 1e-12; final int INF = (int)1e9; void expand(int m, List<Integer> [][] CH, boolean [] E) { if (CH[0][m] != null) { for (int p : CH[0][m]) if (!E[p]) expand(p, CH, E); for (int i = 0; CH[i][m] != null; ++i) for (int p : CH[i][m]) if (CH[i][p] != null) { if (CH[i+1][m] == null) CH[i+1][m] = new ArrayList<Integer>(1); CH[i+1][m].addAll(CH[i][p]); } } E[m] = true; } @SuppressWarnings("unchecked") public E () { Map<String, Integer> NAM = new HashMap<String, Integer>(); int N = sc.nextInt(); int [] C = new int[N]; List<Integer> [][] CH = new List [20][N]; for (int i = 0; i < N; ++i) { String name = sc.next(); if (!NAM.containsKey(name)) NAM.put(name, NAM.size()); C[i] = NAM.get(name); int p = sc.nextInt() - 1; if (p >= 0) { if (CH[0][p] == null) CH[0][p] = new ArrayList<Integer>(1); CH[0][p].add(i); } } boolean [] E = new boolean [N]; for (int i = 0; i < N; ++i) if (!E[i]) expand(i, CH, E); Map<Long, Integer> H = new HashMap<Long, Integer>(); int M = sc.nextInt(); for (int i = 0; i < M; ++i) { int v = sc.nextInt() - 1; int k = sc.nextInt(); long key = 1L * v * N + k; if (!H.containsKey(key)) { Set<Integer> res = new HashSet<Integer>(0); List<Integer> X = new ArrayList<Integer>(); X.add(v); for (int b = 20; b >= 0; --b) { if ((k & (1 << b)) != 0) { List<Integer> Y = new ArrayList<Integer>(); for (int p : X) if (CH[b][p] != null) Y.addAll(CH[b][p]); X = Y; } } for (int p : X) res.add(C[p]); H.put(key, res.size()); } print(H.get(key)); } } //////////////////////////////////////////////////////////////////////////////////// static MyScanner sc; static class MyScanner { public String next() { newLine(); return line[index++]; } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { line = null; return readLine(); } public String [] nextStrings() { line = null; return readLine().split(" "); } public char [] nextChars() { return next().toCharArray(); } public Integer [] nextInts() { String [] L = nextStrings(); Integer [] res = new Integer [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } public Long [] nextLongs() { String [] L = nextStrings(); Long [] res = new Long [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Long.parseLong(L[i]); return res; } public Double [] nextDoubles() { String [] L = nextStrings(); Double [] res = new Double [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Double.parseDouble(L[i]); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error(e); } } private final BufferedReader r; MyScanner () { this(new BufferedReader(new InputStreamReader(System.in))); } MyScanner(BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = readLine().split(" "); index = 0; } } } static void print (Object... a) { pw.println(build(a)); } static void exit (Object... a) { print(a); exit(); } static void exit () { pw.close(); System.out.flush(); System.err.println("------------------"); System.err.println("Time: " + ((millis() - t) / 1000.0)); System.exit(0); } void NO() { throw new Error("NO!"); } //////////////////////////////////////////////////////////////////////////////////// static String build(Object... a) { StringBuilder b = new StringBuilder(); for (Object o : a) append(b, o); return b.toString().trim(); } static void append(StringBuilder b, Object o) { if (o.getClass().isArray()) { int L = Array.getLength(o); for (int i = 0; i < L; ++i) append(b, Array.get(o, i)); } else if (o instanceof Iterable<?>) { for (Object p : (Iterable<?>)o) append(b, p); } else b.append(" ").append(o); } //////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { sc = new MyScanner (); new E(); exit(); } static void start() { t = millis(); } static PrintWriter pw = new PrintWriter(System.out); static long t; static long millis() { return System.currentTimeMillis(); } }
Java
["6\npasha 0\ngerald 1\ngerald 1\nvalera 2\nigor 3\nolesya 1\n5\n1 1\n1 2\n1 3\n3 1\n6 1", "6\nvalera 0\nvalera 1\nvalera 1\ngerald 0\nvalera 4\nkolya 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1"]
3 seconds
["2\n2\n0\n1\n0", "1\n0\n0\n0\n2\n0\n0"]
null
Java 6
standard input
[ "dp", "sortings", "data structures", "binary search", "dfs and similar" ]
e29842d75d7061ed2b4fca6c8488d0e4
The first line of the input contains a single integer n (1 ≀ n ≀ 105) β€” the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≀ ri ≀ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≀ m ≀ 105) β€” the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≀ vi, ki ≀ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
2,400
Print m whitespace-separated integers β€” the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.
standard output
PASSED
3c3f838bc10bfe8b5859c989e13f04cf
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
//package Codeforces; import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; /** * Created by rajanW(683281) on 22-May-15. * at 11:41 PM */ public class Main { static int[] isNotPrime; static void sieve(int n){ isNotPrime= new int[n+1]; for(int i=2;i<n+1;i++){ if(isNotPrime[i]==0){ // all prime numbers : i for(int j=i;j<n+1;j+=i){ // all potential multiples of i int x = j; while(x%i==0){ // all actual multiples of i isNotPrime[j]++; //count++ isNotPrime[j] = number of prime factors, not divisors x/=i;} } } isNotPrime[i]+=isNotPrime[i-1]; //to sum } } public static void main(String args[]) throws Exception { sieve(5000006); //Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] sa; int t = Integer.parseInt(br.readLine().trim()); //sc.nextInt(); while(t-->0){ sa = br.readLine().split(" "); int a = Integer.parseInt(sa[0]); int b = Integer.parseInt(sa[1]); out.println(isNotPrime[a]-isNotPrime[b]); } out.flush(); out.close(); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
b149f40e55dd57bc4284a6ecb2f5e422
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Code_546D_SoldierAndNumberGame{ public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); StringTokenizer in=new StringTokenizer(br.readLine()); long[] primeCount=new long[5000005]; long[] sumCount=new long[5000005]; outer: for(int i=2;i<=5000000;++i){ if(i%2==0){ primeCount[i]=1+primeCount[i/2]; sumCount[i]=primeCount[i]+sumCount[i-1]; }else { int limit=(int)Math.sqrt(i); int num=i; for(int j=3;j<=limit;j+=2){ if(num%j==0){ primeCount[i]=1+primeCount[i/j]; sumCount[i]=primeCount[i]+sumCount[i-1]; continue outer; } } primeCount[i]=1; sumCount[i]=primeCount[i]+sumCount[i-1]; } } int t=Integer.parseInt(in.nextToken()); while(t-->0){ in=new StringTokenizer(br.readLine()); out.println(sumCount[Integer.parseInt(in.nextToken())]-sumCount[Integer.parseInt(in.nextToken())]); } out.close(); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
862dd2a11eb0cca4287230f9152d1034
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.*; import java.util.*; /* * kishan Thesiya * daiict * kishanthesiya25@gmail.com * * */ public class Main { FastScanner in; PrintWriter out; static ArrayList[] adj; class Item implements Comparable<Item> { int num; int val; public Item(int num, int val) { super(); this.num = num; this.val = val; } @Override public int compareTo(Item arg0) { return Integer.compare(val, arg0.val); } } void solve() { Scanner sc = new Scanner(System.in); int n = in.nextInt(); long arr[] = new long[5000001]; arr[2] = 1; arr[3] = 1; arr[4] = 2; arr[5] = 1; for(int i = 6;i<=5000000;i++){ if(i%2 == 0){ arr[i] = arr[i/2] + 1; }else if(isPrime(i)){ arr[i] = 1; }else{ for(int j = 3;j*j<=i;j+=2){ if(i%j == 0){ arr[i] = arr[i/j]+1; break; } } } //pw.println(arr[i] + " " + i); } for(int i = 1;i<=5000000;i++){ arr[i] = arr[i-1]+arr[i]; } for(int i = 0;i<n;i++){ int a = in.nextInt(); int b = in.nextInt(); out.println(arr[a]-arr[b]); } out.close(); } public static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop 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; } void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } class Field{ long a; long b; Field(long a,long b){ this.a = Math.min(a, b); this.b = Math.max(a, b); } boolean greator(Field f){ return (this.a >= f.a && this.b >= f.b); } } public static void main(String[] args) { new Main().run(); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
75cdab3c676fbfa0c26c19456fe6c586
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; /** * Created by fly on 9/4/17. */ public class Main { public static int mod = 1000000007; public static int size = 5000000 + 5; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(); int[] dp = new int[size]; int[] sum = new int[size]; for (int i = 2; i < size; ++i) { if (dp[i] == 0) for (int j = 1; i * j < size; ++j) { for (int k = i * j; k % i == 0; k /= i) { ++dp[i * j]; } } sum[i] = sum[i - 1] + dp[i]; } for (int i = 0; i < n; ++i) { int a = in.nextInt(); int b = in.nextInt(); out.println(sum[a] - sum[b]); } out.close(); } 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.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
3dba4c4a17411dcc8d382cac1e651242
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.*; import java.util.InputMismatchException; public class Cf304D { private static InputReader in = new InputReader(System.in); private static OutputWriter out = new OutputWriter(System.out); private static void solve() throws Exception { boolean[] isNotPrime = new boolean[5000001]; for(int i=2; i<2237; ++i){ if(isNotPrime[i]){ continue; } for(int j=2; i*j<=5000000; ++j){ isNotPrime[i*j] = true; } } int count = 0; for(int i=2; i<=5000000; ++i){ if(!isNotPrime[i]){ count++; } } int[] primes = new int[count]; count = 0; for(int i=2; i<=5000000; ++i){ if(!isNotPrime[i]){ primes[count] = i; count++; } } int[] freq = new int[5000001]; for(int i=0; i<primes.length; ++i){ long temp = primes[i]; while((temp<=5000000)){ for(int j=1; j*temp <= 5000000; ++j){ freq[j*(int)temp]++; } temp = temp*primes[i]; } } for(int i=2; i<=5000000; ++i){ freq[i] += freq[i-1]; } int t = in.readInt(); for(int i=0; i<t; ++i) { int a = in.readInt(); int b = in.readInt(); out.println(freq[a]-freq[b]); } } public static void main(String[] args) throws Exception { solve(); out.close(); } private static class InputReader { private InputStream stream; private byte[] buffer; private int currentIndex; private int bytesRead; public InputReader(InputStream stream) { this.stream = stream; buffer = new byte[131072]; } public InputReader(InputStream stream, int bufferSize) { this.stream = stream; buffer = new byte[bufferSize]; } private int read() throws IOException { if (currentIndex >= bytesRead) { currentIndex = 0; bytesRead = stream.read(buffer); if (bytesRead <= 0) { return -1; } } return buffer[currentIndex++]; } public String readString() throws IOException { int c = read(); while (!isPrintable(c)) { c = read(); } StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (isPrintable(c)); return result.toString(); } public int readInt() throws Exception { int c = read(); int sign = 1; while (!isPrintable(c)) { c = read(); } if (c == '-') { sign = -1; c = read(); } int result = 0; do { if ((c < '0') || (c > '9')) { throw new InputMismatchException(); } result *= 10; result += (c - '0'); c = read(); } while (isPrintable(c)); return sign * result; } public long readLong() throws Exception { int c = read(); int sign = 1; while (!isPrintable(c)) { c = read(); } if (c == '-') { sign = -1; c = read(); } long result = 0; do { if ((c < '0') || (c > '9')) { throw new InputMismatchException(); } result *= 10; result += (c - '0'); c = read(); } while (isPrintable(c)); return sign * result; } public double readDouble() throws Exception { int c = read(); int sign = 1; while (!isPrintable(c)) { c = read(); } if (c == '-') { sign = -1; c = read(); } boolean fraction = false; double multiplier = 1; double result = 0; do { if ((c == 'e') || (c == 'E')) { return sign * result * Math.pow(10, readInt()); } if ((c < '0') || (c > '9')) { if ((c == '.') && (!fraction)) { fraction = true; c = read(); continue; } throw new InputMismatchException(); } if (fraction) { multiplier /= 10; result += (c - '0') * multiplier; c = read(); } else { result *= 10; result += (c - '0'); c = read(); } } while (isPrintable(c)); return sign * result; } private boolean isPrintable(int c) { return ((c > 32) && (c < 127)); } } private static class OutputWriter { private 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 println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
27c3816585cccb6db7a61bb37ef77e39
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.util.*; import java.io.*; public class Soldier_and_Number_Game { static int[] dp; static boolean[] isPrime; public static void main(String args[]) throws Exception { BufferedReader f=new BufferedReader(new InputStreamReader(System.in)); int runs=Integer.parseInt(f.readLine()); dp=new int[5000001]; isPrime=new boolean[5000001]; int[] primes=new int[400000]; int pos=0; for(int x=2;x<isPrime.length;x++) if(!isPrime[x]) { primes[pos]=x; pos++; for(int y=2*x;y<isPrime.length;y+=x) isPrime[y]=true; } int[] prefix_sums=new int[dp.length]; for(int x=2;x<dp.length;x++) { if(!isPrime[x]) dp[x]=1; else { for(int y=0;y<pos;y++) if(x%primes[y]==0) { dp[x]=dp[x/primes[y]]+1; break; } } prefix_sums[x]=prefix_sums[x-1]+dp[x]; } // for(int x=1;x<memoize.length;x++) // solve(x); BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); for(int x=0;x<runs;x++) { StringTokenizer st=new StringTokenizer(f.readLine()); int one=Integer.parseInt(st.nextToken()); int two=Integer.parseInt(st.nextToken()); out.write(prefix_sums[one]-prefix_sums[two]+"\n"); } out.flush(); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
57de9d73ced625c65d448cf922e5e3d4
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class SolveContest { private BufferedReader in; private PrintWriter out; public SolveContest() { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt"),true); solve(); } catch (Exception e) { e.printStackTrace(); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } finally { try { in.close(); } catch (IOException e) { } out.close(); } } StringTokenizer st; String nextToken() { while (st == null || !st.hasMoreTokens()) try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { } return st.nextToken(); } int nextInt() { return Integer.valueOf(nextToken()); } long nextLong() { return Long.valueOf(nextToken()); } final int MAX = 5000010; public void solve() { int t = nextInt(); int[] dl = new int[MAX]; int[] d = new int[MAX]; for (int i = 2; i < MAX; i++) { if (dl[i] == 0) for (int j = i; j < MAX; j+=i) { dl[j] = i; } } for (int i = 2; i < MAX; i++) { int cnt = 0; int dg = i; while (dg > 1) { cnt++; dg /= dl[dg]; } d[i] = d[i-1] + cnt; } while (t-- > 0) { int a = nextInt(); int b = nextInt(); out.println(d[a]-d[b]); } } public static void main(String[] args) { new SolveContest(); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
f019441a105499208557323c20ac61a6
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class Solver { public static final int SIZE = 6000000; private BufferedReader in; private PrintWriter out; Solver() throws IOException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); } catch (Exception ex) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } try { solve(); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } out.close(); } } public static void main(String[] args) throws IOException { new Solver(); } StringTokenizer st; String next() throws IOException { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } String nextLine() throws IOException { return in.readLine(); } int nextInt() throws IOException { return Integer.valueOf(next()); } long nextLong() throws IOException { return Long.valueOf(next()); } private void solve() throws IOException { int t = nextInt(); int[] firstDigDel = new int[SIZE]; for (int i = 2; i < SIZE; i++) { if (firstDigDel[i] == 0) { for (int j = i; j < SIZE; j+=i) { firstDigDel[j] = i; } } } int[] dels = new int[SIZE]; for (int i = 2; i < SIZE; i++) { int cnt = 0; int digit = i; while (digit > 1) { ++cnt; digit /= firstDigDel[digit]; } dels[i] = dels[i-1] + cnt; } while (t --> 0) { int a = nextInt(); int b = nextInt(); out.println(dels[a] - dels[b]); } } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
55d275670f61ca007f2218331520bd42
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class C546D { private StringTokenizer st; private BufferedReader bf; public C546D(){ try { bf = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(bf.readLine()); int[] base = new int[5000001]; // base[1] = 1L; // for(int i = 2; i < 5000001; i++){ // if(base[i] != 0) // continue; // // for(int x = 2; x * i < 5000001; x++){ // int xi = x * i; // int xx = xi; // while(xx % i == 0){ // base[xi]++; // xx /= i; // } // } // base[i]++; // } // // for(int i = 2; i < 5000001; i++){ // base[i] = base[i - 1] + base[i]; // } int N = 5000001; base[1] = 0; int judge = (int)Math.sqrt(N); for (int i = 2; i < N; i++){ if(base[i] != 0) continue; base[i] = i; if (i >= judge) continue; // for (int j = i * i ; j < N && i < Math.sqrt(N); j += i){ for (int j = i * i ; j < N; j += i){ base[j] = i; } } int number[] = new int[N]; for (int i = 2; i < N; i++){ number[i] = number[i / base[i]] + 1; } int acc[] = new int[N]; for (int i = 2; i < N; i++){ acc[i] = acc[i - 1] + number[i]; } int t = nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < t; i++) { int a = nextInt(); int b = nextInt(); // sb.append(base[a] - base[b]); sb.append(acc[a] - acc[b]); sb.append("\n"); } System.out.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); } } private int nextInt() throws IOException { return Integer.parseInt(next()); } private String next() throws IOException { if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public static void main(String[] args) { // TODO Auto-generated method stub C546D c = new C546D(); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
f086f54984df53e187ae86dc9fad8f99
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class C546D { private StringTokenizer st; private BufferedReader bf; public C546D(){ try { bf = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(bf.readLine()); int[] base = new int[5000001]; // base[1] = 1L; // for(int i = 2; i < 5000001; i++){ // if(base[i] != 0) // continue; // // for(int x = 2; x * i < 5000001; x++){ // int xi = x * i; // int xx = xi; // while(xx % i == 0){ // base[xi]++; // xx /= i; // } // } // base[i]++; // } // // for(int i = 2; i < 5000001; i++){ // base[i] = base[i - 1] + base[i]; // } int N = 5000001; base[1] = 0; for (int i = 2; i < N; i++){ if(base[i] != 0) continue; base[i] = i; if (i >= Math.sqrt(N)) continue; // for (int j = i * i ; j < N && i < Math.sqrt(N); j += i){ for (int j = i * i ; j < N; j += i){ base[j] = i; } } int number[] = new int[N]; for (int i = 2; i < N; i++){ number[i] = number[i / base[i]] + 1; } int acc[] = new int[N]; for (int i = 2; i < N; i++){ acc[i] = acc[i - 1] + number[i]; } int t = nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < t; i++) { int a = nextInt(); int b = nextInt(); // sb.append(base[a] - base[b]); sb.append(acc[a] - acc[b]); sb.append("\n"); } System.out.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); } } private int nextInt() throws IOException { return Integer.parseInt(next()); } private String next() throws IOException { if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public static void main(String[] args) { // TODO Auto-generated method stub C546D c = new C546D(); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
df13acb8759981bb1a4b3c11b81ca645
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C546D { private StringTokenizer st; private BufferedReader bf; private static PrintWriter out = new PrintWriter(System.out); public C546D(){ try { bf = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(bf.readLine()); int[] base = new int[5000001]; // base[1] = 1L; // for(int i = 2; i < 5000001; i++){ // if(base[i] != 0) // continue; // // for(int x = 2; x * i < 5000001; x++){ // int xi = x * i; // int xx = xi; // while(xx % i == 0){ // base[xi]++; // xx /= i; // } // } // base[i]++; // } // // for(int i = 2; i < 5000001; i++){ // base[i] = base[i - 1] + base[i]; // } int N = 5000001; base[1] = 0; int judge = (int)Math.sqrt(N); for (int i = 2; i < N; i++){ if(base[i] != 0) continue; base[i] = i; if (i >= judge) continue; // for (int j = i * i ; j < N && i < Math.sqrt(N); j += i){ for (int j = i * i ; j < N; j += i){ base[j] = i; } } int number[] = new int[N]; for (int i = 2; i < N; i++){ number[i] = number[i / base[i]] + 1; } int acc[] = new int[N]; for (int i = 2; i < N; i++){ acc[i] = acc[i - 1] + number[i]; } int t = nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < t; i++) { int a = nextInt(); int b = nextInt(); // sb.append(base[a] - base[b]); // sb.append(acc[a] - acc[b]); // sb.append("\n"); out.println(acc[a] - acc[b]); } // System.out.println(sb.toString()); out.close(); } catch (Exception e) { e.printStackTrace(); } } private int nextInt() throws IOException { return Integer.parseInt(next()); } private String next() throws IOException { if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public static void main(String[] args) { // TODO Auto-generated method stub C546D c = new C546D(); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
fd579a8f3dbdbe07f6f1347f29a413fc
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class C546D { private StringTokenizer st; private BufferedReader bf; public C546D(){ try { bf = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(bf.readLine()); long[] base = new long[5000001]; base[1] = 1L; for(int i = 2; i < 5000001; i++){ if(base[i] != 0) continue; for(int x = 2; x * i < 5000001; x++){ int xi = x * i; int xx = xi; while(xx % i == 0){ base[xi]++; xx /= i; if (xx % i == 0 && base[xx % i] != 0) { base[xi] += base[xx / i]; xx /= xx; } } } base[i]++; } for(int i = 2; i < 5000001; i++){ base[i] = base[i - 1] + base[i]; } int t = nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < t; i++) { int a = nextInt(); int b = nextInt(); sb.append(base[a] - base[b]); sb.append("\n"); } System.out.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); } } private int nextInt() throws IOException { return Integer.parseInt(next()); } private String next() throws IOException { if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public static void main(String[] args) { // TODO Auto-generated method stub C546D c = new C546D(); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
0de29513495d9624104995d5e5ffad7a
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C546D { private StringTokenizer st; private BufferedReader bf; private static PrintWriter out = new PrintWriter(System.out); public C546D(){ try { bf = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(bf.readLine()); int[] base = new int[5000001]; // base[1] = 1L; // for(int i = 2; i < 5000001; i++){ // if(base[i] != 0) // continue; // // for(int x = 2; x * i < 5000001; x++){ // int xi = x * i; // int xx = xi; // while(xx % i == 0){ // base[xi]++; // xx /= i; // } // } // base[i]++; // } // // for(int i = 2; i < 5000001; i++){ // base[i] = base[i - 1] + base[i]; // } int N = 5000001; base[1] = 0; int judge = (int)Math.sqrt(N); for (int i = 2; i < N; i++){ if(base[i] != 0) continue; base[i] = i; if (i >= judge) continue; // for (int j = i * i ; j < N && i < Math.sqrt(N); j += i){ for (int j = i * i ; j < N; j += i){ base[j] = i; } } int number[] = new int[N]; int acc[] = new int[N]; for (int i = 2; i < N; i++){ number[i] = number[i / base[i]] + 1; acc[i] = acc[i - 1] + number[i]; } // int acc[] = new int[N]; // for (int i = 2; i < N; i++){ // acc[i] = acc[i - 1] + number[i]; // } int t = nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < t; i++) { int a = nextInt(); int b = nextInt(); // sb.append(base[a] - base[b]); // sb.append(acc[a] - acc[b]); // sb.append("\n"); out.println(acc[a] - acc[b]); } // System.out.println(sb.toString()); out.close(); } catch (Exception e) { e.printStackTrace(); } } private int nextInt() throws IOException { return Integer.parseInt(next()); } private String next() throws IOException { if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public static void main(String[] args) { // TODO Auto-generated method stub C546D c = new C546D(); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
6df245da5ca911665727d7027ddfce3b
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class C546D { private StringTokenizer st; private BufferedReader bf; public C546D(){ try { bf = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(bf.readLine()); long[] base = new long[5000001]; base[1] = 1L; for(int i = 2; i < 5000001; i++){ if(base[i] != 0) continue; for(int x = 2; x * i < 5000001; x++){ int xi = x * i; int xx = xi; while(xx % i == 0){ base[xi]++; xx /= i; } } base[i]++; } for(int i = 2; i < 5000001; i++){ base[i] = base[i - 1] + base[i]; } int t = nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < t; i++) { int a = nextInt(); int b = nextInt(); sb.append(base[a] - base[b]); sb.append("\n"); } System.out.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); } } private int nextInt() throws IOException { return Integer.parseInt(next()); } private String next() throws IOException { if (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public static void main(String[] args) { // TODO Auto-generated method stub C546D c = new C546D(); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
2b050013e87c70874be3a11c2928fd11
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; /** * */ public class TaskD { public static void main(String[] args) { InputStream inputStream; String str = null; if(str == null){ inputStream = System.in; }else{ inputStream = new ByteArrayInputStream(str.getBytes()); } OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(1, in, out); out.close(); } static class Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int numGames = in.nextInt(); long[] results = new long[5000001]; int[] vals = new int[5000001]; for(int i=1;i<5000001;i++){ vals[i] = i; } for(int i=2;i<=5000000;i++){ if(vals[i] != 1){ for(int d=i;d<results.length;d+=i){ while(vals[d] > 1 && vals[d]%i==0){ vals[d] /= i; results[d]++; } } } } for(int i=2;i<=5000000;i++){ results[i] = results[i]+results[i-1]; } StringBuilder sb = new StringBuilder(); for(int game=0;game<numGames;game++){ int a = in.nextInt(); int b = in.nextInt(); long rounds = results[a] - results[b]; sb.append(rounds); sb.append("\n"); } System.out.println(sb.toString()); } } 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.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
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
f5f41dc9cbb23a9475bb7fe0814549fc
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Scanner; import java.util.StringTokenizer; /** * Created by Paul on 5/23/2015. */ public class Main { static InputStream is; static PrintWriter out; static String INPUT = ""; final static int N = 5000001; static boolean[] isPrime = new boolean[N]; static int[] primes = new int[N]; static int[] f = new int[N]; static void initSieve(){ Arrays.fill(isPrime, true); for(int i = 2; i < N; ++i){ primes[i] = i; } for(int i = 2; i < N; ++i){ if(isPrime[i]) { for (int j = i + i; j < N; j += i) { isPrime[j] = false; primes[j] = i; } } } for(int i = 2; i < N; ++i){ f[i] = f[i/primes[i]] + 1; } for(int i = 2; i < N; ++i){ f[i] = f[i] + f[i - 1]; } } public static void main(String[] args){ initSieve(); is = System.in; out = new PrintWriter(System.out); int times = ni(); int x, y; for(int i = 0; i < times; ++i){ x = ni(); y = ni(); out.println(f[x] - f[y]); } out.flush(); } private static 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(); } } static private byte[] inbuf = new byte[1024]; static private int lenbuf = 0, ptrbuf = 0; static 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++]; } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
0cd6a733fe39ce4b28ca27a2729e44c9
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
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.StringTokenizer; public class SoldierAndNumberGame { /** * @param args */ static void sieve() { // create list of primes in [0..upperbound] N = N + 1; // add 1 to include upperbound prime = new boolean[N]; Arrays.fill(prime, true); // set all bits to 1 prime[0] = prime[1] = false; // except index 0 and 1 for (long i = 2; i < N; i++) if (prime[(int) i]) { // cross out multiples of i starting from i * i! for (long j = i ; j < N; j += i){ factors[(int)j] = factors[(int)j/(int)i]+1; prime[(int) j] = false;} primes.add((int) i); // also add this vector containing list of // primes } } static int N = 5000000+2; static boolean[] prime; static ArrayList<Integer> primes = new ArrayList<Integer>(); static int[] sums = new int[5000000 + 5]; static int[] factors = new int[5000000 + 5]; public static void main(String[] args) throws IOException { sieve(); skp(); // System.out.println(primes.size()); StringBuffer sb = new StringBuffer(); for (int i = 1; i <= 5000000; i++) { sums[i] = sums[i - 1] + factors[i]; } int n = nextInt(); for (int t = 0; t < n; t++) { skp(); int b = nextInt(); int a = nextInt(); int ans = sums[b] - sums[a]; sb.append(ans); if (t != n - 1) sb.append("\n"); } System.out.println(sb); } static boolean skp() throws IOException { String line = r.readLine(); if (line == null) return false; tkn = new StringTokenizer(line); return true; } static int nextInt() { return Integer.parseInt(tkn.nextToken()); } static int readInt() throws NumberFormatException, IOException { return Integer.parseInt(r.readLine()); } static long nextLong() { return Long.parseLong(tkn.nextToken()); } static long readLong() throws NumberFormatException, IOException { return Long.parseLong(r.readLine()); } static double nextDouble() { return Double.parseDouble(tkn.nextToken()); } static BufferedReader r = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer tkn; }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
fd0f325294adc97fcfa8bc51ab2f1960
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int limit=5000001; int a[]=new int[limit]; Arrays.fill(a,1); for(int i=2;i*i < limit ;i++ ) { int i1=i,i2=i; if(a[i]==1) for(int j=i1*i2;j<limit;j=i1*i2) { a[j]=a[i1]+a[i2]; i2++; } } for(int i=2;i<limit;i++) a[i]+=a[i-1]; StringBuilder ans=new StringBuilder(""); int t=Integer.parseInt(br.readLine()); for(int i=0;i<t;i++) { st=new StringTokenizer(br.readLine()); int a1=Integer.parseInt(st.nextToken()); int b1=Integer.parseInt(st.nextToken()); ans.append((a[a1]-a[b1])); ans.append("\n"); } System.out.print(ans); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
051ac205a9f30a9b550e0250ec41fb1d
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; public class NumberGame { static final int limit = (int) 5e6 + 1; static int[] cnt = new int[limit]; static int[] prefix = new int[limit]; public static void main(String[] args) throws Exception { init(); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter( System.out)); int t = Integer.parseInt(bf.readLine()); while (t-- != 0) { String[] s = bf.readLine().split(" "); int a = Integer.parseInt(s[0]); int b = Integer.parseInt(s[1]); out.write("" + (prefix[a] - prefix[b]) + "\n"); } out.close(); } private static void init() { Arrays.fill(cnt, 1); cnt[0] = cnt[1] = 0; for (int i = 2; i < limit; i++) for (int j = i + i; j < limit; j += i) cnt[j] = Math.max(cnt[i] + 1, cnt[j]); for (int i = 1; i < limit; i++) prefix[i] = prefix[i - 1] + cnt[i]; } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
9e303794bfdca008419e6ffda0131ad6
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class NumberGame { static final int limit = (int) 5e6 + 1; static int[] cnt = new int[limit]; static int[] prefix = new int[limit]; public static void main(String[] args) throws Exception { init(); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter( System.out)); int t = Integer.parseInt(bf.readLine()); while (t-- != 0) { StringTokenizer tokenizer = new StringTokenizer(bf.readLine()); int a = Integer.parseInt(tokenizer.nextToken()); int b = Integer.parseInt(tokenizer.nextToken()); out.write("" + (prefix[a] - prefix[b]) + "\n"); } out.close(); } private static void init() { Arrays.fill(cnt, 1); cnt[0] = cnt[1] = 0; for (int i = 2; i < limit; i++) for (int j = i + i; j < limit; j += i) cnt[j] = Math.max(cnt[i] + 1, cnt[j]); for (int i = 1; i < limit; i++) prefix[i] = prefix[i - 1] + cnt[i]; } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
bd4d8a532fad50c0ba73412e09201c27
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.*; import java.util.*; public class Main { public static int MOD; public static int[] arr = new int[5000002]; public static void main(String[] args) throws Exception { MyScanner input = new MyScanner(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); init(); int t = input.nextInt(); int[] sum = new int[arr.length]; sum[0] = arr[0]; for(int i = 1; i < arr.length; i++) sum[i] = sum[i-1] + arr[i]; for(int i = 0; i < t; i++) { int a = input.nextInt(); int b = input.nextInt(); // System.out.println(sum[a] +" "+ sum[b]); out.append((sum[a] - sum[b] + " ")); } out.flush(); } public static void init() { int ind = 2; while(ind != arr.length) { int a = ind; int cnt = 2; arr[a] ++; //System.out.println("in first while " + a); while(a *cnt< arr.length) { // System.out.println("in sec while"); //haghighatan bayad bekhaabam :)) int samp = cnt; arr[a*cnt]++; while(samp % a == 0) { arr[a*cnt]++; samp/= a; } cnt ++; } ind = first(ind); } } public static int first(int ind) { for(int i = ind ; i< arr.length;i++) if(arr[i] == 0) return i; return arr.length; } private static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (IOException e) { e.printStackTrace(); } } public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } public String next() { if (st == null || !st.hasMoreElements()) { try { String line = br.readLine(); if (line == null) { throw new UnknownError(); } while (line.trim().equals("")) { line = br.readLine(); if (line == null) { throw new UnknownError(); } } st = new StringTokenizer(line); } catch (IOException e) { throw new UnknownError(); } } return st.nextToken(); } public String nextLine() { try { String line = br.readLine(); if (line == null) { throw new UnknownError(); } return line; } catch (IOException e) { throw new UnknownError(); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
0b00ed83fe9a86bab44a8b7193630fb4
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.InputMismatchException; public class Queue { public static void main (String[] args) throws NumberFormatException, IOException{ int MAX= 5000001; int[] sp = new int[MAX]; long[] factors = new long[MAX]; long[] acc = new long[MAX]; for (int i = 1; i < MAX; ++i) sp[i] = i; for (int i = 2; i < MAX; ++i) { if (sp[i] == i) for (int j = i*2; j < MAX; j+=i) sp[j] = i; factors[i]=factors[i/sp[i]]+1; acc[i]=acc[i-1]+factors[i]; } InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int t = in.readInt(); for (int i=0;i<t;i++){ out.printLine(acc[in.readInt()]-acc[in.readInt()]); } out.flush(); out.close(); } } 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 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); } } 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(); } public void flush() { writer.flush(); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
a869bb67edc3f0ba6c3c1ad2549a05d3
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class D546 { public static void main(String[] args) throws IOException { initReader(); int n = nextInt(); StringBuilder str = new StringBuilder(); int[] count = new int[5000001]; int cur = 2; while (cur <= 5000000) { if (count[cur] == 0) { for (int i = cur; i <= 5000000; i += cur) { int temp = i; do { count[i]++; temp /= cur; } while (temp % cur == 0); } } cur++; } for (int i = 3; i <= 5000000; ++i) { count[i] = count[i] + count[i - 1]; } for (int i = 0; i < n; ++i) { int a = nextInt(); int b = nextInt(); str.append(count[a] - count[b]); str.append('\n'); } System.out.println(str); } static BufferedReader reader; static StringTokenizer tokenizer; public static void initReader() { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { String n = reader.readLine(); if (n == null) { return null; } tokenizer = new StringTokenizer(n); } return tokenizer.nextToken(); } static String nextLine() throws IOException { return reader.readLine(); } static Integer nextInt() throws IOException { String next = next(); if(next==null){ return null; } return Integer.parseInt(next); } static long nextLong() throws IOException { return Long.parseLong(next()); } static Double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
b3b74e30ea48a860f0f8298eff3908ff
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class D546 { public static void main(String[] args) throws IOException { initReader(); int n = nextInt(); int[] lowestPrimeFactors = enumLowestPrimeFactors(5000005); StringBuilder str = new StringBuilder(); int[] count = new int[5000001]; /* * int cur = 2; while (cur <= 5000000) { if (count[cur] == 0) { for (int * i = cur; i <= 5000000; i += cur) { int temp = i; do { count[i]++; * temp /= cur; } while (temp % cur == 0); } } count[cur] = count[cur] + * count[cur - 1]; cur++; * * } */ int sum[] = new int[5000001]; for (int i = 2; i <= 5000000; ++i) { count[i] = count[i / lowestPrimeFactors[i]] + 1; sum[i] = count[i] + sum[i - 1]; } for (int i = 0; i < n; ++i) { int a = nextInt(); int b = nextInt(); str.append(sum[a] - sum[b]); str.append('\n'); } System.out.println(str); } public static int[] enumLowestPrimeFactors(int n) { int tot = 0; int[] lowestPrimeFactors = new int[n + 1]; int[] primes = new int[n + 1]; for (int i = 2; i <= n; i++) lowestPrimeFactors[i] = i; for (int p = 2; p <= n; p++) { if (lowestPrimeFactors[p] == p) primes[tot++] = p; int tmp; for (int i = 0; i < tot && primes[i] <= lowestPrimeFactors[p] && (tmp = primes[i] * p) <= n; i++) { lowestPrimeFactors[tmp] = primes[i]; } } return lowestPrimeFactors; } static BufferedReader reader; static StringTokenizer tokenizer; public static void initReader() { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static String nextLine() throws IOException { return reader.readLine(); } static Integer 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
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
459977d8c524374fa8fd5e7e50b3ba7c
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class D546 { public static void main(String[] args) throws IOException { initReader(); int n = nextInt(); StringBuilder str = new StringBuilder(); long[] count = new long[5000001]; int cur = 2; while (cur <= 5000000) { if (count[cur] == 0) { for (int i = cur; i <= 5000000; i += cur) { int temp = i; do { count[i]++; temp /= cur; } while (temp % cur == 0); } } cur++; } for (int i = 3; i <= 5000000; ++i) { count[i] = count[i] + count[i - 1]; } for (int i = 0; i < n; ++i) { int a = nextInt(); int b = nextInt(); str.append(count[a] - count[b]); str.append('\n'); } System.out.println(str); } static BufferedReader reader; static StringTokenizer tokenizer; public static void initReader() { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { String n = reader.readLine(); if (n == null) { return null; } tokenizer = new StringTokenizer(n); } return tokenizer.nextToken(); } static String nextLine() throws IOException { return reader.readLine(); } static Integer nextInt() throws IOException { String next = next(); if(next==null){ return null; } return Integer.parseInt(next); } static long nextLong() throws IOException { return Long.parseLong(next()); } static Double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
5437130275e2814fd00699bba7f45f92
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class D { public static void main(String args[]) throws IOException { Reader.init(System.in); int t = Reader.nextInt(); int prime[] = new int[5000001]; int factor[] = new int[5000001]; int sumFactor[] = new int[5000001]; EtratosthenesSieve(prime, 5000000); numfactor(factor, prime, sumFactor, 5000000); StringBuilder sb = new StringBuilder(); for (int i = 0; i < t; ++i) { int a = Reader.nextInt(); int b = Reader.nextInt(); int ret = sumFactor[a] - sumFactor[b]; sb.append(ret + "\n"); } System.out.print(sb); } public static int solve(int a, int b, int prime[], int factor[]) { int ret = 0; if (a == b) return 0; return ret; } // mark all unprime number // 1. progressive increment odd. 2. mark larger or equal than square of // current number /** * * @param set * contains n+1 elements, represent the integer by their position * mark all unprime number * @param n * range from 1-n * */ public static void EtratosthenesSieve(int[] set, int n) { int max = n; for (int i = 4; i <= n; i += 2) set[i] = 2; for (int i = 3; i <= n; i += 2) { if (set[i] == 0) { for (int j = i; j <= n / i; ++j) { set[i * j] = i; } } } } public static void numfactor(int[] factor, int[] prime, int factorSum[], int n) { for (int i = 1; i <= n; ++i) { if (prime[i] == 0) { factor[i] = 1; factorSum[i] = factor[i] + factorSum[i - 1]; } else { factor[i] = factor[i / prime[i]] + 1; factorSum[i] = factor[i] + factorSum[i - 1]; } } } } 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 line */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { // TODO add check for eof if necessary tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static boolean hashnext() throws IOException { if (tokenizer.hasMoreElements()) return true; else return false; } static String nextLine() throws IOException { return reader.readLine(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static short nextShort() throws IOException { return Short.parseShort(next()); } static char[] readCharWord() throws IOException { return next().toCharArray(); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 8
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≀ t ≀ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≀ b ≀ a ≀ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
a1f784c9b9fb504fa6c423e1920b5593
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.IntStream; import java.util.Arrays; import java.util.ArrayList; import java.util.OptionalLong; import java.nio.charset.Charset; import java.util.StringTokenizer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.util.stream.LongStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.util.Objects; import java.util.List; import java.io.Writer; import java.security.AccessControlException; import java.io.BufferedReader; import java.util.regex.Pattern; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); E2ArrayAndSegmentsHardVersion solver = new E2ArrayAndSegmentsHardVersion(); solver.solve(1, in, out); out.close(); } static class E2ArrayAndSegmentsHardVersion { public void solve(int testNumber, LightScanner in, LightWriter out) { Debug.autoEnable(); int n = in.ints(), m = in.ints(); long[] a = in.longs(n); if (m == 0) { out.ans(IntMath.max(a) - IntMath.min(a)).ln() .ans(0).ln(); return; } else if (n == 1) { out.ans(0).ln() .ans(0).ln(); return; } Vec3i[] segs = new Vec3i[m]; for (int i = 0; i < m; i++) { segs[i] = new Vec3i(in.ints() - 1, in.ints() - 1, i + 1); } MergeSort.sort(segs, Comparator.comparing(seg -> seg.y)); long[] lb = a.clone(); long t = Integer.MAX_VALUE; long[] minLeft = new long[n]; minLeft[0] = t; int c = 0; for (int i = 1; i < n; i++) { t = Math.min(t, a[i - 1]); while (c < m && segs[c].y < i) { for (int j = segs[c].x; j <= segs[c].y; j++) { lb[j]--; t = Math.min(t, lb[j]); } c++; } minLeft[i] = t; } MergeSort.sort(segs, Comparator.comparing(seg -> -seg.x)); lb = a.clone(); t = Integer.MAX_VALUE; long[] minRight = new long[n]; minRight[n - 1] = t; c = 0; for (int i = n - 2; i >= 0; i--) { t = Math.min(t, a[i + 1]); while (c < m && segs[c].x > i) { for (int j = segs[c].x; j <= segs[c].y; j++) { lb[j]--; t = Math.min(t, lb[j]); } c++; } minRight[i] = t; } //System.out.println(Arrays.toString(minLeft)); //System.out.println(Arrays.toString(minRight)); long ans = -1; long ansi = -1; for (int i = 0; i < n; i++) { long ta = a[i] - Math.min(minLeft[i], minRight[i]); if (ta > ans) { ans = ta; ansi = i; } } //System.out.println("ANIS="+ansi); List<Vec3i> res = new ArrayList<>(); for (Vec3i seg : segs) { if (seg.y < ansi || ansi < seg.x) { res.add(seg); } } out.ans(ans).ln().ans(res.size()).ln(); for (Vec3i seg : res) { out.ans(seg.z); } out.ln(); } } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public int ints() { return Integer.parseInt(string()); } public long longs() { return Long.parseLong(string()); } public long[] longs(int length) { return IntStream.range(0, length).mapToLong(x -> longs()).toArray(); } } static class MergeSort { private static final int INSERTIONSORT_THRESHOLD = 7; private MergeSort() { } static <T> void sort(T[] src, T[] dest, int low, int high, int off, Comparator<? super T> comparator) { int length = high - low; if (length < INSERTIONSORT_THRESHOLD) { InsertionSort.sort(dest, low, high, comparator); return; } int destLow = low; int destHigh = high; low += off; high += off; int mid = (low + high) / 2; sort(dest, src, low, mid, -off, comparator); sort(dest, src, mid, high, -off, comparator); if (comparator.compare(src[mid - 1], src[mid]) <= 0) { System.arraycopy(src, low, dest, destLow, length); return; } for (int i = destLow, p = low, q = mid; i < destHigh; i++) { if (q >= high || p < mid && comparator.compare(src[p], src[q]) <= 0) { dest[i] = src[p++]; } else { dest[i] = src[q++]; } } } public static <T> void sort(T[] a, Comparator<? super T> comparator) { sort(a.clone(), a, 0, a.length, 0, comparator); } } static class Debug { private static final String DEBUG_PROPERTY = "debug"; private static final String DEBUG_CALL_PATTERN = "^.+\\.debug\\((.+)\\);.*$"; private static Pattern debugRegex; private static boolean enabled = false; private static String src; public static void enable(String s) { enabled = true; src = s; if (debugRegex == null) { debugRegex = Pattern.compile(DEBUG_CALL_PATTERN); } } public static boolean autoEnable() { try { String s = System.getProperty(DEBUG_PROPERTY); if (s != null) { enable(s); return true; } } catch (AccessControlException ex) { src = null; } return false; } } static class Vec3i { public int x; public int y; public int z; public Vec3i(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Vec3i vec3i = (Vec3i) o; return x == vec3i.x && y == vec3i.y && z == vec3i.z; } public int hashCode() { return Objects.hash(x, y, z); } public String toString() { return "(" + x + ", " + y + ", " + z + ")"; } } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset()))); } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ans(String s) { if (!breaked) { print(' '); } return print(s); } public LightWriter ans(long l) { return ans(Long.toString(l)); } public LightWriter ans(int i) { return ans(Integer.toString(i)); } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } } static class InsertionSort { private InsertionSort() { } static <T> void sort(T[] a, int low, int high, Comparator<? super T> comparator) { for (int i = low; i < high; i++) { for (int j = i; j > low && comparator.compare(a[j - 1], a[j]) > 0; j--) { T t = a[j]; a[j] = a[j - 1]; a[j - 1] = t; } } } } static final class IntMath { private IntMath() { } public static long min(long... v) { return Arrays.stream(v).min().orElseThrow(NoSuchElementException::new); } public static long max(long... v) { return Arrays.stream(v).max().orElseThrow(NoSuchElementException::new); } } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
b77d929270dac108614f965ceec320b1
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import javafx.scene.layout.Priority; import java.io.*; import java.lang.reflect.Array; import java.net.Inet4Address; import java.util.*; import java.lang.*; import java.util.HashMap; import java.util.PriorityQueue; public class templ implements Runnable { static class pair implements Comparable { int f,s; pair(int fi,int se) { f=fi; s=se; } public int compareTo(Object o) { pair pr=(pair)o; if(f>pr.f) return 1; else return -1; } public boolean equals(Object o) { pair ob=(pair)o; int ff; int ss; if(o!=null) { ff=ob.f; ss=ob.s; if((ff==this.f)&&(ss==this.s)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s).hashCode(); } } public class triplet implements Comparable { int f,s; int t; triplet(int f,int s,int t) { this.f=f; this.s=s; this.t=t; } public boolean equals(Object o) { triplet ob=(triplet)o; int ff,ss; int tt; if(o!=null) { ff=ob.f; ss=ob.s; tt=ob.t; if((ff==this.f)&&(ss==this.s)&&(tt==this.t)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s+" "+this.t).hashCode(); } public int compareTo(Object o) { triplet tr=(triplet)o; if(f>tr.f) return 1; else if(f==tr.f) { if(s>tr.s) return -1; else return 1; } else return -1; } } int tree[]; int lazy[]; int a[]; void build(int node,int start,int end) { if(start==end) { tree[node]=a[start]; return; } int mid=(start+end)/2; build(2*node,start,mid); build(2*node+1,mid+1,end); tree[node]=Math.max(tree[2*node],tree[2*node+1]); } void update(int node,int start,int end,int l,int r,int val) { if(lazy[node]!=0) { tree[node]+=lazy[node]; if(start!=end) { lazy[2*node]+=lazy[node]; lazy[2*node+1]+=lazy[node]; } lazy[node]=0; } if(end<l||r<start) return; if(start>=l&&end<=r) { tree[node]+=val; if(start!=end) { lazy[2*node]+=val; lazy[2*node+1]+=val; } return; } int mid=(start+end)/2; update(2*node,start,mid,l,r,val); update(2*node+1,mid+1,end,l,r,val); tree[node]=Math.max(tree[2*node],tree[2*node+1]); } int query(int node,int start,int end,int l,int r) { if(lazy[node]!=0) { tree[node]+=lazy[node]; if(start!=end) { lazy[2*node]+=lazy[node]; lazy[2*node+1]+=lazy[node]; } lazy[node]=0; } if(end<l||r<start) return -100000000; if(start>=l&&end<=r) { return tree[node]; } int mid=(start+end)/2; int x=query(2*node,start,mid,l,r); int y=query(2*node+1,mid+1,end,l,r); return Math.max(x,y); } public static void main(String args[])throws Exception { new Thread(null,new templ(),"templ",1<<27).start(); } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n=in.ni(); int m=in.ni(); a=new int[n+1]; tree=new int[4*n+1]; lazy=new int[4*n+1]; for(int i=1;i<=n;i++) a[i]=in.ni(); build(1,1,n); ArrayList<Integer>start[]=new ArrayList[n+1]; ArrayList<Integer>end[]=new ArrayList[n+1]; int L[]=new int[m+1]; int R[]=new int[m+1]; for(int i=1;i<=n;i++) { start[i]=new ArrayList<>(); end[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { int l=in.ni(); int r=in.ni(); L[i]=l; R[i]=r; start[l].add(r); end[r].add(l); } int ans=-1,ind=-1; for(int i=1;i<=n;i++) { for(int j : start[i]) update(1,1,n,i,j,-1); int k=query(1,1,n,1,n)-query(1,1,n,i,i); if(k>ans) { ans=k; ind=i; } for(int j : end[i]) update(1,1,n,j,i,1); } out.println(ans); ArrayList<Integer>al=new ArrayList<>(); for(int i=1;i<=m;i++) { if(L[i]<=ind&&R[i]>=ind) al.add(i); } out.println(al.size()); for(int i : al) out.print(i+" "); out.close(); } catch(Exception e){ return; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } 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 ni() { 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 nl() { 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] = ni(); } 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
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
6292aaa04fbb4283a6ebbe8e972933c6
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; //https://codeforces.com/problemset/problem/1108/E2 public class ArrayAndSegments { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int[] params = Arrays.stream(br.readLine().split(" ")) .mapToInt(x -> Integer.parseInt(x)).toArray(); int n = params[0]; int m = params[1]; int[] a = Arrays.stream(br.readLine().split(" ")) .mapToInt(x -> Integer.parseInt(x)).toArray(); TreeSet<Integer> endpoints = new TreeSet<>(); Segment[] segments = new Segment[m]; for (int i = 0; i < m; i++) { int[] in = Arrays.stream(br.readLine().split(" ")) .mapToInt(x -> Integer.parseInt(x)).toArray(); int st = in[0] - 1; int end = in[1]; segments[i] = new Segment(st, end - 1, i + 1); endpoints.add(st); endpoints.add(end); } endpoints.add(0); endpoints.remove(n); // map from location in the input array to the location in shortened array. Map<Integer, Integer> effectiveLocation = new HashMap<>(); int ind = 0; for (int point : endpoints) { effectiveLocation.put(point, ind++); } int[] max = new int[effectiveLocation.size()]; int[] min = new int[effectiveLocation.size()]; Arrays.fill(min, Integer.MAX_VALUE); Arrays.fill(max, Integer.MIN_VALUE); ind = -1; for (int i = 0; i < n; i++) { if (endpoints.contains(i)) { ind++; } max[ind] = Math.max(max[ind], a[i]); min[ind] = Math.min(min[ind], a[i]); } List<Integer> bestSet = new ArrayList<>(); List<Integer> curSet = new ArrayList<>(); int best = 0; // for every pair of two points, subtract from low as much as possible to get the solution for (int highInd : endpoints) { for (int lowInd : endpoints) { int count = 0; for (Segment seg : segments) { // if (lowInd in segment) and (highInd not in segment) if ((seg.start <= lowInd && seg.end >= lowInd) && (seg.start > highInd || seg.end < highInd)) { count++; curSet.add(seg.index); } } int diff = max[effectiveLocation.get(highInd)] - min[effectiveLocation.get(lowInd)] + count; if (diff > best) { bestSet = curSet; curSet = new ArrayList<>(); best = diff; } curSet.clear(); } } pw.println(best); pw.println(bestSet.size()); for (int i = 0; i < bestSet.size() - 1; i++) { pw.print(bestSet.get(i) + " "); } if(!bestSet.isEmpty()) { pw.print(bestSet.get(bestSet.size() - 1)); } pw.println(); pw.flush(); br.close(); pw.close(); } private static class Segment { int start; int end; int index; public Segment(int st, int end, int ind) { start = st; this.end = end; index = ind; } } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
3c3a325bb446426f7168eb5ef6f5b53f
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.io.*; import java.util.*; public class E { static Scanner in=new Scanner(System.in); static PrintWriter out=new PrintWriter(System.out); static int n,T,res=0; static int[] a=new int[100005],SaveL=new int[100005],SaveR=new int[100005]; static int[] tree=new int[400005],lazy=new int[400005]; static List<Integer> rs=new ArrayList<>(); static List<Integer>[] L=new List[100005],R=new List[100005]; static void Init(int k,int l,int r) { if(l==r) { tree[k]=a[l]; return; } int mid=(l+r)/2; Init(2*k,l,mid); Init(2*k+1,mid+1,r); tree[k]=Math.min(tree[2*k],tree[2*k+1]); } static void Down(int k) { tree[2*k]+=lazy[k]; lazy[2*k]+=lazy[k]; tree[2*k+1]+=lazy[k]; lazy[2*k+1]+=lazy[k]; lazy[k]=0; } static void Update(int k,int l,int r,int L,int R) { if(l>R||L>r) return; if(L<=l&&r<=R) { tree[k]--; lazy[k]--; return; } Down(k); int mid=(l+r)/2; Update(2*k,l,mid,L,R); Update(2*k+1,mid+1,r,L,R); tree[k]=Math.min(tree[2*k],tree[2*k+1]); } public static void main(String args[]) { n=in.nextInt(); T=in.nextInt(); for(int i=1;i<=n;i++) { a[i]=in.nextInt(); L[i]=new ArrayList<>(); R[i]=new ArrayList<>(); } for(int i=1;i<=T;i++) { SaveL[i]=in.nextInt(); SaveR[i]=in.nextInt(); L[SaveL[i]].add(SaveR[i]); R[SaveR[i]].add(SaveL[i]); } Init(1,1,n); for(int i=1;i<=4*n;i++) lazy[i]=0; int id=0,type=0; for(int r=1;r<=n;r++) { if(res<a[r]-tree[1]) { res=a[r]-tree[1]; id=r; } for(int l:R[r]) Update(1,1,n,l,r); } Init(1,1,n); for(int i=1;i<=4*n;i++) lazy[i]=0; for(int l=n;l>=1;l--) { if(res<a[l]-tree[1]) { res=a[l]-tree[1]; id=l; type=1; } for(int r:L[l]) Update(1,1,n,l,r); } for(int i=1;i<=T;i++) if((type==0&&SaveR[i]<id)||(type==1&&id<SaveL[i])) rs.add(i); out.println(res+"\n"+rs.size()); for(int tmp:rs) out.print(tmp+" "); out.close(); } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
d74dec0345254699950e0c0ac4ce8074
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.util.*; import java.io.*; //267630EY public class Main1108E2 { static PrintWriter out=new PrintWriter(System.out); static class segMent { int[] t; int n; int[] lazy; boolean[] marked; public segMent(int[] a,int n) { this.n=n; lazy=new int[4*n]; marked=new boolean[4*n]; t=new int[4*n]; build(1,0,a.length-1,a); } public void build(int v,int tl,int tr,int[] a) { if(tl==tr) { t[v]=a[tl]; } else { int tm=(tl+tr)/2; build(2*v,tl,tm,a); build(2*v+1,tm+1,tr,a); t[v]=Math.min(t[2*v+1],t[2*v]); } } public void push(int v) { t[2*v]+=lazy[v]; t[2*v+1]+=lazy[v]; lazy[2*v]+=lazy[v]; lazy[2*v+1]+=lazy[v]; lazy[v]=0; } public void update(int v,int tl,int tr,int l,int r,int val) { if(l>r) return; else if(l==tl&&r==tr) { t[v]+=val; lazy[v]+=val; } else { push(v); int tm=(tl+tr)/2; update(2*v,tl,tm,l,Math.min(tm,r),val); update(2*v+1,tm+1,tr,Math.max(l,tm+1),r,val); t[v]=Math.min(t[2*v],t[2*v+1]); } } public int query(int v,int tl,int tr,int l,int r) { if(l>r) return 1000000000; else if(l<=tl&&r>=tr) { return t[v]; } else { push(v); int tm=(tl+tr)/2; return Math.min(query(2*v,tl,tm,l,Math.min(tm,r)),query(2*v+1,tm+1,tr,Math.max(tm+1,l),r)); } } } public static int max(int[] a) { int res=-10000000; for(int i=0;i<a.length;i++) { if(res<a[i]) res=a[i]; } return res; } public static int min(int[] a) { int min=100000000; for(int i=0;i<a.length;i++) { if(min>a[i]) min=a[i]; } return min; } public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); //long startTime=System.nanoTime(); int n=sc.nextInt(); int m=sc.nextInt(); int[] a=sc.nextIntArray(n); int[] l=new int[m]; int[] r=new int[m]; for(int i=0;i<m;i++) { l[i]=sc.nextInt(); r[i]=sc.nextInt(); l[i]-=1; r[i]-=1; } int ans=max(a)-min(a); Vector<Integer> sol=new Vector<Integer>(); Vector<Integer>[] pos=(Vector<Integer>[]) new Vector[n+1]; Vector<Integer>[] neg=(Vector<Integer>[]) new Vector[n+1]; for(int i=0;i<=n;i++) { pos[i]=new Vector<Integer>(); neg[i]=new Vector<Integer>(); } for(int j=0;j<m;j++) { pos[r[j]+1].add(j); neg[l[j]].add(j); } int ansin=0; segMent tr=new segMent(a,n); for(int i=0;i<m;i++) tr.update(1,0,a.length-1,l[i],r[i],-1); for(int i=0;i<n;i++) { for(int j=0;j<pos[i].size();j++) { int k=pos[i].elementAt(j); tr.update(1,0,a.length-1,l[k],r[k],-1); } for(int j=0;j<neg[i].size();j++) { int k=neg[i].elementAt(j); tr.update(1,0,a.length-1,l[k],r[k],+1); } int minNew=tr.query(1,0,a.length-1,0,a.length-1); if(a[i]-minNew>=ans) { ans=a[i]-minNew; ansin=i; } } for(int i=0;i<m;i++) { if(!(l[i]<=ansin&&r[i]>=ansin)) sol.add(i); } out.println(ans); out.println(sol.size()); for(int i:sol) out.print((i+1)+" "); out.flush(); //long endTime=System.nanoTime(); //out.println((endTime-startTime)+"ns"); //out.flush(); } static class Scanner { BufferedReader br; StringTokenizer tk=new StringTokenizer(""); public Scanner(InputStream is) { br=new BufferedReader(new InputStreamReader(is)); } public int nextInt() throws IOException { if(tk.hasMoreTokens()) return Integer.parseInt(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextInt(); } public long nextLong() throws IOException { if(tk.hasMoreTokens()) return Long.parseLong(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextLong(); } public String next() throws IOException { if(tk.hasMoreTokens()) return (tk.nextToken()); tk=new StringTokenizer(br.readLine()); return next(); } public String nextLine() throws IOException { tk=new StringTokenizer(""); return br.readLine(); } public double nextDouble() throws IOException { if(tk.hasMoreTokens()) return Double.parseDouble(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextDouble(); } public char nextChar() throws IOException { if(tk.hasMoreTokens()) return (tk.nextToken().charAt(0)); tk=new StringTokenizer(br.readLine()); return nextChar(); } public int[] nextIntArray(int n) throws IOException { int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public int[] nextIntArrayOneBased(int n) throws IOException { int a[]=new int[n+1]; for(int i=1;i<=n;i++) a[i]=nextInt(); return a; } public long[] nextLongArrayOneBased(int n) throws IOException { long a[]=new long[n+1]; for(int i=1;i<=n;i++) a[i]=nextLong(); return a; } } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
60299c7f691914baa20afde67e3504fa
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.util.*; import java.io.*; //267630EY public class Main1108E2 { static PrintWriter out=new PrintWriter(System.out); static class segMent { int[] t; int n; int[] lazy; boolean[] marked; public segMent(int[] a,int n) { this.n=n; lazy=new int[4*n]; marked=new boolean[4*n]; t=new int[4*n]; build(1,0,a.length-1,a); } public void build(int v,int tl,int tr,int[] a) { if(tl==tr) { t[v]=a[tl]; } else { int tm=(tl+tr)/2; build(2*v,tl,tm,a); build(2*v+1,tm+1,tr,a); t[v]=Math.min(t[2*v+1],t[2*v]); } } public void push(int v) { t[2*v]+=lazy[v]; t[2*v+1]+=lazy[v]; lazy[2*v]+=lazy[v]; lazy[2*v+1]+=lazy[v]; lazy[v]=0; } public void update(int v,int tl,int tr,int l,int r,int val) { if(l>r) return; else if(l==tl&&r==tr) { t[v]+=val; lazy[v]+=val; } else { push(v); int tm=(tl+tr)/2; update(2*v,tl,tm,l,Math.min(tm,r),val); update(2*v+1,tm+1,tr,Math.max(l,tm+1),r,val); t[v]=Math.min(t[2*v],t[2*v+1]); } } public int query(int v,int tl,int tr,int l,int r) { if(l>r) return 1000000000; else if(l<=tl&&r>=tr) { return t[v]; } else { push(v); int tm=(tl+tr)/2; return Math.min(query(2*v,tl,tm,l,Math.min(tm,r)),query(2*v+1,tm+1,tr,Math.max(tm+1,l),r)); } } } public static int max(int[] a) { int res=-10000000; for(int i=0;i<a.length;i++) { if(res<a[i]) res=a[i]; } return res; } public static int min(int[] a) { int min=100000000; for(int i=0;i<a.length;i++) { if(min>a[i]) min=a[i]; } return min; } public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); //long startTime=System.nanoTime(); int n=sc.nextInt(); int m=sc.nextInt(); int[] a=sc.nextIntArray(n); int[] l=new int[m]; int[] r=new int[m]; for(int i=0;i<m;i++) { l[i]=sc.nextInt(); r[i]=sc.nextInt(); l[i]-=1; r[i]-=1; } int ans=max(a)-min(a); //Vector<Integer>[] ad=(Vector<Integer>[]) new Vector[n+1]; Vector<Integer> sol=new Vector<Integer>(); Vector<Integer>[] pos=(Vector<Integer>[]) new Vector[n+1]; Vector<Integer>[] neg=(Vector<Integer>[]) new Vector[n+1]; for(int i=0;i<=n;i++) { //ad[i]=new Vector<Integer>(); pos[i]=new Vector<Integer>(); neg[i]=new Vector<Integer>(); } for(int j=0;j<m;j++) { pos[r[j]+1].add(j); neg[l[j]].add(j); } int ansin=0; segMent tr=new segMent(a,n); for(int i=0;i<m;i++) tr.update(1,0,a.length-1,l[i],r[i],-1); for(int i=0;i<n;i++) { for(int j=0;j<pos[i].size();j++) { int k=pos[i].elementAt(j); tr.update(1,0,a.length-1,l[k],r[k],-1); } for(int j=0;j<neg[i].size();j++) { int k=neg[i].elementAt(j); tr.update(1,0,a.length-1,l[k],r[k],+1); } int minNew=tr.query(1,0,a.length-1,0,a.length-1); //System.out.println(minNew+" "+a[i]); if(a[i]-minNew>=ans) { ans=a[i]-minNew; ansin=i; //System.out.println(ansin); } } //out.println(ansin); for(int i=0;i<m;i++) { if(!(l[i]<=ansin&&r[i]>=ansin)) sol.add(i); } out.println(ans); out.println(sol.size()); for(int i:sol) out.print((i+1)+" "); out.flush(); //long endTime=System.nanoTime(); //out.println((endTime-startTime)+"ns"); //out.flush(); } static class Scanner { BufferedReader br; StringTokenizer tk=new StringTokenizer(""); public Scanner(InputStream is) { br=new BufferedReader(new InputStreamReader(is)); } public int nextInt() throws IOException { if(tk.hasMoreTokens()) return Integer.parseInt(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextInt(); } public long nextLong() throws IOException { if(tk.hasMoreTokens()) return Long.parseLong(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextLong(); } public String next() throws IOException { if(tk.hasMoreTokens()) return (tk.nextToken()); tk=new StringTokenizer(br.readLine()); return next(); } public String nextLine() throws IOException { tk=new StringTokenizer(""); return br.readLine(); } public double nextDouble() throws IOException { if(tk.hasMoreTokens()) return Double.parseDouble(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextDouble(); } public char nextChar() throws IOException { if(tk.hasMoreTokens()) return (tk.nextToken().charAt(0)); tk=new StringTokenizer(br.readLine()); return nextChar(); } public int[] nextIntArray(int n) throws IOException { int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public int[] nextIntArrayOneBased(int n) throws IOException { int a[]=new int[n+1]; for(int i=1;i<=n;i++) a[i]=nextInt(); return a; } public long[] nextLongArrayOneBased(int n) throws IOException { long a[]=new long[n+1]; for(int i=1;i<=n;i++) a[i]=nextLong(); return a; } } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
e0872a5761f02994fd6bce6b07c69b28
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; //Solution Credits: Taranpreet Singh public class Main{ //SOLUTION BEGIN void pre() throws Exception{} void solve(int TC) throws Exception{ int n = ni(), m = ni(); int[] a = new int[n]; for(int i = 0; i< n; i++)a[i] = ni(); LazySegTree t = new LazySegTree(a); int[][] seg = new int[m][], segl = new int[m][], segr = new int[m][]; for(int i = 0; i< m; i++){ int l = ni()-1, r = ni()-1; t.rng(l, r, 0, t.m-1, 1, -1); seg[i] = new int[]{l,r}; segl[i] = new int[]{l,r}; segr[i] = new int[]{l,r}; } Arrays.sort(segl, (int[] i1, int[] i2) -> Integer.compare(i1[0], i2[0])); Arrays.sort(segr, (int[] i1, int[] i2) -> Integer.compare(i1[1], i2[1])); long ans= 0;int ind = 0; for(int i = 0, j = 0, k = 0; i< n; i++){ while(j<m && segl[j][0]<=i){ t.rng(segl[j][0], segl[j][1], 0, t.m-1, 1, 1); j++; } while(k< m && segr[k][1]<i){ t.rng(segr[k][0], segr[k][1], 0, t.m-1, 1, -1); k++; } long x = t.sum(0, n, 0, t.m-1, 1); if(a[i]-x>ans){ ans = a[i]-x; ind = i; } } pn(ans); StringBuilder aa = new StringBuilder("");int c = 0; for(int i = 0; i< m; i++)if(seg[i][0]>ind || seg[i][1]<ind){ aa.append((i+1)+" ");c++; } pn(c+"\n"+aa.toString()); } class LazySegTree{ int m = 1; long[] t, lazy; public LazySegTree(int[] a){ while(m<a.length)m<<=1; t = new long[m<<1]; lazy = new long[m<<1|1]; for(int i = 0; i< a.length; i++)t[m+i] = a[i]; for(int i = a.length; i< m; i++)t[m+i] = MX; for(int i = m-1; i> 0; i--)t[i] = Math.min(t[i<<1], t[i<<1|1]); } void rng(int l, int r, int ll, int rr, int i, long x){ if(lazy[i]!=0){ t[i] += lazy[i]; if(ll!=rr){ lazy[i<<1] += lazy[i]; lazy[i<<1|1] += lazy[i]; } lazy[i] = 0; } if(r<ll || rr<l)return; if(l<=ll && rr<=r){ t[i] += x; if(ll!=rr){ lazy[i<<1] += x; lazy[i<<1|1] += x; } return; } int mid = (ll+rr)>>1; rng(l,r,ll,mid,i<<1,x);rng(l,r,mid+1,rr,i<<1|1,x); t[i] = Math.min(t[i<<1],t[i<<1|1]); } long sum(int l, int r, int ll, int rr, int i){ if(lazy[i]!=0){ t[i] += lazy[i]; if(ll!=rr){ lazy[i<<1] += lazy[i]; lazy[i<<1|1] += lazy[i]; } lazy[i] = 0; } if(r<ll || rr<l)return MX; if(l<=ll && rr<=r)return t[i]; int mid = (ll+rr)>>1; return Math.min(sum(l,r,ll,mid,i<<1),sum(l,r,mid+1,rr,i<<1|1)); } } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} long mod = (long)1e9+7, IINF = (long)4e18; final int INF = (int)2e9, MX = (int)1e6+1; DecimalFormat df = new DecimalFormat("0.000000000000000"); double PI = 3.1415926535897932384626433832792884197169399375105820974944, eps = 1e-8; static boolean multipleTC = false, memory = false; FastReader in;PrintWriter out; void run() throws Exception{ in = new FastReader(); out = new PrintWriter(System.out); int T = (multipleTC)?ni():1; //Solution Credits: Taranpreet Singh pre();for(int i = 1; i<= T; i++)solve(i); out.flush(); out.close(); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str = ""; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
0d305ae5a34e9c929a8269d291b19b37
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
//package round535; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.List; public class E { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); int[] a = na(n); for(int i = 0;i < n;i++)a[i] = -a[i]; int[][] rs = new int[m][]; for(int i = 0;i < m;i++){ rs[i] = new int[]{ni()-1, ni()-1}; } int[][] es = new int[2*m][]; int p = 0; for(int i = 0;i < m;i++){ es[p++] = new int[]{rs[i][0], i, -1}; es[p++] = new int[]{rs[i][1]+1, i, 1}; } Arrays.sort(es, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[0] - b[0]; } }); StarrySkyTree sst = new StarrySkyTree(a); int q = 0; long ans = 0; int arg = -1; for(int i = 0;i < n;i++){ while(q < 2*m && es[q][0] <= i){ sst.add(rs[es[q][1]][0], rs[es[q][1]][1]+1, -es[q][2]); q++; } int min = -sst.min(i, i+1); int max = Math.max(-sst.min(0, i), -sst.min(i+1, n)); if(max-min > ans){ ans = max-min; arg = i; } } out.println(ans); List<Integer> args = new ArrayList<>(); for(int i = 0;i < m;i++){ if(rs[i][0] <= arg && arg <= rs[i][1]){ args.add(i+1); } } out.println(args.size()); for(int v : args){ out.print(v + " "); } out.println(); } public class StarrySkyTree { public int M, H, N; public int[] st; public int[] plus; public int I = Integer.MAX_VALUE/4; // I+plus<int public StarrySkyTree(int n) { N = n; M = Integer.highestOneBit(Math.max(n-1, 1))<<2; H = M>>>1; st = new int[M]; plus = new int[H]; } public StarrySkyTree(int[] a) { N = a.length; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; st = new int[M]; for(int i = 0;i < N;i++){ st[H+i] = a[i]; } plus = new int[H]; Arrays.fill(st, H+N, M, I); for(int i = H-1;i >= 1;i--)propagate(i); } private void propagate(int i) { st[i] = Math.min(st[2*i], st[2*i+1]) + plus[i]; } public void add(int l, int r, int v){ if(l < r)add(l, r, v, 0, H, 1); } private void add(int l, int r, int v, int cl, int cr, int cur) { if(l <= cl && cr <= r){ if(cur >= H){ st[cur] += v; }else{ plus[cur] += v; propagate(cur); } }else{ int mid = cl+cr>>>1; if(cl < r && l < mid){ add(l, r, v, cl, mid, 2*cur); } if(mid < r && l < cr){ add(l, r, v, mid, cr, 2*cur+1); } propagate(cur); } } public int min(int l, int r){ return l >= r ? I : min(l, r, 0, H, 1);} private int min(int l, int r, int cl, int cr, int cur) { if(l <= cl && cr <= r){ return st[cur]; }else{ int mid = cl+cr>>>1; int ret = I; if(cl < r && l < mid){ ret = Math.min(ret, min(l, r, cl, mid, 2*cur)); } if(mid < r && l < cr){ ret = Math.min(ret, min(l, r, mid, cr, 2*cur+1)); } return ret + plus[cur]; } } public void fall(int i) { if(i < H){ if(2*i < H){ plus[2*i] += plus[i]; plus[2*i+1] += plus[i]; } st[2*i] += plus[i]; st[2*i+1] += plus[i]; plus[i] = 0; } } public int firstle(int l, int v) { int cur = H+l; for(int i = 1, j = Integer.numberOfTrailingZeros(H)-1;i <= cur;j--){ fall(i); i = i*2|cur>>>j&1; } while(true){ fall(cur); if(st[cur] <= v){ if(cur < H){ cur = 2*cur; }else{ return cur-H; } }else{ cur++; if((cur&cur-1) == 0)return -1; cur = cur>>>Integer.numberOfTrailingZeros(cur); } } } public int lastle(int l, int v) { int cur = H+l; for(int i = 1, j = Integer.numberOfTrailingZeros(H)-1;i <= cur;j--){ fall(i); i = i*2|cur>>>j&1; } while(true){ fall(cur); if(st[cur] <= v){ if(cur < H){ cur = 2*cur+1; }else{ return cur-H; } }else{ if((cur&cur-1) == 0)return -1; cur = cur>>>Integer.numberOfTrailingZeros(cur); cur--; } } } public int[] toArray() { return toArray(1, 0, H, new int[H]); } private int[] toArray(int cur, int l, int r, int[] ret) { if(r-l == 1){ ret[cur-H] = st[cur]; }else{ toArray(2*cur, l, l+r>>>1, ret); toArray(2*cur+1, l+r>>>1, r, ret); for(int i = l;i < r;i++)ret[i] += plus[cur]; } return ret; } } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new E().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 boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
b25caf3c792202bddb711b77c70c33fe
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.io.*; import java.util.*; public class Task { public static void main(String[] args) throws Exception { new Task().go(); } PrintWriter out; Reader in; BufferedReader br; Task() throws IOException { try { //br = new BufferedReader( new FileReader("input.txt") ); //in = new Reader("input.txt"); in = new Reader("input.txt"); out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); } catch (Exception e) { //br = new BufferedReader( new InputStreamReader( System.in ) ); in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); } } void go() throws Exception { //int t = in.nextInt(); int t = 1; while (t > 0) { solve(); t--; } out.flush(); out.close(); } int inf = 2000000000; int mod = 1000000007; double eps = 0.000000001; int n; int m; void solve() throws IOException { int n = in.nextInt(); int m = in.nextInt(); int[] a = new int[n]; int[] b = new int[n]; int[] c = new int[n]; for (int i = 0; i < n; i++) { a[i] = b[i] = c[i] = in.nextInt(); } Pair[] p = new Pair[m]; ArrayList<Integer>[] ls = new ArrayList[n]; ArrayList<Integer>[] rs = new ArrayList[n]; for (int i = 0; i < n; i++) { ls[i] = new ArrayList<>(); rs[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { p[i] = new Pair(in.nextInt() - 1, in.nextInt() - 1); ls[p[i].b].add(p[i].a); rs[p[i].a].add(p[i].b); } int[] pref = new int[n]; int[] suff = new int[n]; int min = inf; for (int i = 0; i < n; i++) { pref[i] = min; min = Math.min(min, a[i]); for (int l : ls[i]) { for (int j = l; j <= i; j++) { a[j]--; min = Math.min(min, a[j]); } } } min = inf; for (int i = n - 1; i >= 0; i--) { suff[i] = min; min = Math.min(min, b[i]); for (int r : rs[i]) for (int j = i; j <= r; j++) { b[j]--; min = Math.min(min, b[j]); } } int ans = 0; int cnt = 0; int ind = 0; ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { min = Math.min(pref[i], suff[i]); if (ans < c[i] - min) { ans = c[i] - min; ind = i; } } for (int i = 0; i < m; i++) { if (p[i].b < ind || p[i].a > ind) { cnt++; list.add(i+1); } } out.println(ans); out.println(cnt); for (int k : list) out.print(k+" "); } class Pair implements Comparable<Pair>{ int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (a > p.a) return -1; if (a < p.a) return 1; if (b > p.b) return -1; if (b < p.b) return 1; return 0; } } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } } static class InputReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public InputReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public InputReader(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
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
a946506b40279c421ad7f9be68cc8286
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Main { static Tree[] trees; static int[] a; public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int m = input.nextInt(); a = new int[n + 1]; int[][] segment = new int[m+1][2]; ArrayList<Integer>[] q1 = new ArrayList[n+1]; ArrayList<Integer>[] q2 = new ArrayList[n+1]; for (int i = 0; i < n+1; i++) q1[i] = new ArrayList<>(); for (int i = 0; i < n+1; i++) q2[i] = new ArrayList<>(); for (int i = 1; i <= n; i++) a[i] = input.nextInt(); for (int i = 1; i <= m; i++) { segment[i][0] = input.nextInt(); segment[i][1] = input.nextInt(); q1[segment[i][0]].add(i); q2[segment[i][1]].add(i); } trees = new Tree[4 * n]; build(1, 1, n); int result = Integer.MIN_VALUE; ArrayList<Integer> choiceSeg = new ArrayList<>(); int len = 0; int tmp = 0; int id = 0; for (int i = 1; i <= n; i++) { len = q2[i-1].size(); for (int j = 0; j < len; j++) { tmp = q2[i-1].get(j); update(1,segment[tmp][0],segment[tmp][1],1); } len = q1[i].size(); for (int j = 0; j < len; j++) { tmp = q1[i].get(j); update(1,segment[tmp][0],segment[tmp][1],-1); } if ( result < trees[1].max - trees[1].min){ result = trees[1].max - trees[1].min; id = i; } } System.out.println(result); for (int i = 1; i <= m; i++) if (segment[i][0] <= id && segment[i][1] >= id) choiceSeg.add(i); System.out.println(choiceSeg.size()); for(int i : choiceSeg) System.out.print(i+" "); } public static void PushUP(int k) { trees[k].max = Math.max(trees[k << 1].max, trees[k << 1 | 1].max); trees[k].min = Math.min(trees[k << 1].min, trees[k << 1 | 1].min); } public static void Pushdown(int k) { if (trees[k].l != trees[k].r) { trees[k << 1].max += trees[k].flag; trees[k << 1].min += trees[k].flag; trees[k << 1 | 1].max += trees[k].flag; trees[k << 1 | 1].min += trees[k].flag; trees[k << 1].flag += trees[k].flag; trees[k << 1 | 1].flag += trees[k].flag; } trees[k].flag = 0; } public static void build(int k, int l, int r) { trees[k] = new Tree(); trees[k].l = l; trees[k].r = r; if (l == r) { trees[k].max = a[l]; trees[k].min = a[l]; return; } int mid = (l + r) >> 1; build(k << 1, l, mid); build(k << 1 | 1, mid + 1, r); PushUP(k); } public static void update(int k, int l, int r, int x) { if (trees[k].flag != 0) Pushdown(k); if (l <= trees[k].l && r>=trees[k].r){ trees[k].min += x; trees[k].max += x; trees[k].flag += x; return; } int mid = (trees[k].l + trees[k].r) >> 1; if (r <= mid) update(k << 1, l, r, x); else if (l > mid) update(k << 1 | 1, l, r, x); else { update(k << 1, l, mid, x); update(k << 1 | 1, mid + 1, r, x); } PushUP(k); } } class Tree { int l; int r; int min; int max; int flag; }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
41e96c86e629ff50aeeb7de8e3267940
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** What do you think? What do you think? 1st on Billboard, what do you think of it Next is a Grammy, what do you think of it However you think, I’m sorry, but shit, I have no fucking interest ******************************* Higher, higher, even higher, to the point you won’t even be able to see me https://www.a2oj.com/Ladder16.html ******************************* NEVER DO 300IQ CONTESTS EVER 300IQ AS WRITER = EXTRA NONO */ import java.util.*; import java.io.*; import java.math.*; public class E2 { public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int[] arr = new int[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); Range[] ranges = new Range[M]; for(int i=0; i < M; i++) { st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken())-1; int b = Integer.parseInt(st.nextToken())-1; ranges[i] = new Range(a,b); } LazySegTree segtree = new LazySegTree(); for(int i=0; i < N; i++) segtree.update(i, i, arr[i]); for(Range r: ranges) segtree.update(r.left, r.right, -1); int res = boof(arr); int dex = -1; ArrayList<Integer>[] begin = new ArrayList[N]; ArrayList<Integer>[] end = new ArrayList[N]; for(int i=0; i < N; i++) { begin[i] = new ArrayList<Integer>(); end[i] = new ArrayList<Integer>(); } for(int i=0; i < M; i++) { Range r = ranges[i]; begin[r.left].add(i); if(r.right+1 < N) end[r.right+1].add(i); } for(int i=0; i < N; i++) { for(int rr: begin[i]) segtree.update(ranges[rr].left, ranges[rr].right, 1); for(int rr: end[i]) segtree.update(ranges[rr].left, ranges[rr].right, -1); int temp = arr[i]-segtree.minQuery(0, N-1); if(res < temp) { res = temp; dex = i; } } System.out.println(res); ArrayList<Integer> ids = new ArrayList<Integer>(); for(int i=0; i < M; i++) { Range r = ranges[i]; if((r.left > dex || r.right < dex) && dex != -1) ids.add(i); } System.out.println(ids.size()); StringBuilder sb = new StringBuilder(); for(int x: ids) sb.append(x+1).append(" "); System.out.println(sb); } public static int boof(int[] arr) { int min = arr[0]; int max = arr[0]; for(int x: arr) { min = Math.min(min, x); max = Math.max(max, x); } return max-min; } } class Range { public int left; public int right; public Range(int a, int b) { left = a; right = b; } } class LazySegTree { private int[] min; private int[] lazy; private int size; public LazySegTree() { this.size = 100001; min = new int[400000]; lazy = new int[400000]; } public void update(int l, int r, int inc) { update(1, 0, size-1, l, r, inc); } private void pushDown(int index, int l, int r) { min[index] += lazy[index]; if(l != r) { lazy[2*index] += lazy[index]; lazy[2*index+1] += lazy[index]; } lazy[index] = 0; } private void pullUp(int index, int l, int r) { int m = (l+r)/2; min[index] = Math.min(evaluateMin(2*index, l, m), evaluateMin(2*index+1, m+1, r)); } private int evaluateMin(int index, int l, int r) { return min[index] + lazy[index]; } private void update(int index, int l, int r, int left, int right, int inc) { if(r < left || l > right) return; if(l >= left && r <= right) { lazy[index] += inc; return; } pushDown(index, l, r); int m = (l+r)/2; update(2*index, l, m, left, right, inc); update(2*index+1, m+1, r, left, right, inc); pullUp(index, l, r); } public int minQuery(int l, int r) { return minQuery(1, 0, size-1, l, r); } private int minQuery(int index, int l, int r, int left, int right) { if(r < left || l > right) return Integer.MAX_VALUE; if(l >= left && r <= right) { return evaluateMin(index, l, r); } pushDown(index, l, r); int m = (l+r)/2; int ret = Integer.MAX_VALUE; ret = Math.min(ret, minQuery(2*index, l, m, left, right)); ret = Math.min(ret, minQuery(2*index+1, m+1, r, left, right)); pullUp(index, l, r); return ret; } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
553d86e28cf39a0e2b89fdd5c8da2dec
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.util.*; import java.io.*; public class Main { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int N = (int)1e5+5, n,m,h; int[] a = new int[2*N],d = new int[N]; //set the value at given index void apply(int p,int value){ a[p] += value; if(p<n) d[p] += value; } // build the initial tree void build(){ for(int i=n-1;i>0;i--)a[i] = Math.min(a[i<<1],a[i<<1|1]); } // update all parents of child at index p void build(int p){ while(p>1){ p>>=1; a[p] = Math.min(a[p<<1],a[p<<1|1])+d[p]; } } // increment a[i] by value (l<=i<r) void inc(int l,int r,int value){ l += n; r += n; int l0 = l, r0 = r; while(l<r){ if((l&1)==1)apply(l++,value); if((r&1)==1)apply(--r,value); l>>=1; r>>=1; } build(l0); build(r0-1); } // push all the delayed changes to child at index p void push(int p){ for (int s = h; s > 0; --s) { int i = p >> s; if (d[i] != 0) { apply(i<<1, d[i]); apply(i<<1|1, d[i]); d[i] = 0; } } } // query[l,r) int query(int l, int r) { l += n; r += n; push(l); push(r - 1); int res = (int)2e9; for (; l < r; l >>= 1, r >>= 1) { if ((l&1)==1) res = Math.min(res, a[l++]); if ((r&1)==1) res = Math.min(a[--r], res); } return res; } // main code void solve(){ n = in.ni(); m = in.ni(); h = (int)(Math.log(n)/Math.log(2)); ArrayList<Integer>[] lf = new ArrayList[n], rf = new ArrayList[n]; int[] data = new int[n]; for(int i=0;i<n;i++){ data[i] = in.ni(); lf[i] = new ArrayList<>(); rf[i] = new ArrayList<>(); } int[][] seg = new int[m][2]; for(int i=0;i<m;i++){ int l = in.ni(), r = in.ni(); l--; r--; lf[r].add(l); rf[l].add(r); seg[i][0] = l; seg[i][1] = r; } int ans, ind = -1,min = data[0],max = data[0]; for(int i : data){ min = Math.min(min,i); max = Math.max(max,i); } ans = max-min; //left for(int i=0;i<n;i++)a[i+n] = data[i]; build(); for(int i=0;i<n;i++){ if(ans<data[i]-min){ ans = data[i]-min; ind = i; } for(int k : lf[i]){ inc(k,i+1,-1); min = query(0,n); } } // right Arrays.fill(d,0,n,0); Arrays.fill(a,0,n,0); for(int i=0;i<n;i++)a[i+n] = data[i]; build(); min = data[n-1]; for(int i=n-1;i>=0;i--){ if(ans<data[i]-min){ ans = data[i]-min; ind = i; } for(int k : rf[i]){ inc(i,k+1,-1); min = query(0,n); } } out.println(ans); int c = 0; ArrayList<Integer> res = new ArrayList<>(); for(int i=0;i<m && ind!=-1;i++) if(seg[i][0]>ind || seg[i][1]<ind){ res.add(i); c++; } out.println(c); for(int i : res) out.print((i+1)+" "); } void run(){ solve(); out.close(); } public static void main(String[] args) { new Main().run(); } // class for fast I/O class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } int nextInt(){return Integer.parseInt(in.next());} long nextLong(){return Long.parseLong(in.next());} double nextDouble(){return Double.parseDouble(in.next());} int ni(){return Integer.parseInt(in.next());} long nl(){return Long.parseLong(in.next());} double nd(){return Double.parseDouble(in.next());} } void pn(Object o){out.println(o);out.flush();} class pair{ int f,s; public pair(int f,int s){ this.f = f; this.s = s; } } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
bdbda916eff7b6aa92f2b8a679bfb2d3
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.util.*; import java.io.*; public class Main { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int N = (int)1e5+5, n,m,h; int[] a = new int[2*N],d = new int[N]; void apply(int p,int value){ a[p] += value; if(p<n) d[p] += value; } void build(){ for(int i=n-1;i>0;i--)a[i] = Math.min(a[i<<1],a[i<<1|1]); } void build(int p){ while(p>1){ p>>=1; a[p] = Math.min(a[p<<1],a[p<<1|1])+d[p]; } } void inc(int l,int r,int value){ l += n; r += n; int l0 = l, r0 = r; while(l<r){ if((l&1)==1)apply(l++,value); if((r&1)==1)apply(--r,value); l>>=1; r>>=1; } build(l0); build(r0-1); } void push(int p){ for (int s = h; s > 0; --s) { int i = p >> s; if (d[i] != 0) { apply(i<<1, d[i]); apply(i<<1|1, d[i]); d[i] = 0; } } } int query(int l, int r) { l += n; r += n; push(l); push(r - 1); int res = (int)2e9; for (; l < r; l >>= 1, r >>= 1) { if ((l&1)==1) res = Math.min(res, a[l++]); if ((r&1)==1) res = Math.min(a[--r], res); } return res; } void solve(){ n = in.ni(); m = in.ni(); h = (int)(Math.log(n)/Math.log(2)); ArrayList<Integer>[] lf = new ArrayList[n], rf = new ArrayList[n]; int[] data = new int[n]; for(int i=0;i<n;i++){ data[i] = in.ni(); lf[i] = new ArrayList<>(); rf[i] = new ArrayList<>(); } int[][] seg = new int[m][2]; for(int i=0;i<m;i++){ int l = in.ni(), r = in.ni(); l--; r--; lf[r].add(l); rf[l].add(r); seg[i][0] = l; seg[i][1] = r; } int ans, ind = -1,min = data[0],max = data[0]; for(int i : data){ min = Math.min(min,i); max = Math.max(max,i); } ans = max-min; //left for(int i=0;i<n;i++)a[i+n] = data[i]; build(); for(int i=0;i<n;i++){ if(ans<data[i]-min){ ans = data[i]-min; ind = i; } for(int k : lf[i]){ inc(k,i+1,-1); min = query(0,n); } } // right Arrays.fill(d,0,n,0); Arrays.fill(a,0,n,0); for(int i=0;i<n;i++)a[i+n] = data[i]; build(); min = data[n-1]; for(int i=n-1;i>=0;i--){ if(ans<data[i]-min){ ans = data[i]-min; ind = i; } for(int k : rf[i]){ inc(i,k+1,-1); min = query(0,n); } } out.println(ans); int c = 0; ArrayList<Integer> res = new ArrayList<>(); for(int i=0;i<m && ind!=-1;i++) if(seg[i][0]>ind || seg[i][1]<ind){ res.add(i); c++; } out.println(c); for(int i : res) out.print((i+1)+" "); } void run(){ solve(); out.close(); } public static void main(String[] args) { new Main().run(); } class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } int nextInt(){return Integer.parseInt(in.next());} long nextLong(){return Long.parseLong(in.next());} double nextDouble(){return Double.parseDouble(in.next());} int ni(){return Integer.parseInt(in.next());} long nl(){return Long.parseLong(in.next());} double nd(){return Double.parseDouble(in.next());} } void pn(Object o){out.println(o);out.flush();} class pair{ int f,s; public pair(int f,int s){ this.f = f; this.s = s; } } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
fd98c03836c3381e6d4b825bda8f3245
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.util.*; import java.io.*; public class Main { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int N = (int)1e5, n,m,h; int[] a,d; void apply(int p,int value){ a[p] += value; if(p<n) d[p] += value; } void build(){ for(int i=n-1;i>0;i--)a[i] = Math.min(a[i<<1],a[i<<1|1]); } void build(int p){ while(p>1){ p>>=1; a[p] = Math.min(a[p<<1],a[p<<1|1])+d[p]; } } void inc(int l,int r,int value){ l += n; r += n; int l0 = l, r0 = r; while(l<r){ if((l&1)==1)apply(l++,value); if((r&1)==1)apply(--r,value); l>>=1; r>>=1; } build(l0); build(r0-1); } void push(int p){ for (int s = h; s > 0; --s) { int i = p >> s; if (d[i] != 0) { apply(i<<1, d[i]); apply(i<<1|1, d[i]); d[i] = 0; } } } int query(int l, int r) { l += n; r += n; push(l); push(r - 1); int res = (int)2e9; for (; l < r; l >>= 1, r >>= 1) { if ((l&1)==1) res = Math.min(res, a[l++]); if ((r&1)==1) res = Math.min(a[--r], res); } return res; } void solve(){ n = in.ni(); m = in.ni(); h = (int)(Math.log(n)/Math.log(2))+1; ArrayList<Integer>[] lf = new ArrayList[n], rf = new ArrayList[n]; int[] data = new int[n]; for(int i=0;i<n;i++){ data[i] = in.ni(); lf[i] = new ArrayList<>(); rf[i] = new ArrayList<>(); } int[][] seg = new int[m][2]; for(int i=0;i<m;i++){ int l = in.ni(), r = in.ni(); l--; r--; lf[r].add(l); rf[l].add(r); seg[i][0] = l; seg[i][1] = r; } //left a = new int[2*n]; d = new int[2*n]; for(int i=0;i<n;i++)a[i+n] = data[i]; build(); int ans, ind = -1,min = data[0],max = data[0]; for(int i : data){ min = Math.min(min,i); max = Math.max(max,i); } ans = max-min; for(int i=0;i<n;i++){ if(ans<data[i]-min){ ans = data[i]-min; ind = i; } for(int k : lf[i]){ inc(k,i+1,-1); min = query(0,n); } } // right a = new int[2*n]; d = new int[2*n]; for(int i=0;i<n;i++)a[i+n] = data[i]; build(); min = data[n-1]; for(int i=n-1;i>=0;i--){ if(ans<data[i]-min){ ans = data[i]-min; ind = i; } for(int k : rf[i]){ inc(i,k+1,-1); min = query(0,n); } } out.println(ans); int c = 0; ArrayList<Integer> res = new ArrayList<>(); for(int i=0;i<m && ind!=-1;i++) if(seg[i][0]>ind || seg[i][1]<ind){ res.add(i); c++; } out.println(c); for(int i : res) out.print((i+1)+" "); } void run(){ solve(); out.close(); } public static void main(String[] args) { new Main().run(); } class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } int nextInt(){return Integer.parseInt(in.next());} long nextLong(){return Long.parseLong(in.next());} double nextDouble(){return Double.parseDouble(in.next());} int ni(){return Integer.parseInt(in.next());} long nl(){return Long.parseLong(in.next());} double nd(){return Double.parseDouble(in.next());} } void pn(Object o){out.println(o);out.flush();} class pair{ int f,s; public pair(int f,int s){ this.f = f; this.s = s; } } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
dea54f40e87ebe6f9d72d8b15435b64c
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.util.*; import java.io.*; public class Main { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int N = (int)1e5+5, n,m,h; int[] a = new int[2*N],d = new int[N]; void apply(int p,int value){ a[p] += value; if(p<n) d[p] += value; } void build(){ for(int i=n-1;i>0;i--)a[i] = Math.min(a[i<<1],a[i<<1|1]); } void build(int p){ while(p>1){ p>>=1; a[p] = Math.min(a[p<<1],a[p<<1|1])+d[p]; } } void inc(int l,int r,int value){ l += n; r += n; int l0 = l, r0 = r; while(l<r){ if((l&1)==1)apply(l++,value); if((r&1)==1)apply(--r,value); l>>=1; r>>=1; } build(l0); build(r0-1); } void push(int p){ for (int s = h; s > 0; --s) { int i = p >> s; if (d[i] != 0) { apply(i<<1, d[i]); apply(i<<1|1, d[i]); d[i] = 0; } } } int query(int l, int r) { l += n; r += n; push(l); push(r - 1); int res = (int)2e9; for (; l < r; l >>= 1, r >>= 1) { if ((l&1)==1) res = Math.min(res, a[l++]); if ((r&1)==1) res = Math.min(a[--r], res); } return res; } void solve(){ n = in.ni(); m = in.ni(); h = (int)(Math.log(n)/Math.log(2))+1; ArrayList<Integer>[] lf = new ArrayList[n], rf = new ArrayList[n]; int[] data = new int[n]; for(int i=0;i<n;i++){ data[i] = in.ni(); lf[i] = new ArrayList<>(); rf[i] = new ArrayList<>(); } int[][] seg = new int[m][2]; for(int i=0;i<m;i++){ int l = in.ni(), r = in.ni(); l--; r--; lf[r].add(l); rf[l].add(r); seg[i][0] = l; seg[i][1] = r; } int ans, ind = -1,min = data[0],max = data[0]; for(int i : data){ min = Math.min(min,i); max = Math.max(max,i); } ans = max-min; //left for(int i=0;i<n;i++)a[i+n] = data[i]; build(); for(int i=0;i<n;i++){ if(ans<data[i]-min){ ans = data[i]-min; ind = i; } for(int k : lf[i]){ inc(k,i+1,-1); min = query(0,n); } } // right // a = new int[2*n]; // d = new int[2*n]; Arrays.fill(d,0,n,0); Arrays.fill(a,0,n,0); for(int i=0;i<n;i++)a[i+n] = data[i]; build(); min = data[n-1]; for(int i=n-1;i>=0;i--){ if(ans<data[i]-min){ ans = data[i]-min; ind = i; } for(int k : rf[i]){ inc(i,k+1,-1); min = query(0,n); } } out.println(ans); int c = 0; ArrayList<Integer> res = new ArrayList<>(); for(int i=0;i<m && ind!=-1;i++) if(seg[i][0]>ind || seg[i][1]<ind){ res.add(i); c++; } out.println(c); for(int i : res) out.print((i+1)+" "); } void run(){ solve(); out.close(); } public static void main(String[] args) { new Main().run(); } class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } int nextInt(){return Integer.parseInt(in.next());} long nextLong(){return Long.parseLong(in.next());} double nextDouble(){return Double.parseDouble(in.next());} int ni(){return Integer.parseInt(in.next());} long nl(){return Long.parseLong(in.next());} double nd(){return Double.parseDouble(in.next());} } void pn(Object o){out.println(o);out.flush();} class pair{ int f,s; public pair(int f,int s){ this.f = f; this.s = s; } } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
ea5829cc3404880dbaa254e2fc7e8cc9
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.util.*; import java.io.*; public class Main { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int N = (int)1e5, n,m,h; int[] a,d; void apply(int p,int value){ a[p] += value; if(p<n) d[p] += value; } void build(){ for(int i=n-1;i>0;i--)a[i] = Math.min(a[i<<1],a[i<<1|1]); } void build(int p){ while(p>1){ p>>=1; a[p] = Math.min(a[p<<1],a[p<<1|1])+d[p]; } } void inc(int l,int r,int value){ l += n; r += n; int l0 = l, r0 = r; while(l<r){ if((l&1)==1)apply(l++,value); if((r&1)==1)apply(--r,value); l>>=1; r>>=1; } build(l0); build(r0-1); } void push(int p){ for (int s = h; s > 0; --s) { int i = p >> s; if (d[i] != 0) { apply(i<<1, d[i]); apply(i<<1|1, d[i]); d[i] = 0; } } } int query(int l, int r) { l += n; r += n; push(l); push(r - 1); int res = (int)2e9; for (; l < r; l >>= 1, r >>= 1) { if ((l&1)==1) res = Math.min(res, a[l++]); if ((r&1)==1) res = Math.min(a[--r], res); } return res; } void solve(){ n = in.ni(); m = in.ni(); h = (int)(Math.log(n)/Math.log(2))+1; ArrayList<Integer>[] lf = new ArrayList[n], rf = new ArrayList[n]; int[] data = new int[n]; for(int i=0;i<n;i++){ data[i] = in.ni(); lf[i] = new ArrayList<>(); rf[i] = new ArrayList<>(); } int[][] seg = new int[m][2]; for(int i=0;i<m;i++){ int l = in.ni(), r = in.ni(); l--; r--; lf[r].add(l); rf[l].add(r); seg[i][0] = l; seg[i][1] = r; } //left a = new int[2*n]; d = new int[2*n]; for(int i=0;i<n;i++)a[i+n] = data[i]; build(); int ans = Integer.MIN_VALUE, ind = -1,min = data[0]; for(int i=0;i<n;i++){ // pn("ans = "+ans+" "+data[i]+" "+min); min = query(0,n); // out.println(" min = "+min); if(ans<data[i]-min){ ans = data[i]-min; ind = i; } for(int k : lf[i]){ inc(k,i+1,-1); // min = query(0,n); // pn("i = "+i+" k = "+k); } } // for(int i=1;i<2*n;i++)out.println("a["+i+"] = "+a[i]); // out.println(" min32 = "+query(0,n)); // out.println("final "+ans); // right a = new int[2*n]; d = new int[2*n]; for(int i=0;i<n;i++)a[i+n] = data[i]; build(); min = data[n-1]; for(int i=n-1;i>=0;i--){ min = query(0,n); if(ans<data[i]-min){ ans = data[i]-min; ind = i; } for(int k : rf[i]){ inc(i,k+1,-1); } } out.println(ans); int c = 0; ArrayList<Integer> res = new ArrayList<>(); for(int i=0;i<m && ind!=-1;i++) if(seg[i][0]>ind || seg[i][1]<ind){ res.add(i); c++; } out.println(c); for(int i : res) out.print((i+1)+" "); } void run(){ solve(); out.close(); } public static void main(String[] args) { new Main().run(); } class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } int nextInt(){return Integer.parseInt(in.next());} long nextLong(){return Long.parseLong(in.next());} double nextDouble(){return Double.parseDouble(in.next());} int ni(){return Integer.parseInt(in.next());} long nl(){return Long.parseLong(in.next());} double nd(){return Double.parseDouble(in.next());} } void pn(Object o){out.println(o);out.flush();} class pair{ int f,s; public pair(int f,int s){ this.f = f; this.s = s; } } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
3b4c109ffb2f76cf4fea08871696517f
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; 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); E2ArrayAndSegmentsHardVersion solver = new E2ArrayAndSegmentsHardVersion(); solver.solve(1, in, out); out.close(); } static class E2ArrayAndSegmentsHardVersion { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.ni(); int m = in.ni(); int[] ar = new int[n]; long lo = Integer.MAX_VALUE; long hi = Integer.MIN_VALUE; for (int i = 0; i < n; ++i) { ar[i] = in.ni(); lo = Math.min(lo, ar[i]); hi = Math.max(hi, ar[i]); } Pair[] pr = new Pair[m]; segTree st = new segTree(n); st.build(1, 0, n - 1, ar); Pair[] start = new Pair[m]; Pair[] end = new Pair[m]; for (int i = 0; i < m; ++i) { int a = in.ni() - 1, b = in.ni() - 1; st.update(1, 0, n - 1, a, b, -1); start[i] = new Pair(a, b); end[i] = new Pair(a, b); pr[i] = new Pair(a, b); } Arrays.sort(start, new Comparator<Pair>() { public int compare(Pair o1, Pair o2) { return Integer.compare(o1.F, o2.F); } }); Arrays.sort(end, new Comparator<Pair>() { public int compare(Pair o1, Pair o2) { return Integer.compare(o1.S, o2.S); } }); long ans = hi - lo; int idx = -1; int s = 0, e = 0; for (int i = 0; i < n; ++i) { long max = ar[i]; while (s < m && start[s].F == i) { st.update(1, 0, n - 1, start[s].F, start[s].S, 1); s++; } while (e < m && end[e].S == i - 1) { st.update(1, 0, n - 1, end[e].F, end[e].S, -1); e++; } if (max - st.tree[1] > ans) { ans = max - st.tree[1]; idx = i; } } if (idx == -1) { out.println(ans); out.print(0); } else { out.println(ans); ArrayList<Integer> arr = new ArrayList<>(); for (int i = 0; i < m; ++i) { if (pr[i].F > idx || pr[i].S < idx) arr.add(i + 1); } out.println(arr.size()); for (int g : arr) out.print(g + " "); } } public class segTree { int[] tree; int[] lazy; public segTree(int n) { tree = new int[4 * n + 2]; lazy = new int[4 * n + 2]; } public void build(int node, int l, int r, int[] ar) { if (l == r) { tree[node] = ar[l]; return; } int mid = (l + r) / 2; build(2 * node, l, mid, ar); build(2 * node + 1, mid + 1, r, ar); tree[node] = Math.min(tree[2 * node], tree[2 * node + 1]); } public void update(int node, int l, int r, int s, int e, int val) { if (lazy[node] != 0) { tree[node] += lazy[node]; if (l != r) { lazy[2 * node] += lazy[node]; lazy[2 * node + 1] += lazy[node]; } lazy[node] = 0; } if (l > e || r < s) return; if (l >= s && r <= e) { tree[node] += val; if (l != r) { lazy[2 * node] += val; lazy[2 * node + 1] += val; } return; } int mid = (l + r) / 2; update(2 * node, l, mid, s, e, val); update(2 * node + 1, mid + 1, r, s, e, val); tree[node] = Math.min(tree[2 * node], tree[2 * node + 1]); } } public class Pair { int F; int S; public Pair(int f, int s) { F = f; S = s; } } } 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.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
6d80cb95c24f3fda78a46b44a2d6e12f
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { static final long mod=(int)1e9+7; public static void main(String[] args) throws Exception { FastReader in=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int n=in.nextInt(); int m=in.nextInt(); long[] arr=new long[n+1]; for(int i=1;i<=n;i++) arr[i]=in.nextInt(); ArrayList<Integer[]>[] segl=new ArrayList[n+2]; ArrayList<Integer[]>[] segr=new ArrayList[n+2]; for(int i=0;i<=n+1;i++) { segl[i]=new ArrayList(); segr[i]=new ArrayList(); } for(int i=0;i<m;i++) { Integer[] a=new Integer[]{in.nextInt(),in.nextInt(),i+1}; segl[a[1]+1].add(a); segr[a[0]-1].add(a); } long ans=0,min=Integer.MAX_VALUE; int[] add=new int[n+1]; ArrayList<Integer[]> ans1=new ArrayList(); ArrayList<Integer[]> temp=new ArrayList(); for(int i=1;i<=n;i++) { for(Integer[] j:segl[i]) { temp.add(j); for(int k=j[0];k<=j[1];k++) { add[k]++; min=Math.min(min,arr[k]-add[k]); } } if(arr[i]-min>ans) { ans1=new ArrayList(); ans1.addAll(temp); ans=arr[i]-min; // System.out.println(i+" "+ans+" "+temp.size()); } min=Math.min(min,arr[i]); } add=new int[n+1]; temp=new ArrayList(); min=Integer.MAX_VALUE; for(int i=n;i>0;i--) { for(Integer[] j:segr[i]) { temp.add(j); for(int k=j[0];k<=j[1];k++) { add[k]++; min=Math.min(min,arr[k]-add[k]); } } if(arr[i]-min>ans) { ans1=new ArrayList(); ans1.addAll(temp); ans=arr[i]-min; } min=Math.min(min,arr[i]); } pw.println(ans); pw.println(ans1.size()); for(int i=0;i<ans1.size();i++) pw.print(ans1.get(i)[2]+" "); pw.flush(); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if(st==null || !st.hasMoreElements()) { 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()); } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
2f19ee62bfac4637faf88e750315c47a
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.io.*; import java.util.*; public class ProblemE_2 { public static InputStream inputStream = System.in; public static OutputStream outputStream = System.out; public static void main(String[] args) { MyScanner scanner = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); int n = scanner.nextInt(); int m = scanner.nextInt(); int[] list = new int[n]; for (int i = 0; i < n; i++) { list[i] = scanner.nextInt(); } Map<Integer, List<Integer>> leftMap = new HashMap<>(); Map<Integer, List<Integer>> rightMap = new HashMap<>(); List<Pair<Integer, Integer>> segments = new ArrayList<>(); for (int i = 0; i < m; i++) { int x = scanner.nextInt() - 1; int y = scanner.nextInt() - 1; if (!leftMap.containsKey(x)) { leftMap.put(x, new ArrayList<>()); } if (!rightMap.containsKey(y)) { rightMap.put(y, new ArrayList<>()); } leftMap.get(x).add(y); rightMap.get(y).add(x); segments.add(new Pair<>(x, y)); } int minIndex = -1; int min = list[0]; int max = list[0]; for (int i = 0; i < n; i++) { if (list[i] < min) { min = list[i]; minIndex = i; } if (list[i] > max) { max = list[i]; } } for (int i = 0; i < n; i++) { boolean reCalculate = false; if (leftMap.containsKey(i)) { for (int y : leftMap.get(i)) { for (int j = i; j <= y; j++) { list[j]--; } } reCalculate = true; } if (rightMap.containsKey(i - 1)) { for (int x : rightMap.get(i - 1)) { for (int j = x; j <= i - 1; j++) { list[j]++; } } reCalculate = true; } if (reCalculate) { int innerMin = Integer.MAX_VALUE; int innerMax = Integer.MIN_VALUE; for (int x : list) { innerMin = Math.min(innerMin, x); innerMax = Math.max(innerMax, x); } if (innerMax - innerMin > max - min) { max = innerMax; min = innerMin; minIndex = i; } } } out.println(max - min); List<Integer> ans = new ArrayList<>(); for (int i = 0; i < m; i++) { Pair<Integer, Integer> segment = segments.get(i); if (segment.first <= minIndex && segment.second >= minIndex) { ans.add(i + 1); } } out.println(ans.size()); for (int x : ans) { out.print(x + " "); } out.println(); out.flush(); } private static class MyScanner { private BufferedReader bufferedReader; private StringTokenizer stringTokenizer; private MyScanner(InputStream inputStream) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); } private String next() { while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) { try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return stringTokenizer.nextToken(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } private String nextLine() { String str = ""; try { str = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } private static class Pair<F, S> { private F first; private S second; public Pair() {} public Pair(F first, S second) { this.first = first; this.second = second; } } private static class Triple<F, S, T> { private F first; private S second; private T third; public Triple() {} public Triple(F first, S second, T third) { this.first = first; this.second = second; this.third = third; } } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
7adbadf43556a92ca76e7dad30a06a77
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.io.ByteArrayInputStream; 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.InputMismatchException; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Main { private static final int MAXN = 5000; private static final String NO = "NO"; private static final String YES = "YES"; InputStream is; PrintWriter out; String INPUT = ""; private static final long MOD = 1000000007L; private static final int MAX = 200000; void solve() { int N = ni(); int M = ni(); int[] a = na(N); segTree tr = new segTree(N); tr.build(1, 0, N - 1, a); List<Integer> left[] = new List[N]; List<Integer> right[] = new List[N]; for (int i = 0; i < N; i++) { left[i] = new ArrayList<Integer>(); right[i] = new ArrayList<Integer>(); } int[][] querys = new int[M][]; for (int i = 0; i < M; i++) { querys[i] = new int[] { ni() - 1, ni() - 1 }; left[querys[i][1]].add(querys[i][0]); right[querys[i][0]].add(querys[i][1]); tr.update(1, 0, N - 1, querys[i][0], querys[i][1], -1); } long max = Long.MIN_VALUE; int maxI = 0; for (int i = 0; i < N; i++) { for (int j : right[i]) { tr.update(1, 0, N - 1, i, j, 1); } long cur = a[i] - tr.tree[1]; if (cur > max) { max = cur; maxI = i; } // tr(i, cur, a[i], tr.tree[1]); for (int j : left[i]) { tr.update(1, 0, N - 1, j, i, -1); } } out.println(max); int cnt = 0; StringBuffer sb = new StringBuffer(); for (int i = 0; i < M; i++) { if (maxI >= querys[i][0] && maxI <= querys[i][1]) ; else { sb.append(i + 1).append(' '); cnt++; } } out.println(cnt); out.println(sb); } class segTree { int[] tree; int[] lazy; public segTree(int n) { tree = new int[4 * n + 2]; lazy = new int[4 * n + 2]; } public void build(int node, int l, int r, int[] ar) { if (l == r) { tree[node] = ar[l]; return; } int mid = (l + r) / 2; build(2 * node, l, mid, ar); build(2 * node + 1, mid + 1, r, ar); tree[node] = Math.min(tree[2 * node], tree[2 * node + 1]); } public void update(int node, int l, int r, int s, int e, int val) { if (lazy[node] != 0) { tree[node] += lazy[node]; if (l != r) { lazy[2 * node] += lazy[node]; lazy[2 * node + 1] += lazy[node]; } lazy[node] = 0; } if (l > e || r < s) return; if (l >= s && r <= e) { tree[node] += val; if (l != r) { lazy[2 * node] += val; lazy[2 * node + 1] += val; } return; } int mid = (l + r) / 2; update(2 * node, l, mid, s, e, val); update(2 * node + 1, mid + 1, r, s, e, val); tree[node] = Math.min(tree[2 * node], tree[2 * node + 1]); } } long power(long a, long b) { long x = 1, y = a; while (b > 0) { if (b % 2 != 0) { x = (x * y) % MOD; } y = (y * y) % MOD; b /= 2; } return x % MOD; } private long gcd(long a, long b) { while (a != 0) { long tmp = b % a; b = a; a = tmp; } return b; } 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 boolean vis[]; 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) { if (!(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 List<Integer> na2(int n) { List<Integer> a = new ArrayList<Integer>(); for (int i = 0; i < n; i++) a.add(ni()); return a; } private int[][] na(int n, int m) { int[][] a = new int[n][]; for (int i = 0; i < n; i++) a[i] = na(m); 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(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } 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
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
7edba5c9dcaa50e1efd60157e2cb4214
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import javafx.scene.layout.Priority; import java.io.*; import java.lang.reflect.Array; import java.net.Inet4Address; import java.util.*; import java.lang.*; import java.util.HashMap; import java.util.PriorityQueue; public class templ implements Runnable { static class pair implements Comparable { int f,s; pair(int fi,int se) { f=fi; s=se; } public int compareTo(Object o) { pair pr=(pair)o; if(f>pr.f) return 1; else return -1; } public boolean equals(Object o) { pair ob=(pair)o; int ff; int ss; if(o!=null) { ff=ob.f; ss=ob.s; if((ff==this.f)&&(ss==this.s)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s).hashCode(); } } public class triplet implements Comparable { int f,s; int t; triplet(int f,int s,int t) { this.f=f; this.s=s; this.t=t; } public boolean equals(Object o) { triplet ob=(triplet)o; int ff,ss; int tt; if(o!=null) { ff=ob.f; ss=ob.s; tt=ob.t; if((ff==this.f)&&(ss==this.s)&&(tt==this.t)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s+" "+this.t).hashCode(); } public int compareTo(Object o) { triplet tr=(triplet)o; if(f>tr.f) return 1; else if(f==tr.f) { if(s>tr.s) return -1; else return 1; } else return -1; } } int tree[]; int lazy[]; int a[]; void build(int node,int start,int end) { if(start==end) { tree[node]=a[start]; return; } int mid=(start+end)/2; build(2*node,start,mid); build(2*node+1,mid+1,end); tree[node]=Math.max(tree[2*node],tree[2*node+1]); } void update(int node,int start,int end,int l,int r,int val) { if(lazy[node]!=0) { tree[node]+=lazy[node]; if(start!=end) { lazy[2*node]+=lazy[node]; lazy[2*node+1]+=lazy[node]; } lazy[node]=0; } if(end<l||r<start) return; if(start>=l&&end<=r) { tree[node]+=val; if(start!=end) { lazy[2*node]+=val; lazy[2*node+1]+=val; } return; } int mid=(start+end)/2; update(2*node,start,mid,l,r,val); update(2*node+1,mid+1,end,l,r,val); tree[node]=Math.max(tree[2*node],tree[2*node+1]); } int query(int node,int start,int end,int l,int r) { if(lazy[node]!=0) { tree[node]+=lazy[node]; if(start!=end) { lazy[2*node]+=lazy[node]; lazy[2*node+1]+=lazy[node]; } lazy[node]=0; } if(end<l||r<start) return -100000000; if(start>=l&&end<=r) { return tree[node]; } int mid=(start+end)/2; int x=query(2*node,start,mid,l,r); int y=query(2*node+1,mid+1,end,l,r); return Math.max(x,y); } public static void main(String args[])throws Exception { new Thread(null,new templ(),"templ",1<<27).start(); } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n=in.ni(); int m=in.ni(); a=new int[n+1]; tree=new int[4*n+1]; lazy=new int[4*n+1]; for(int i=1;i<=n;i++) a[i]=in.ni(); build(1,1,n); ArrayList<Integer>start[]=new ArrayList[n+1]; ArrayList<Integer>end[]=new ArrayList[n+1]; int L[]=new int[m+1]; int R[]=new int[m+1]; for(int i=1;i<=n;i++) { start[i]=new ArrayList<>(); end[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { int l=in.ni(); int r=in.ni(); L[i]=l; R[i]=r; start[l].add(r); end[r].add(l); } int ans=-1,ind=-1; for(int i=1;i<=n;i++) { for(int j : start[i]) update(1,1,n,i,j,-1); int k=query(1,1,n,1,n)-query(1,1,n,i,i); if(k>ans) { ans=k; ind=i; } for(int j : end[i]) update(1,1,n,j,i,1); } out.println(ans); ArrayList<Integer>al=new ArrayList<>(); for(int i=1;i<=m;i++) { if(L[i]<=ind&&R[i]>=ind) al.add(i); } out.println(al.size()); for(int i : al) out.print(i+" "); out.close(); } catch(Exception e){ return; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } 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 ni() { 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 nl() { 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] = ni(); } 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
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
5c02f4d853e7377adecbc8567e5e545c
train_001.jsonl
1548254100
The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.lang.*; import java.math.*; import java.util.*; import java.io.*; public class Main { void solve(){ int n=ni(),m=ni(); a=new int[n+1]; lazy=new int[4*n+1]; tree=new int[4*n+1]; for(int i=1;i<=n;i++) a[i]=ni(); build(1,1,n); int L[]=new int[m+1]; int R[]=new int[m+1]; ArrayList<Integer> st[]=new ArrayList[n+1]; ArrayList<Integer> ed[]=new ArrayList[n+1]; for(int i=1;i<=n;i++) { st[i]=new ArrayList<>(); ed[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { L[i]=ni(); R[i]=ni(); st[L[i]].add(R[i]); ed[R[i]].add(L[i]); } int ans=Integer.MIN_VALUE,id=-1; for(int i=1;i<=n;i++){ for(int r : st[i]){ update(1,i,r,1,n,-1); } int mx=query(1,1,n,1,n)-query(1,i,i,1,n); if(mx>ans){ ans=mx; id=i; } for(int l : ed[i]){ update(1,l,i,1,n,1); } } Queue<Integer> q=new LinkedList<>(); for(int i=1;i<=m;i++){ if(L[i]<=id && id<=R[i]) q.offer(i); } pw.println(ans); pw.println(q.size()); while(!q.isEmpty()) pw.print(q.poll()+" "); pw.println(""); // pw.println(id); } int a[]; int tree[]; int lazy[]; void build(int id,int l,int r){ if(l==r){ tree[id]=a[l]; }else { int mid=(l+r)>>1; build(2*id,l,mid); build(2*id+1,mid+1,r); tree[id]=Math.max(tree[2*id],tree[2*id+1]); } } void update(int id,int x,int y,int l,int r,int val){ if(lazy[id]!=0){ tree[id]+=lazy[id]; if(l!=r){ lazy[2*id]+=lazy[id]; lazy[2*id+1]+=lazy[id]; } lazy[id]=0; } if(r<x || l>y) return; if(x<=l && r<=y){ tree[id]+=val; if(l!=r){ lazy[2*id]+=val; lazy[2*id+1]+=val; } return; } int mid=(l+r)>>1; update(2*id,x,y,l,mid,val); update(2*id+1,x,y,mid+1,r,val); tree[id]=Math.max(tree[2*id],tree[2*id+1]); } int query(int id,int x,int y,int l,int r){ if(lazy[id]!=0){ tree[id]+=lazy[id]; if(l!=r){ lazy[2*id]+=lazy[id]; lazy[2*id+1]+=lazy[id]; } lazy[id]=0; } if(r<x || l>y) return Integer.MIN_VALUE; if(x<=l && r<=y) return tree[id]; int mid=(l+r)>>1; return Math.max(query(2*id,x,y,l,mid),query(2*id+1,x,y,mid+1,r)); } long M= (long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.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 boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } }
Java
["5 4\n2 -2 3 1 2\n1 3\n4 5\n2 5\n1 3", "5 4\n2 -2 3 1 4\n3 5\n3 4\n2 4\n2 5", "1 0\n1000000"]
2 seconds
["6\n2\n1 4", "7\n2\n3 2", "0\n0"]
NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.
Java 8
standard input
[ "data structures", "implementation" ]
2b1595ffe5d233f788c976e155fff26f
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) β€” the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.
2,100
In the first line of the output print one integer $$$d$$$ β€” the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) β€” the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) β€” indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.
standard output
PASSED
8144870eaa0cceb7fc234a4d8d0c1fef
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class A { public static void main(String[] s){ Scanner in = new Scanner(System.in); int numb = in.nextInt(); int data[][] = new int[numb][numb]; for (int i = 0; i < data.length; i++) { for (int j = 0; j < data.length; j++) { data[i][j] = in.nextInt(); } } int one = diagonal(data); int two = seredina(data); int three = 3*data[data.length/2 ][data.length/2]; int four = pobochna(data); int result = one + two - three+four; System.out.print(result); } public static int diagonal(int a[][]){ int result = 0; for (int i = 0; i < a.length; i++) { result+=a[i][i]; } return result; } public static int pobochna(int a[][]){ int result = 0; for (int i = a.length-1,j = 0 ; i >= 0; i--,j++) { result+=a[i][j]; } return result; } public static int seredina(int a[][]){ int result = 0; for (int i = 0; i < a.length; i++) { result+=a[a.length/2 ][i]; result+=a[i][a.length/2]; } return result; } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
3a03e02edff6307b09fd86fe1b270def
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { new Main().run(); } Scanner in; PrintWriter out; void run() { in = new Scanner(System.in); out = new PrintWriter(System.out); try { solve(); } finally { out.close(); } } class Point { int x; int y; Point(int X, int Y) { x = X; y = Y; } @Override public boolean equals(Object o) { Point p = (Point) o; return p.x == x && p.y == y; } @Override public String toString() { return "( " + x + ", " + y + " )"; } @Override public int hashCode() { return x * 31 + y; } } void solve() { int n = in.nextInt(); int[][] a = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = in.nextInt(); } } int ans = 0; int med = (n - 1) / 2; boolean[][] add = new boolean[n][n]; for (int i = 0; i < n; i++) { if (!add[med][i]) { ans += a[med][i]; add[med][i] = true; } if (!add[i][med]) { ans += a[i][med]; add[i][med] = true; } if (!add[i][i]) { ans += a[i][i]; add[i][i] = true; } if (!add[n - 1 - i][i]) { ans += a[n - i - 1][i]; add[n - 1 - i][i] = true; } } out.println(ans); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
45b67a84b2fa8e734eef9ac69b3c1ddf
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; import java.io.*; public class Codeforces { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); int n = in.nextInt(); int a[][] = new int[n+1][n+1]; for (int i = 1; i <= n; ++i) for (int j = 1; j <= n; ++j) a[i][j] = in.nextInt(); in.close(); int sum = 0; for (int i = 1; i <=n; ++i) sum += a[i][i] + a[i][n-i+1] + a[i][(n+1)/2]+a[(n+1)/2][i]; sum -= 3*a[(n+1)/2][(n+1)/2]; System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
eb0d639c30c863c269ba91fef863d74f
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.*; import java.util.*; public class A1 { public void solve() throws IOException { int n = nextInt(); int[][] a = new int[n][n]; boolean[][] ok = new boolean[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i][j] = nextInt(); for (int i = 0; i < n; i++) { ok[i][i] = true; ok[n - i - 1][i] = true; } for (int i = 0; i < n; i++) { ok[n / 2][i] = true; ok[i][n / 2] = true; } int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (ok[i][j]) sum += a[i][j]; writer.println(sum); } public static void main(String[] args) throws FileNotFoundException { new A1().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { long tbegin = System.currentTimeMillis(); reader = new BufferedReader(new InputStreamReader(System.in)); //reader = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); tokenizer = null; writer = new PrintWriter(System.out); //writer = new PrintWriter(new FileOutputStream("output.txt")); solve(); //reader.close(); //System.out.println(System.currentTimeMillis() - tbegin + "ms"); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
1629341ce4c39b8df226de267a538a99
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.StringTokenizer; public class TaskA { BufferedReader in; PrintWriter out; StringTokenizer tokenizer; Integer n, summa = 0; String[] str; LinkedHashMap<Integer, ArrayList<Integer>> map; ArrayList<Integer> list; Integer[][] a; public TaskA() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); map = new LinkedHashMap<Integer, ArrayList<Integer>>(); } public void solve() throws IOException { n = nextInt(); str = new String[n]; a = new Integer[n + 1][n + 1]; for (int i = 1; i <= n; i++) { str = in.readLine().split(" "); for (int j = 1; j <= n; j++) { a[i][j] = Integer.parseInt(str[j - 1]); } } Integer k = (n / 2) + 1; for (int i = 1; i <= n; i++) { summa += a[k][i]; a[k][i] = 0; summa += a[i][k]; a[i][k] = 0; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (j == i || i + j - 1 == n) { summa += a[i][j]; a[i][j] = 0; } } } out.println(summa); out.flush(); } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } public static void main(String[] args) throws IOException { long startTime = System.currentTimeMillis(); TaskA ob = new TaskA(); ob.solve(); System.err.printf("%.3f\n", 1e-3 * (System.currentTimeMillis() - startTime)); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
df544bf362ff74e08c6d80d788394cf9
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Vector; public class Main { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); int n=Integer.parseInt(in.readLine()); int[][] mas=new int[n][n]; for(int i=0; i<n; i++){ String[] cur=in.readLine().split(" "); for(int j=0; j<n; j++){ mas[i][j]=Integer.parseInt(cur[j]); } } int count=mas[n/2][n/2]; for(int i=0; i<n; i++){ count+=mas[i][i]; count+=mas[i][n-i-1]; } for(int i=0; i<n; i++){ count+=mas[n/2][i]; count+=mas[i][n/2]; } count-=mas[n/2][n/2]*4; out.println(count); out.close(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
27f5afdaeed866b59379fc2cb1abb624
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.awt.Point; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Start { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } public static void main(String[] args) { new Start().run(); } public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int levtIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (levtIndex < rightIndex) { if (rightIndex - levtIndex <= MAGIC_VALUE) { insertionSort(a, levtIndex, rightIndex); } else { int middleIndex = (levtIndex + rightIndex) / 2; mergeSort(a, levtIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, levtIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int levtIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - levtIndex + 1; int length2 = rightIndex - middleIndex; int[] levtArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, levtIndex, levtArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = levtIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = levtArray[i++]; } else { a[k] = levtArray[i] <= rightArray[j] ? levtArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int levtIndex, int rightIndex) { for (int i = levtIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= levtIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } class LOL { int x; int y; public LOL(int x, int k) { this.x = x; y = k; } } public void solve() throws IOException { int n = readInt(); int [][] d = new int [n][n]; boolean [][] b = new boolean [n][n]; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ d[i][j] = readInt(); } } long dioganal = 0; long pob = 0; long hori = 0; long vert = 0; for (int i = 0; i < n; i++){ dioganal += d[i][i]; b[i][i] = true; } for (int i = 0; i < n; i++){ if (b[i][n-1-i]==false){ pob += d[i][n-1-i]; b[i][n-1-i] = true; } } for (int i =0; i<n; i++){ if (b[i][n/2]==false){ hori += d[i][n/2]; b[i][n/2] = true; } } for (int i =0; i<n; i++){ if (b[n/2][i]==false){ vert += d[n/2][i]; b[n/2][i] = true; } } out.print(hori+vert+dioganal+pob); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
3a6a9955e5986535d59766604cecffa2
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class P177A { public static void main(String[] args) { Scanner inScanner = new Scanner(System.in); int n = inScanner.nextInt(); long sum = 0; int mid = (n - 1) / 2; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int x = inScanner.nextInt(); if (i == mid || j == mid || i == j || i + j == n - 1) { sum += x; } } } System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
810fe9a61665bca9581e39dccd4a289a
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.*; import java.util.*; public class A { BufferedReader in; StringTokenizer st; PrintWriter out; String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } void solve() throws Exception { int n = nextInt(); int a[][] = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i][j] = nextInt(); int m[][] = new int[n][n]; for (int i = 0; i < n; i++) m[i][i] = 1; for (int i = 0; i < n; i++) m[n / 2][i] = 1; for (int i = 0; i < n; i++) m[i][n / 2] = 1; for (int i = 0; i < n; i++) m[n - i - 1][i] = 1; long ans = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) ans += a[i][j] * m[i][j]; out.println(ans); } void run() { try { Locale.setDefault(Locale.US); boolean oj = System.getProperty("ONLINE_JUDGE") != null; Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt"); Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt"); in = new BufferedReader(reader); out = new PrintWriter(writer); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { new A().run(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
6625dcce2440f4d0fbc712ecae7eb0e1
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.awt.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; /* br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); */ public class Main { private static BufferedReader br; private static StringTokenizer st; private static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = readInt(); int[][] grid = new int[n][n]; loadArray(grid); int ret = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { boolean a = i == j; boolean b = i+j == n-1; boolean c = i == n/2; boolean d = j == n/2; if(a||b||c||d) ret += grid[i][j]; } } pw.println(ret); pw.close(); } /* NOTEBOOK CODE */ public static void loadArray(int[][] grid) throws IOException { for(int[] a: grid) loadArray(a); } public static void loadArray(int[] in) throws IOException { for(int i = 0; i < in.length; i++) in[i] = readInt(); } public static void loadArray(long[] in) throws IOException { for(int i = 0; i < in.length; i++) in[i] = readLong(); } private static long readLong() throws IOException { return Long.parseLong(nextToken()); } private static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } private static int readInt() throws IOException { return Integer.parseInt(nextToken()); } private static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { if(!br.ready()) { pw.close(); System.exit(0); } st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
4d3127241f1c434e9edf51d00d2bba47
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; import java.io.*; public class prob { static Scanner sc; static PrintWriter pw; static int[][] a; static int n; public static void main(String[] args) { sc = new Scanner(System.in); pw = new PrintWriter(System.out); try{ n = sc.nextInt(); a = new int[n][n]; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) a[i][j] = sc.nextInt(); if(n == 1) { pw.println(a[0][0]); return; } long s = 0; for(int i = 0; i < n; i++) s += a[i][i] + a[n - i - 1][i] + a[(n - 1) / 2 + (n - 1) % 2][i] + a[i][(n - 1) / 2 + (n - 1) % 2]; s -= 3 * a[(n - 1) / 2 + (n - 1) % 2][(n - 1) / 2 + (n - 1) % 2]; pw.println(s); } finally { pw.close(); } } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
c07c02c2dcc0f687b307992ba47bf7ed
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; import java.io.*; public class ProblemA { Scanner sc = new Scanner(System.in); PrintStream out = System.out; void start() { int n = sc.nextInt(); int ans = 0; int tmp; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { tmp = sc.nextInt(); if (good(i,j,n)) ans += tmp; } out.println (ans); } private boolean good(int i, int j, int n) { if (i == j) return true; if (i + j == n-1) return true; if (i == (n - 1) / 2) return true; if (j == (n-1) / 2) return true; return false; } public static void main(String[] args) { new ProblemA().start(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
b9a9711d59d37e4295c58e8c71722cdd
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][]a = new int[n+1][n+1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { a[i][j] = sc.nextInt(); } } int sum = 0; boolean[][]used = new boolean[n+1][n+1]; for (int i = 1; i <= n; i++) { if (!used[i][i]) { used[i][i] = true; sum += a[i][i]; } if (!used[i][n+1-i]) { used[i][n+1-i] = true; sum += a[i][n+1-i]; } if (!used[i][(n+1)/2]) { used[i][(n+1)/2] = true; sum += a[i][(n+1)/2]; } if (!used[(n+1)/2][i]) { used[(n+1)/2][i] = true; sum += a[(n+1)/2][i]; } } System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
73dbad96f5f1be8d6ef7e349fdf56642
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner theIn=new Scanner(System.in); int n=theIn.nextInt(); int[][] k=new int[n+1][n+1]; for (int i=1; i<=n; i++) { for (int j=1; j<=n; j++) { k[i][j]=theIn.nextInt(); } } long sum=0; for (int i=1; i<=n; i++) { sum+=k[i][i]; sum+=k[i][n+1-i]; sum+=k[i][n/2+1]; sum+=k[n/2+1][i]; } sum=sum-k[n/2+1][n/2+1]*3; System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
9985be9a12d4a11a3e4bb6c28eb88a8f
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A implements Runnable { private void Solution() throws IOException { int n = nextInt(); int[][] mas = new int[n][n]; boolean[][] used = new boolean[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mas[i][j] = nextInt(); int sum = 0; for (int i = 0; i < n; i++) { sum += mas[i][i]; used[i][i] = true; } for (int i = 0; i < n; i++) { if (!used[i][n - i - 1]) { sum += mas[i][n - i - 1]; used[i][n - i - 1] = true; } } for (int i = 0; i < n; i++) { if (!used[i][n / 2]) { sum += mas[i][n / 2]; used[i][n / 2] = true; } } for (int i = 0; i < n; i++) { if (!used[n / 2][i]) { sum += mas[n / 2][i]; used[n / 2][i] = true; } } print(sum); } public static void main(String[] args) { new A().run(); } BufferedReader in; PrintWriter out; StringTokenizer tokenizer; public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); Solution(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } void print(Object... o) { for (int i = 0; i < o.length; i++) { if (i != 0) out.print(" "); out.print(o[i]); } } void println(Object... o) { for (int i = 0; i < o.length; i++) { if (i != 0) print(" "); print(o[i]); } print("\n"); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return in.readLine(); } String next() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
2014db03f67377918abcd8465ce66abb
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] f = new int[n][n]; boolean[][] b = new boolean[n][n]; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { f[i][j] = in.nextInt(); if (i==j) { b[i][j] = true; } if ((j+i)==(n-1)) { b[i][j] = true; } if (i==((n-1)/2)) { b[i][j] = true; } if (j==((n-1)/2)) { b[i][j] = true; } } } long res = 0; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { if (b[i][j]) { res+=f[i][j]; } } } System.out.println(res); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
03d1607ba4ac7dce3fa46ff0d21a6a6e
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.HashSet; import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), mid = (n - 1) / 2; long sum = 0; HashSet<String> g = new HashSet<String>(101 * 101); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int e = sc.nextInt(); if (i == j || i == mid || j == mid || n - i - 1 == j || n - j - 1 == i) if (!g.contains(i + " " + j)) { sum += e; g.add(i + " " + j); } } } System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
fdc6bcd60298e7b88556ec160ae993d1
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class Test { public static void get(){ int n =0; Scanner s =new Scanner(System.in); n =s.nextInt(); long t =0; for (int i=0; i<n ; i++){ for (int j =0; j<n ; j++){ if (i==j|| j == n -i -1 || j == (n-1)/2 || i == (n-1)/2){ t+= s.nextInt(); } else { s.nextInt(); } // a[i][j] = } } System.out.println(t); } public static void main(String[] args) { get(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
0accf1ec6dd98391168ea049e694fdfe
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; public class A2_177 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int a[][] = new int[n][n]; boolean visited[][] = new boolean[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { a[i][j] = in.nextInt(); } } int sum = 0; //Main diagonal for(int i = 0; i < n; i++) { if(!visited[i][i]) { sum += a[i][i]; visited[i][i] = true; } } //Secondary diagonal for(int i = 0, j = n - 1; i < n; i++, j--) { if(!visited[i][j]) { sum += a[i][j]; visited[i][j] = true; } } //Middle row int midrow = n / 2; for(int j = 0; j < n; j++) { if(!visited[midrow][j]) { sum += a[midrow][j]; visited[midrow][j] = true; } } //Middle column int midcol = n / 2; for(int i = 0; i < n; i++) { if(!visited[i][midcol]) { sum += a[i][midcol]; visited[i][midcol] = true; } } System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
ec103acd75423aea299a360f80065bd2
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.IOException; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov (egor@egork.net) */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int size = in.readInt(); int[][] matrix = IOUtils.readIntTable(in, size, size); int sum = 0; for (int i = 0; i < size; i++) { sum += matrix[i][i]; sum += matrix[i][size - i - 1]; sum += matrix[size / 2][i]; sum += matrix[i][size / 2]; } sum -= 3 * matrix[size / 2][size / 2]; out.printLine(sum); } } 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 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(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 int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) { int[][] table = new int[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readIntArray(in, columnCount); return table; } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
53312e205fc2cf21c068466fddbb4a62
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; public class ABA { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int[][] array = new int[N][N]; boolean[][] B = new boolean[N][N]; long ans = 0; for(int a=0;a<N;a++){ for(int b=0;b<N;b++){ array[a][b]=sc.nextInt(); } } for(int a=0;a<N;a++){ for(int b=0;b<N;b++){ if(a==b){ if(!B[a][b]){ B[a][b]=true; ans+=array[a][b]; } } } } for(int a=0;a<N;a++){ for(int b=0;b<N;b++){ if(a==(N-1-b)){ if(!B[a][b]){ B[a][b]=true; ans+=array[a][b]; } } } } for(int a=0;a<N;a++){ //for(int b=0;b<N;b++){ int b = N/2; if(!B[a][b]){ B[a][b]=true; ans+=array[a][b]; } } for(int a=0;a<N;a++){ //for(int b=0;b<N;b++){ int b = N/2; if(!B[b][a]){ B[b][a]=true; ans+=array[b][a]; } } System.out.println(ans); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
68bfa214bdbd1230d05c652a4aa09cf5
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int[][] array = new int[n][n]; for(int i=0; i< n; ++i){ for(int j=0; j< n; ++j) { array[i][j] = stdin.nextInt(); } } long sum=0; int midl = (n-1)/2; //сСрСдина Π²Π΅Ρ€Ρ‚ΠΈΠΊΠ°Π»ΡŒ for(int j=0; j< n; ++j) { sum+=array[j][midl]; } //сСрСдина Π³ΠΎΡ€ for(int j=0; j< n; ++j) { sum+=array[midl][j]; } sum-=array[midl][midl]; for(int j=0; j< n; ++j) { sum+=array[j][j]; } sum-=array[midl][midl]; for(int j=0; j< n; ++j) { sum+=array[j][n-1-j]; } sum-=array[midl][midl]; System.out.print(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
7fef0e7ee8ca5cea99278a821e33ba98
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; public class Main { public void doIt(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int [][] array = new int[n][n]; for(int i=0; i < n; i++){ for(int j=0; j < n; j++){ array[i][j] = sc.nextInt(); } } int sum=0; int mid = (n - 1) /2; for(int i=0; i < n; i++ ){ sum += array[i][i]; sum += array[i][n - 1 - i]; sum += array[mid][i]; sum += array[i][mid]; } sum -= array[mid][mid] * 3; System.out.println(sum); } public static void main(String[] args) { Main obj = new Main(); obj.doIt(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
acce18e2d2b6ca4d0a32eb9df0160c6f
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; import static java.lang.Math.*; import static java.lang.System.out; public class Main { Scanner sc = new Scanner(System.in); public static void main(String[] args) { new Main().A(); } void A(){ int n=sc.nextInt(); int[][] a = new int[n][n]; boolean[][] b = new boolean[n][n]; for(int i=0; i<n; i++){ for(int j=0; j<n; j++) a[j][i]=sc.nextInt(); } int ans=0; for(int i=0,j=0; i<n; i++,j++){ ans+= b[j][i]? 0: a[j][i]; b[j][i]=true; } for(int i=n-1, j=0; j<n; i--,j++){ ans+= b[j][i]? 0: a[j][i]; b[j][i]=true; } int m=(n-1)/2; for(int i=0; i<n; i++){ ans+= b[m][i]? 0: a[m][i]; b[m][i]=true; } for(int i=0; i<n; i++){ ans+= b[i][m]? 0: a[i][m]; b[i][m]=true; } out.println(ans); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
913b8da40f1b950f0a67c3004b63d12c
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; public class A { Scanner sc = new Scanner(System.in); void doIt() { int n = sc.nextInt(); int ans = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { int v = sc.nextInt(); if(i == j) ans += v; else if(i + j + 1 == n) ans += v; else if(i == n/2) ans += v; else if(j == n/2) ans += v; } } System.out.println(ans); } public static void main(String[] args) { new A().doIt(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
a12c60d274fb8e10abb37713b9c1ce5a
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; import java.io.*; public class a { public static void main(String[] args) throws IOException { boolean[] sieve = new boolean[1000001]; Arrays.fill(sieve, true); sieve[0]=sieve[1]=false; for(int i = 2; i<sieve.length; i++) if(sieve[i]) for(long j = (long)i*i; j<sieve.length; j+=i) sieve[(int)j] = false; //Scanner input = new Scanner(new File("input.txt")); //PrintWriter out = new PrintWriter(new File("output.txt")); PrintWriter out = new PrintWriter(System.out); input.init(System.in); int n = input.nextInt(), res = 0; int[][] data = new int[n][n]; for(int i = 0; i<n; i++) for(int j = 0; j<n; j++) { data[i][j] = input.nextInt(); if(i == n/2 || j == n/2 || i == j || i+j == n-1) res += data[i][j]; } out.println(res); out.close(); } public static long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a%b); } public static class input { 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() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary 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 class IT { int[] left,right, val, a, b; IT(int n) { left = new int[3*n]; right = new int[3*n]; val = new int[3*n]; a = new int[3*n]; b = new int[3*n]; init(0,0, n); } int init(int at, int l, int r) { a[at] = l; b[at] = r; if(l==r) left[at] = right [at] = -1; else { int mid = (l+r)/2; left[at] = init(2*at+1,l,mid); right[at] = init(2*at+2,mid+1,r); } return at++; } //return the sum over [x,y] int get(int x, int y) { return go(x,y, 0); } int go(int x,int y, int at) { if(at==-1) return 0; if(x <= a[at] && y>= b[at]) return val[at]; if(y<a[at] || x>b[at]) return 0; return go(x, y, left[at]) + go(x, y, right[at]); } //add v to elements x through y void add(int x, int y, int v) { go3(x, y, v, 0); } void go3(int x, int y, int v, int at) { if(at==-1) return; if(y < a[at] || x > b[at]) return; val[at] += (Math.min(b[at], y) - Math.max(a[at], x) + 1)*v; go3(x, y, v, left[at]); go3(x, y, v, right[at]); } } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
8ed212f359e57ce6094c756428e30800
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class GoodElements { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long sum = 0; int mid = ((n-1)/2); int x = 0; for (int i = 0;i<n;i++) for (int j = 0;j<n;j++) { x=in.nextInt(); if ((i==j) || (i==mid) || (j==mid) || (i+j==n-1)) { sum+=x; } } System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
973f265290b71bd1e621ff2b3383f8bb
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
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.io.StreamTokenizer; public class E { static StreamTokenizer st; static PrintWriter pw; private static int nextInt() throws IOException { st.nextToken(); return (int) st.nval; } public static void main(String[] args) throws IOException { st = new StreamTokenizer(new BufferedReader(new InputStreamReader( System.in))); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter( System.out))); // -----------begin------------------------- int n = nextInt(); int a[][] = new int[n + 1][n + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { a[i][j] = nextInt(); } } int sum = 0; for (int i = 1; i <= n; i++) { sum += a[i][i]; sum += a[i][n - i + 1]; } for (int i = 1; i <= n; i++) { sum += a[i][(n + 1) / 2]; sum += a[(n + 1) / 2][i]; } pw.print(sum-3*a[(n+1)/2][(n+1)/2]); pw.close(); // ------------end-------------------------- } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
2cc2d318fb0800742104476e3939a347
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import static java.lang.System.out; import java.util.Scanner; public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner cin = new Scanner(System.in); int n = cin.nextInt(); long sum = 0; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ int num = cin.nextInt(); if (i == j || j == n - i - 1 || i == (n-1)/2 || j == (n-1)/2){ sum+=num; } } } out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
1d20620663f9e3c131f0e54b48264693
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class Prob177A1 { public static void main(String[] Args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (i == j || i == (n - 1) / 2 || j == (n - 1) / 2 || i + j == n - 1) sum += scan.nextInt(); else scan.nextInt(); System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
b18eecebf05c0b327cf0f0a923bb90b0
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.FileReader; import java.io.PrintWriter; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class Main { Scanner in; PrintWriter out; void asserT(boolean e) { if (!e) { throw new Error(); } } void solve() { int n = in.nextInt(); in.nextLine(); int ar[][] = new int[n][n]; for (int i = 0; i < ar.length; i++) { for (int j = 0; j < ar.length; j++) { ar[i][j] = in.nextInt(); } } int sum = 0; for (int i = 0; i < ar.length; i++) { sum += ar[i][i]; } for (int i = 0; i < ar.length; i++) { sum += ar[i][n - 1 - i]; } for (int i = 0; i < ar.length; i++) { sum += ar[(n - 1) / 2][i]; } for (int i = 0; i < ar.length; i++) { sum += ar[i][(n - 1) / 2]; } sum -= 3 * ar[(n - 1) / 2][(n - 1) / 2]; out.println(sum); } void run() { in = new Scanner(System.in); out = new PrintWriter(System.out); try { solve(); } finally { out.close(); } } public static void main(String[] args) { new Main().run(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
d0e494688bb652a7d2e7d5e7c8e919e4
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class ABYE{ static BufferedReader br; public static void main(String args[])throws Exception{ br=new BufferedReader(new InputStreamReader(System.in)); int n=toInt(); int b[][]=new int[n][n]; int mid=(n+1)/2-1; for(int i=0;i<n;i++){ String st[]=toStrArray(); for(int j=0;j<st.length;j++){ b[i][j]=Integer.parseInt(st[j]); } } int sum=0; for(int i=0;i<n;i++){ sum+=b[i][i]; } for(int i=0;i<n;i++){ if(i==mid)continue; sum+=b[i][n-1-i]; } for(int i=0;i<n;i++){ if(i==mid)continue; sum+=b[i][mid]; } for(int i=0;i<n;i++){ if(i==mid)continue; sum+=b[mid][i]; } System.out.println(sum); } /****************************************************************/ public static int[] toIntArray()throws Exception{ String str[]=br.readLine().split(" "); int k[]=new int[str.length]; for(int i=0;i<str.length;i++){ k[i]=Integer.parseInt(str[i]); } return k; } public static int toInt()throws Exception{ return Integer.parseInt(br.readLine()); } public static long[] toLongArray()throws Exception{ String str[]=br.readLine().split(" "); long k[]=new long[str.length]; for(int i=0;i<str.length;i++){ k[i]=Long.parseLong(str[i]); } return k; } public static long toLong()throws Exception{ return Long.parseLong(br.readLine()); } public static double[] toDoubleArray()throws Exception{ String str[]=br.readLine().split(" "); double k[]=new double[str.length]; for(int i=0;i<str.length;i++){ k[i]=Double.parseDouble(str[i]); } return k; } public static double toDouble()throws Exception{ return Double.parseDouble(br.readLine()); } public static String toStr()throws Exception{ return br.readLine(); } public static String[] toStrArray()throws Exception{ String str[]=br.readLine().split(" "); return str; } /****************************************************************/ }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
d3fc4af84c1ea84547ff31d363a3c95d
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class A177 { static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter out = new PrintWriter(System.out); static int nextInt() throws Exception { in.nextToken(); return (int)in.nval; } static String nextString() throws Exception { in.nextToken(); return in.sval; } public static void main(String[] args) throws Exception { int n = nextInt(); int ans = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { int x = nextInt(); if (i == j || i == n-1-j || i == n/2 || j == n/2) ans += x; } out.println(ans); out.flush(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
525bdf66dac3a291fc4e90c46e331bf2
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class Main { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int matrix[][] = new int[N][N]; for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ matrix[i][j] = sc.nextInt(); } } System.out.println(calc(matrix, N)); } static int calc(int[][] matrix, int N){ int value = 0; int middle = N/2; for(int i = 0; i < N; i++){ value += matrix[i][i]; } for(int i = 0; i < N; i++){ value += matrix[i][N - i - 1]; } value -= matrix[middle][middle]; for(int i = 0; i < N; i++){ value += matrix[middle][i]; } value -= matrix[middle][middle]; for(int i = 0; i < N; i++){ value += matrix[i][middle]; } value -= matrix[middle][middle]; return value; } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
79cfb3026fcde2721ac2875c8c65b82b
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.*; import java.util.*; public class Main { BufferedReader br; public void go() throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int n = Integer.parseInt(s); int[][] a = new int[n][n]; for (int i = 0; i < n; i++) { s = br.readLine(); String[] ss = s.split(" "); for (int j = 0; j < n; j++) a[i][j] = Integer.parseInt(ss[j]); } int mid = n >> 1; int ac = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (i == j || i == mid || j == mid || i == n - 1 - j) ac += a[i][j]; System.out.println(ac); } public static void main(String[] args) throws Exception { new Main().go(); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
2f41cff6f99c5b2532d46583d942fb03
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer token = new StringTokenizer(reader.readLine()); int n = Integer.parseInt(token.nextToken()); int a[][] = new int[n][n]; for (int i = 0; i < n; i++) { token = new StringTokenizer(reader.readLine()); for (int j = 0; j < n; j++) { a[i][j] = Integer.parseInt(token.nextToken()); } } int sum = 0; for (int i = 0; i < n; i++) { sum += a[i][i]; sum += a[i][n - i - 1]; sum += a[n / 2][i]; sum += a[i][n / 2]; } sum -= 3 * a[n / 2][n / 2]; System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
a0a5a06a7ecf2f4f04d224ce1cd2a1b9
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int r = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { int v = s.nextInt(); if (i == j || i == n - 1 - j || i == n / 2 || j == n / 2) { r += v; } } } System.out.println(r); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
00e9a546ec2a3c7ffd56cffde3fd6270
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.*; import java.util.*; public class ABBYY_A1 { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int rows = Integer.parseInt(br.readLine()); int sum = 0; for (int i = 0; i < rows; i++) { String[] str = br.readLine().split(" "); if (i == rows/2) { for (int j = 0; j < str.length; j++) sum += Integer.parseInt(str[j]); } else { sum += Integer.parseInt(str[i]); sum += Integer.parseInt(str[rows-i-1]); sum += Integer.parseInt(str[rows/2]); } } System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
2c7e3056c0f35cb0e4bc44a6e463b187
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; /** * */ /** * @author antonio081014 * @since Apr 21, 2012, 6:56:03 AM */ public class A { public static void main(String[] args) throws Exception { A main = new A(); main.run(); System.exit(0); } public void run() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); int[][] matrix = new int[N][N]; for (int i = 0; i < N; i++) { String[] str = br.readLine().split("\\s"); for (int j = 0; j < N; j++) { matrix[i][j] = Integer.parseInt(str[j]); } } int count = mainCol(matrix) + mainDig(matrix) + mainDig2(matrix) + mainRow(matrix); System.out.println(count - 3 * matrix[N / 2][N / 2]); } public int mainRow(int[][] matrix) { int count = 0; int N = matrix.length; for (int i = 0; i < N; i++) { count += matrix[N / 2][i]; } return count; } public int mainCol(int[][] matrix) { int count = 0; int N = matrix.length; for (int i = 0; i < N; i++) { count += matrix[i][N / 2]; } return count; } public int mainDig(int[][] matrix) { int count = 0; int N = matrix.length; for (int i = 0; i < N; i++) { count += matrix[i][i]; } return count; } public int mainDig2(int[][] matrix) { int count = 0; int N = matrix.length; for (int i = 0; i < N; i++) { count += matrix[i][N - i - 1]; } return count; } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
9895f2c777f52aa486f8462ebb327469
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); // PrintWriter out = new PrintWriter(new FileOutputStream(new File("output.txt"))); int n = in.nextInt(); int [][]data = new int[n][n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ data[i][j] = in.nextInt(); } } long total = 0; for(int i = 0; i < n; i++){ total += data[i][i]; total += data[n - i - 1][i]; total += data[i][n/2]; total += data[n/2][i]; } total -= 3*data[n/2][n/2]; out.println(total); out.close(); } static double dist(Point a, Point b) { long total = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); return Math.sqrt(total); } static class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } 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; } static class FT { int[] data; FT(int n) { data = new int[n]; } void update(int index, int val) { // System.out.println("UPDATE INDEX " + index); while (index < data.length) { data[index] += val; index += index & (-index); // System.out.println("NEXT " +index); } } int get(int index) { // System.out.println("GET INDEX " + index); int result = 0; while (index > 0) { result += data[index]; index -= index & (-index); // System.out.println("BACK " + index); } return result; } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int pow(int a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } int val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * val * a; } } // static Point intersect(Point a, Point b, Point c) { // double D = cross(a, b); // if (D != 0) { // return new Point(cross(c, b) / D, cross(a, c) / D); // } // return null; // } // // static Point convert(Point a, double angle) { // double x = a.x * cos(angle) - a.y * sin(angle); // double y = a.x * sin(angle) + a.y * cos(angle); // return new Point(x, y); // } // static Point minus(Point a, Point b) { // return new Point(a.x - b.x, a.y - b.y); // } // // static Point add(Point a, Point b) { // return new Point(a.x + b.x, a.y + b.y); // } // // static double cross(Point a, Point b) { // return a.x * b.y - a.y * b.x; // // // } // // static class Point { // // int x, y; // // Point(int x, int y) { // this.x = x; // this.y = y; // } // // @Override // public String toString() { // return "Point: " + x + " " + y; // } // } 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 FileReader(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
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
bc9a2656c038647a21684f34aa75a0a0
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { //BufferedReader c=new BufferedReader(new InputStreamReader(System.in)); Scanner c=new Scanner(System.in); int N=c.nextInt(); int A[][]=new int[N][N]; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { A[i][j]=c.nextInt(); } } long ans=0; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { if(i==j||i==(N-j-1)||(i==N/2)||(j==N/2)) ans+=A[i][j]; } } System.out.println(ans); } } //must declare new classes here
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
7cf0facf0d23f4f2dd3483716f1ffb3c
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; /* * * A1.java * Written by Andy Huang: 11:55:27 AM Apr 21, 2012 */ public class A1 { static void solve() { int n = in.nInt(); int sum = 0; for(int i = 0; i < n; i++){ for(int j =0; j < n; j++){ if (i == j || n-j-1 == i || i == n/2 || j == n/2) sum += in.nInt(); else in.nInt(); } } out.appendln(sum); } public static void main(String[] args) { in = new Input(); out = new Output(); solve(); out.print(); } static Output out; static Input in; static void pln(Object o) { System.out.println(o); } static void pf(Object o) { System.out.print(o); } } final class Input { private java.io.BufferedReader reader; private java.util.StringTokenizer tokenizer; public Input() { reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new java.util.StringTokenizer(reader.readLine()); } catch (java.io.IOException e) { throw new RuntimeException("I/O Error"); } } return tokenizer.nextToken(); } public String nLine() { try { return reader.readLine(); } catch (java.io.IOException e) { throw new RuntimeException(e); } } public long nLong() { return Long.parseLong(next()); } public int nInt() { return Integer.parseInt(next()); } public double nDouble() { return Double.parseDouble(next()); } } final class Output { public StringBuilder buffer; Output() { buffer = new StringBuilder(); } Output(int size) { buffer = new StringBuilder(size); } void print() { System.out.print(buffer.toString()); } void flush() { System.out.flush(); } <T> void append(T obj) { buffer.append(obj); } <T> void appendln(T obj) { append(obj); append('\n'); } void delete(int index) { buffer.deleteCharAt(index); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
552d04e1de1125b87d96bd9dc2580e5e
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class A1 { public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int units[][] = new int[n][n]; int sum = 0; //in.next(); for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++){ int tmp = in.nextInt(); if ((i == j) || (i == (n-j+1)) || (i == (n/2 + 1)) || (j == (n/2 + 1))) sum += tmp; } System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
98fa2ea5ee7907ee5cf6ff24946e5e02
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.*; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int [][] a = new int[n][n]; int d1=0,d2=0,r=0,c=0; int middle=0; for(int i =0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j && i!=((n-1)/2)) d1+=in.nextInt(); else if(j==((n-1)/2) && i!=((n-1)/2)) c+=in.nextInt(); else if(i==((n-1)/2) && j!=((n-1)/2)) r+=in.nextInt(); else if(j==n-1-i && i!=((n-1)/2) ) d2+=in.nextInt(); else if(i==((n-1)/2) && j==((n-1)/2)) middle=in.nextInt(); else in.nextInt(); } } System.out.println(d1+d2+c+r+middle); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output
PASSED
6a57ebffe8d76e700a2524366f31384c
train_001.jsonl
1335016800
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.
256 megabytes
import java.util.Scanner; public class CF_177A { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] val = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { val[i][j] = in.nextInt(); } } int center = (n - 1) / 2; int sum = 0; for(int i = 0; i < n; i++) { // main diagonal sum += val[i][i]; // secondary diagonal sum += val[n-i-1][i]; // center row sum += val[center][i]; // center column sum += val[i][center]; } sum -= 3 * val[center][center]; System.out.println(sum); } }
Java
["3\n1 2 3\n4 5 6\n7 8 9", "5\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1\n1 1 1 1 1"]
2 seconds
["45", "17"]
NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Java 6
standard input
[ "implementation" ]
5ebfad36e56d30c58945c5800139b880
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101
800
Print a single integer β€” the sum of good matrix elements.
standard output