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
5c52ba5c751977b536d56d9c64ca63c4
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.*; import java.math.*; import static java.lang.Math.*; import java.security.SecureRandom; import static java.util.Arrays.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import sun.misc.Regexp; import java.awt.geom.*; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import sun.net.www.content.text.plain; public class Main { static double EPS = pow(10, -9); public static void main(String[] args) throws IOException { new Main().run(); } StreamTokenizer in; PrintWriter out; //deb//////////////////////////////////////////////// public static void deb(String n, Object n1) { System.out.println(n + " is : " + n1); } public static void deb(int[] A) { for (Object oo : A) { System.out.print(oo + " "); } System.out.println(""); } public static void deb(long[] A) { for (Object oo : A) { System.out.print(oo + " "); } System.out.println(""); } public static void deb(boolean[] A) { for (Object oo : A) { System.out.print(oo + " "); } System.out.println(""); } public static void deb(double[] A) { for (Object oo : A) { System.out.print(oo + " "); } System.out.println(""); } public static void deb(String[] A) { for (Object oo : A) { System.out.print(oo + " "); } System.out.println(""); } public static void deb(int[][] A) { for (int i = 0; i < A.length; i++) { for (Object oo : A[i]) { System.out.print(oo + " "); } System.out.println(""); } } public static void deb(double[][] A) { for (int i = 0; i < A.length; i++) { for (Object oo : A[i]) { System.out.print(oo + " "); } System.out.println(""); } } public static void deb(long[][] A) { for (int i = 0; i < A.length; i++) { for (Object oo : A[i]) { System.out.print(oo + " "); } System.out.println(""); } } public static void deb(String[][] A) { for (int i = 0; i < A.length; i++) { for (Object oo : A[i]) { System.out.print(oo + " "); } System.out.println(""); } } ///////////////////////////////////////////////////////////// int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } void run() throws IOException { // in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt"))); // out = new PrintWriter(new FileWriter("output.txt")); in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); } //boolean inR(int x,int y){ //return (x<=0)&&(x<4)&&(y<=0)&&(y<4); //} @SuppressWarnings("unchecked") void solve() throws IOException { // BufferedReader re= new BufferedReader(new FileReader("C:\\Users\\ASELA\\Desktop\\PROBLEMSET\\input\\F\\10.in")); // BufferedReader re = new BufferedReader(new InputStreamReader(System.in)); // Scanner sc= new Scanner(System.in); int N=nextInt(); long[][] A=new long[N+1][N+1]; for (int i = 1; i <= N; i++) { for (int j = 1; j <=N; j++) { A[i][j]=nextInt(); } } boolean[] vis=new boolean[N+1]; int[] qq= new int[N]; for (int i = 0; i < N; i++) { qq[i]=nextInt(); } long[] ans= new long[N]; long tmp=0; for (int i = 0; i < N; i++) { int cur=qq[N-i-1]; tmp=0; vis[cur]=true; for (int j = 1; j <= N; j++) { for (int k = 1; k <=N; k++) { A[j][k]=min(A[j][k],A[j][cur]+A[cur][k]); } } for (int j = 1; j <= N; j++) { if(vis[j]) { for (int k = j+1; k <= N; k++) { if(vis[k])tmp+=(A[j][k]+A[k][j]); } } } ans[N-i-1]=tmp; } for (int i = 0; i < N; i++) { out.print(ans[i]+" "); } out.println(""); } } class node { int parent = -1; TreeSet<Integer> children = new TreeSet<Integer>(); }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
7a6fe2c5af10d5b6d7b64d4a8529b07c
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class Greg_and_Graph { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Reader r=new Reader(); int n=r.nextInt(); long dis[][]=new long[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++) dis[i][j]=r.nextLong(); } int order[]=new int[n]; long ans[]=new long[n]; for(int i=0;i<n;i++)order[i]=r.nextInt()-1; boolean used[]=new boolean[n]; for(int k=0;k<n;k++){ used[order[n-1-k]]=true; long sum=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ dis[i][j]=Math.min(dis[i][j],dis[i][order[n-1-k]]+dis[order[n-1-k]][j]); if(used[i] && used[j]) sum+=dis[i][j]; } } ans[n-1-k]=sum; } for(int i=0;i<n;i++)System.out.print(ans[i]+" "); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000]; 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
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
305a775e716c242a9b52b827d07daa95
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.util.*; import java.io.*; public class source { static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); static StreamTokenizer strt = new StreamTokenizer(bf); public static void main(String[] args) throws IOException { try { int n = nextInt(); if(n == 1) exit("0"); 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[] x = new int[n]; for(int i = 0; i < n; i++) x[i] = nextInt() - 1; boolean[] on = new boolean[n]; on[ x[n - 1] ] = true; int[][] dist = new int[n][n]; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) dist[i][j] = Integer.MAX_VALUE / 2; for(int i = 0; i < n; i++) dist[i][i] = 0; int cnt = n - 2; long answer[] = new long[n]; for(int e = n - 2; e >= 0; e--) { int add = x[e]; for(int i = 0; i < n; i++) if(on[i]) { dist[add][i] = a[add][i]; for(int j = 0; j < n; j++) if(on[j] && i != j) dist[add][i] = dist[add][i] > a[add][j] + dist[j][i] ? a[add][j] + dist[j][i] : dist[add][i] ; } for(int i = 0; i < n; i++) if(on[i]) { dist[i][add] = a[i][add]; for(int j = 0; j < n; j++) if(on[j] && i != j) dist[i][add] = dist[i][add] > dist[i][j] + a[j][add] ? dist[i][j] + a[j][add] : dist[i][add]; } for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) if(on[i] && on[j] && dist[i][j] > dist[i][add] + dist[add][j]) dist[i][j] = dist[i][add] + dist[add][j]; on[add] = true; long ans = 0; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) if(on[i] && on[j]) ans += dist[i][j]; answer[cnt] = ans; cnt--; } for(int i = 0; i < n; i++) pw.print(answer[i] + " "); } finally { pw.close(); } } static String next() throws IOException { strt.nextToken(); return strt.sval; } static int nextInt() throws IOException { strt.nextToken(); return (int) strt.nval; } static long nextLong() throws IOException { strt.nextToken(); return (long) strt.nval; } static double nextDouble() throws IOException { strt.nextToken(); return strt.nval; } static void exit(Object s) { pw.println(s.toString()); pw.close(); System.exit(0); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
f7c24f27cca7408acb9bb1b8763b768a
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
/** * Created by Alex on 10/20/2014. */ import java.io.*; import java.util.*; public class B295 { BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { new B295().run(); } final int INF = Integer.MAX_VALUE / 2; public void solve() throws IOException { int n = nextInt(); int[][] d = new int[n][n]; for (int i = 0; i < n; ++i) { Arrays.fill(d[i], INF); } for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) d[i][j] = nextInt(); int[] queries = new int[n]; for (int i = 0; i < n; ++i) queries[i] = nextInt() - 1; ArrayList<Long> ans = new ArrayList<Long>(); boolean[] checked = new boolean[n]; for (int k = n - 1; k >= 0; --k) { long sum = 0; checked[queries[k]] = true; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { d[i][j] = Math.min(d[i][j], d[i][queries[k]] + d[queries[k]][j]); if (!checked[i] || !checked[j]) continue; sum += d[i][j]; } ans.add(sum); } Collections.reverse(ans); for (long x : ans) out.print(x + " "); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
71457afbe63e40248fa039e9964f8022
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class B { static StringTokenizer st; static BufferedReader in; public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int[][]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[]x = new int[n+1]; for (int i = 1; i <= n; i++) { x[i] = nextInt(); } long[]ans = new long[n+1]; long[][]d = new long[n+1][n+1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { d[i][j] = a[i][j]; } } int[]k = new int[n+1]; int cnt = 0; for (int i = n; i >= 1; i--) { k[++cnt] = x[i]; for (int j = 1; j <= n; j++) { for (int j2 = 1; j2 <= n; j2++) { d[j][j2] = Math.min(d[j][j2], d[j][x[i]]+d[x[i]][j2]); } } for (int j = 1; j <= cnt; j++) { for (int j2 = 1; j2 <= cnt; j2++) { ans[i] += d[k[j]][k[j2]]; } } } for (int i = 1; i <= n; i++) { pw.print(ans[i]+" "); } pw.close(); } private static int nextInt() throws IOException{ return Integer.parseInt(next()); } private static long nextLong() throws IOException{ return Long.parseLong(next()); } private static double nextDouble() throws IOException{ return Double.parseDouble(next()); } private static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
53bf2c1b08ee11b5561f0242e4621737
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.util.Scanner; /** * Created with IntelliJ IDEA. * Author : Dylan * Date : 2013-07-22 * Time : 13:29 * Project : Greg and Graph */ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] graph = new int[n + 1][n + 1]; for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) graph[i][j] = in.nextInt(); int[] x = new int[n + 1]; for(int i = n; i >= 1; i--) x[i] = in.nextInt(); long[] ans = new long[n + 1]; for(int i = 1; i <= n; i++) { int k = x[i]; for(int u = 1; u <= n; u++) { for(int v = 1; v <= n; v++) { if(u == v || u == k || v == k) continue; graph[u][v] = Math.min(graph[u][v], graph[u][k] + graph[k][v]); } } for(int u = 1; u < i; u++) { for(int v = u + 1; v <= i; v++) { ans[i] += (graph[x[u]][x[v]] + graph[x[v]][x[u]]); } } } for(int i = n; i >= 1; i--) { System.out.print(ans[i] + " "); } System.out.println(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
6a0b42824786bec1309ec297704f605d
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; import java.math.BigInteger; public class Main { public static void main(String args[]) throws FileNotFoundException, IOException { //Scanner in =new Scanner(new FileReader("input.txt")); //PrintWriter out = new PrintWriter(new FileWriter("output.txt")); //Scanner in=new Scanner(System.in); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); StringTokenizer st;//=new StringTokenizer(br.readLine()); int n=ni(br.readLine()); int arr[][]=new int[n][n]; long dis[][]=new long[n][n]; for(int i=0;i<n;i++) { st=new StringTokenizer(br.readLine()); for(int j=0;j<n;j++) { arr[i][j]=ni(st.nextToken()); dis[i][j]=arr[i][j]; } } st=new StringTokenizer(br.readLine()); int no[]=new int[n]; for(int i=0;i<n;i++) no[i]=ni(st.nextToken()); String ans=""; for(int k=n-1;k>=0;k--) { long sum=0; for(int i=0;i<n;i++) for(int j=0;j<n;j++) dis[i][j]=Math.min(dis[i][j],dis[i][no[k]-1]+dis[no[k]-1][j]); for(int i=k;i<n;i++) for(int j=k;j<n;j++) sum+=dis[no[i]-1][no[j]-1]; ans=sum+" "+ans; } out.print(ans); out.close(); } private static class pair implements Comparable<pair> { int first; int second; pair() { first=0; second=0; } pair(int f,int s) { first=f; second=s; } public int compareTo(pair o) { if(first > o.first) return 1; else if(first < o.first) return -1; else { if(second < o.second ) return 1; else if(second > o.second) return -1; else return 0; } } } public static Integer ni(String s) { return Integer.parseInt(s); } public static BigInteger nb(String s) { return BigInteger.valueOf(Long.parseLong(s)); } public static Long nl(String s) { return Long.parseLong(s); } public static Double nd(String s) { return Double.parseDouble(s); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
0f2f3f8471005ffd9fdf30f651b96408
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long[][] a = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = in.nextInt(); } } int[] remove = new int[n]; for (int i = 0; i < n; i++) { remove[i] = in.nextInt() - 1; } boolean[] was = new boolean[n]; long[] result = new long[n]; for (int step = n - 1; step >= 0; step--) { was[remove[step]] = true; int k = remove[step]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = Math.min(a[i][j], a[i][k] + a[k][j]); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (was[i] && was[j]) { result[step] += a[i][j]; } } } } for (int i = 0; i < n; i++) { out.print(result[i] + " "); } } } 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()); } } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
d03d180778d82074e5c4574041ce5af7
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.util.*; public class B { private static Scanner in; public void run() { int inf = Integer.MAX_VALUE / 3; 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[] p = new int[n]; for (int i = 0; i < n; i++) { p[n - 1 - i] = in.nextInt() - 1; } int[][] b = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { b[i][j] = a[p[i]][p[j]]; } b[i][i] = inf; } long[] ans = new long[n]; for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (j == i) { continue; } a[i][j] = Math.min(b[i][j], b[i][k] + b[k][j]); if (i <= k && j <= k) { ans[k] += a[i][j]; } } a[i][i] = inf; } int[][] c = a; a = b; b = c; } for (int i = n - 1; i >= 0; i--) { System.out.print(ans[i] + " "); } } public static void main(String[] args) { Locale.setDefault(Locale.US); in = new Scanner(System.in); new B().run(); in.close(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
877ff7980191d8d32fac49db975f96ce
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static StreamTokenizer in = new StreamTokenizer(System.in); public static int ni() throws Exception {in.nextToken(); return (int)in.nval;} public static void main(String[] args) throws Exception { int n1 = ni(); int[][] adjList = new int[n1][n1]; for (int i = 0; i < n1; i++){ for (int j =0 ;j < n1; j++){ adjList[i][j] = ni(); } } int[] removeOrder = new int[n1]; for (int i = 0 ; i < n1; i++){ removeOrder[removeOrder.length -1 - i] = ni() - 1; } int[][] dp = new int[n1][n1]; int INF = (int)1e9; for (int[] e: dp){ Arrays.fill(e, INF); } for (int i = 0; i < n1; i++){ dp[i][i] = 0; } long[] ans = new long[n1]; int ansPtr = 0; boolean[] ex = new boolean[n1 + 5]; // resList.add(0); // System.out.println(Arrays.toString(removeOrder)); for (int addedNo = 0; addedNo < n1; addedNo++){ int addVertex = removeOrder[addedNo]; for (int i = 0; i < addedNo; i++){ int curFrom = removeOrder[i]; dp[curFrom][addVertex] = Math.min(dp[curFrom][addVertex], adjList[curFrom][addVertex]); dp[addVertex][curFrom] = Math.min(dp[addVertex][curFrom], adjList[addVertex][curFrom]); } for (int i = 0; i < addedNo; i++){ for (int j = 0; j < addedNo; j++){ int from = removeOrder[i]; int mid = removeOrder[j]; dp[from][addVertex] = Math.min(dp[from][addVertex], dp[from][mid] + adjList[mid][addVertex]); dp[addVertex][from] = Math.min(dp[addVertex][from], dp[mid][from] + adjList[addVertex][mid]); } } for (int i = 0; i < addedNo; i++){ for (int j = 0; j < addedNo; j++){ int from = removeOrder[i]; int to = removeOrder[j]; dp[from][to] = Math.min(dp[from][to], dp[from][addVertex] + dp[addVertex][to]); } } long totalSum = 0; for (int i = 0; i < addedNo + 1; i++){ for (int j = 0; j < addedNo + 1; j++){ int from = removeOrder[i]; int to = removeOrder[j]; totalSum += (long)dp[from][to]; } } // for (int[] e: dp){ // System.out.println(Arrays.toString(e)); // } // System.out.println(); ans[ansPtr++] = totalSum; } for (int i = 0; i < ansPtr >> 1; i++){ long temp = ans[i]; ans[i] = ans[ansPtr -1 - i]; ans[ansPtr -1 - i] = temp; } StringBuilder fin = new StringBuilder(); for (int i = 0; i < n1; i++){ fin.append(ans[i] + " "); } System.out.println(fin); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
3a190b9f0adaaaf1ed70f2c1c981a9c7
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static StreamTokenizer in = new StreamTokenizer(System.in); public static int ni() throws Exception {in.nextToken(); return (int)in.nval;} public static void main(String[] args) throws Exception { int n1 = ni(); int[][] adjList = new int[n1][n1]; for (int i = 0; i < n1; i++){ for (int j =0 ;j < n1; j++){ adjList[i][j] = ni(); } } int[] removeOrder = new int[n1]; for (int i = 0 ; i < n1; i++){ removeOrder[removeOrder.length -1 - i] = ni() - 1; } long[] ans = new long[n1]; int ansPtr = 0; // resList.add(0); // System.out.println(Arrays.toString(removeOrder)); for (int addedNo = 0; addedNo < n1; addedNo++){ int addVertex = removeOrder[addedNo]; for (int i = 0; i < n1; i++){ if (i == addVertex) continue; for (int j = 0; j < n1; j++){ if (j == addVertex) continue; adjList[i][j] = Math.min(adjList[i][j], adjList[i][addVertex] + adjList[addVertex][j]); } } long totalSum = 0; for (int i = 0; i < addedNo + 1; i++){ for (int j = 0; j < addedNo + 1; j++){ int from = removeOrder[i]; int to = removeOrder[j]; totalSum += (long)adjList[from][to]; } } // for (int[] e: dp){ // System.out.println(Arrays.toString(e)); // } // System.out.println(); ans[ansPtr++] = totalSum; } for (int i = 0; i < ansPtr >> 1; i++){ long temp = ans[i]; ans[i] = ans[ansPtr -1 - i]; ans[ansPtr -1 - i] = temp; } StringBuilder fin = new StringBuilder(); for (int i = 0; i < n1; i++){ fin.append(ans[i] + " "); } System.out.println(fin); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
2c1afdaaa3c0033bc14ff27bdb2870c1
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Niyaz Nigmatullin */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int[][] 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[] x = new int[n]; for (int i = 0; i < n; i++) { x[n - i - 1] = in.nextInt() - 1; } long[] answer = new long[n]; int[][] b = new int[n][n]; for (int[] d : b) { Arrays.fill(d, Integer.MAX_VALUE); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { b[i][j] = a[x[i]][x[j]]; } } for (int k = 0; k < n; k++) { int[] bk = b[k]; long cur = 0; for (int i = 0; i < n; i++) { int[] bi = b[i]; for (int j = 0; j < n; j++) { int val = bi[k] + bk[j]; if (val < bi[j]) { bi[j] = val; } if (i <= k && j <= k) { cur += bi[j]; } } } answer[k] = cur; } for (int i = 0; i < n; i++) { if (i > 0) out.print(' '); out.print(answer[n - i - 1]); } out.println(); } } class FastScanner extends BufferedReader { boolean isEOF; public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); if (isEOF && ret < 0) { throw new InputMismatchException(); } isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
6fd2cc32adb45f1d4cb19fc9baba4396
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static StreamTokenizer in = new StreamTokenizer(System.in); public static int ni() throws Exception {in.nextToken(); return (int)in.nval;} public static void main(String[] args) throws Exception { int n1 = ni(); int[][] adjList = new int[n1][n1]; for (int i = 0; i < n1; i++){ for (int j =0 ;j < n1; j++){ adjList[i][j] = ni(); } } int[] removeOrder = new int[n1]; for (int i = 0 ; i < n1; i++){ removeOrder[removeOrder.length -1 - i] = ni() - 1; } long[] ans = new long[n1]; int ansPtr = 0; // resList.add(0); // System.out.println(Arrays.toString(removeOrder)); for (int addedNo = 0; addedNo < n1; addedNo++){ int addVertex = removeOrder[addedNo]; for (int i = 0; i < n1; i++){ for (int j = 0; j < n1; j++){ int val = adjList[i][addVertex] + adjList[addVertex][j]; if (val < adjList[i][j]){ adjList[i][j] = val; } } } long totalSum = 0; for (int i = 0; i < addedNo + 1; i++){ int from = removeOrder[i]; for (int j = 0; j < addedNo + 1; j++){ int to = removeOrder[j]; totalSum += (long)adjList[from][to]; } } // for (int[] e: dp){ // System.out.println(Arrays.toString(e)); // } // System.out.println(); ans[n1 - 1 - (ansPtr++)] = totalSum; } StringBuilder fin = new StringBuilder(); for (int i = 0; i < n1; i++){ fin.append(ans[i] + " "); } System.out.println(fin); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
68d20ded91fc468840636e9f8055e9b3
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static StreamTokenizer in = new StreamTokenizer(System.in); public static int ni() throws Exception {in.nextToken(); return (int)in.nval;} public static void main(String[] args) throws Exception { int n1 = ni(); int[][] adjList = new int[n1][n1]; for (int i = 0; i < n1; i++){ for (int j =0 ;j < n1; j++){ adjList[i][j] = ni(); } } int[] removeOrder = new int[n1]; for (int i = 0 ; i < n1; i++){ removeOrder[removeOrder.length -1 - i] = ni() - 1; } long[] ans = new long[n1]; int ansPtr = 0; // resList.add(0); // System.out.println(Arrays.toString(removeOrder)); for (int addedNo = 0; addedNo < n1; addedNo++){ int addVertex = removeOrder[addedNo]; for (int i = 0; i < n1; i++){ for (int j = 0; j < n1; j++){ adjList[i][j] = Math.min(adjList[i][j], adjList[i][addVertex] + adjList[addVertex][j]); } } long totalSum = 0; for (int i = 0; i < addedNo + 1; i++){ int from = removeOrder[i]; for (int j = 0; j < addedNo + 1; j++){ int to = removeOrder[j]; totalSum += (long)adjList[from][to]; } } // for (int[] e: dp){ // System.out.println(Arrays.toString(e)); // } // System.out.println(); ans[ansPtr++] = totalSum; } for (int i = 0; i < ansPtr >> 1; i++){ long temp = ans[i]; ans[i] = ans[ansPtr -1 - i]; ans[ansPtr -1 - i] = temp; } StringBuilder fin = new StringBuilder(); for (int i = 0; i < n1; i++){ fin.append(ans[i] + " "); } System.out.println(fin); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
00f8cb61685fed5f2aaac6112e40e0ed
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.util.*; import java.io.*; public class Main implements Runnable { public void solve() throws IOException { 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[] x = new int[N]; for(int i = 0; i < N; i++) x[i] = nextInt() - 1; //reverse x, because we will use this asssuming, that the graph is empty initially and //then we will add node by node until we will make the complete graph int[] xx = new int[N]; for(int i = 0; i < N; i++) xx[N - 1 - i] = x[i]; //Now make the new Array representation of graph which use the node adding order int[][] b = new int[N][N]; for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) b[i][j] = a[xx[i]][xx[j]]; //now find the shortest path while adding kth node long[] ans = new long[N]; for(int k = 0; k < N; k++){ int[] bk = b[k]; long cur = 0; for(int i = 0; i < N; i++){ int[] bi = b[i]; for(int j = 0; j < N; j++){ int val = bi[k] + bk[j]; if(val < bi[j]){ bi[j] = val; } if(i <= k && j <= k) cur += bi[j]; //NOTE: here i <= k && j <= k (ie, we are calculating shortest path for sub-array) // (1, 1) then (2, 2) ..... (N, N) while building the graph. } } ans[k] = cur; } //now print the answer in reverse order for(int i = 0; i < N; i++) System.out.print(ans[N - 1 - i] + " "); System.out.println(); } //----------------------------------------------------------- public static void main(String[] args) { new Main().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); tok = null; solve(); in.close(); } catch (IOException e) { System.exit(0); } } public String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BufferedReader in; StringTokenizer tok; }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
edb5a5969e26ea9a47a68e795416b81e
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.util.*; import java.io.*; public class Codeforces { FastScanner in; PrintWriter out; public void solve() throws IOException { 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[] p = new int[n]; for (int i = 0; i < n; i++) { p[i] = in.nextInt() - 1; } int[][] dist = new int[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(dist[i], Integer.MAX_VALUE / 4); } ArrayList<Integer> inGraph = new ArrayList<Integer>(); ArrayList<Long> res = new ArrayList<Long>(); boolean[] was = new boolean[n]; for (int i = n - 1; i >= 0; i--) { int cur = p[i]; inGraph.add(cur); for (int ii = 0; ii < inGraph.size(); ii++) { int x = inGraph.get(ii); dist[cur][x] = a[cur][x]; dist[x][cur] = a[x][cur]; } for (int ii = 0; ii < inGraph.size(); ii++) { int x = inGraph.get(ii); for (int jj = 0; jj < inGraph.size(); jj++) { int y = inGraph.get(jj); if (dist[cur][x] + dist[x][y] < dist[cur][y]) { dist[cur][y] = dist[cur][x] + dist[x][y]; } if (dist[y][x] + dist[x][cur] < dist[y][cur]) { dist[y][cur] = dist[y][x] + dist[x][cur]; } } } long ans = 0; for (int ii = 0; ii < inGraph.size(); ii++) { int x = inGraph.get(ii); for (int jj = 0; jj < inGraph.size(); jj++) { int y = inGraph.get(jj); if (dist[x][y] > dist[x][cur] + dist[cur][y]) { dist[x][y] = dist[x][cur] + dist[cur][y]; } ans += dist[x][y]; } } res.add(ans); } for (int i = res.size() - 1; i >= 0; i--) { out.print(res.get(i) + " "); } } public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } boolean hasNext() { while (st == null || !st.hasMoreTokens()) { try { String s = br.readLine(); if (s == null) { return false; } st = new StringTokenizer(s); } catch (IOException e) { e.printStackTrace(); } } return true; } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] arg) { new Codeforces().run(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
64f164458c19646e38a71a07141462bc
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.util.*; import java.io.*; public class Codeforces { FastScanner in; PrintWriter out; public void solve() throws IOException { 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[] p = new int[n]; for (int i = 0; i < n; i++) { p[i] = in.nextInt() - 1; } int[][] dist = new int[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(dist[i], Integer.MAX_VALUE / 4); } ArrayList<Integer> inGraph = new ArrayList<>(); ArrayList<Long> res = new ArrayList<Long>(); boolean[] was = new boolean[n]; for (int i = n - 1; i >= 0; i--) { int cur = p[i]; inGraph.add(cur); for (int ii = 0; ii < inGraph.size(); ii++) { int x = inGraph.get(ii); dist[cur][x] = a[cur][x]; dist[x][cur] = a[x][cur]; } for (int ii = 0; ii < inGraph.size(); ii++) { int x = inGraph.get(ii); for (int jj = 0; jj < inGraph.size(); jj++) { int y = inGraph.get(jj); if (dist[cur][x] + dist[x][y] < dist[cur][y]) { dist[cur][y] = dist[cur][x] + dist[x][y]; } if (dist[y][x] + dist[x][cur] < dist[y][cur]) { dist[y][cur] = dist[y][x] + dist[x][cur]; } } } long ans = 0; for (int ii = 0; ii < inGraph.size(); ii++) { int x = inGraph.get(ii); for (int jj = 0; jj < inGraph.size(); jj++) { int y = inGraph.get(jj); if (dist[x][y] > dist[x][cur] + dist[cur][y]) { dist[x][y] = dist[x][cur] + dist[cur][y]; } ans += dist[x][y]; } } res.add(ans); } for (int i = res.size() - 1; i >= 0; i--) { out.print(res.get(i) + " "); } } public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } boolean hasNext() { while (st == null || !st.hasMoreTokens()) { try { String s = br.readLine(); if (s == null) { return false; } st = new StringTokenizer(s); } catch (IOException e) { e.printStackTrace(); } } return true; } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] arg) { new Codeforces().run(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
f86973e86c46840069ea9b036fd75dd1
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.util.*; import java.io.*; public class Codeforces { FastScanner in; PrintWriter out; public void solve() throws IOException { 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[] p = new int[n]; for (int i = 0; i < n; i++) { p[i] = in.nextInt() - 1; } int[][] dist = new int[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(dist[i], Integer.MAX_VALUE / 4); } ArrayList<Integer> inGraph = new ArrayList<Integer>(); ArrayList<Long> res = new ArrayList<Long>(); boolean[] was = new boolean[n]; for (int i = n - 1; i >= 0; i--) { int cur = p[i]; inGraph.add(cur); for (int x : inGraph) { dist[cur][x] = a[cur][x]; } for (int x : inGraph) { for (int y : inGraph) { if (dist[cur][x] + dist[x][y] < dist[cur][y]) { dist[cur][y] = dist[cur][x] + dist[x][y]; } } } for (int x : inGraph) { dist[x][cur] = a[x][cur]; } for (int x : inGraph) { for (int y : inGraph) { if (dist[y][x] + dist[x][cur] < dist[y][cur]) { dist[y][cur] = dist[y][x] + dist[x][cur]; } } } long ans = 0; for (int x : inGraph) { for (int y : inGraph) { if (x != y) { if (dist[x][y] > dist[x][cur] + dist[cur][y]) { dist[x][y] = dist[x][cur] + dist[cur][y]; } ans += dist[x][y]; } } } res.add(ans); } for (int i = res.size() - 1; i >= 0; i--) { out.print(res.get(i) + " "); } } public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } boolean hasNext() { while (st == null || !st.hasMoreTokens()) { try { String s = br.readLine(); if (s == null) { return false; } st = new StringTokenizer(s); } catch (IOException e) { e.printStackTrace(); } } return true; } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] arg) { new Codeforces().run(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
326cf1e893df0890ed7697b69df9b053
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static void main(String[]args){ ScanReader in=new ScanReader(System.in); int n=in.nextInt(),x=0,y,z; int[][]D=new int[n][n]; for(;n>x;++x) for(y=0;n>y;D[x][y++]=in.nextInt()); Deque<Integer>V=new ArrayDeque<Integer>(n); for(;0<x--;V.push(in.nextInt()-1)); boolean[]F=new boolean[n]; Deque<Long>S=new ArrayDeque<Long>(n); for(long s;!V.isEmpty();S.push(s)) for(s=0,F[z=V.pop()]=true,x=n;0<x--;) if(F[x]||z!=x) for(y=n;0<y--;s+=F[x]&&F[y]?D[x][y]:0) D[x][y]=Math.min(D[x][y],D[x][z]+D[z][y]); for(;!S.isEmpty();System.out.print(S.pop()+" ")); } } class ScanReader{ private final StreamTokenizer st; public ScanReader(Reader in){ if(null==in) throw new NullPointerException(); st=new StreamTokenizer(new BufferedReader(in)); } public ScanReader(InputStream in){ this(null!=in?new InputStreamReader(in):null); } public boolean hasNext(){ int ttype=0; try{ttype=st.nextToken();} catch(IOException e){throw new RuntimeException(e);} return StreamTokenizer.TT_EOF!=ttype; } public int nextInt(){ if(!hasNext()) throw new NoSuchElementException(); return (int)st.nval; } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
f3143bbd828a43e24bfa28b60d36942a
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static void main(String[]args){ ScanReader in=new ScanReader(System.in); int n=in.nextInt(),x=n,y,k=n; int[]V=new int[n],D[]=new int[n][n]; for(int[]E:D) for(y=0;n>y;E[y++]=in.nextInt()); for(;0<x;V[--x]=in.nextInt()-1); boolean[]F=new boolean[n]; long[]S=new long[n]; for(int e:V) for(--k,F[e]=true,x=n;0<x--;) if(F[x]||e!=x) for(y=n;0<y--;S[k]+=F[x]&&F[y]?D[x][y]:0) D[x][y]=Math.min(D[x][y],D[x][e]+D[e][y]); PrintWriter out=new PrintWriter(System.out); for(long e:S) out.print(e+" "); out.close(); } } class ScanReader{ private final StreamTokenizer st; public ScanReader(Reader in){ if(null==in) throw new NullPointerException(); st=new StreamTokenizer(new BufferedReader(in)); } public ScanReader(InputStream in){ this(null!=in?new InputStreamReader(in):null); } public boolean hasNext(){ int ttype=0; try{ttype=st.nextToken();} catch(IOException e){throw new RuntimeException(e);} return StreamTokenizer.TT_EOF!=ttype; } public int nextInt(){ if(!hasNext()) throw new NoSuchElementException(); return (int)st.nval; } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
692a011036e75d3319f8b7af9485cb9c
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.List; import java.io.IOException; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.NoSuchElementException; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov ([email protected]) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int count = in.readInt(); int[][] distance = IOUtils.readIntTable(in, count, count); int[] order = IOUtils.readIntArray(in, count); MiscUtils.decreaseByOne(order); boolean[] present = new boolean[count]; long[] answer = new long[count]; for (int ii = count - 1; ii >= 0; ii--) { int i = order[ii]; for (int j = 0; j < count; j++) { if (present[j]) { for (int k = 0; k < count; k++) { if (present[k]) { distance[i][j] = Math.min(distance[i][j], distance[i][k] + distance[k][j]); distance[j][i] = Math.min(distance[j][i], distance[j][k] + distance[k][i]); } } answer[ii] += distance[i][j] + distance[j][i]; } } for (int j = 0; j < count; j++) { if (present[j]) { for (int k = 0; k < count; k++) { if (present[k]) { answer[ii] += distance[j][k] = Math.min(distance[j][k], distance[j][i] + distance[i][k]); } } } } present[i] = true; } out.printLine(answer); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(long[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) writer.print(' '); writer.print(array[i]); } } public void printLine(long[] array) { print(array); 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; } } class MiscUtils { public static void decreaseByOne(int[]...arrays) { for (int[] array : arrays) { for (int i = 0; i < array.length; i++) array[i]--; } } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
30a914b91e94da34512563c499c5ec35
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.util.*; public class Problem295B { public static void main (String [] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long[][] matrix = new long[n+1][n+1]; int[] r = new int[n+1]; for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) matrix[i][j] = in.nextInt(); for(int i=1; i<=n; i++) r[i] = in.nextInt(); String answer = ""; for(int k=n; k>=1; k--) { long sum=0; for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) matrix[i][j] = Math.min(matrix[i][j], matrix[i][r[k]]+matrix[r[k]][j]); for(int i=k; i<=n; i++) for(int j=k; j<=n; j++) sum+=matrix[r[i]][r[j]]; answer = sum+" "+answer; } System.out.println(answer); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
c47f0cbda1331316034ef108a552a364
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Pavel Chuprikov */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); long[][] oa = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { oa[i][j] = in.nextInt(); } } long[][] dp = new long[n][n]; for (long[] l : dp) { Arrays.fill(l, Long.MAX_VALUE); } int[] vs = new int[n]; for (int i = 0; i < n; i++) { vs[i] = in.nextInt() - 1; } long[][]a = new long[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { a[i][j] = oa[vs[i]][vs[j]]; } long[] res = new long[n]; for (int i = n - 1; i >= 0; i--) { dp[i][i] = 0; for (int j = i + 1; j < n; j++) { for (int k = i + 1; k < n; k++) { if (dp[k][j] != Long.MAX_VALUE) dp[i][j] = Math.min(a[i][k] + dp[k][j], dp[i][j]); } for (int k = i + 1; k < n; k++) { if (dp[j][k] != Long.MAX_VALUE) dp[j][i] = Math.min(dp[j][k] + a[k][i], dp[j][i]); } } for (int j = i; j < n; j++) { for (int k = i; k < n; k++) { if (dp[j][i] != Long.MAX_VALUE && dp[i][k] != Long.MAX_VALUE) dp[j][k] = Math.min(dp[j][k], dp[j][i] + dp[i][k]); } } long sum = 0; for (int j = i; j < n; j++) { for (int k = i; k < n; k++) { if (dp[j][k] != Long.MAX_VALUE) sum += dp[j][k]; } } res[i] = sum; } for (long l : res) { out.print(l + " "); } out.println(); } } class FastScanner { private BufferedReader br; private StringTokenizer st; public FastScanner(InputStream in) { this.br = new BufferedReader(new InputStreamReader(in)); } public boolean hasNext() { try { while (st == null || !st.hasMoreTokens()) { final String nextLine = br.readLine(); if (nextLine == null) { return false; } else { st = new StringTokenizer(nextLine); } } } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return true; } public String next() { return hasNext() ? st.nextToken() : null; } public int nextInt() { return Integer.parseInt(next()); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
a2f201e03da8ccdd404714ac053fb42a
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; public class CFFF { static PrintWriter out; static final int oo = 987654321; public static void main(String[] args) { MScanner sc = new MScanner(); out = new PrintWriter(System.out); int N = sc.nextInt(); int[][] E = sc.nextInt(N, N); long[] sum = new long[N]; int[] order = sc.nextInt(N); for(int a=0;a<N;a++)order[a]--; for (int q = N - 1; q >= 0; q--) { for (int j = 0; j < N; j++) for (int k = 0; k < N; k++) E[order[j]][order[k]] = Math.min(E[order[j]][order[k]], E[order[j]][order[q]] + E[order[q]][order[k]]); for (int a = q; a < N; a++) for (int b = q; b < N; b++) sum[q] += E[order[a]][order[b]]; } for (int a = 0; a < N; a++) out.print(sum[a] + " "); out.close(); } static class MScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public MScanner() { stream = System.in; // stream = new FileInputStream(new File("dec.in")); } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } int nextInt() { return Integer.parseInt(next()); } int[] nextInt(int N) { int[] ret = new int[N]; for (int a = 0; a < N; a++) ret[a] = nextInt(); return ret; } int[][] nextInt(int N, int M) { int[][] ret = new int[N][M]; for (int a = 0; a < N; a++) ret[a] = nextInt(M); return ret; } long nextLong() { return Long.parseLong(next()); } long[] nextLong(int N) { long[] ret = new long[N]; for (int a = 0; a < N; a++) ret[a] = nextLong(); return ret; } double nextDouble() { return Double.parseDouble(next()); } double[] nextDouble(int N) { double[] ret = new double[N]; for (int a = 0; a < N; a++) ret[a] = nextDouble(); return ret; } String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } String[] next(int N) { String[] ret = new String[N]; for (int a = 0; a < N; a++) ret[a] = next(); return ret; } String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } String[] nextLine(int N) { String[] ret = new String[N]; for (int a = 0; a < N; a++) ret[a] = nextLine(); return ret; } } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
f95fc1c755b39043f23681c67a59579b
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
/* ID: nikchee1 PROB: Greg and Graph LANG: JAVA */ import java.io.*; import java.util.*; public class Main { static Scanner in = new Scanner(System.in); static int N = in.nextInt(); static long[][] D = new long[N + 1][N + 1]; static int[] remove = new int[N + 1]; static long[] ans = new long[N]; public static void main (String [] args) { for(int i=1; i <= N; i++) for(int j = 1; j <= N; j++) D[i][j] = in.nextInt(); for(int i=1; i <= N; i++) remove[i] = in.nextInt(); long sum = 0; for(int rep = N; rep >= 1; rep--) { sum = 0; int cr = remove[rep]; for(int i = 1; i <= N; i++){ for(int j = 1; j <= N; j++){ long cd = D[i][cr] + D[cr][j]; if(D[i][j] > cd){ D[i][j] = cd; } } } for(int i = rep; i <= N; i++){ for(int j = rep; j <= N; j++) { sum += D[ remove[i] ][ remove[j] ]; } } ans[rep - 1] = sum; } for(int i = 0; i < N; i++){ System.out.print(ans[i] + " "); } System.out.println(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
7ab0db37cae2dd9285e11b8f9ac9a2f6
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class sol { private static BufferedReader in; private static StringTokenizer tok; private static PrintWriter out; private static String readString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } private static int readInt() throws IOException { return Integer.parseInt(readString()); } private static long readLong() throws IOException { return Long.parseLong(readString()); } static ArrayList<Integer>[] graph; static boolean[] vis; static void dfs(int x){ vis[x]=true; for (int y:graph[x]){ if (!vis[y]) { dfs(y); } } } public static void Solve() throws IOException{ int n=readInt(); int[][] a=new int[n][n]; for (int i=0;i<n;i++){ for (int j=0;j<n;j++){ a[i][j]=readInt(); } } int[] b=new int[n]; for (int i=0;i<n;i++){ b[i]=readInt()-1; } int[][] c=new int[n][n]; for (int i=0;i<n;i++){ Arrays.fill(c[i], Integer.MAX_VALUE); } vis=new boolean[n]; long[] res=new long[n]; for (int l=n-1;l>=0;l--){ for (int i=0;i<n;i++){ if (vis[i]){ for (int j=0;j<n;j++){ if (vis[j]){ a[b[l]][i]=Math.min(a[b[l]][i],a[b[l]][j]+a[j][i]); a[i][b[l]]=Math.min(a[i][b[l]],a[i][j]+a[j][b[l]]); } } res[l]+=(long)a[b[l]][i]+a[i][b[l]]; } } for (int i=0;i<n;i++){ if (vis[i]){ for (int j=0;j<n;j++){ if (vis[j]){ a[i][j]=Math.min(a[i][j], a[i][b[l]]+a[b[l]][j]); res[l]+=(long)a[i][j]; } } } } vis[b[l]]=true; } for (int i=0;i<n;i++){ out.print(res[i]+" "); } } public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); Solve(); in.close(); out.close(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
18129e3960f861732573fdc8a562bcd7
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Locale; import java.io.OutputStream; import java.util.RandomAccess; import java.io.PrintWriter; import java.util.AbstractList; import java.io.Writer; import java.util.List; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.InputMismatchException; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Jacob Jiang */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); long[][] dis = in.next2DLongArray(n, n); int[] x = in.nextIntArray(n); ArrayUtils.decreaseByOne(x); ArrayUtils.reverse(x); long[] answer = new long[n]; int index = n - 1; boolean[] visited = new boolean[n]; for (int k : x) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dis[i][j] = Math.min(dis[i][j], dis[i][k] + dis[k][j]); } } visited[k] = true; long result = 0; for (int i = 0; i < n; i++) { if (visited[i]) { for (int j = 0; j < n; j++) { if (visited[j]) { result += dis[i][j]; } } } } answer[index--] = result; } out.printLine(answer); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int count) { int[] result = new int[count]; for (int i = 0; i < count; i++) { result[i] = nextInt(); } return result; } public long[] nextLongArray(int count) { long[] result = new long[count]; for (int i = 0; i < count; i++) { result[i] = nextLong(); } return result; } public long[][] next2DLongArray(int n, int m) { long[][] result = new long[n][]; for (int i = 0; i < n; i++) { result[i] = nextLongArray(m); } return result; } } class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(long l) { writer.print(l); } public void println() { writer.println(); } public void print(char c) { writer.print(c); } public void close() { writer.close(); } public void printItems(long[] items) { for (int i = 0; i < items.length; i++) { if (i != 0) { print(' '); } print(items[i]); } } public void printLine(long[] items) { printItems(items); println(); } } class ArrayUtils { public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { for (int i = 0; i < array.length; i++) { array[i]--; } } } public static int[] reverse(int[] array) { int a = 0, b = array.length - 1; while (a < b) { int temp = array[a]; array[a] = array[b]; array[b] = temp; a++; b--; } return array; } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
59d52e8ce122fcd8021adf93ffaa6d2c
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.*; import java.util.*; public class B { void solve() throws IOException { int n = nextInt(); long[][] d = new long[n][n]; long[][] a = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = nextLong(); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { d[i][j] = Long.MAX_VALUE / 3; } } int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = nextInt() - 1; } long[] res = new long[n]; boolean[] was = new boolean[n]; for (int i = n - 1; i >= 0; i--) { was[x[i]] = true; int v = x[i]; d[v][v] = 0; for (int to = i + 1; to < n; to++) { for (int beg = i + 1; beg < n; beg++) { if (d[v][x[to]] > d[x[beg]][x[to]] + a[v][x[beg]]) { d[v][x[to]] = d[x[beg]][x[to]] + a[v][x[beg]]; } } } for (int from = i + 1; from < n; from++) { for (int last = i + 1; last < n; last++) { if (d[x[from]][v] > d[x[from]][x[last]] + a[x[last]][v]) { d[x[from]][v] = d[x[from]][x[last]] + a[x[last]][v]; } } } res[i] = 0; for (int j = i; j < n; j++) { for (int k = i; k < n; k++) { if (j != k) { d[x[j]][x[k]] = Math.min(d[x[j]][x[k]], d[x[j]][x[i]] + d[x[i]][x[k]]); res[i] += d[x[j]][x[k]]; } } } } for (int i = 0; i < n - 1; i++) { out.print(res[i] + " "); } out.println(res[n - 1]); } void run() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new B().run(); } BufferedReader br; PrintWriter out; StringTokenizer str; String next() throws IOException { while (str == null || !str.hasMoreTokens()) { str = new StringTokenizer(br.readLine()); } return str.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
1544427e0d39dfbbde66baa62311b295
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class GregAndGraph { private static int n,INF=100000000; private static int adjMatrix[][] = new int[501][501]; private static int removedNode[] = new int[501]; public static void main(String[] args) { BufferedTokenizer io = new BufferedTokenizer(System.in); n = io.nextInt(); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) adjMatrix[i][j] = io.nextInt(); for (int i = 0; i < n; i++) removedNode[i] = io.nextInt()-1; long sum; String result = ""; for (int k = n-1; k >= 0 ; k--) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { adjMatrix[i][j] = Math.min(adjMatrix[i][j], adjMatrix[i][removedNode[k]]+adjMatrix[removedNode[k]][j]); } } sum=0; for (int i = k; i < n; i++) { for (int j = k; j < n; j++) sum+=adjMatrix[ removedNode[i] ][ removedNode[j] ]; } result = sum+" "+result; } io.println(result.substring(0,result.length()-1)); } public static class BufferedTokenizer { private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter writer; public BufferedTokenizer(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); writer = new PrintWriter(System.out); 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 void println(String x) { writer.println(x); writer.flush(); } public void print(String x) { writer.print(x); writer.flush(); } } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
ab50a0a02aa8f4b39ee6136393391d4f
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { static int n; public static void main(String[] args)throws Exception{ BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); n=Integer.parseInt(br.readLine()); long[][] dist=new long[n+5][n+5]; String[] in; for(int i=1;i<=n;i++){ in=br.readLine().split(" "); for(int j=1;j<=n;j++) dist[i][j]=Integer.parseInt(in[j-1]); } int[] removed=new int[n+5]; in=br.readLine().split(" "); for(int i=0;i<n;i++) removed[i]=Integer.parseInt(in[i]); long[] answer=new long[n+5]; boolean[] taken=new boolean[n+5]; int counter=0; for(int k=1;k<=n;k++){ long sum=0; taken[removed[n-k]]=true; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ dist[i][j]=Math.min(dist[i][j], dist[i][removed[n-k]]+dist[removed[n-k]][j]); if(taken[i] && taken[j]){ sum+=dist[i][j]; } } } answer[counter++]=sum; } for(int i=n-1;i>0;i--) System.out.print(answer[i]+" "); System.out.println(answer[0]); br.close(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
d01abba649b45363ad6887a551569665
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) { OutputStream outputStream = System.out; InputStream inputStream = System.in; InputFast in = new InputFast(); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); // int testNumber = in.nextInt(); // for (int i = 1; i <= testNumber; i++) { solver.solve(1, in, out); // } out.close(); } } class Task { final int MOD = 1000 * 1000 * 1000 + 7; public void solve(int testNumber, InputFast in, PrintWriter out) { int n = in.nextInt(); long[][] c = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { c[i][j] = in.nextLong(); } } int[] v = new int[n]; for (int i = 0; i < n; i++) { v[i] = in.nextInt() - 1; } long[] res = new long[n]; boolean[] vis = new boolean[n]; for (int k = n - 1; k >= 0; k--) { int dv = v[k]; vis[dv] = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { c[i][j] = Math.min(c[i][j], c[i][dv] + c[dv][j]); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (vis[i] && vis[j]) res[k] += c[i][j]; } } } for (int i = 0; i < n; i++) { out.print(res[i] + " "); } out.println(); } } class InputFast { static InputStream is = System.in; static private byte[] buffer = new byte[1024]; static private int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return buffer[ptrbuf++]; } private boolean isSpace(int c) { return !(c >= 33 && c <= 126); } private int read() { int b; while ((b = readByte()) != -1 && isSpace(b)) ; return b; } public double nextDouble() { return Double.parseDouble(next()); } public char nextChar() { return (char) read(); } public String next() { int b = read(); StringBuilder sb = new StringBuilder(); while (!(isSpace(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public char[] next(int n) { char[] buf = new char[n]; int b = read(), p = 0; while (p < n && !(isSpace(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } public int nextInt() { 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(); } } public long nextLong() { 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(); } } } class Input { public BufferedReader reader; public StringTokenizer tokenizer; public Input(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; 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 String nextLine() { String s = ""; try { s = reader.readLine(); } catch (IOException e) { try { throw new IOException(); } catch (IOException e1) { e1.printStackTrace(); } } return s; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
b7cbc06dbb32552af8aa54b4699a2b48
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Niyaz Nigmatullin */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int[][] 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[] x = new int[n]; for (int i = 0; i < n; i++) { x[n - i - 1] = in.nextInt() - 1; } long[] answer = new long[n]; int[][] b = new int[n][n]; for (int[] d : b) { Arrays.fill(d, Integer.MAX_VALUE); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { b[i][j] = a[x[i]][x[j]]; } } for (int k = 0; k < n; k++) { int[] bk = b[k]; long cur = 0; for (int i = 0; i < n; i++) { int[] bi = b[i]; for (int j = 0; j < n; j++) { int val = bi[k] + bk[j]; if (val < bi[j]) { bi[j] = val; } if (i <= k && j <= k) { cur += bi[j]; } } } answer[k] = cur; } for (int i = 0; i < n; i++) { if (i > 0) out.print(' '); out.print(answer[n - i - 1]); } out.println(); } } class FastScanner extends BufferedReader { boolean isEOF; public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); if (isEOF && ret < 0) { throw new InputMismatchException(); } isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
4744944246cef31408610b20ab803285
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
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.Arrays; import java.util.List; public class Main { public static BufferedReader in; public static PrintWriter out; public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); boolean showLineError = true; if (showLineError) { solve(); out.close(); } else { try { solve(); } catch (Exception e) { } finally { out.close(); } } } static void debug(Object... os) { out.println(Arrays.deepToString(os)); } private static void solve() throws IOException { int n = Integer.parseInt(in.readLine()); long[][] g = new long[n][n]; for (int i = 0; i < n; i++) { String[] line = in.readLine().split(" "); for (int j = 0; j < n; j++) g[i][j] = Integer.parseInt(line[j]); } String[] line = in.readLine().split(" "); List<Integer> seq = new ArrayList<Integer>(); for (int i = 0; i < n; i++) seq.add(Integer.valueOf(line[i])-1); List<Integer> seen2 = new ArrayList<Integer>(); List<String> ret = new ArrayList<String>(); while (!seq.isEmpty()) { int last = seq.remove(seq.size() - 1); int[] seen = transform(seen2); for (int i : seen) for (int k : seen) g[i][last] = (g[i][last]<g[i][k] + g[k][last]?g[i][last]: g[i][k] + g[k][last]); for (int i : seen) for (int k : seen) g[last][i] = (g[last][i]<g[k][i] + g[last][k]? g[last][i]: g[k][i] + g[last][k]); for(int i : seen) for(int j : seen) g[i][j]=(g[i][j]<g[i][last]+g[last][j]?g[i][j]: g[i][last]+g[last][j]); seen2.add(last); seen = transform(seen2); long show=0; for(int i : seen) for(int j : seen) show+=g[i][j]; if(seen2.size()==1){ ret.add(""+show); }else{ ret.add(show+" "); } } for(int i =ret.size()-1;i>=0;i--) out.print(ret.get(i)); out.println(); } private static int[] transform(List<Integer> lista) { int n = lista.size(); int[] ret = new int[n]; for(int i =0;i<n;i++) ret[i]=lista.get(i); return ret; } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
3ed40b315c0c687d56e6f63b29d2083e
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.*; import java.util.*; public class Pr295B { public static void main(String[] args) throws IOException { new Pr295B().run(); } BufferedReader in; PrintWriter out; StringTokenizer st; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out, true); solve(); out.flush(); } final long inf = Long.MAX_VALUE; void solve() throws IOException { int n = nextInt(); long[][] d = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { d[i][j] = nextLong(); } } int[] a = new int[n]; int[] oa = new int[n]; for (int ik = 0; ik < n; ik++) { a[n - ik - 1] = nextInt() - 1; oa[a[n - ik - 1]] = n - ik - 1; } long[] ans = new long[n]; for (int ik = 0; ik < n; ik++) { int k = a[ik]; long ans1 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { d[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]); if (oa[i] <= ik && oa[j] <= ik) { ans[n - ik - 1] += d[i][j]; } } } } for (int i = 0; i < n; i++) { out.print(ans[i] + " "); } } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
5545f8f3c7763d70cabe26344cd1b70b
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class B implements Runnable { static BufferedReader in; static PrintWriter out; static StringTokenizer st; static Random rnd; final int inf = Integer.MAX_VALUE; class Edge implements Comparable<Edge> { int u, v, d; public Edge(int u, int v, int d) { this.u = u; this.v = v; this.d = d; } public int compareTo(Edge o) { return Integer.compare(d, o.d); } } void solve() throws IOException { int n = nextInt(); int[][] g = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) g[i][j] = nextInt(); int[][] d = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { d[i][j] = (i == j) ? 0 : inf; } } int[] order = new int[n], leftOrder = new int[n], rightOrder = new int[n]; for (int i = 0; i < n; i++) order[i] = nextInt() - 1; long[] reses = new long[n]; Edge[] inEdges = new Edge[n], outEdges = new Edge[n]; for (int it = n - 1; it >= 0; it--) { int k = order[it]; for (int i = 0; i < n; i++) inEdges[i] = new Edge(i, k, g[i][k]); for (int i = 0; i < n; i++) outEdges[i] = new Edge(k, i, g[k][i]); Arrays.sort(inEdges); Arrays.sort(outEdges); int ptr = 0; for (Edge edge : inEdges) { int u = edge.u, v = edge.v; d[u][v] = Math.min(d[u][v], edge.d); leftOrder[ptr++] = u; } ptr = 0; for (Edge edge : outEdges) { int u = edge.u, v = edge.v; d[u][v] = Math.min(d[u][v], edge.d); rightOrder[ptr++] = v; } for (int l = 0; l < n; l++) { for (int r = 0; r < n; r++) { int u = leftOrder[l], v = rightOrder[r]; d[u][v] = Math.min(d[u][v], d[u][k] + d[k][v]); } } reses[it] = getRes(it, n - 1, order, d); } for (int i = 0; i < n; i++) { out.print(reses[i]); out.print((i + 1) == n ? "\n" : " "); } } private long getRes(int l, int r, int[] order, int[][] d) { long res = 0; for (int i = l; i <= r; i++) for (int j = l; j <= r; j++) res += d[order[i]][order[j]]; return res; } public static void main(String[] args) { new B().run(); } public void run() { try { final String className = this.getClass().getName().toLowerCase(); try { in = new BufferedReader(new FileReader(className + ".in")); out = new PrintWriter(new FileWriter(className + ".out")); // in = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter(new FileWriter("output.txt")); } catch (FileNotFoundException e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } rnd = new Random(); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(42); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
bcdc59da62430c4539dad8d1cdd3ce44
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class GregAndGraph { public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); int n = in.nextInt(); int[][] mat = new int[n][n]; long sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { mat[i][j] = in.nextInt(); } int[] order = new int[n]; for (int i = 0; i < order.length; i++) order[i] = in.nextInt() - 1; int k; StringBuilder out = new StringBuilder(); int t; boolean[] deleted = new boolean[n]; Arrays.fill(deleted, true); long[] result = new long[n]; for (int x = 0; x < n; x++) { sum = 0; k = order[n - 1 - x]; deleted[k] = false; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { t = mat[i][k] + mat[k][j]; if (mat[i][j] > t) mat[i][j] = t; else t = mat[i][j]; if (!deleted[i] && !deleted[j]) sum += t; } result[n - 1 - x] = sum; } for(int i = 0;i<result.length;i++)out.append(result[i]+" "); System.out.println(new String(out)); } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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()); } } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
c1d8ca434bf44fdd25040b17b70f2e31
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.*; import java.util.*; public class B295 { BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { new B295().run(); } public void solve() throws IOException { int n = nextInt(); long[][] am = new long[n][n]; long[][] d = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { am[i][j] = nextInt(); d[i][j] = Long.MAX_VALUE / 2; } } int[] del = new int[n]; for (int i = 0; i < n; i++) { del[n - 1 - i] = nextInt() - 1; } long[] res = new long[n]; boolean[] added = new boolean[n]; for (int k = 0; k < n; k++) { int newv = del[k]; added[newv] = true; long sum = 0; for (int i = 0; i < n; i++) { d[newv][i] = Math.min(d[newv][i], am[newv][i]); d[i][newv] = Math.min(d[i][newv], am[i][newv]); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { d[i][j] = Math.min(d[i][j], d[i][newv] + d[newv][j]); if (added[i] && added[j]) { sum += d[i][j]; } } } res[n - 1 - k] = sum; } for (int i = 0; i < n; i++) { out.print(res[i] + " "); } } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
5ee78560be04491a7fa746ff29aa65e2
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class C20 { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); long[][] a = new long[n][n]; int[] x = new int[n]; StringTokenizer st; for (int i = 0; i < n; i++) { st = new StringTokenizer(in.readLine()); for (int j = 0; j < n; j++) { a[i][j] = Integer.parseInt(st.nextToken()); } } st = new StringTokenizer(in.readLine()); for (int i = 0; i < n; i++) { x[i] = Integer.parseInt(st.nextToken()) - 1; } boolean[] used = new boolean[n]; long[] ans = new long[n]; for (int k = 0; k < n; k++) { long sum = 0; used[x[n - 1 - k]] = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = Math.min(a[i][j], a[i][x[n - 1 - k]] + a[x[n - 1 - k]][j]); if (used[i] && used[j]) { sum += a[i][j]; } } } ans[n - 1 - k] = sum; } for (int i = 0; i < n; i++) { System.out.println(ans[i]); } in.close(); } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
a0f5fcb11169713116d75dfad3cc8e3f
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { public static void main(String[] args) throws Exception { int nodeCnt = nextInt(); long[][] graph = new long[nodeCnt][nodeCnt]; for (int i = 0; i < nodeCnt; i++) { for (int j = 0; j < nodeCnt; j++) { graph[i][j] = nextInt(); } } int[] removed = new int[nodeCnt]; int[] removalOrder = new int[nodeCnt]; for (int i = 0; i < nodeCnt; i++) { removed[i] = nextInt() - 1; removalOrder[removed[i]] = i; } PrintWriter out = new PrintWriter(System.out); long[] print = new long[nodeCnt]; for (int _ = nodeCnt - 1; _ >= 0; _--) { int i = removed[_]; long res = 0; for (int j = 0; j < nodeCnt; j++) { for (int k = 0; k < nodeCnt; k++) { graph[j][k] = Math.min(graph[j][k], graph[j][i] + graph[i][k]); if (!(removalOrder[j] < _ || removalOrder[k] < _)) res += graph[j][k]; } } print[_] = res; } for (int i = 0; i < nodeCnt; i++) { out.print(print[i] + " "); } out.println(); out.flush(); } static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer st = new StringTokenizer(""); static int nextInt() throws Exception { return Integer.parseInt(next()); } static String next() throws Exception { while (true) { if (st.hasMoreTokens()) { return st.nextToken(); } String s = br.readLine(); if (s == null) { return null; } st = new StringTokenizer(s); } } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
686d9a0df7a481cd06df4eefda2e785b
train_001.jsonl
1365694200
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.
256 megabytes
import static java.lang.Math.*; import static java.util.Arrays.*; import java.util.*; import java.io.*; public class Main { void solve() { int n = sc.nextInt(); int[][] a = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i][j] = sc.nextInt(); int[] x = new int[n]; for (int i = 0; i < n; i++) x[i] = sc.nextInt() - 1; int inf = 1001001001; int[][] g = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) g[i][j] = inf; for (int i = 0; i < n; i++) g[i][i] = 0; boolean[] on = new boolean[n]; long[] res = new long[n]; for (int k = n-1; k >= 0; k--) { on[x[k]] = true; for (int i = 0; i < n; i++) g[x[k]][i] = min(g[x[k]][i], a[x[k]][i]); for (int i = 0; i < n; i++) g[i][x[k]] = min(g[i][x[k]], a[i][x[k]]); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { g[i][j] = min(g[i][j], g[i][x[k]] + g[x[k]][j]); } long ans = 0; for (int i = 0; i < n; i++) if (on[i]) { for (int j = 0; j < n; j++) if (on[j]) { ans += g[i][j]; } } res[k] = ans; } out.print(res[0]); for (int i = 1; i < n; i++) { out.print(" " + res[i]); } out.println(""); } public static void main(String[] args) throws Exception { Class<?> here = new Object(){}.getClass().getEnclosingClass(); try { String packageName = here.getPackage().getName(); packageName = "src/" + packageName.replaceAll("\\.", "/") + "/"; System.setIn(new FileInputStream(packageName + "input.txt")); // System.setOut(new PrintStream(new FileOutputStream(packageName + "output.txt"))); } catch (FileNotFoundException e) { } catch (NullPointerException e) { } Object o = Class.forName(here.getName()).newInstance(); o.getClass().getMethod("run").invoke(o); } static void tr(Object... os) { System.err.println(deepToString(os)); } MyScanner sc = null; PrintWriter out = null; public void run() throws Exception { sc = new MyScanner(System.in); out = new PrintWriter(System.out); for (;sc.hasNext();) { solve(); out.flush(); } out.close(); } void print(int[] a) { out.print(a[0]); for (int i = 1; i < a.length; i++) out.print(" " + a[i]); out.println(); } class MyScanner { String line; BufferedReader reader; StringTokenizer tokenizer; public MyScanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public void eat() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { line = reader.readLine(); if (line == null) { tokenizer = null; return; } tokenizer = new StringTokenizer(line); } catch (IOException e) { throw new RuntimeException(e); } } } public String next() { eat(); return tokenizer.nextToken(); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public boolean hasNext() { eat(); return (tokenizer != null && tokenizer.hasMoreElements()); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } } }
Java
["1\n0\n1", "2\n0 5\n4 0\n1 2", "4\n0 3 1 1\n6 0 400 1\n2 4 0 1\n1 1 1 0\n4 1 2 3"]
3 seconds
["0", "9 0", "17 23 404 0"]
null
Java 7
standard input
[ "dp", "graphs", "shortest paths" ]
46920a192a8f5fca0f2aad665ba2c22d
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
1,700
Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
standard output
PASSED
3d422068b04df6ed66a77b3f421affcf
train_001.jsonl
1330804800
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?
256 megabytes
import java.util.Scanner; public class Main{ public static void main(String[] args) { int n=0,a1=0,a2=0,a3=0,a4=0,count=0; Scanner sc=new Scanner(System.in); n=sc.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++){ a[i]=sc.nextInt(); if(a[i]%4==0) a4++; else if(a[i]%3==0) a3++; else if(a[i]%2==0) a2++; else a1++; } // System.out.println(" 1 ="+a1+"\n2 = "+a2+"\n 3 = "+a3+ "\n 4 = "+a4); if(a2%2==0){ count=count+a2/2; a2=0; } else{ count=count+a2/2; a2=a2%2; } if(a3-a1>=0) { a1=0; count=count+a3; } else{ a1=a1-a3; count=count+a3; } if(a2-a1>=0) { a1=0; count=count+a2; } else{ count=count+a2; a1=a1-2*a2; } if(a1%4==0) { count = count + a1 / 4; a1 = 0; } else { count = count + a1 / 4; a1 = a1 % 4; } if(a1>0) System.out.println(count+a4+1); else System.out.println(count+a4); } }
Java
["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"]
3 seconds
["4", "5"]
NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars.
Java 11
standard input
[ "implementation", "*special", "greedy" ]
371100da1b044ad500ac4e1c09fa8dcb
The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group.
1,100
Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus.
standard output
PASSED
e80ae7954005d9792cfa13f83114de3e
train_001.jsonl
1330804800
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Arrays; public class Solution { public static void main(String args[]) throws IOException { InputReader inp = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); solve(inp, out); inp.bufferedReader.close(); out.close(); } public static void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int taxi = 0; int[] num = new int[4]; Arrays.fill(num, 0); for (int i = 0; i < n; i++) { num[in.nextInt() - 1]++; } taxi += num[3]; taxi += num[1] / 2; if (num[0] <= num[2]) { taxi += num[2] + (num[1] % 2); } else { taxi += num[2] + ((num[0] - num[2]) / 4) + ((((num[0] - num[2]) % 4) + (num[1] % 2) * 2) / 4); if (((((num[0] - num[2]) % 4) + (num[1] % 2) * 2)) % 4 != 0) { taxi++; } } out.print(taxi); } } class InputReader { public BufferedReader bufferedReader; public StringTokenizer stringTokenizer; public InputReader(InputStream in) { this.bufferedReader = new BufferedReader(new InputStreamReader(in)); this.stringTokenizer = null; } public String next() { if(this.stringTokenizer == null || !this.stringTokenizer.hasMoreTokens()) { try { this.stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException e) { System.out.print(e.getStackTrace()); } } return this.stringTokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(this.next()); } public long nextLong() { return Long.parseLong(this.next()); } public double nextDouble() { return Double.parseDouble(this.next()); } }
Java
["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"]
3 seconds
["4", "5"]
NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars.
Java 11
standard input
[ "implementation", "*special", "greedy" ]
371100da1b044ad500ac4e1c09fa8dcb
The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group.
1,100
Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus.
standard output
PASSED
3b118162075393807d953034728b887e
train_001.jsonl
1330804800
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Arrays; import java.lang.Math; public class Solution { public static void main(String args[]) throws IOException { InputReader inp = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); solve(inp, out); inp.bufferedReader.close(); out.close(); } public static void solve(InputReader in, PrintWriter out) throws IOException { int n = in.nextInt(); int taxi = 0; int[] num = new int[4]; Arrays.fill(num, 0); for (int i = 0; i < n; i++) { num[in.nextInt() - 1]++; } taxi += num[3]; taxi += num[1] / 2; taxi += num[2]; num[0] = Math.max(0, num[0] - num[2]); if (num[1] % 2 == 1) { taxi++; num[0] = Math.max(0, num[0] - 2); } taxi += (num[0] / 4) + ((num[0] % 4 == 0) ? 0 : 1); out.print(taxi); } } class InputReader { public BufferedReader bufferedReader; public StringTokenizer stringTokenizer; public InputReader(InputStream in) { this.bufferedReader = new BufferedReader(new InputStreamReader(in)); this.stringTokenizer = null; } public String next() { if(this.stringTokenizer == null || !this.stringTokenizer.hasMoreTokens()) { try { this.stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException e) { System.out.print(e.getStackTrace()); } } return this.stringTokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(this.next()); } public long nextLong() { return Long.parseLong(this.next()); } public double nextDouble() { return Double.parseDouble(this.next()); } }
Java
["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"]
3 seconds
["4", "5"]
NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars.
Java 11
standard input
[ "implementation", "*special", "greedy" ]
371100da1b044ad500ac4e1c09fa8dcb
The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group.
1,100
Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus.
standard output
PASSED
b26740a13bd3871dcf456ce0d9393675
train_001.jsonl
1330804800
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; import java.util.TreeMap; public class Main { public static void main(String[] args) throws FileNotFoundException { InputStream inputStream = System.in;//new FileInputStream("input.txt"); OutputStream outputStream = System.out;//new FileOutputStream("output.txt"); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(in, out); out.close(); } static class TaskB { int n, tmp, ans=0; int[] cnt = new int[5]; void solve(InputReader in, PrintWriter out) { n = in.nextInt(); for(int i=0; i<n; i++) { tmp = in.nextInt(); cnt[tmp]++; } ans += cnt[4]; if(cnt[3] >= cnt[1]) { ans += cnt[3]; if(cnt[2] > 0) { ans += (cnt[2] / 2); ans += cnt[2] % 2; } } else { ans += cnt[3]; cnt[1] -= cnt[3]; if(cnt[2] > 0) { ans += (cnt[2] / 2); if(cnt[2] % 2 > 0) { ans += 1; cnt[1] -= 2; } } if(cnt[1]>0 && cnt[1]<4) { ans += 1; } else if(cnt[1] >= 4) { ans += cnt[1]/4; if(cnt[1]%4 >0) ans++; } } out.println(ans); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"]
3 seconds
["4", "5"]
NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars.
Java 11
standard input
[ "implementation", "*special", "greedy" ]
371100da1b044ad500ac4e1c09fa8dcb
The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group.
1,100
Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus.
standard output
PASSED
69ce90653b19d459d4d677719a5ae13c
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
//TEMPLATE V2 import java.io.*; import java.util.*; import java.math.*; public class Main { //Solution goes below: ------------------------------------ static class Node{ int br; int op; int cl; Node(){//Filler node. br=0; op=0; cl=0; } Node(int b, int o, int c){ br=b; op=o; cl=c; } Node merge(Node other){ int newpairs = Math.min(this.op,other.cl); return( new Node( this.br+other.br+newpairs, this.op+other.op-newpairs, this.cl+other.cl-newpairs ) ); } } static Node[] tree; static Node Go(int level, int pos){ //This is recursive, and should run in O(log N) time. Node n = tree[level+pos]; int l = (int)(size/level)*pos; int r = (int)(size/level)*(pos+1)-1;//I fucking hate rounding errors. if(left<=l&&r<right){ return n;//Yay we're done. }else if(r<left || right<=l){ return new Node();//Nothing to see here... }else{ return Go(level*2,pos*2).merge(Go(level*2,pos*2+1)); } } static int size; static int left,right;//Query public static void solution() throws IOException{ char[] paren = nextLine().toCharArray(); size = paren.length==1?1:Integer.highestOneBit(paren.length - 1)*2; tree = new Node[size*2];//Segment tree. for(int i =0; i<paren.length;i++){ if(paren[i]=='('){ tree[size+i]= new Node(0,1,0); }else{ tree[size+i]=new Node(0,0,1); } } for(int i =paren.length; i<size;i++){//FUCK ROUNDING ERRORS tree[size+i]=new Node(); } for(int i=size-1; i>=1;i--){ //Takes them two at a time. tree[i] = tree[2*i].merge(tree[2*i+1]); } /* for(int i =1; i<size*2;i++){ Node n=tree[i]; print(n.br);print(" "); print(n.op);print(" "); print(n.cl);print(" "); println(); println("----"); flush(); } */ int n = nextInt(); for(int q=0;q<n;q++){ left=nextInt()-1; right=nextInt();//Not b-1 bc it's inclusive. println(2*Go(1,0).br); } } //Solution goes above: ------------------------------------ public static final String IN_FILE = ""; public static final String OUT_FILE = ""; //-------------------- ------------------------------------ //IO public static BufferedReader br; public static StringTokenizer st; public static BufferedWriter bw; public static void main(String[] args) throws IOException{ if(IN_FILE==""){ br = new BufferedReader(new InputStreamReader(System.in)); }else{ try { br = new BufferedReader(new FileReader(IN_FILE)); } catch (FileNotFoundException e) { e.printStackTrace(); } } if (OUT_FILE==""){ bw = new BufferedWriter(new OutputStreamWriter(System.out)); }else{ bw = new BufferedWriter (new FileWriter(OUT_FILE) ); } solution(); bw.close();//Flushes too. } public static String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } public static String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static int nextInt() { return Integer.parseInt(nextToken()); } public static long nextLong() { return Long.parseLong(nextToken()); } public static double nextDouble() { return Double.parseDouble(nextToken()); } public static void println(Object s) throws IOException{ bw.write(s.toString()+"\n"); } public static void println() throws IOException{ bw.newLine(); } public static void print(Object s) throws IOException{ bw.write(s.toString()); } public static void flush() throws IOException{//Useful for debug bw.flush(); } //Other public static class Arr<T> extends ArrayList<T> {} //I hate typing ArrayList }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
054e5e2e659f90ce227cc8447fb79d4c
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
//TEMPLATE V2 import java.io.*; import java.util.*; import java.math.*; public class Main { //Solution goes below: ------------------------------------ static int[][] tree; static int[] Go(int level, int pos){ //This is recursive, and should run in O(log N) time. int[] n = tree[level+pos]; int l = (int)(size/level)*pos; int r = (int)(size/level)*(pos+1)-1;//I fucking hate rounding errors. if(left<=l&&r<right){ return n;//Yay we're done. }else if(r<left || right<=l){ return new int[3];//Nothing to see here... }else{ return(m(Go(level*2,pos*2),Go(level*2,pos*2+1))); } } static int[] m(int[] a, int[] b){ int np = Math.min(a[1],b[2]); return(new int[]{ a[0]+b[0]+np, a[1]+b[1]-np, a[2]+b[2]-np }); } static int size; static int left,right;//Query public static void solution() throws IOException{ char[] paren = nextLine().toCharArray(); size = paren.length==1?1:Integer.highestOneBit(paren.length - 1)*2; tree = new int[size*2][3];//Segment tree. for(int i =0; i<paren.length;i++){ if(paren[i]=='('){ tree[size+i]= new int[]{0,1,0}; }else{ tree[size+i]=new int[]{0,0,1}; } } for(int i =paren.length; i<size;i++){//FUCK ROUNDING ERRORS tree[size+i]=new int[3]; } for(int i=size-1; i>=1;i--){ //Takes them two at a time. tree[i] = m(tree[2*i],tree[2*i+1]); } int n = nextInt(); for(int q=0;q<n;q++){ left=nextInt()-1; right=nextInt();//Not b-1 bc it's inclusive. println(2*Go(1,0)[0]); } } //Solution goes above: ------------------------------------ public static final String IN_FILE = ""; public static final String OUT_FILE = ""; //-------------------- ------------------------------------ //IO public static BufferedReader br; public static StringTokenizer st; public static BufferedWriter bw; public static void main(String[] args) throws IOException{ if(IN_FILE==""){ br = new BufferedReader(new InputStreamReader(System.in)); }else{ try { br = new BufferedReader(new FileReader(IN_FILE)); } catch (FileNotFoundException e) { e.printStackTrace(); } } if (OUT_FILE==""){ bw = new BufferedWriter(new OutputStreamWriter(System.out)); }else{ bw = new BufferedWriter (new FileWriter(OUT_FILE) ); } solution(); bw.close();//Flushes too. } public static String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } public static String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static int nextInt() { return Integer.parseInt(nextToken()); } public static long nextLong() { return Long.parseLong(nextToken()); } public static double nextDouble() { return Double.parseDouble(nextToken()); } public static void println(Object s) throws IOException{ bw.write(s.toString()+"\n"); } public static void println() throws IOException{ bw.newLine(); } public static void print(Object s) throws IOException{ bw.write(s.toString()); } public static void flush() throws IOException{//Useful for debug bw.flush(); } //Other public static class Arr<T> extends ArrayList<T> {} //I hate typing ArrayList }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
130ce798212d7be9677f4a2df976d089
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
//TEMPLATE V2 import java.io.*; import java.util.*; import java.math.*; public class Main { //Solution goes below: ------------------------------------ static int[][] tree; static int[] Go(int level, int pos){ //This is recursive, and should run in O(log N) time. int[] n = tree[level+pos]; int l = (int)(size/level)*pos; int r = (int)(size/level)*(pos+1)-1;//I fucking hate rounding errors. if(left<=l&&r<right){ return n;//Yay we're done. }else if(r<left || right<=l){ return new int[3];//Nothing to see here... }else{ return(m(Go(level*2,pos*2),Go(level*2,pos*2+1))); } } static int[] m(int[] a, int[] b){ int np = Math.min(a[1],b[2]); return(new int[]{ a[0]+b[0]+np, a[1]+b[1]-np, a[2]+b[2]-np }); } static int size; static int left,right;//Query public static void solution() throws IOException{ char[] paren = nextLine().toCharArray(); size = paren.length==1?1:Integer.highestOneBit(paren.length - 1)*2; tree = new int[size*2][];//Segment tree. for(int i =0; i<paren.length;i++){ if(paren[i]=='('){ tree[size+i]= new int[]{0,1,0}; }else{ tree[size+i]=new int[]{0,0,1}; } } for(int i =paren.length; i<size;i++){//FUCK ROUNDING ERRORS tree[size+i]=new int[3]; } for(int i=size-1; i>=1;i--){ //Takes them two at a time. tree[i] = m(tree[2*i],tree[2*i+1]); } int n = nextInt(); for(int q=0;q<n;q++){ left=nextInt()-1; right=nextInt();//Not b-1 bc it's inclusive. println(2*Go(1,0)[0]); } } //Solution goes above: ------------------------------------ public static final String IN_FILE = ""; public static final String OUT_FILE = ""; //-------------------- ------------------------------------ //IO public static BufferedReader br; public static StringTokenizer st; public static BufferedWriter bw; public static void main(String[] args) throws IOException{ if(IN_FILE==""){ br = new BufferedReader(new InputStreamReader(System.in)); }else{ try { br = new BufferedReader(new FileReader(IN_FILE)); } catch (FileNotFoundException e) { e.printStackTrace(); } } if (OUT_FILE==""){ bw = new BufferedWriter(new OutputStreamWriter(System.out)); }else{ bw = new BufferedWriter (new FileWriter(OUT_FILE) ); } solution(); bw.close();//Flushes too. } public static String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } public static String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static int nextInt() { return Integer.parseInt(nextToken()); } public static long nextLong() { return Long.parseLong(nextToken()); } public static double nextDouble() { return Double.parseDouble(nextToken()); } public static void println(Object s) throws IOException{ bw.write(s.toString()+"\n"); } public static void println() throws IOException{ bw.newLine(); } public static void print(Object s) throws IOException{ bw.write(s.toString()); } public static void flush() throws IOException{//Useful for debug bw.flush(); } //Other public static class Arr<T> extends ArrayList<T> {} //I hate typing ArrayList }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
308ebbc9a4c3d11f9717ebc0a879d557
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class A { static final int INF = (int)1e9; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); char[] s = sc.next().toCharArray(); int n = 1; while(n < s.length) n <<= 1; int[] prefix = new int[n + 1]; Arrays.fill(prefix, INF); prefix[0] = 0; for(int i = 1; i <= s.length; ++i) prefix[i] = prefix[i-1] + (s[i-1] == '(' ? 1 : -1); SegmentTree st = new SegmentTree(prefix); int q = sc.nextInt(); while(q-->0) { int l = sc.nextInt(), r = sc.nextInt(); int offset = prefix[l-1]; st.update(l, r, -offset); int extraClose = Math.max(-st.query(l, r), 0); int extraOpen = extraClose + st.query(r, r); out.println(r - l + 1 - (extraClose + extraOpen)); st.update(l, r, offset); } out.flush(); out.close(); } static class SegmentTree { int[] array, sTree, lazy; int N; SegmentTree(int[] in) { N = in.length - 1; sTree = new int[N<<1]; lazy = new int[N<<1]; array = in; build(1, 1, N); } void build(int node, int b, int e) { if(b == e) { sTree[node] = array[b]; return; } build(node<<1, b, (b+e) / 2); build((node<<1) + 1, (b+e) / 2 + 1, e); sTree[node] = Math.min(sTree[node<<1], sTree[(node<<1) + 1]); } void update(int l, int r, int val) { update(1, 1, N, l, r, val); } void update(int node, int b, int e, int l, int r, int val) { if(r < b || e < l) return; if(l <= b && e <= r) { lazy[node] += val; sTree[node] += val; return; } propagate(node, b, e); update(node<<1, b, (b+e) / 2, l, r, val); update((node<<1) + 1, (b+e) / 2 + 1, e, l, r, val); } void propagate(int node, int b, int e) { if(lazy[node] == 0) return; int val = lazy[node]; lazy[node<<1] += val; lazy[(node<<1) + 1] += val; sTree[(node<<1)] += val; sTree[(node<<1) + 1] += val; lazy[node] = 0; } int query(int l, int r) { return query(1, 1, N, l, r); } int query(int node, int b, int e, int l, int r) { if(r < b || e < l) return INF; if(l <= b && e <= r) return sTree[node]; propagate(node, b, e); int q1 = query(node<<1, b, (b+e)/2, l, r); int q2 = query((node<<1) +1 , (b+e)/2 + 1, e, l, r); return Math.min(q1, q2); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader r){ br = new BufferedReader(r);} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
21836417a1790d77943ad9e5c6d71559
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.PrintWriter; public class C380 { static class SegmentTree { int n; int tree[][]; int start[]; int end[]; int ref[]={0,0,0}; public SegmentTree(char a[]) { n=a.length-1; tree=new int[4*n+7][3]; start=new int[4*n+7]; end=new int[4*n+7]; build(a,1,0,n); } void build(char a[],int node,int s,int e) { start[node]=s; end[node]=e; if(s==e) { if(a[s]=='(') tree[node][1]=1; else tree[node][2]=1; } else { int mid=(s+e)/2; build(a,2*node,s,mid); build(a,2*node+1,mid+1,e); int t=Math.min(tree[2*node][1],tree[2*node+1][2]); for(int i=0;i<3;i++) tree[node][i]=tree[2*node][i]+tree[2*node+1][i]-t; tree[node][0]+=3*t; } } int query(int l,int r) { return query(1,l,r)[0]; } int[] query(int node,int l,int r) { if(start[node]>r||end[node]<l) return ref; if(start[node]>=l&&end[node]<=r) return tree[node]; int leftValue[]=query(2*node,l,r); int rightValue[]=query(2*node+1,l,r); int ret[]=new int[3]; int t=Math.min(leftValue[1],rightValue[2]); for(int i=0;i<3;i++) ret[i]=leftValue[i]+rightValue[i]-t; ret[0]+=3*t; return ret; } } 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; } } public static void main(String args[]) throws IOException { Scanner in=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); char c[]=in.next().toCharArray(); SegmentTree st=new SegmentTree(c); int n=in.nextInt(); for(int i=0;i<n;i++) out.println(st.query(in.nextInt()-1, in.nextInt()-1)); out.close(); } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
62116f727a72eba2c7541203c67c5c2b
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.*; import java.math.*; import java.security.KeyStore.Entry; import java.util.*; public class TestClass { private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; public static class Pair implements Comparable<Pair> { long u; long v; public Pair(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v); } public String toString() { return u+" "+v; } } static Pair p[] = new Pair[10000000]; public static void Build(int l,int r,int c,String a){ if(l==r){ long op = 0; if(a.charAt(l)=='(') op = ((long)1)<<32; else op = 1; p[c] = new Pair(op,0); return ; } int mid = (l+r)>>1; Build(l,mid,2*c+1,a); Build(mid+1,r,2*c+2,a); p[c] = combine(p[2*c+1],p[2*c+2]); } public static Pair combine(Pair a,Pair b){ long kl = 2*Math.min((a.u>>32),(int) b.u); long open = (a.u>>32) + (b.u>>32) - kl/2; long close = (int)a.u + (int)b.u - kl/2; return new Pair((open<<32)|close,a.v+b.v+kl); } public static Pair get(int l,int r,int c,int x,int y){ if(l>r||x>y||l>y||x>r) return new Pair(0,0); if(x<=l&&y>=r) return p[c]; int mid = (l+r)>>1; Pair a1 = get(l,mid,2*c+1,x,y); Pair a2 = get(mid+1,r,2*c+2,x,y); return combine(a1,a2); } private static void soln(){ String a = nLi(); Build(0,a.length()-1,0,a); int m = nI(); while(m-->0){ int x = nI()-1,y = nI()-1; pw.println(get(0,a.length()-1,0,x,y).v); } } public static void main(String[] args) { InputReader(System.in); pw = new PrintWriter(System.out); soln(); pw.close(); } // To Get Input // Some Buffer Methods public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } private static int nI() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static long nL() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static String nLi() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
f34014f447a61566ee3238c828227fcb
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.*; import java.util.*; /* * Heart beats fast * Colors and promises * How to be brave * How can I love when I am afraid to fall... */ //read the question correctly (is y a vowel? what are the exact constraints?) //look out for SPECIAL CASES (n=1?) and overflow (ll vs int?) public class Main { static class segtree { //segment tree //n is segment tree size //take input from i=n to 2*n-1 int n; int[][]tr; int[] combine(int[]a,int[]b) { int t=Math.min(a[0],b[1]); return new int[]{a[0]+b[0]-t,a[1]+b[1]-t,a[2]+b[2]+t}; } void build() { for(int i=n-1; i>0; i--) tr[i]=combine(tr[i<<1],tr[(i<<1)|1]); } int[] query(int l, int r) { r++; //both are inclusive int res[]= {0,0,0}; int res1[]= {0,0,0}; for(l+=n, r+=n; l<r; l>>=1,r>>=1) { if(l%2!=0) res=combine(res,tr[l++]); if(r%2!=0) res1=combine(tr[--r],res1); } return combine(res,res1); } } public static void main(String[] args) { String s=ns(); int n=s.length(); segtree a=new segtree(); a.tr=new int[2*n][3]; a.n=n; for(int i=n; i<2*n; i++) if(s.charAt(i-n)=='(') a.tr[i][0]=1; else a.tr[i][1]=1; a.build(); int q=ni(); for(int i=0; i<q; i++) { pr(2*a.query(ni()-1, ni()-1)[2]); } System.out.print(output); } /////////////////////////////////////////// /////////////////////////////////////////// ///template from here static interface combiner { public int combine(int a, int b); } static final int mod=1000000007; static final double eps=1e-8; static final long inf=100000000000000000L; static Reader in=new Reader(); static StringBuilder output=new StringBuilder(); static Random rn=new Random(); public static void sort(int[]a) { int te; for(int i=0; i<a.length; i++) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); } public static void sort(long[]a) { int te; for(int i=0; i<a.length; i++) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); }public static void sort(double[]a) { int te; double te1; for(int i=0; i<a.length; i++) { te=rn.nextInt(a.length); if(i!=te) { te1=a[te]; a[te]=a[i]; a[i]=te1; } } Arrays.sort(a); } public static void sort(int[][]a) { Arrays.sort(a, new Comparator<int[]>() { public int compare(int[]a,int[]b) { if(a[0]>b[0]) return 1; if(b[0]>a[0]) return -1; return 0; } }); } static int lowerbound(int[]a, int key) { /* * returns index of smallest element larger than equal to given element between indices l and r inclusive */ int low=0,high=a.length-1,mid=(low+high)/2; while(low<high) { if(a[mid] >= key) high=mid; else low=mid+1; mid=(low+high)/2; } return mid; } static int upperbound(int[]a, int key) { /* * returns index of largest element smaller than equal to given element */ int low=0,high=a.length-1,mid=(low+high+1)/2; while(low<high) { if(a[mid] <= key) low=mid; else high=mid-1; mid=(low+high+1)/2; } return mid; } static int lowerbound(int[]a, int l, int r, int key) { /* * returns index of smallest element larger than equal to given element between indices l and r inclusive */ int low=l,high=r,mid=(low+high)/2; while(low<high) { if(a[mid] >= key) high=mid; else low=mid+1; mid=(low+high)/2; } return mid; } static int upperbound(int[]a, int l, int r, int key) { /* * returns index of largest element smaller than equal to given element */ int low=l,high=r,mid=(low+high+1)/2; while(low<high) { if(a[mid] <= key) low=mid; else high=mid-1; mid=(low+high+1)/2; } return mid; } static class pair { int a,b; pair() { } pair(int c,int d) { a=c; b=d; } } void sort(pair[]a) { Arrays.sort(a,new Comparator<pair>() { @Override public int compare(pair a,pair b) { if(a.a>b.a) return 1; if(b.a>a.a) return -1; return 0; } }); } static int log2n(long a) { int te=0; while(a>0) { a>>=1; ++te; } return te; } static class iter { vecti a; int zin=0; iter(vecti b) { a=b; } public boolean hasNext() { if(a.size>zin) return true; return false; } public int next() { return a.a[zin++]; } public void previous() { zin--; } } static class vecti { int a[],size; vecti() { a=new int[10]; size=0; } vecti(int n) { a=new int[n]; size=0; } public void add(int b) { if(++size==a.length) a=Arrays.copyOf(a, 2*size); a[size-1]=b; } public void sort() { Arrays.sort(a, 0, size); } public void sort(int l, int r) { Arrays.sort(a, l, r); } public iter iterator() { return new iter(this); } } static class lter { vectl a; int curi=0; lter(vectl b) { a=b; } public boolean hasNext() { if(a.size>curi) return true; return false; } public long next() { return a.a[curi++]; } public long prev() { return a.a[--curi]; } } static class vectl { long a[]; int size; vectl() { a=new long[10]; size=0; } vectl(int n) { a=new long[n]; size=0; } public void add(long b) { if(++size==a.length) a=Arrays.copyOf(a, 2*size); a[size-1]=b; } public void sort() { Arrays.sort(a, 0, size); } public void sort(int l, int r) { Arrays.sort(a, l, r); } public lter iterator() { return new lter(this); } } static class dter { vectd a; int curi=0; dter(vectd b) { a=b; } public boolean hasNext() { if(a.size>curi) return true; return false; } public double next() { return a.a[curi++]; } public double prev() { return a.a[--curi]; } } static class vectd { double a[]; int size; vectd() { a=new double[10]; size=0; } vectd(int n) { a=new double[n]; size=0; } public void add(double b) { if(++size==a.length) a=Arrays.copyOf(a, 2*size); a[size-1]=b; } public void sort() { Arrays.sort(a, 0, size); } public void sort(int l, int r) { Arrays.sort(a, l, r); } public dter iterator() { return new dter(this); } } //output functions//////////////// static void pr(Object a){output.append(a+"\n");} static void pr(){output.append("\n");} static void p(Object a){output.append(a);} static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");} static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");} static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");} static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");} static void sop(Object a){System.out.println(a);} static void flush(){System.out.println(output);output=new StringBuilder();} ////////////////////////////////// //input functions///////////////// static int ni(){return in.nextInt();} static long nl(){return Long.parseLong(in.next());} static String ns(){return in.next();} static double nd(){return Double.parseDouble(in.next());} static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;} static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;} static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;} static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;} static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;} static vecti niv(int n) {vecti a=new vecti(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=ni();return a;} static vectl nlv(int n) {vectl a=new vectl(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=nl();return a;} static vectd ndv(int n) {vectd a=new vectd(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=nd();return a;} ////////////////////////////////// //some utility functions static void exit(){System.exit(0);} static void psort(int[][] a) { Arrays.sort(a, new Comparator<int[]>() { @Override public int compare(int[]a,int[]b) { if(a[0]>b[0]) return 1; else if(b[0]>a[0]) return -1; return 0; } }); } static String pr(String a, long b) { String c=""; while(b>0) { if(b%2==1) c=c.concat(a); a=a.concat(a); b>>=1; } return c; } static long powm(long a, long b, long m) { long an=1; long c=a; while(b>0) { if(b%2==1) an=(an*c)%m; c=(c*c)%m; b>>=1; } return an; } static int gcd(int a, int b) { if(b==0) return a; else return gcd(b, a%b); } static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in), 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()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
8e066ddcb91e57ee182f20a252294e32
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; import java.util.Stack; /** * Created by lenovo on 3/6/2016. */ public class Brackets { public static void main(String[] args) throws IOException { //Scanner scanner = new Scanner(System.in); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1014*1024); String input = br.readLine(); int n = Integer.parseInt(br.readLine()); ArrayList<Node> results = new ArrayList<Node>(); ArrayList<Integer> answer = new ArrayList<Integer>(); ArrayList<Interval> intervals = new ArrayList<Interval>(); Stack<Integer> index = new Stack(); for (int i = 0; i < n; i++) { String line = br.readLine(); String[] split = line.split("\\s"); int l = Integer.parseInt(split[0]); int r = Integer.parseInt(split[1]); intervals.add(new Interval(l, r, i)); answer.add(0); } Collections.sort(intervals); int rightIndex = 0; for (int i = 0; i < input.length(); i++) results.add(new Node(0, null, null, null)); Node root = makeTree(results, 0, input.length()); for (int i = 0; i < input.length(); i++) { if (input.charAt(i) == '(') { index.push(i); } else if (index.size() != 0) { int addIndex = index.pop(); add(results, addIndex); } while((rightIndex < n) && (intervals.get(rightIndex).right - 1) == i) { answer.set(intervals.get(rightIndex).number ,2 * partialSum(results, root, 0, input.length(), intervals.get(rightIndex).left - 1, intervals.get(rightIndex).right)); rightIndex++; } } for (int i = 0; i < n; i++) { sb.append(answer.get(i)).append('\n'); } System.out.println(sb.toString()); } public static Node makeTree(ArrayList<Node> a, int start, int end) { int mid = (start + end) / 2; if (end - start == 1) { return a.get(start); } Node left = makeTree(a, start, mid); Node right = makeTree(a, mid, end); Node newNode = new Node(left.value + right.value, right, left, null); left.parent = newNode; right.parent = newNode; return newNode; } public static void add(ArrayList<Node> a, int index) { Node current = a.get(index); current.value++; while (current.parent != null) { current = current.parent; current.value++; } } public static int partialSum(ArrayList<Node> a, Node root, int start, int end, int l, int r) { int mid = (start + end) / 2; int left = 0, right = 0; if(start == l && end == r) return root.value; if (l < mid) left = partialSum(a, root.left, start, mid, l, Math.min(mid, r)); if (r > mid) right = partialSum(a, root.right, mid, end, Math.max(mid, l), r); return left + right; } } class Node { public int value; public Node left; public Node right; public Node parent; public Node(int value, Node right, Node left, Node parent) { this.value = value; this.left = left; this.right = right; this.parent = parent; } } class Interval implements Comparable<Interval>{ public int left; public int right; public int number; public Interval(int left, int right, int number) { this.left = left; this.right = right; this.number = number; } @Override public int compareTo(Interval o) { return this.right - o.right; } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
bab4e08378fed62d699de030951da9ce
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static int N, Q; public static String str; public static node[] nodes; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); str = f.readLine(); N = str.length(); nodes = new node[(N + 2) << 2 | 1]; build(); Q = Integer.parseInt(f.readLine()); StringBuilder sb = new StringBuilder(); for (; Q > 0; Q--) { StringTokenizer st = new StringTokenizer(f.readLine()); int l = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); sb.append(query(l, r).a * 2).append("\n"); } System.out.print(sb.toString()); } public static void build() { build(1, N, 1); } public static node query(int left, int right) { return query(left, right, 1, N, 1); } public static void build(int l, int r, int index) { nodes[index] = new node(); if (l == r) { if (str.charAt(l - 1) == '(') nodes[index].b = 1; else nodes[index].c = 1; return; } int m = (l + r) >> 1; build(l, m, index << 1); build(m + 1, r, index << 1 | 1); pushUp(index); } public static node query(int L, int R, int l, int r, int index) { if (L <= l && r <= R) { return nodes[index]; } int m = (l + r) >> 1; node res1 = new node(); node res2 = new node(); if (L <= m) { res1 = query(L, R, l, m, index << 1); } if (R > m) { res2 = query(L, R, m + 1, r, index << 1 | 1); } node res = new node(); int X = Math.min(res1.b, res2.c); res.a = res1.a + res2.a + X; res.b = res1.b + res2.b - X; res.c = res1.c + res2.c - X; return res; } public static void pushUp(int index) { int X = Math.min(nodes[index << 1].b, nodes[index << 1 | 1].c); nodes[index].a = nodes[index << 1].a + nodes[index << 1 | 1].a + X; nodes[index].b = nodes[index << 1].b + nodes[index << 1 | 1].b - X; nodes[index].c = nodes[index << 1].c + nodes[index << 1 | 1].c - X; } } class node { public int a, b, c; }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
4d1dbff33c4df29d5cc57484b2cc6ab0
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static int N, Q; public static String str; public static node[] nodes; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); str = f.readLine(); N = str.length(); nodes = new node[(N + 2) << 2 | 1]; build(); Q = Integer.parseInt(f.readLine()); StringBuilder sb = new StringBuilder(); for (; Q > 0; Q--) { StringTokenizer st = new StringTokenizer(f.readLine()); int l = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); sb.append(query(l, r).a * 2).append("\n"); } System.out.print(sb.toString()); } public static void build() { build(1, N, 1); } public static node query(int left, int right) { return query(left, right, 1, N, 1); } public static void build(int l, int r, int index) { nodes[index] = new node(); if (l == r) { if (str.charAt(l - 1) == '(') nodes[index].b = 1; else nodes[index].c = 1; return; } int m = (l + r) >> 1; build(l, m, index << 1); build(m + 1, r, index << 1 | 1); pushUp(index); } public static node query(int L, int R, int l, int r, int index) { if (L <= l && r <= R) { return nodes[index]; } int m = (l + r) >> 1; node res1 = new node(); node res2 = new node(); if (L <= m) { res1 = query(L, R, l, m, index << 1); } if (R > m) { res2 = query(L, R, m + 1, r, index << 1 | 1); } node res = new node(); int X = Math.min(res1.b, res2.c); res.a = res1.a + res2.a + X; res.b = res1.b + res2.b - X; res.c = res1.c + res2.c - X; return res; } public static void pushUp(int index) { int X = Math.min(nodes[index << 1].b, nodes[index << 1 | 1].c); nodes[index].a = nodes[index << 1].a + nodes[index << 1 | 1].a + X; nodes[index].b = nodes[index << 1].b + nodes[index << 1 | 1].b - X; nodes[index].c = nodes[index << 1].c + nodes[index << 1 | 1].c - X; } } class node { public int a, b, c; public String toString() { return a + " " + b + " " + c; } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
554bf24e08fbbe641e006aa6dc21db75
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
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.Arrays; import java.util.StringTokenizer; import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MaximizeAction; public class Main { static PrintWriter pw = new PrintWriter(System.out); static final int NINF=-(int)(1e9); public static void main(String[] args) throws IOException, InterruptedException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st ; String in = bf.readLine(); int n =in.length(); int N=1; while(N<n)N<<=1; node[] arr =new node[N+1]; arr[0]= new node(0,0, 0); for(int i=1;i<=N;i++) { if(i<=n) { if(in.charAt(i-1)=='(') { arr[i]=new node(1, 0, 0); }else { arr[i]=new node(0, 1, 0); } }else { arr[i]= new node(0,0, 0); } } SegmentTree segmentTree= new SegmentTree(arr); int q =Integer.parseInt(bf.readLine()); for(int i=0;i<q;i++) { st= new StringTokenizer(bf.readLine()); pw.println(2*segmentTree.query(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())).sum); } pw.flush(); pw.close(); } static class node{ int leftOpen,rightOpen,sum; public node(int preMax,int sufMax,int sum) { this.sum=sum; this.leftOpen=preMax; this.rightOpen=sufMax; } } static public class SegmentTree { int N; node[] array; node[] sTree; public node combine(node a,node b) { int maxPos=Math.min(Math.abs(a.leftOpen),Math.abs( b.rightOpen)); return new node(a.leftOpen-maxPos+b.leftOpen,a.rightOpen+b.rightOpen-maxPos,a.sum+b.sum+maxPos); } public SegmentTree(node[] arr) {//note arr must be 1 based arr array=arr; N=arr.length-1;// arr must be power of 2 and 1 based array sTree=new node[N<<1]; // no of nodes is 2N-1 but we add 1 to be 1 index build(1,1,N); } public void build(int v,int b ,int e) {//o(N) if(b==e) { sTree[v]=array[b]; }else { int mid =(b+e)>>1; build((v<<1),b,mid); build((v<<1)|1,mid+1,e); sTree[v]=combine(sTree[v<<1],sTree[(v<<1)|1]); } } public node query(int i, int j) {//O(2log(n)) return query(1, 1,N,i,j); } public node query(int node , int b ,int e , int i , int j) { if(b>j||e<i)return new node(0,0,0); int mid =(b+e)>>1; if(b>=i&&e<=j) { return sTree[node]; } node leftChild =query(node<<1, b,mid,i,j); node rightChild =query((node<<1)|1, mid+1,e,i,j); return combine( leftChild,rightChild); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
0f654c6fe9256ec58d2a1153dd07e58d
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; 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.Arrays; import java.util.StringTokenizer; public class Seraj_brackets { static int mod; static int[][] st; static char[] arr; // static int[] pre,st; static int n; public static void build() { st=new int[n<<2][3]; build(1,1,n); } public static void build(int v ,int b, int e) { if(b==e) { st[v][1]=(arr[b-1]=='(')?1:0; st[v][0]=(arr[b-1]==')')?1:0; }else { int mid=b+e>>1; build(v<<1,b,mid); build(v<<1|1,mid+1,e); st[v][1]=Math.max(0,st[v<<1][1]-st[v<<1|1][0])+st[v<<1|1][1]; st[v][0]=Math.max(0, st[v<<1|1][0]-st[v<<1][1])+st[v<<1][0]; st[v][2]=st[v<<1][2]+ st[v<<1|1][2]+2*Math.min(st[v<<1][1],st[v<<1|1][0]); } } //public static void build(int v ,int b, int e) { // if(b==e) { // st[v]=pre[b-1]; // }else { // int mid=b+e>>1; // // build(v<<1,b,mid); // build(v<<1|1,mid+1,e); // st[v]=Math.max(st[v<<1], st[v<<1|1]); // } // } //public static int query(int l , int r ) { // return query(1,1,n,l,r); //} //public static int query(int v ,int b, int e, int l ,int r) { // if(l>e||r<b)return 0; // if(l<=b&&e<=r)return st[v]; // int mid=b+e>>1; // return Math.max( query(v<<1, b,mid,l,r),query(v<<1|1, mid+1, e, l, r)); // //} public static int query(int l , int r ) { return query(1,1,n,l,r)[2]; } public static int[] query(int v ,int b, int e, int l ,int r) { if(l>e||r<b)return new int[3]; if(l<=b&&e<=r)return st[v]; int mid=b+e>>1; int[] left= query(v<<1, b,mid,l,r); int[] right=query(v<<1|1, mid+1, e, l, r); int[] ans=new int[3]; ans[1]=Math.max(0,left[1]-right[0])+right[1]; ans[0]=Math.max(0, right[0]-left[1])+left[0]; ans[2]=left[2]+ right[2]+2*Math.min(left[1],right[0]); return ans; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); arr=sc.next().toCharArray(); n=arr.length; build(); int m=sc.nextInt(); for(int i=0;i<m;i++) pw.println(query(sc.nextInt(), sc.nextInt())); pw.flush(); } static long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } static long lcm(long a, long b) { return a / gcd(a, b) * b; } public static int log(int n, int base) { int ans = 0; while (n + 1 > base) { ans++; n /= base; } return ans; } static int pow(int b, long e) { int ans = 1; while (e > 0) { if ((e & 1) == 1) ans = (int) ((ans * 1l * b)); e >>= 1; { } b = (int) ((b * 1l * b)); } return ans; } static long powmod(long b, long e, int mod) { long ans = 1; b %= mod; while (e > 0) { if ((e & 1) == 1) ans = (int) ((ans * 1l * b) % mod); e >>= 1; b = (int) ((b * 1l * b) % mod); } return ans; } public static long add(long a, long b) { return (a + b) % mod; } public static long sub(long a, long b) { return (a - b + mod) % mod; } public static long mul(long a, long b) { return ((a % mod) * (b % mod)) % mod; } static class longPair implements Comparable<longPair> { long x, y; public longPair(long a, long b) { x = a; y = b; } public int compareTo(longPair p) { return (p.x == x) ? ((p.y == y) ? 0 : (y > p.y) ? 1 : -1) : (x > p.x) ? 1 : -1; } } static class Pair implements Comparable<Pair> { int x; int y; public Pair(int a, int b) { this.x = a; y = b; } public int compareTo(Pair o) { return (x == o.x) ? ((y > o.y) ? 1 : (y == o.y) ? 0 : -1) : ((x > o.x) ? 1 : -1); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s)); } public long[] nextLongArr(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine(), " ,"); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) { if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } if (sb.length() == 18) { res += Long.parseLong(sb.toString()) / f; sb = new StringBuilder("0"); } } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } public static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
0ea964f2182c9d529df8744ed23508f4
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class SerejaBrackets { public static void main(String[] args) throws IOException { long start = System.currentTimeMillis(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1014*1024); String s = br.readLine(); SegmentTreeT sum = new SegmentTreeT(s.length()) { public Seq combine(Seq a, Seq b) { int t = Math.min(a.leftUnused, b.rightUnused); return new Seq(a.len + b.len + 2 * t, a.leftUnused + b.leftUnused - t, a.rightUnused + b.rightUnused - t); } }; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(') { sum.init(i, new Seq(0, 1, 0)); } else { sum.init(i, new Seq(0, 0, 1)); } } sum.build(); int m = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < m; ++i) { String line = br.readLine(); String[] split = line.split("\\s"); int l = Integer.parseInt(split[0]); int r = Integer.parseInt(split[1]); Seq query = sum.query(l - 1, r); sb.append(query.len).append('\n'); } System.out.println(sb.toString()); // System.err.println("Runtime: " + (System.currentTimeMillis() - start) ); } public static class Seq { int len; int leftUnused; int rightUnused; public Seq() { } public Seq(int len, int leftUnused, int rightUnused) { this.len = len; this.leftUnused = leftUnused; this.rightUnused = rightUnused; } @Override public String toString() { return "Seq{" + "len=" + len + ", leftUnused=" + leftUnused + ", rightUnused=" + rightUnused + '}'; } } static abstract class SegmentTreeT { private final int n; // array size private final Seq t[]; public SegmentTreeT(int n) { this.n = n; this.t = new Seq[2 * n]; } public abstract Seq combine(Seq a, Seq b); public void build() { // build the tree for (int i = n - 1; i > 0; --i) { t[i] = combine(t[i << 1], t[i << 1 | 1]); } } public void init(int i, Seq value) { t[i + n] = value; } public void modify(int p, Seq value) { // set value at position p //for (t[p += n] = value; p > 1; p >>= 1) t[p >> 1] = t[p] + t[p ^ 1]; for (t[p += n] = value; (p >>= 1) > 0; ) t[p] = combine(t[p << 1], t[p << 1 | 1]); } public Seq query(int l, int r) { // sum on interval [l, r) Seq resl = defaultValue(); Seq resr = defaultValue(); for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) > 0) resl = combine(resl, t[l++]); if ((r & 1) > 0) resr = combine(t[--r], resr); } return combine(resl, resr); } private Seq defaultValue(){ return new Seq(); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
5e4b6465f39445dcc7ebdf784463f747
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.*; import java.util.*; public class Serejandbrackets { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.flush();out.close(); } static class TaskE { class pair{ int cnt,l,r;pair(int a,int b,int c){cnt=a;l=b;r=c;} } String S;pair seg[]; void b(int n,int s,int e){ if(s==e){ if(S.charAt(s)=='('){ seg[n].l++; }else seg[n].r++; return; } int m=(s+e)>>1; b(2*n+1,s,m);b(2*n+2,m+1,e); int x=Math.min(seg[2*n+1].l,seg[2*n+2].r); seg[n].cnt+=seg[2*n+1].cnt+seg[2*n+2].cnt+2*x; seg[n].l=seg[2*n+1].l+seg[2*n+2].l-x; seg[n].r=seg[2*n+1].r+seg[2*n+2].r-x; } pair q(int n,int s,int e,int qs,int qe){ if(s>qe||e<qs)return new pair(0,0,0); if(s>=qs&&e<=qe){ return seg[n]; }int m=(s+e)>>1; pair L=q(2*n+1,s,m,qs,qe); pair R=q(2*n+2,m+1,e,qs,qe); int cnt=L.cnt+R.cnt; int x=Math.min(L.l,R.r); return new pair(cnt+2*x,L.l+R.l-x,L.r+R.r-x); } public void solve(int testNumber, InputReader in, PrintWriter out) { S=in.next().trim(); int l=S.length();seg=new pair[4*l]; for(int i=0;i<4*l;i++)seg[i]=new pair(0,0,0); b(0,0,l-1); int q=in.nextInt(); while(q-->0){ int L=in.nextInt()-1,R=in.nextInt()-1; out.println(q(0,0,l-1,L,R).cnt); } } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); st = null; } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
e212770fe6b6c65b13814ea219a32c4d
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; // tutorial public class Solution { static int[] low = new int[1200000 * 4]; static int[] high = new int[1200000 * 4]; static int[] tot = new int[1200000 * 4]; static int[] open = new int[1200000 * 4]; static int[] close = new int[1200000 * 4]; static char[] rel = new char[1200000 * 4]; public static void main(String[] args) throws NumberFormatException, IOException { //Scanner in = new Scanner(System.in); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] line; String s = in.readLine(); for(int i=0; i<s.length(); i++ ){ rel[i] = s.charAt(i); } int q = Integer.parseInt(in.readLine()); init(1, 0, s.length()-1); for(int i=0; i<q; i++) { line = in.readLine().split("\\s+"); int l = Integer.parseInt(line[0])-1; int r = Integer.parseInt(line[1])-1; out.println(getTot(1, l, r)[0] * 2); } out.close(); } private static int[] getTot(int i, int l, int r) { if(low[i] > r || high[i] < l) { return new int[]{0, 0, 0}; } else if(low[i] >= l && high[i] <=r) { return new int[]{tot[i], open[i], close[i]}; } int[] arr1 = getTot(2*i, l, r); int[] arr2 = getTot(2*i+1, l, r); int mike = Math.min(arr1[1], arr2[2]); int[] ans = new int[3]; ans[0] = arr1[0] + arr2[0] + mike; ans[1] = arr1[1] + arr2[1] - mike; ans[2] = arr1[2] + arr2[2] - mike; return ans; } private static void init(int i, int l, int r) { low[i] = l; high[i] = r; if(l == r) { if(rel[l] == '(') { open[i]++; } else { close[i]++; } return; } int mid = (l +r )/2; init(2*i, l, mid); init(2*i + 1, mid+1, r); int left = 2*i; int right = 2*i + 1; int mike = Math.min(open[left], close[right]); tot[i] = tot[left] + tot[right] + mike; open[i] = open[left] + open[right] - mike; close[i] = close[left] + close[right] - mike; } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
ac08d9daa555e58f137416bc00a2334e
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.String; import java.util.Scanner; public class C{ public static void main(String[] args) { // TODO Auto-generated method stub BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer= new PrintWriter(System.out); try{ String sequence = reader.readLine(); Segment test = new Segment(sequence); test.build(0, 0, sequence.length()); int m = Integer.parseInt(reader.readLine()); for(int i = 0; i < m; i++){ String[] strs = reader.readLine().split("\\s+"); writer.println(test.querry(Integer.parseInt(strs[0]) - 1, Integer.parseInt(strs[1]))); } reader.close(); }catch(IOException e){ e.printStackTrace(); } //writer.println(test); writer.flush(); writer.close(); } } final class Segment { char[] root; int[][] segment; public Segment(String sequence){ root = sequence.toCharArray(); segment = new int[root.length*4][]; for(int i = 0; i < segment.length; i++){ segment[i] = new int[3]; segment[i][0] = segment[i][1] = segment[i][2] = 0; } } public void build(int id, int left, int right){ if(right - left < 2){ if(root[left] == '(') segment[id][1] = 1; else if(root[left] == ')') segment[id][2] = 1; return; } else{ int mid = (left+right)/2; build(2*id + 1, left, mid); build(2*id + 2, mid, right); int tmp = Math.min(segment[2 * id + 1][1], segment[2 * id + 2][2]); segment[id][0] = segment[2 * id + 1][0] + segment[2 * id + 2][0] + 2 * tmp; segment[id][1] = segment[2 * id + 1][1] + segment[2 * id + 2][1] - tmp; segment[id][2] = segment[2 * id + 1][2] + segment[2 * id + 2][2] - tmp; } } private int[] node(int x, int y, int id, int left, int right ){ if(left >= y || x >= right) return new int[]{0,0,0}; if(x <= left && right <= y){ return segment[id]; } int mid = (left + right)/2; int[] a = node(x, y, 2 * id + 1, left , mid); int[] b = node(x, y, 2 * id + 2, mid, right); int T, temp, O, C; temp = Math.min(a[1] , b[2]); T = a[0] + b[0] + 2 * temp; O = a[1] + b[1] - temp; C = a[2] + b[2] - temp; return new int[]{T, O, C}; } public int querry(int left, int right){ return node(left, right, 0, 0, root.length)[0]; } @Override public String toString(){ return new String(root); } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
a545002bb1f8d5c8ae3e4915e377d79c
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; import java.util.TreeSet; public class Main { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); InputReader inputReader = new InputReader(in); PrintWriter out = new PrintWriter(System.out); String str = inputReader.getNextToken(); int n = inputReader.getNextInt(); int[] ans = new int[n]; Query[] queries = new Query[n]; for(int i = 0; i < n; i++) { int l = inputReader.getNextInt() - 1; int r = inputReader.getNextInt() - 1; queries[i] = new Query(l, r, i); } Arrays.sort(queries, (q1, q2) -> q1.second - q2.second); int cntQuery = 0; FenwickTree set = new FenwickTree(str.length()); Deque<Integer> deque = new ArrayDeque<>(); for(int i = 0; i < str.length(); i++) { if(str.charAt(i) == '(') { deque.addLast(i); } else { if (!deque.isEmpty()) { int val = deque.pollLast(); set.addElement(val, 1); } } while(cntQuery < queries.length && queries[cntQuery].second == i) { ans[queries[cntQuery].ordinal] = set.getSum(queries[cntQuery].first, queries[cntQuery].second) * 2; cntQuery++; } } for(int i = 0; i < ans.length; i++) { System.out.println(ans[i]); } in.close(); out.close(); } public static class Query { int first; int second; int ordinal; Query(int first, int second, int ordinal) { this.first = first; this.second = second; this.ordinal = ordinal; } } public static class FenwickTree { private int[] arr; FenwickTree(int n) { arr = new int[n+1]; } void addElement(int position, int value) { for(int i = position + 1; i < arr.length; i += (i & (-i))) { arr[i] += value; } } int getSum(int left, int right) { return prefixSum(right) - prefixSum(left-1); } int prefixSum(int x) { int sum = 0; for(int i = x+1; i > 0; i -= (i & (-i))) { sum = sum + arr[i]; } return sum; } } public static class InputReader { static final String SEPARATOR = " "; String[] split; int head = 0; BufferedReader in; public InputReader(BufferedReader in) { this.in = in; } private void fillBuffer() throws IOException { if(split == null || head >= split.length) { head = 0; split = in.readLine().split(SEPARATOR); } } public String getNextToken() throws IOException { fillBuffer(); return split[head++]; } public int getNextInt() throws IOException { return Integer.parseInt(getNextToken()); } public long getNextLong() throws IOException { return Long.parseLong(getNextToken()); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
749bd36b27956fbc4f0445ad88d726ff
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
//package CF; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { static class Pair { int open; int close; int ans; public Pair(int a,int b, int c){ open = a; close = b; ans = c; } public String toString(){ return open + " " + close + " " + ans; } } public static void main(String[] args) throws IOException { Scanner bf = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); String s = bf.nextLine(); int n = s.length(); int q = bf.nextInt(); int N = 1; while(N < n) N <<= 1; int[] in = new int[N + 1]; for(int i = 1; i <= n; i++) in[i] = s.charAt(i-1) == '('?0:1; SegmentTree sg = new SegmentTree(in); // out.println(Arrays.toString(sg.sTree)); for (int i = 0; i < q; i++) { out.println(sg.query(bf.nextInt(), bf.nextInt()).ans); } out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } static class SegmentTree { int N; int[] array; Pair [] sTree; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new Pair[N<<1]; build(1,1,N); } void build(int node, int b, int e) { if(b == e) sTree[node] = new Pair(array[b]==0?1:0,array[b]==1?1:0,0); else { build(node<<1,b,(b+e)/2); build((node<<1)+1,(b+e)/2+1,e); Pair q1 = sTree[node<<1]; Pair q2 = sTree[(node<<1)+1]; int min = Math.min(q1.open, q2.close); sTree[node] = new Pair(q1.open+q2.open-min,q1.close+q2.close-min,q1.ans+q2.ans+min*2); } } Pair query(int i, int j) { return query(1,1,N,i,j); } Pair query(int node, int b, int e, int i, int j) { if(i>e || j <b){ return new Pair(0,0,0); } if(b>= i && e <= j) return sTree[node]; Pair q1 = query(node<<1,b,(b+e)/2,i,j); Pair q2 = query((node<<1)+1,(b+e)/2+1,e,i,j); int min = Math.min(q1.open, q2.close); return new Pair(q1.open+q2.open-min,q1.close+q2.close-min,q1.ans+q2.ans+min*2); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
47581a1a64d12363d1f82dd1ab8e0860
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
//package CF; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { static class Pair { int open; int close; int ans; public Pair(int a,int b, int c){ open = a; close = b; ans = c; } public String toString(){ return open + " " + close + " " + ans; } } public static void main(String[] args) throws IOException { Scanner bf = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); String s = bf.nextLine(); int n = s.length(); int q = bf.nextInt(); int N = 1; while(N < n) N <<= 1; int[] in = new int[N + 1]; for(int i = 1; i <= n; i++) in[i] = s.charAt(i-1) == '('?0:1; SegmentTree sg = new SegmentTree(in); // out.println(Arrays.toString(sg.sTree)); for (int i = 0; i < q; i++) { out.println(sg.query(bf.nextInt(), bf.nextInt()).ans); } out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } static class SegmentTree { int N; int[] array; Pair [] sTree; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new Pair[N<<1]; build(1,1,N); } void build(int node, int b, int e) { if(b == e) sTree[node] = new Pair(array[b]==0?1:0,array[b]==1?1:0,0); else { build(node<<1,b,(b+e)/2); build((node<<1)+1,(b+e)/2+1,e); Pair q1 = sTree[node<<1]; Pair q2 = sTree[(node<<1)+1]; int min = Math.min(q1.open, q2.close); sTree[node] = new Pair(q1.open+q2.open-min,q1.close+q2.close-min,q1.ans+q2.ans+min*2); } } Pair query(int i, int j) { return query(1,1,N,i,j); } Pair query(int node, int b, int e, int i, int j) { if(i>e || j <b){ return new Pair(0,0,0); } if(b>= i && e <= j) return sTree[node]; Pair q1 = query(node<<1,b,(b+e)/2,i,j); Pair q2 = query((node<<1)+1,(b+e)/2+1,e,i,j); int min = Math.min(q1.open, q2.close); return new Pair(q1.open+q2.open-min,q1.close+q2.close-min,q1.ans+q2.ans+min*2); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
63807ae6dd1a5d5a3f026038efb41c00
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import static java.lang.Math.*; public class code1 { private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static Reader in; private static PrintWriter out; //////////////////////////////////////////////////////////////////////////////////////////////////// private static int min(int... a){int min=a[0]; for(int i:a) min=Math.min(min, i); return min;} private static int max(int... a){int max=a[0]; for(int i:a) max=Math.max(max, i); return max;} private static long min(long... a){long min=a[0]; for(long i:a)min=Math.min(min, i); return min;} private static long max(long... a){long max=a[0]; for(long i:a)max=Math.max(max, i); return max;} private static String strm(String str, long m) { String ans=""; while(m>0) { if(m%2==1) ans=ans.concat(str); str=str.concat(str); m>>=1; } return ans; } private static long mod(long a, long mod) {long res = a%mod; return res>=0 ? res : res+mod;} private static int mod(int a, int mod) {int res = a%mod; return res>=0 ? res : res+mod;} private static long modpow(long x, int n, int mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = mod((mod(p, mod)*mod(p, mod)), mod)) { if ((n & 1) != 0) res = mod(mod(res, mod) * mod(p, mod), mod); } return res; } private static long gcd(long a, long b) {return b == 0 ? Math.abs(a) : gcd(b, a % b);} private static int gcd(int a, int b) {return b == 0 ? Math.abs(a) : gcd(b, a % b);} private static long gcd(long... a) {long gcd=a[0]; for(long x:a) gcd=gcd(gcd, x); return gcd;} private static int gcd(int... a) {int gcd=a[0]; for(int x:a) gcd=gcd(gcd, x); return gcd;} private static long lcm(long a, long b) {return Math.abs(a / gcd(a, b) * b);} private static class Pair { public int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Pair)) return false; Pair pair = (Pair)obj; return this.x == pair.x && this.y == pair.y; } @Override public String toString() { return ("(" + this.x + "," + this.y + ")"); } @Override public int hashCode() { return (this.x+" "+this.y).hashCode(); } } private static class Triplet { public int x, y, z; public Triplet(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Triplet)) return false; Triplet triplet = (Triplet)obj; return this.x == triplet.x && this.y == triplet.y && this.z == triplet.z; } @Override public String toString() { return ("(" + this.x + "," + this.y + "," + this.z + ")"); } @Override public int hashCode() { return (this.x+" "+this.y+" "+this.z).hashCode(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// static class Reader { private BufferedReader br; private StringTokenizer token; private Reader(FileReader obj) { br = new BufferedReader(obj, 32768); token = null; } private Reader() { br = new BufferedReader(new InputStreamReader(System.in), 32768); token = null; } private String next() { while(token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (Exception e) {e.printStackTrace();} } return token.nextToken(); } private String nextLine() { String str=""; try { str = br.readLine(); } catch (Exception e) {e.printStackTrace();} return str; } private int nextInt() {return Integer.parseInt(next());} private long nextLong() {return Long.parseLong(next());} private double nextDouble() {return Double.parseDouble(next());} private long[] nextLongArr(int n) { long[] arr = new long[n]; for(int i=0; i<n; i++) arr[i] = nextLong(); return arr; } private int[] nextIntArr(int n) { int[] arr = new int[n]; for(int i=0; i<n; i++) arr[i] = nextInt(); return arr; } } //////////////////////////////////////////////////////////////////////////////////////////////////// private static final int mod = 1_000_000_007; private static int n; private static String str; static class SegmentTree { private int[][] st; private SegmentTree() { int x = (int)ceil(log(n)/log(2)); st = new int[(1<<(x+1)) - 1][3]; buildtree(0, 0, n-1); } private int getMid (int sts, int ste) { return (sts+ste)>>1; } private void buildtree(int sti, int sts, int ste) { if (sts == ste) { if (str.charAt(sts) == '(') st[sti] = new int[]{0, 0, 1}; else st[sti] = new int[]{1, 0, 0}; return; } int mid = getMid(sts, ste); buildtree((sti<<1)|1, sts, mid); buildtree((sti+1)<<1, mid+1, ste); st[sti][1] = st[(sti<<1)|1][1] + st[(sti+1)<<1][1] + 2*min(st[(sti<<1)|1][2], st[(sti+1)<<1][0]); if (st[(sti<<1)|1][2] > st[(sti+1)<<1][0]) st[sti][2] += st[(sti<<1)|1][2] - st[(sti+1)<<1][0]; else st[sti][0] += st[(sti+1)<<1][0] - st[(sti<<1)|1][2]; st[sti][0] += st[(sti<<1)|1][0]; st[sti][2] += st[(sti+1)<<1][2]; } private int query(int qs, int qe) { int[] ans = queryUTIL(0, 0, n-1, qs, qe); return ans[1]; } private int[] queryUTIL(int sti, int sts, int ste, int qs, int qe) { if (qs>ste || qe<sts) return new int[]{0, 0, 0}; else if (qs<=sts && ste<=qe) return st[sti]; int mid = getMid(sts, ste); int left[] = queryUTIL((sti<<1)|1, sts, mid, qs, qe); int right[] = queryUTIL((sti+1)<<1, mid+1, ste, qs, qe); int[] ans = new int[3]; ans[1] = left[1] + right[1] + 2*min(left[2], right[0]); if (left[2] > right[0]) ans[2] += left[2] - right[0]; else ans[0] += right[0] - left[2]; ans[0] += left[0]; ans[2] += right[2]; return ans; } } private static void solve() throws Exception { str = in.nextLine(); n = str.length(); SegmentTree segtree = new SegmentTree(); int q = in.nextInt(); while (q-->0) { int l = in.nextInt()-1, r = in.nextInt()-1; out.printf("%d\n", segtree.query(l, r)); } } private static void run() throws Exception { // in = new Reader(); // in = new Reader(new FileReader("input.txt")); // out = new PrintWriter(new FileWriter("output.txt")); in = oj ? new Reader() : new Reader(new FileReader("/home/raiden/Desktop/input.txt")); out = new PrintWriter(System.out); long ti = System.currentTimeMillis(); solve(); out.flush(); if (!oj) System.out.println("\n"+(System.currentTimeMillis()-ti)+"ms"); } public static void main(String[] args) throws Exception {run();} }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
215f37df79b727f384cade7768e9aa9c
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static class Reader { private BufferedReader br; private StringTokenizer token; protected Reader(FileReader obj) { br = new BufferedReader(obj, 32768); token = null; } protected Reader() { br = new BufferedReader(new InputStreamReader(System.in), 32768); token = null; } protected String next() { while(token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (Exception e) {e.printStackTrace();} } return token.nextToken(); } protected int nextInt() {return Integer.parseInt(next());} protected long nextLong() {return Long.parseLong(next());} protected double nextDouble() {return Double.parseDouble(next());} } static int n; static char[] arr; static class SegmentTree { private int[][] st; protected SegmentTree() { int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); int max_size = 2 * (int) Math.pow(2, x) - 1; st = new int[max_size][3]; buildTree(0, 0, n-1); } private void buildTree(int sti, int sts, int ste) { if (sts == ste) { if (arr[sts] == ')') st[sti] = new int[]{0, 1, 0}; else st[sti] = new int[]{0, 0, 1}; } else { int mid = (sts + ste)/2; buildTree(2*sti+1, sts, mid); buildTree(2*sti+2, mid+1, ste); int min = min(st[2*sti+1][2], st[2*sti+2][1]); st[sti][0] = st[2*sti+1][0] + st[2*sti+2][0] + (min<<1); st[sti][1] = st[2*sti+1][1] + st[2*sti+2][1] - min; st[sti][2] = st[2*sti+1][2] + st[2*sti+2][2] - min; } } private int[] queryUTIL(int sti, int sts, int ste, int qs, int qe) { if (sts>qe || ste<qs) return new int[]{0, 0, 0}; else if (qs<=sts && ste<=qe) return st[sti]; else { int[] temp1 = queryUTIL(2*sti+1, sts, (sts+ste)/2, qs, qe); int[] temp2 = queryUTIL(2*sti+2, 1+(sts+ste)/2, ste, qs, qe); int min = min(temp1[2], temp2[1]); return new int[]{temp1[0] + temp2[0] + (min<<1), temp1[1] + temp2[1] - min, temp1[2] + temp2[2] - min}; } } protected int query(int qs, int qe) { return queryUTIL(0, 0, n-1, qs, qe)[0]; } } public static void main(String[] args) throws IOException { Reader in = new Reader(); PrintWriter out = new PrintWriter(System.out); String str = in.next(); n = str.length(); arr = str.toCharArray(); SegmentTree tree = new SegmentTree(); int m = in.nextInt(); while (m-->0) { int qs = in.nextInt()-1, qe = in.nextInt()-1; out.printf("%d\n", tree.query(qs, qe)); } out.close(); } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
8957aac6da7ab7984c5d432cd3fa0a55
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class SegmentTree { static class tri{ int a;int b;int c; tri(int x,int y,int z) { a=x;b=y;c=z; } } int N; //the number of elements in the array as a power of 2 (i.e. after padding) tri[] sTree, lazy; char array; char[] in; SegmentTree(char []in) { this.in=in; N = in.length - 1; sTree = new tri[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new tri[N<<1]; build(1,1,N); } void build(int node, int b, int e) // O(n) { if(b == e) sTree[node] = new tri(0,in[b]=='('?1:0,in[b]==')'?1:0); else { int mid = b + e >> 1; build(node<<1,b,mid); build(node<<1|1,mid+1,e); int a=sTree[node<<1].a+sTree[node<<1|1].a+2*Math.min(sTree[node<<1].b,sTree[node<<1|1].c); int s=sTree[node<<1].b+sTree[node<<1|1].b-Math.min(sTree[node<<1].b,sTree[node<<1|1].c); int c=sTree[node<<1].c+sTree[node<<1|1].c-Math.min(sTree[node<<1].b,sTree[node<<1|1].c); sTree[node] =new tri(a,s,c) ; } } tri query(int i,int j) { return query(1,1,N,i,j); } tri query(int node, int b, int e, int i, int j) // O(log n) { if(i>e || j <b) return new tri(0,0,0); if(b>= i && e <= j) return sTree[node]; int mid = b + e >> 1; tri q1 = query(node<<1,b,mid,i,j); tri q2 = query(node<<1|1,mid+1,e,i,j); int a=q1.a+q2.a+2*Math.min(q1.b,q2.c); int s=q1.b+q2.b-Math.min(q1.b,q2.c); int c=q1.c+q2.c-Math.min(q1.b,q2.c); return new tri(a,s,c); } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine(); PrintWriter pw=new PrintWriter(System.out); int n=s.length(); int N=1; while(N<n)N<<=1; char []in=new char[N+1]; for(int i=1;i<n+1;i++) { in[i]=s.charAt(i-1); } SegmentTree w=new SegmentTree(in); int t=Integer.parseInt(br.readLine()); while(t-->0) { StringTokenizer st=new StringTokenizer(br.readLine()); pw.println(w.query(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken())).a); } pw.flush(); } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
797bb33513f1d84fff74c776cbe91bf0
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class C380 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); String x = sc.next(); int n = x.length(); int N = 1; while (N < n) N <<= 1; // padding Pair[] in = new Pair[N + 1]; for (int i = 1; i <= n; i++) in[i] = x.charAt(i - 1) == '(' ? new Pair(1,0) : new Pair(0,1); for (int i = n + 1; i < in.length; i++) { in[i] = null; } SegmentTree st = new SegmentTree(in); int m =sc.nextInt(); while(m-->0) { pw.println(st.query(sc.nextInt(), sc.nextInt(),pw)); } pw.flush(); } public static Pair combine(Pair l, Pair r) { if(l==null) return r; if(r==null) return l; int nc = l.c; int no = r.o; if (l.o > r.c) no += l.o - r.c; else if (r.c > l.o) nc += r.c - l.o; Pair n = new Pair(no, nc); return n; } static class Pair { int o, c; public Pair(int o, int c) { this.o = o; this.c = c; } } static class SegmentTree { int N; Pair[] array, sTree; SegmentTree(Pair[] in) { array = in; N = in.length - 1; sTree = new Pair[N << 1]; build(1, 1, N); } void build(int node, int b, int e) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = combine(sTree[node << 1] , sTree[node << 1 | 1]); } } int query(int i, int j,PrintWriter pw) { Pair p = query(1, 1, N, i, j); if(p==null) return 0; //pw.println(p.c + " "+ p.o); return j-i+1-p.c-p.o; } Pair query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return null; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; Pair q1 = query(node << 1, b, mid, i, j); Pair q2 = query(node << 1 | 1, mid + 1, e, i, j); return combine(q1 , q2); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
dc14fe0dd5162d3c21a34328ca2a852d
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class SegmentTreeBracket2 { private static String s; private static int[] valids; private static int[] leftBrackets; private static int[] rightBrackets; public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); s = sc.next(); int n = sc.nextInt(); valids = new int[4 * s.length()]; leftBrackets = new int[4 * s.length()]; rightBrackets = new int[4 * s.length()]; build(1, 0, s.length()); for (int i = 0; i < n; i++) { // 1<=left<=right<=n int left = sc.nextInt(); int right = sc.nextInt(); out.println(getValids(left - 1, right, 1, 0, s.length()).valids); } out.close(); } // [left, right) private static void build(int id, int left, int right) { if (left + 1 == right) { if (s.charAt(left) == '(') leftBrackets[id]++; else rightBrackets[id]++; return; } int mid = (left + right) / 2; build(id * 2, left, mid); build(id * 2 + 1, mid, right); int min = Math.min(leftBrackets[id * 2], rightBrackets[id * 2 + 1]); valids[id] = valids[id * 2] + valids[id * 2 + 1] + 2 * min; leftBrackets[id] = leftBrackets[id * 2] - min + leftBrackets[id * 2 + 1]; rightBrackets[id] = rightBrackets[id * 2] + rightBrackets[id * 2 + 1] - min; } // [left, right) private static Valid getValids(int x, int y, int id, int left, int right) { if (right <= x || left >= y) return new Valid(0, 0, 0); if (left >= x && right <= y) return new Valid(valids[id], leftBrackets[id], rightBrackets[id]); int mid = (left + right) / 2; Valid validLeft = getValids(x, y, id * 2, left, mid); Valid validRight = getValids(x, y, id * 2 + 1, mid, right); Valid res = new Valid(0, 0, 0); int min = Math.min(validLeft.leftBrackets, validRight.rightBrackets); res.valids = validLeft.valids + validRight.valids + 2 * min; res.leftBrackets = validLeft.leftBrackets - min + validRight.leftBrackets; res.rightBrackets = validLeft.rightBrackets + validRight.rightBrackets - min; return res; } private static class Valid { int valids; int leftBrackets; int rightBrackets; public Valid(int valids, int leftBrackets, int rightBrackets) { this.valids = valids; this.leftBrackets = leftBrackets; this.rightBrackets = rightBrackets; } } // -----------PrintWriter for faster output--------------------------------- public static PrintWriter out; // -----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
ea076642ab89e910f8670c8bfce5a854
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.util.*; import java.io.*; public class SegmentTreeBracket { private static String s; private static int[] valids; private static int[] leftBrackets; private static int[] rightBrackets; private static int[] v; private static int[] l; private static int[] r; public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); s = sc.next(); int n = sc.nextInt(); valids = new int[4 * s.length()]; leftBrackets = new int[4 * s.length()]; rightBrackets = new int[4 * s.length()]; v = new int[4 * s.length()]; l = new int[4 * s.length()]; r = new int[4 * s.length()]; build(1, 0, s.length()); for (int i = 0; i < n; i++) { // 1<=left<=right<=n int left = sc.nextInt(); int right = sc.nextInt(); search(left - 1, right, 1, 0, s.length()); out.println(v[1]); } out.close(); } // [left, right) private static void build(int id, int left, int right) { if (left + 1 == right) { if (s.charAt(left) == '(') leftBrackets[id]++; else rightBrackets[id]++; return; } int mid = (left + right) / 2; build(id * 2, left, mid); build(id * 2 + 1, mid, right); int min = Math.min(leftBrackets[id * 2], rightBrackets[id * 2 + 1]); valids[id] = valids[id * 2] + valids[id * 2 + 1] + 2 * min; leftBrackets[id] = leftBrackets[id * 2] - min + leftBrackets[id * 2 + 1]; rightBrackets[id] = rightBrackets[id * 2] + rightBrackets[id * 2 + 1] - min; } // [left, right) private static void search(int x, int y, int id, int left, int right) { if (right <= x || left >= y){ l[id] = 0; r[id] = 0; v[id] = 0; return; } if (left >= x && right <= y){ v[id] = valids[id]; l[id] = leftBrackets[id]; r[id] = rightBrackets[id]; return; } int mid = (left + right) / 2; search(x, y, id * 2, left, mid); search(x, y, id * 2 + 1, mid, right); int min = Math.min(l[id*2], r[id*2+1]); v[id] = v[id * 2] + v[id * 2 + 1] + 2 * min; l[id] = l[id * 2] - min + l[id * 2 + 1]; r[id] = r[id * 2] + r[id * 2 + 1] - min; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
4a251eeb8bd5b4e470efc7027fafc508
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; public class Solution { static InputReader in = new InputReader(System.in); static OutputWriter out = new OutputWriter(System.out); static int exp = (int) (1e9); static Node[] segtree; static char[] arr; private static Node query(int tl, int tr, int l, int r, int index) { if (r < tl || tr < l) { return new Node(0, 0, 0); } if (l <= tl && tr <= r) { return segtree[index]; } int mid = (tl + tr) >> 1; return merge(query(tl, mid, l, r, index * 2 + 1), query(mid + 1, tr, l, r, index * 2 + 2)); } private static Node merge(Node pfx, Node sfx) { int min = Math.min(pfx.open, sfx.close); return new Node(pfx.open + sfx.open - min, pfx.close + sfx.close - min, pfx.count + sfx.count + min * 2); } private static void construct(int left, int right, int node) { if (left > right) { return; } if (left == right) { segtree[node] = arr[left] == '(' ? new Node(1, 0, 0) : new Node(0, 1, 0); return; } int mid = (left + right) >> 1; construct(left, mid, node * 2 + 1); construct(mid + 1, right, node * 2 + 2); segtree[node] = merge(segtree[node * 2 + 1], segtree[node * 2 + 2]); } private static Node qry(int left, int right) { return query(0, arr.length - 1, left, right, 0); } public static void main(String[] args) { String str = in.readLine(); arr = str.toCharArray(); int m = in.nextInt(); segtree = new Node[arr.length << 2]; construct(0, arr.length - 1, 0); for (int i = 0; i < m; i++) { out.println(qry(in.nextInt() - 1, in.nextInt() - 1).count); } out.close(); } } class Node { int open; int close; int count; public Node() { } public Node(int open, int close, int count) { super(); this.open = open; this.close = close; this.count = count; } @Override public String toString() { return "Node [open=" + open + ", close=" + close + ", count=" + count + "]"; } } class OutputWriter { public 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(); } } class InputReader { private BufferedReader reader; private 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 String readLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } 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 float nextFloat() { return Float.parseFloat(next()); } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
ee929d10f44421261e8e37da55c9181c
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class SerejaBrackets2 { int n; Node[] t; void solve() { char[] s = in.nextToken().toCharArray(); n = s.length; t = new Node[n << 1]; for (int i = 0; i < n; i++) { t[n + i] = new Node(0, s[i] == '(' ? 1 : 0, s[i] == ')' ? 1 : 0); } for (int i = n - 1; i > 0; i--) { t[i] = combine(t[i << 1], t[i << 1 | 1]); } int q = in.nextInt(); for (int i = 0; i < q; i++) { int l = in.nextInt() - 1, r = in.nextInt(); Node res = query(l, r); out.println(res.pair << 1); } } Node query(int l, int r) { Node L = new Node(), R = new Node(); for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) > 0) L = combine(L, t[l++]); if ((r & 1) > 0) R = combine(t[--r], R); } return combine(L, R); } Node combine(Node a, Node b) { int cnt = Math.min(a.open, b.close); return new Node(a.pair + b.pair + cnt, a.open + b.open - cnt, a.close + b.close - cnt); } static class Node { int pair, open, close; public Node() { } public Node(int pair, int open, int close) { this.pair = pair; this.open = open; this.close = close; } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new SerejaBrackets2().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
90e9dd095a300a07f1fbb1a7131e48df
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class SerejaBrackets2 { int n; Node[] t; void solve() { char[] s = in.nextToken().toCharArray(); int m = s.length; n = 1; while (n < m) n <<= 1; t = new Node[n << 1]; for (int i = 0; i < n; i++) { if (i < m) t[n + i] = new Node(0, s[i] == '(' ? 1 : 0, s[i] == ')' ? 1 : 0); else t[n + i] = new Node(0, 0, 0); } for (int i = n - 1; i > 0; i--) { t[i] = combine(t[i << 1], t[i << 1 | 1]); } int q = in.nextInt(); for (int i = 0; i < q; i++) { int l = in.nextInt() - 1, r = in.nextInt(); Node res = query(l, r); out.println(res.pair << 1); } } Node query(int l, int r) { Node L = new Node(), R = new Node(); for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) > 0) L = combine(L, t[l++]); if ((r & 1) > 0) R = combine(t[--r], R); } return combine(L, R); } Node combine(Node a, Node b) { int cnt = Math.min(a.open, b.close); return new Node(a.pair + b.pair + cnt, a.open + b.open - cnt, a.close + b.close - cnt); } static class Node { int pair, open, close; public Node() { } public Node(int pair, int open, int close) { this.pair = pair; this.open = open; this.close = close; } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new SerejaBrackets2().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
b934b38c64579cd54a9189613abd4c87
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.*; import java.util.*; public class Parens { static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StreamTokenizer in; static int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } static class ParGroup { int open, correct, closed; ParGroup(int o, int r, int c) { open = o; correct = r; closed = c; } static ParGroup merge(ParGroup l, ParGroup r) { int matched = Math.min(l.open, r.closed); return new ParGroup(l.open + r.open - matched, l.correct + r.correct + (matched << 1), l.closed + r.closed - matched); } public String toString() { return String.format("<%s,%s,%s>", open, correct, closed); } static ParGroup empty = new ParGroup(0, 0, 0); static ParGroup oneOpen = new ParGroup(1, 0, 0); static ParGroup oneClosed = new ParGroup(0, 0, 1); } static class Tree { int from, to; Tree left, right; ParGroup pars; Tree(ParGroup _pars, Tree _l, Tree _r, int _f, int _t) { left = _l; right = _r; from = _f; to = _t; pars = _pars; } static Tree merge(Tree l, Tree r) { return new Tree(ParGroup.merge(l.pars, r.pars), l, r, l.from, r.to); } static Tree leaf(ParGroup _pars, int _f, int _t) { return new Tree(_pars, null, null, _f, _t); } @Override public String toString() { String l = (left == null) ? "" : (", " + left); String r = (right == null) ? "" : (", " + right); return "{" + pars + l + r + "}"; } ParGroup lookup(int f, int t) { if (f <= from && t >= to) return pars; if (f >= to || t <= from) return ParGroup.empty; return ParGroup.merge(left.lookup(f, t), right.lookup(f, t)); } } public static void main(String[] args) throws Exception { String parseq = br.readLine(); int n = parseq.length(); Tree[] prevLevel = new Tree[n]; Tree[] currLevel; for (int i = 0; i < n; i++) prevLevel[i] = Tree.leaf(parseq.charAt(i) == '(' ? ParGroup.oneOpen : ParGroup.oneClosed, i, i+1); int t = (n + 1) / 2; do { currLevel = new Tree[t]; for (int i = 0; i < t; i++) { Tree left = prevLevel[i*2]; if (prevLevel.length < (i + 1) * 2) { currLevel[i] = left; } else { currLevel[i] = Tree.merge(left, prevLevel[i*2+1]); } } prevLevel = currLevel; t = (t == 1) ? 0 : ((t + 1) / 2); } while (t > 0); Tree root = prevLevel[0]; // System.out.println(root); // Queries in = new StreamTokenizer(br); int q = nextInt(); for (int i = 0; i < q; i++) out.write("" + root.lookup(nextInt()-1, nextInt()).correct + "\n"); out.flush(); } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
69d45860158db2f702338ffb44ddc20c
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.*; import java.util.*; public class Parens { static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StreamTokenizer in; static int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } static class ParGroup { int open, correct, closed; ParGroup(int o, int r, int c) { open = o; correct = r; closed = c; } static ParGroup merge(ParGroup l, ParGroup r) { int matched = Math.min(l.open, r.closed); return new ParGroup(l.open + r.open - matched, l.correct + r.correct + (matched << 1), l.closed + r.closed - matched); } public String toString() { return String.format("<%s,%s,%s>", open, correct, closed); } static ParGroup empty = new ParGroup(0, 0, 0); static ParGroup oneOpen = new ParGroup(1, 0, 0); static ParGroup oneClosed = new ParGroup(0, 0, 1); } static class Tree { int from, to; Tree left, right; ParGroup pars; Tree(ParGroup _pars, Tree _l, Tree _r, int _f, int _t) { left = _l; right = _r; from = _f; to = _t; pars = _pars; } @Override public String toString() { String l = (left == null) ? "" : (", " + left); String r = (right == null) ? "" : (", " + right); return "{" + pars + l + r + "}"; } ParGroup lookup(int f, int t) { if (f <= from && t >= to) return pars; if (f >= to || t <= from) return ParGroup.empty; return ParGroup.merge(left.lookup(f, t), right.lookup(f, t)); } } public static void main(String[] args) throws Exception { String parseq = br.readLine(); int n = parseq.length(); Tree[] prevLevel = new Tree[n]; Tree[] currLevel; for (int i = 0; i < n; i++) prevLevel[i] = new Tree(parseq.charAt(i) == '(' ? ParGroup.oneOpen : ParGroup.oneClosed, null, null, i, i+1); int t = (n + 1) / 2; do { currLevel = new Tree[t]; for (int i = 0; i < t; i++) { Tree left = prevLevel[i*2]; if (prevLevel.length < (i + 1) * 2) { currLevel[i] = left; } else { Tree right = prevLevel[i*2+1]; currLevel[i] = new Tree(ParGroup.merge(left.pars, right.pars), left, right, left.from, right.to); } } prevLevel = currLevel; t = (t == 1) ? 0 : ((t + 1) / 2); } while (t > 0); Tree root = prevLevel[0]; // System.out.println(root); // Queries in = new StreamTokenizer(br); int q = nextInt(); for (int i = 0; i < q; i++) out.write("" + root.lookup(nextInt()-1, nextInt()).correct + "\n"); out.flush(); } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
631378cff494367aada1a7ce40ee2087
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Parens { static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StreamTokenizer in; static int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } static class ParGroup { int open, correct, closed; ParGroup(int o, int r, int c) { open = o; correct = r; closed = c; } @Override public String toString() { return String.format("<%s,%s,%s>", open, correct, closed); } // static Sums destroyed = new Sums(-1, -1, -1, false); static ParGroup empty = new ParGroup(0, 0, 0); } static long max(long... as) { long m = Long.MIN_VALUE; for (long l : as) if (m < l) m = l; return m; } static class Tree { int from, to; Tree left, right; ParGroup pars; Tree(ParGroup _pars, Tree _l, Tree _r, int _f, int _t) { left = _l; right = _r; from = _f; to = _t; pars = _pars; } @Override public String toString() { String l = (left == null) ? "" : (", " + left); String r = (right == null) ? "" : (", " + right); return "{" + pars + l + r + "}"; } ParGroup merge(int f, int t) { if (f <= from && t >= to) return pars; if (f >= to || t <= from) return ParGroup.empty; ParGroup l = left.merge(f, t); ParGroup r = right.merge(f, t); int matched = Math.min(l.open, r.closed); ParGroup newpar = new ParGroup(l.open + r.open - matched, l.correct + r.correct + (matched << 1), l.closed + r.closed - matched); return newpar; } // int query(int f, int t) { // if // int midpoint = (f + t) / 2; // } // void destroy(int index) { // if ((index < from) || (index >= to)) return; // if (from == index && to == index + 1) { // sums = Sums.destroyed; // return; // } // if (left != null) // left.destroy(index); // if (right != null) // right.destroy(index); // Sums leftM = (left != null) ? left.sums : null; // Sums rightM = (right != null) ? right.sums : null; // sums.left = leftM.left; // sums.right = rightM.right; // if (leftM.cont && (sums.left != -1) && (rightM.left != -1) ) // sums.left += rightM.left; // if (rightM.cont && (sums.right != -1) && (leftM.right != -1)) // sums.right += leftM.right; // sums.in = max(sums.left, sums.right, leftM.in, rightM.in, // (leftM.right > -1 && rightM.left > -1) ? // leftM.right + rightM.left : -1); // sums.cont = false; // } } public static void main(String[] args) throws Exception { String parseq = br.readLine(); int n = parseq.length(); Tree[] prevLevel = new Tree[n]; Tree[] currLevel; for (int i = 0; i < n; i++) prevLevel[i] = new Tree(parseq.charAt(i) == '(' ? new ParGroup(1, 0, 0) : new ParGroup(0, 0, 1), null, null, i, i+1); // System.out.println(Arrays.toString(prevLevel)); // int n = nextInt(); // Tree[] prevLevel = new Tree[n]; // Tree[] currLevel; // for (int i = 0; i < n; i++) // prevLevel[i] = new Tree(nextInt(), null, null, i, i+1); int t = (n + 1) / 2; do { currLevel = new Tree[t]; for (int i = 0; i < t; i++) { Tree left = prevLevel[i*2]; if (prevLevel.length < (i + 1) * 2) { currLevel[i] = left; } else { Tree right = prevLevel[i*2+1]; int matched = Math.min(left.pars.open, right.pars.closed); ParGroup newpar = new ParGroup(left.pars.open + right.pars.open - matched, left.pars.correct + right.pars.correct + (matched << 1), left.pars.closed + right.pars.closed - matched); currLevel[i] = new Tree(newpar, left, right, left.from, right.to); } } prevLevel = currLevel; t = (t == 1) ? 0 : ((t + 1) / 2); } while (t > 0); Tree root = prevLevel[0]; // System.out.println(root); // Queries in = new StreamTokenizer(br); int q = nextInt(); for (int i = 0; i < q; i++) out.write("" + root.merge(nextInt()-1, nextInt()).correct + "\n"); out.flush(); // System.out.println(root.merge(1, 10)); // for (int i = 0; i < n; i++) { // root.destroy(nextInt()-1); // System.out.println(max(0, root.sums.in)); // } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
63479128aa1431db86c325948df96539
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
/** * * @author meashish */ import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Serializable; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Random; import java.util.Set; import java.util.Stack; public class Main { InputReader in; Printer out; long MOD = 1000000007; private void start() throws Exception { String str = in.next(); int n = str.length(); int forward[] = new int[str.length()]; int backward[] = new int[str.length()]; Arrays.fill(forward, -1); Arrays.fill(backward, -1); Stack<Integer> stack = new Stack(); for (int i = 0; i < n; i++) { char c = str.charAt(i); if (c == '(') { stack.push(i); } else if (!stack.isEmpty()) { int val = stack.pop(); forward[val] = i; } } // // stack.clear(); // for (int i = n - 1; i >= 0; i--) { // char c = str.charAt(i); // // if (c == ')') { // stack.push(i); // } else if (!stack.isEmpty()) { // int val = stack.pop(); // // backward[val] = i; // } // } // out.println(Arrays.toString(forward)); // out.println(Arrays.toString(backward)); ArrayList<Pair<Integer, Integer>> intervals = new ArrayList<>(); for (int i = 0; i < n; i++) { if (forward[i] != -1) { intervals.add(new Pair<>(i, forward[i])); } } Collections.sort(intervals, (Pair<Integer, Integer> p1, Pair<Integer, Integer> p2) -> { if (p1.key.intValue() != p2.key) { return p1.key - p2.key; } return p1.value - p2.value; }); int q = in.nextInt(); ArrayList<Query> list = new ArrayList<>(); for (int i = 0; i < q; i++) { int l = in.nextInt() - 1; int r = in.nextInt() - 1; Query query = new Query(i, l, r); list.add(query); } Collections.sort(list, (Query A, Query B) -> { if (A.l != B.l) { return A.l - B.l; } return A.r - B.r; }); int addedIndex = 0; Bit bit = new Bit(n); for (Pair<Integer, Integer> pair : intervals) { bit.update(pair.value + 1, pair.value + 1, 1); } // for (Pair<Integer, Integer> pair : intervals) { // out.print((pair.key + 1) + "=" + (pair.value + 1) + " "); // } // out.println(); // out.println(list); outer: for (Query query : list) { if (addedIndex >= intervals.size()) { break; } Pair<Integer, Integer> pair = intervals.get(addedIndex); while (pair.key < query.l) { bit.update(pair.value + 1, pair.value + 1, -1); addedIndex++; if (addedIndex >= intervals.size()) { break outer; } pair = intervals.get(addedIndex); } query.res = 2 * bit.query(1, query.r + 1); // out.println(query + " " + addedIndex + " " + query.res); } Collections.sort(list, (Query A, Query B) -> { return A.index - B.index; }); for (Query query : list) { out.println(query.res); } } class Query { int l, r; int index; long res; Query(int ind, int l, int r) { index = ind; this.l = l; this.r = r; } @Override public String toString() { return (l + 1) + "=" + (r + 1); } } Pair<Integer, Integer> diameter(int root, HashSet<Integer> visited, ArrayList<Integer>[] list) { visited.add(root); int maxI = root, max = -1; for (int child : list[root]) { if (visited.contains(child)) { continue; } Pair<Integer, Integer> pair = diameter(child, visited, list); if (max < pair.value) { maxI = pair.key; max = pair.value; } } return new Pair<>(maxI, max + 1); } long power(long x, long n) { if (n <= 0) { return 1; } long y = power(x, n / 2); if ((n & 1) == 1) { return (((y * y) % MOD) * x) % MOD; } return (y * y) % MOD; } public long gcd(long a, long b) { a = Math.abs(a); b = Math.abs(b); return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue(); } public Integer[] input(int n) { Integer a[] = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } return a; } public static void main(String[] args) throws Exception { InputReader in; PrintStream out; // in = new InputReader(new FileInputStream(new File("in.txt"))); // out = new PrintStream("out.txt"); in = new InputReader(System.in); out = System.out; Main main = new Main(); main.in = in; main.out = new Printer(out); main.start(); main.out.flush(); } private static 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 nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } private static class Printer { PrintStream out; StringBuilder buffer = new StringBuilder(); boolean autoFlush; public Printer(PrintStream out) { this.out = out; } public Printer(PrintStream out, boolean autoFlush) { this.out = out; this.autoFlush = autoFlush; } public void println() { buffer.append("\n"); if (autoFlush) { flush(); } } public void println(int n) { println(Integer.toString(n)); } public void println(long n) { println(Long.toString(n)); } public void println(double n) { println(Double.toString(n)); } public void println(float n) { println(Float.toString(n)); } public void println(boolean n) { println(Boolean.toString(n)); } public void println(char n) { println(Character.toString(n)); } public void println(byte n) { println(Byte.toString(n)); } public void println(short n) { println(Short.toString(n)); } public void println(Object o) { println(o.toString()); } public void println(Object[] o) { println(Arrays.deepToString(o)); } public void println(String s) { buffer.append(s).append("\n"); if (autoFlush) { flush(); } } public void print(char s) { buffer.append(s); if (autoFlush) { flush(); } } public void print(String s) { buffer.append(s); if (autoFlush) { flush(); } } public void flush() { try { BufferedWriter log = new BufferedWriter(new OutputStreamWriter(out)); log.write(buffer.toString()); log.flush(); buffer = new StringBuilder(); } catch (Exception e) { e.printStackTrace(); } } } private class Pair<T, U> implements Serializable { int indexOfSec; private T key; public T getKey() { return key; } private U value; public U getValue() { return value; } public Pair(T key, U value) { this.key = key; this.value = value; } @Override public String toString() { return key + "=" + value; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pair other = (Pair) obj; if (!this.key.equals(other.key)) { return false; } return this.value.equals(other.value); } @Override public int hashCode() { return key.hashCode() + 13 * value.hashCode(); } } private class PairSet<T, S> { HashMap<T, HashSet<S>> map = new HashMap<>(); public void add(T a, S b) { if (map.containsKey(a)) { map.get(a).add(b); } HashSet<S> set = new HashSet<>(); set.add(b); map.put(a, set); } public boolean contains(T a, S b) { if (map.containsKey(a)) { return map.get(a).contains(b); } return false; } } private class Bit { int N; long ft1[], ft2[]; Bit(int n) { N = n; ft1 = new long[N + 1]; ft2 = new long[N + 1]; } void update(long ft[], int p, long v) { for (; p <= N; p += p & (-p)) { ft[p] += v; // ft[p] %= MOD; } } void update(int a, int b, long v) { update(ft1, a, v); update(ft1, b + 1, -v); update(ft2, a, v * (a - 1)); update(ft2, b + 1, -v * b); } long query(long ft[], int b) { long sum = 0; for (; b > 0; b -= b & (-b)) { sum += ft[b]; // sum %= MOD; } return sum; } long query(int b) { return query(ft1, b) * b - query(ft2, b); } long query(int a, int b) { return query(b) - query(a - 1); } } class Bipartite { int m, n; boolean[][] graph; boolean seen[]; int matchL[]; //What left vertex i is matched to (or -1 if unmatched) int matchR[]; //What right vertex j is matched to (or -1 if unmatched) public Bipartite(boolean[][] graph) { this.graph = graph; m = graph.length; n = graph[0].length; matchL = new int[m]; matchR = new int[n]; seen = new boolean[n]; } int maximumMatching() { //Read input and populate graph[][] //Set m to be the size of L, n to be the size of R Arrays.fill(matchL, -1); Arrays.fill(matchR, -1); int count = 0; for (int i = 0; i < m; i++) { Arrays.fill(seen, false); if (bpm(i)) { count++; } } return count; } boolean bpm(int u) { //try to match with all vertices on right side for (int v = 0; v < n; v++) { if (!graph[u][v] || seen[v]) { continue; } seen[v] = true; //match u and v, if v is unassigned, or if v's match on the left side can be reassigned to another right vertex if (matchR[v] == -1 || bpm(matchR[v])) { matchL[u] = v; matchR[v] = u; return true; } } return false; } } public static Set<Integer[]> getPermutationsRecursive(Integer[] num) { if (num == null) { return null; } Set<Integer[]> perms = new HashSet<>(); //base case if (num.length == 0) { perms.add(new Integer[0]); return perms; } //shave off first int then get sub perms on remaining ints. //...then insert the first into each position of each sub perm..recurse int first = num[0]; Integer[] remainder = Arrays.copyOfRange(num, 1, num.length); Set<Integer[]> subPerms = getPermutationsRecursive(remainder); for (Integer[] subPerm : subPerms) { for (int i = 0; i <= subPerm.length; ++i) { // '<=' IMPORTANT !!! Integer[] newPerm = Arrays.copyOf(subPerm, subPerm.length + 1); for (int j = newPerm.length - 1; j > i; --j) { newPerm[j] = newPerm[j - 1]; } newPerm[i] = first; perms.add(newPerm); } } return perms; } public class SuffixArray { /* // Usage: SuffixArray sf = new SuffixArray(); String s1 = "abcab"; int[] sa1 = sf.suffixArray(s1); // print suffixes in lexicographic order for (int p : sa1) { System.out.println(s1.substring(p)); } System.out.println("lcp = " + Arrays.toString(sf.lcp(sa1, s1))); */ // sort suffixes of S in O(n*log(n)) public int[] suffixArray(CharSequence S) { int n = S.length(); Integer[] order = new Integer[n]; for (int i = 0; i < n; i++) { order[i] = n - 1 - i; } // stable sort of characters Arrays.sort(order, (a, b) -> Character.compare(S.charAt(a), S.charAt(b))); int[] sa = new int[n]; int[] classes = new int[n]; for (int i = 0; i < n; i++) { sa[i] = order[i]; classes[i] = S.charAt(i); } // sa[i] - suffix on i'th position after sorting by first len characters // classes[i] - equivalence class of the i'th suffix after sorting by first len characters for (int len = 1; len < n; len *= 2) { int[] c = classes.clone(); for (int i = 0; i < n; i++) { // condition sa[i - 1] + len < n simulates 0-symbol at the end of the string // a separate class is created for each suffix followed by simulated 0-symbol classes[sa[i]] = i > 0 && c[sa[i - 1]] == c[sa[i]] && sa[i - 1] + len < n && c[sa[i - 1] + len / 2] == c[sa[i] + len / 2] ? classes[sa[i - 1]] : i; } // Suffixes are already sorted by first len characters // Now sort suffixes by first len * 2 characters int[] cnt = new int[n]; for (int i = 0; i < n; i++) { cnt[i] = i; } int[] s = sa.clone(); for (int i = 0; i < n; i++) { // s[i] - order of suffixes sorted by first len characters // (s[i] - len) - order of suffixes sorted only by second len characters int s1 = s[i] - len; // sort only suffixes of length > len, others are already sorted if (s1 >= 0) { sa[cnt[classes[s1]]++] = s1; } } } return sa; } // sort rotations of S in O(n*log(n)) public int[] rotationArray(CharSequence S) { int n = S.length(); Integer[] order = new Integer[n]; for (int i = 0; i < n; i++) { order[i] = i; } Arrays.sort(order, (a, b) -> Character.compare(S.charAt(a), S.charAt(b))); int[] sa = new int[n]; int[] classes = new int[n]; for (int i = 0; i < n; i++) { sa[i] = order[i]; classes[i] = S.charAt(i); } for (int len = 1; len < n; len *= 2) { int[] c = classes.clone(); for (int i = 0; i < n; i++) { classes[sa[i]] = i > 0 && c[sa[i - 1]] == c[sa[i]] && c[(sa[i - 1] + len / 2) % n] == c[(sa[i] + len / 2) % n] ? classes[sa[i - 1]] : i; } int[] cnt = new int[n]; for (int i = 0; i < n; i++) { cnt[i] = i; } int[] s = sa.clone(); for (int i = 0; i < n; i++) { int s1 = (s[i] - len + n) % n; sa[cnt[classes[s1]]++] = s1; } } return sa; } // longest common prefixes array in O(n) public int[] lcp(int[] sa, CharSequence s) { int n = sa.length; int[] rank = new int[n]; for (int i = 0; i < n; i++) { rank[sa[i]] = i; } int[] lcp = new int[n - 1]; for (int i = 0, h = 0; i < n; i++) { if (rank[i] < n - 1) { for (int j = sa[rank[i] + 1]; Math.max(i, j) + h < s.length() && s.charAt(i + h) == s.charAt(j + h); ++h) { } lcp[rank[i]] = h; if (h > 0) { --h; } } } return lcp; } public void main() { String s1 = "abcab"; int[] sa1 = suffixArray(s1); // print suffixes in lexicographic order for (int p : sa1) { System.out.println(s1.substring(p)); } System.out.println("lcp = " + Arrays.toString(lcp(sa1, s1))); // random test Random rnd = new Random(1); for (int step = 0; step < 100000; step++) { int n = rnd.nextInt(100) + 1; StringBuilder s = new StringBuilder(); for (int i = 0; i < n; i++) { s.append((char) ('\1' + rnd.nextInt(10))); } int[] sa = suffixArray(s); int[] ra = rotationArray(s.toString() + '\0'); int[] lcp = lcp(sa, s); for (int i = 0; i + 1 < n; i++) { String a = s.substring(sa[i]); String b = s.substring(sa[i + 1]); if (a.compareTo(b) >= 0 || !a.substring(0, lcp[i]).equals(b.substring(0, lcp[i])) || (a + " ").charAt(lcp[i]) == (b + " ").charAt(lcp[i]) || sa[i] != ra[i + 1]) { throw new RuntimeException(); } } } System.out.println("Test passed"); } } class LazySegmentTree { final int MAX = 262146; int tree[] = new int[MAX]; int lazy[] = new int[MAX]; void updateRangeUtil(int si, int ss, int se, int us, int ue, int diff) { if (lazy[si] != 0) { tree[si] += (se - ss + 1) * lazy[si]; if (ss != se) { lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; } lazy[si] = 0; } if (ss > se || ss > ue || se < us) { return; } if (ss >= us && se <= ue) { tree[si] += (se - ss + 1) * diff; if (ss != se) { lazy[si * 2 + 1] += diff; lazy[si * 2 + 2] += diff; } return; } int mid = (ss + se) / 2; updateRangeUtil(si * 2 + 1, ss, mid, us, ue, diff); updateRangeUtil(si * 2 + 2, mid + 1, se, us, ue, diff); tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; } void updateRange(int n, int us, int ue, int diff) { updateRangeUtil(0, 0, n - 1, us, ue, diff); } int getSumUtil(int ss, int se, int qs, int qe, int si) { if (lazy[si] != 0) { tree[si] += (se - ss + 1) * lazy[si]; if (ss != se) { lazy[si * 2 + 1] += lazy[si]; lazy[si * 2 + 2] += lazy[si]; } lazy[si] = 0; } if (ss > se || ss > qe || se < qs) { return 0; } if (ss >= qs && se <= qe) { return tree[si]; } int mid = (ss + se) / 2; return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); } int getSum(int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { System.out.println("Invalid Input"); return -1; } return getSumUtil(0, n - 1, qs, qe, 0); } void constructSTUtil(int arr[], int ss, int se, int si) { // out of range as ss can never be greater than se if (ss > se) { return; } /* If there is one element in array, store it in current node of segment tree and return */ if (ss == se) { tree[si] = arr[ss]; return; } /* If there are more than one elements, then recur for left and right subtrees and store the sum of values in this node */ int mid = (ss + se) / 2; constructSTUtil(arr, ss, mid, si * 2 + 1); constructSTUtil(arr, mid + 1, se, si * 2 + 2); tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]; } void constructST(int arr[], int n) { // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, 0); } public void main() { int arr[] = {1, 3, 5, 7, 9, 11}; int n = arr.length; LazySegmentTree segTree = new LazySegmentTree(); // Build segment tree from given array segTree.constructST(arr, n); // Print sum of values in array from index 1 to 3 System.out.println("Sum of values in given range = " + segTree.getSum(n, 1, 3)); // Add 10 to all nodes at indexes from 1 to 5. segTree.updateRange(n, 1, 5, 10); // Find sum after the value is updated System.out.println("Updated sum of values in given range = " + segTree.getSum(n, 1, 3)); } } class DisjointUnionSets { int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each void makeSet() { for (int i = 0; i < n; i++) { // Initially, all elements are in // their own set. parent[i] = i; } } // Returns representative of x's set int find(int x) { // Finds the representative of the set // that x is an element of if (parent[x] != x) { // if x is not the parent of itself // Then x is not the representative of // his set, parent[x] = find(parent[x]); // so we recursively call Find on its parent // and move i's node directly under the // representative of this set } return parent[x]; } // Unites the set that includes x and the set // that includes x void union(int x, int y) { // Find representatives of two sets int xRoot = find(x), yRoot = find(y); // Elements are in the same set, no need // to unite anything. if (xRoot == yRoot) { return; } // If x's rank is less than y's rank if (rank[xRoot] < rank[yRoot]) // Then move x under y so that depth // of tree remains less { parent[xRoot] = yRoot; } // Else if y's rank is less than x's rank else if (rank[yRoot] < rank[xRoot]) // Then move y under x so that depth of // tree remains less { parent[yRoot] = xRoot; } else // if ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + 1; } } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
01d1343e66bc597f7282a3a2c7aedc50
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.util.*; import java.io.*; /** * * @author umang */ public class C380 { public static int mod = 1000000007; public static class SegmentTree { int[][] st; SegmentTree(String s, int n) { int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); int max_size = 2 * (int) Math.pow(2, x) - 1; st=new int[max_size][3]; constructSTUtil(s, 0, n - 1, 0); } int getMid(int s, int e) { return s + (e - s) / 2; } int[] getMaxUtil(int ss, int se, int qs, int qe, int si){ if (qs <= ss && qe >= se){ // System.out.println(" "+qs+" "+qe+" "+st[si][0]+" "+si); return st[si]; } if (se < qs || ss > qe) return null; int mid = getMid(ss, se); int[] a1=getMaxUtil(ss, mid, qs, qe, 2 * si + 1); int[] a2=getMaxUtil(mid + 1, se, qs, qe, 2 * si + 2); if(a1==null) return a2; else if(a2==null) return a1; int[] a=new int[3]; int t=min(a1[1],a2[2]); a[0]=a1[0]+a2[0]+t; a[1]=a1[1]+a2[1]-t; a[2]=a1[2]+a2[2]-t; return a; } int[] get(int n, int qs, int qe){ if (qs < 0 || qe > n - 1 || qs > qe) { return null; } return getMaxUtil(0, n - 1, qs, qe, 0); } int[] constructSTUtil(String s, int ss, int se, int si){ if (ss == se) { st[si][0]=st[si][1]=st[si][2]=0; if(s.charAt(ss)=='(') st[si][1]=1; else st[si][2]=1; return st[si]; } int mid = getMid(ss, se); int[] a1=constructSTUtil(s, ss, mid, si * 2 + 1); int[] a2=constructSTUtil(s, mid + 1, se, si * 2 + 2); int t=min(a1[1],a2[2]); st[si][0]=a1[0]+a2[0]+t; st[si][1]=a1[1]+a2[1]-t; st[si][2]=a1[2]+a2[2]-t; return st[si]; } } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); String s=in.readString(); SegmentTree st=new SegmentTree(s, s.length()); int q=in.nextInt(); for(int i=0;i<q;i++){ int l=in.nextInt()-1; int r=in.nextInt()-1; int[] p=st.get(s.length(), l, r); w.println(p[0]*2); } w.close(); } public static boolean isPal(String s){ for(int i=0, j=s.length()-1;i<=j;i++,j--){ if(s.charAt(i)!=s.charAt(j)) return false; } return true; } public static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } public static long gcd(long x,long y){ if(x%y==0) return y; else return gcd(y,x%y); } public static int gcd(int x,int y){ if(x%y==0) return y; else return gcd(y,x%y); } public static int abs(int a,int b){ return (int)Math.abs(a-b); } public static long abs(long a,long b){ return (long)Math.abs(a-b); } public static int max(int a,int b){ if(a>b) return a; else return b; } public static int min(int a,int b){ if(a>b) return b; else return a; } public static long max(long a,long b){ if(a>b) return a; else return b; } public static long min(long a,long b){ if(a>b) return b; else return a; } public static long pow(long n,long p,long m){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static class Pair{ int x; int y; int z; Pair(int x,int y,int z){ this.x=x; this.y=y; this.z=z; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(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; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
b9de74b4d0e3fec6e60ad5a40365c943
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.*; import java.nio.charset.StandardCharsets; import java.util.StringTokenizer; import static java.lang.System.currentTimeMillis; public class Algo9 { public static char[] s; public static int m; //public static int[][] a; public static int output; public static int[][] t; //public static String[] answer; public static int[] sum_intervals(int[] arr1, int[] arr2) { int[] ret = new int[3]; if (arr1[0] >= arr2[1]) { ret[0] = arr1[0] + arr2[0] - arr2[1]; ret[1] = arr1[1]; ret[2] = arr2[1] + arr1[2] + arr2[2]; } else { ret[0] = arr2[0]; ret[1] = arr1[1] + arr2[1] - arr1[0]; ret[2] = arr1[0] + arr1[2] + arr2[2]; } return ret; } public static void build (char[] s, int v, int tl, int tr) { if (tl == tr) { if (s[tl] == '(') { t[v][0] = 1; //t[v][1] = 0; //t[v][2] = 0; } else { //t[v][0] = 0; t[v][1] = 1; //t[v][2] = 0; } } else { int tm = (tl + tr) / 2; build (s, v*2, tl, tm); build (s, v*2+1, tm+1, tr); t[v] = sum_intervals(t[v<<1],t[(v<<1)+1]); } } public static int[] sum(int v, int tl, int tr, int l, int r) { if (l > r) { int[] ret = {0,0,0}; //ret = new int[] {0,0,0}; return ret; } if (l == tl && r == tr) return t[v]; int tm = (tl + tr) >> 1; return sum_intervals(sum (v<<1, tl, tm, l, Math.min(r,tm)),sum ((v<<1)+1, tm+1, tr, Math.max(l,tm+1), r)); } public static void main(String[] args) throws IOException { BufferedReader sc = new BufferedReader(new InputStreamReader(System.in), 8192*8); s = sc.readLine().toCharArray(); long t1 = currentTimeMillis(); //s = new char[1000000]; //for(int j=0; j<1000000;j++) //{s[j] = '(';} m = Integer.parseInt(sc.readLine()); //m = 100000; StringTokenizer b; int n = s.length; int N = 1; while (Math.pow(2,N) < 2*n) { N = N + 1; } t = new int[(int) Math.pow(2,N)][3]; build(s,1,0,n-1); //answer = new String[m]; //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); BufferedOutputStream bw = new BufferedOutputStream(System.out); for(int i=0;i<m;i++) { b = new StringTokenizer(sc.readLine()," "); //b = new StringTokenizer("233 999545"," "); output = sum(1, 0, n - 1, Integer.parseInt(b.nextToken()) - 1, Integer.parseInt(b.nextToken()) - 1)[2]*2; //answer[i] = String.valueOf((Integer.toString(output) + "\n").getBytes(StandardCharsets.UTF_8)); bw.write((Integer.toString(output)+"\n").getBytes(StandardCharsets.UTF_8)); //bw.write("\n".getBytes(StandardCharsets.UTF_8)); } bw.flush(); //bw.close(); long t2 = currentTimeMillis(); //System.out.println(String.valueOf(currentTimeMillis() * 1000)); //System.out.println(String.valueOf(t2-t1)); //bw.write(answer); //System.out.println("finish"); //System.out.println("finish2"); } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
bf215ff4f950810bbec463b2fdb8cea0
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.*; import java.util.*; public class jkl{ static int seg[]; public static void main(String args[]){ Scan sc=new Scan(System.in); char ch[]=sc.next().toCharArray(); int n=ch.length; int dp[]=new int[n+1]; seg=new int[4*n+1]; for(int i=0;i<n;i++){ dp[i+1]=dp[i]; if(ch[i]=='(') dp[i+1]++; else dp[i+1]--; } // for(int i:dp) // System.out.print(i+" "); // System.out.println(query(0,n-1,)); build(0,n,0,dp); StringBuilder sb=new StringBuilder(); int m=sc.nextInt(); while(m-->0){ int x=sc.nextInt(); int y=sc.nextInt(); int ans=y-x+1; int temp=query(0,n,x,y,0); temp-=dp[x-1]; int temp1=dp[y]-dp[x-1]; if(temp<0) {ans+=temp; temp1-=temp; } if(temp1>0){ ans-=temp1; } sb.append(ans+"\n"); } System.out.println(sb.toString()); } public static void build(int l,int r,int pos,int arr[]){ if(l==r) {seg[pos]=arr[l];return;} int m=(l+r)/2; build(l,m,2*pos+1,arr); build(m+1,r,2*pos+2,arr); seg[pos]=Math.min(seg[2*pos+1],seg[2*pos+2]); } public static int query(int l,int r,int ql,int qr,int pos){ if(ql>r || qr<l) return Integer.MAX_VALUE; if(ql<=l && qr>=r) return seg[pos]; int m=(l+r)/2; return Math.min(query(l,m,ql,qr,2*pos+1),query(m+1,r,ql,qr,2*pos+2)); } static class Scan { StringTokenizer st; BufferedReader br; public Scan(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } ; } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
3414773f564970b2cc7ef81848b532cb
train_001.jsonl
1389540600
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.
256 megabytes
import java.io.*; import java.util.*; public class SerejaAndBrackets{ static int[] tree; static int n; static void build(int[] aa) { for (int i = 0; i < n; i++) tree[n + i] = aa[i]; for (int i = n - 1; i > 0; i--) tree[i] = Math.min(tree[i << 1] , tree[i << 1 | 1]); } static int query(int l, int r) { int a = 0x3f3f3f3f; for (l += n, r += n; l <= r; l >>= 1, r >>= 1) { if ((l & 1) == 1) a = Math.min(a, tree[l++]); if ((r & 1) == 0) a = Math.min(a, tree[r--]); } return a; } public static void main(String[] args) throws IOException { BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); char[] bracket = br.readLine().toCharArray(); n = bracket.length + 1; int[] aa = new int[n]; int a = 0; for (int i = 1; i < n; i++) { if (bracket[i - 1] == '(') a++; else a--; aa[i] = a; } tree = new int[n + n]; build(aa); int q = Integer.parseInt(br.readLine()); while (q-- > 0) { StringTokenizer st= new StringTokenizer(br.readLine()); int left = Integer.parseInt(st.nextToken()) - 1; int right = Integer.parseInt(st.nextToken()); a = query(left, right); System.out.println(right - left - (aa[left] - a) - (aa[right] - a)); } } }
Java
["())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10"]
1 second
["0\n0\n2\n10\n4\n6\n6"]
NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 &lt; k2 &lt; ... &lt; k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be Ā«()Ā».For the fourth query required sequence will be Ā«()(())(())Ā».
Java 8
standard input
[ "data structures", "schedules" ]
a3e88504793c44fb3110a322d9dbdf17
The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.
2,000
Print the answer to each question on a single line. Print the answers in the order they go in the input.
standard output
PASSED
0556287b455b35d9406fa524d7c548e5
train_001.jsonl
1587911700
You are given an array $$$a$$$ consisting of $$$n$$$ elements. You may apply several operations (possibly zero) to it.During each operation, you choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$; $$$i \ne j$$$), increase $$$a_j$$$ by $$$a_i$$$, and remove the $$$i$$$-th element from the array (so the indices of all elements to the right to it decrease by $$$1$$$, and $$$n$$$ also decreases by $$$1$$$).Your goal is to make the array $$$a$$$ strictly ascending. That is, the condition $$$a_1 &lt; a_2 &lt; \dots &lt; a_n$$$ should hold (where $$$n$$$ is the resulting size of the array).Calculate the minimum number of actions required to make the array strictly ascending.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); FMakeItAscending solver = new FMakeItAscending(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } static class FMakeItAscending { int inf = (int) 1e9; int[][][] dp = new int[16][15][1 << 15]; int[][][] lastJ = new int[16][15][1 << 15]; int[][][] lastS = new int[16][15][1 << 15]; int[] a = new int[15]; int[] sum = new int[1 << 15]; Debug debug = new Debug(true); public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); for (int i = 0; i < n; i++) { a[i] = in.readInt(); } int mask = (1 << n) - 1; for (int i = 1; i <= n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k <= mask; k++) { dp[i][j][k] = -1; } } } sum[0] = 0; for (int i = 1; i <= mask; i++) { int log = Log2.floorLog(Integer.lowestOneBit(i)); sum[i] = sum[i - (1 << log)] + a[log]; } int ansI = -1; int ansJ = -1; for (int i = n; i >= 1 && ansI == -1; i--) { for (int j = 0; j < n && ansI == -1; j++) { if (dp(i, j, mask - (1 << j)) == inf) { continue; } ansI = i; ansJ = j; } } out.println(n - ansI); int s = mask - (1 << ansJ); IntegerBIT bit = new IntegerBIT(n); for (int i = 1; i <= n; i++) { bit.update(i, 1); } while (ansI > 0) { int ls = lastS[ansI][ansJ][s]; int lj = lastJ[ansI][ansJ][s]; int x = s - ls; if (ansI > 1) { x -= (1 << lj); } if (s < 0) { throw new RuntimeException(); } debug.debug("j", ansJ); debug.debug("s", Integer.toString(s, 2)); for (int i = 0; i < n; i++) { if (Bits.bitAt(x, i) == 0) { continue; } out.append(bit.query(i + 1)).append(' ').append(bit.query(ansJ + 1)).println(); bit.update(i + 1, -1); } s = ls; ansJ = lj; ansI--; } } public int dp(int i, int j, int k) { if (i == 0) { return k == 0 ? 0 : inf; } if (dp[i][j][k] == -1) { dp[i][j][k] = inf; lastJ[i][j][k] = -1; lastS[i][j][k] = -1; if (Integer.bitCount(k) + 1 < i || Bits.bitAt(k, j) == 1) { return dp[i][j][k]; } if (i == 1) { lastS[i][j][k] = 0; lastJ[i][j][k] = 0; return dp[i][j][k] = sum[k + (1 << j)]; } if (j == 0) { return dp[i][j][k]; } for (int t = i - 2; t < j; t++) { if (Bits.bitAt(k, t) == 0) { continue; } int remain = k - (1 << t); for (int x = remain; ; x = (x - 1) & remain) { int s = sum[(remain - x) | (1 << j)]; if (!(s >= dp[i][j][k] || dp(i - 1, t, x) >= s)) { dp[i][j][k] = s; lastJ[i][j][k] = t; lastS[i][j][k] = x; } if (x == 0) { break; } } } } return dp[i][j][k]; } } static class Debug { private boolean offline; private PrintStream out = System.err; public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public Debug debug(String name, int x) { if (offline) { debug(name, "" + x); } return this; } public Debug debug(String name, String x) { if (offline) { out.printf("%s=%s", name, x); out.println(); } return this; } } static class FastInput { private final InputStream is; private StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private byte[] buf = new byte[1 << 20]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public String next() { return readString(); } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } } static class Bits { private Bits() { } public static int bitAt(int x, int i) { return (x >>> i) & 1; } } static class IntegerBIT { private int[] data; private int n; public IntegerBIT(int n) { this.n = n; data = new int[n + 1]; } public int query(int i) { int sum = 0; for (; i > 0; i -= i & -i) { sum += data[i]; } return sum; } public void update(int i, int mod) { if (i <= 0) { return; } for (; i <= n; i += i & -i) { data[i] += mod; } } public String toString() { StringBuilder builder = new StringBuilder(); for (int i = 1; i <= n; i++) { builder.append(query(i) - query(i - 1)).append(' '); } return builder.toString(); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(int c) { cache.append(c); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class Log2 { public static int floorLog(int x) { return 31 - Integer.numberOfLeadingZeros(x); } } }
Java
["4\n8\n2 1 3 5 1 2 4 5\n15\n16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1\n2\n3 3\n14\n1 2 3 4 5 6 7 8 9 10 11 12 13 14"]
7 seconds
["3\n6 8\n1 6\n4 1\n7\n1 15\n1 13\n1 11\n1 9\n1 7\n1 5\n1 3\n1\n2 1\n0"]
NoteIn the first test case, the sequence of operations changes $$$a$$$ as follows:$$$[2, 1, 3, 5, 1, 2, 4, 5] \rightarrow [2, 1, 3, 5, 1, 4, 7] \rightarrow [1, 3, 5, 1, 6, 7] \rightarrow [2, 3, 5, 6, 7]$$$.
Java 8
standard input
[ "dp", "bitmasks", "brute force" ]
2ff113d7c71c6e91c8254cbdaf27e9ae
The first line contains one integer $$$T$$$ ($$$1 \le T \le 10000$$$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$1 \le n \le 15$$$) — the number of elements in the initial array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^6$$$). It is guaranteed that: the number of test cases having $$$n \ge 5$$$ is not greater than $$$5000$$$; the number of test cases having $$$n \ge 8$$$ is not greater than $$$500$$$; the number of test cases having $$$n \ge 10$$$ is not greater than $$$100$$$; the number of test cases having $$$n \ge 11$$$ is not greater than $$$50$$$; the number of test cases having $$$n \ge 12$$$ is not greater than $$$25$$$; the number of test cases having $$$n \ge 13$$$ is not greater than $$$10$$$; the number of test cases having $$$n \ge 14$$$ is not greater than $$$3$$$; the number of test cases having $$$n \ge 15$$$ is not greater than $$$1$$$.
3,000
For each test case, print the answer as follows: In the first line, print $$$k$$$ — the minimum number of operations you have to perform. Then print $$$k$$$ lines, each containing two indices $$$i$$$ and $$$j$$$ for the corresponding operation. Note that the numeration of elements in the array changes after removing elements from it. If there are multiple optimal sequences of operations, print any one of them.
standard output
PASSED
f31796e72e61c826527d68c2adf022e6
train_001.jsonl
1587911700
You are given an array $$$a$$$ consisting of $$$n$$$ elements. You may apply several operations (possibly zero) to it.During each operation, you choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$; $$$i \ne j$$$), increase $$$a_j$$$ by $$$a_i$$$, and remove the $$$i$$$-th element from the array (so the indices of all elements to the right to it decrease by $$$1$$$, and $$$n$$$ also decreases by $$$1$$$).Your goal is to make the array $$$a$$$ strictly ascending. That is, the condition $$$a_1 &lt; a_2 &lt; \dots &lt; a_n$$$ should hold (where $$$n$$$ is the resulting size of the array).Calculate the minimum number of actions required to make the array strictly ascending.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); FMakeItAscending solver = new FMakeItAscending(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } static class FMakeItAscending { int inf = (int) 1e9; int[][][] dp = new int[16][15][1 << 15]; int[][][] lastJ = new int[16][15][1 << 15]; int[][][] lastS = new int[16][15][1 << 15]; int[] a = new int[15]; int[] sum = new int[1 << 15]; Debug debug = new Debug(true); public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); for (int i = 0; i < n; i++) { a[i] = in.readInt(); } int mask = (1 << n) - 1; for (int i = 1; i <= n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k <= mask; k++) { dp[i][j][k] = -1; } } } sum[0] = 0; for (int i = 1; i <= mask; i++) { int log = CachedLog2.floorLog(Integer.lowestOneBit(i)); sum[i] = sum[i - (1 << log)] + a[log]; } int ansI = -1; int ansJ = -1; for (int i = n; i >= 1 && ansI == -1; i--) { for (int j = 0; j < n && ansI == -1; j++) { if (dp(i, j, mask - (1 << j)) == inf) { continue; } ansI = i; ansJ = j; } } out.println(n - ansI); int s = mask - (1 << ansJ); IntegerBIT bit = new IntegerBIT(n); for (int i = 1; i <= n; i++) { bit.update(i, 1); } while (ansI > 0) { int ls = lastS[ansI][ansJ][s]; int lj = lastJ[ansI][ansJ][s]; int x = s - ls; if (ansI > 1) { x -= (1 << lj); } if (s < 0) { throw new RuntimeException(); } debug.debug("j", ansJ); debug.debug("s", Integer.toString(s, 2)); for (int i = 0; i < n; i++) { if (Bits.bitAt(x, i) == 0) { continue; } out.append(bit.query(i + 1)).append(' ').append(bit.query(ansJ + 1)).println(); bit.update(i + 1, -1); } s = ls; ansJ = lj; ansI--; } } public int dp(int i, int j, int k) { if (i == 0) { return k == 0 ? 0 : inf; } if (dp[i][j][k] == -1) { dp[i][j][k] = inf; lastJ[i][j][k] = -1; lastS[i][j][k] = -1; if (CachedBitCount.bitCount(k) + 1 < i || Bits.bitAt(k, j) == 1) { return dp[i][j][k]; } if (i == 1) { lastS[i][j][k] = 0; lastJ[i][j][k] = 0; return dp[i][j][k] = sum[k + (1 << j)]; } if (j == 0) { return dp[i][j][k]; } for (int t = i - 2; t < j; t++) { if (Bits.bitAt(k, t) == 0) { continue; } int remain = k - (1 << t); for (int x = remain; ; x = (x - 1) & remain) { int s = sum[(remain - x) | (1 << j)]; if (!(s >= dp[i][j][k] || dp(i - 1, t, x) >= s)) { dp[i][j][k] = s; lastJ[i][j][k] = t; lastS[i][j][k] = x; } if (x == 0) { break; } } } } return dp[i][j][k]; } } static class Debug { private boolean offline; private PrintStream out = System.err; public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public Debug debug(String name, int x) { if (offline) { debug(name, "" + x); } return this; } public Debug debug(String name, String x) { if (offline) { out.printf("%s=%s", name, x); out.println(); } return this; } } static class FastInput { private final InputStream is; private StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private byte[] buf = new byte[1 << 20]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public String next() { return readString(); } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } } static class Bits { private Bits() { } public static int bitAt(int x, int i) { return (x >>> i) & 1; } } static class CachedLog2 { private static final int BITS = 16; private static final int LIMIT = 1 << BITS; private static final byte[] CACHE = new byte[LIMIT]; static { int b = 0; for (int i = 0; i < LIMIT; i++) { while ((1 << (b + 1)) <= i) { b++; } CACHE[i] = (byte) b; } } public static int floorLog(int x) { return x < LIMIT ? CACHE[x] : (BITS + CACHE[x >>> BITS]); } } static class CachedBitCount { private static final int BITS = 16; private static final int LIMIT = 1 << BITS; private static final int MASK = LIMIT - 1; private static final byte[] CACHE = new byte[LIMIT]; static { for (int i = 1; i < LIMIT; i++) { CACHE[i] = (byte) (CACHE[i - (i & -i)] + 1); } } public static int bitCount(int x) { return CACHE[x & MASK] + CACHE[(x >>> 16) & MASK]; } } static class IntegerBIT { private int[] data; private int n; public IntegerBIT(int n) { this.n = n; data = new int[n + 1]; } public int query(int i) { int sum = 0; for (; i > 0; i -= i & -i) { sum += data[i]; } return sum; } public void update(int i, int mod) { if (i <= 0) { return; } for (; i <= n; i += i & -i) { data[i] += mod; } } public String toString() { StringBuilder builder = new StringBuilder(); for (int i = 1; i <= n; i++) { builder.append(query(i) - query(i - 1)).append(' '); } return builder.toString(); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(int c) { cache.append(c); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } }
Java
["4\n8\n2 1 3 5 1 2 4 5\n15\n16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1\n2\n3 3\n14\n1 2 3 4 5 6 7 8 9 10 11 12 13 14"]
7 seconds
["3\n6 8\n1 6\n4 1\n7\n1 15\n1 13\n1 11\n1 9\n1 7\n1 5\n1 3\n1\n2 1\n0"]
NoteIn the first test case, the sequence of operations changes $$$a$$$ as follows:$$$[2, 1, 3, 5, 1, 2, 4, 5] \rightarrow [2, 1, 3, 5, 1, 4, 7] \rightarrow [1, 3, 5, 1, 6, 7] \rightarrow [2, 3, 5, 6, 7]$$$.
Java 8
standard input
[ "dp", "bitmasks", "brute force" ]
2ff113d7c71c6e91c8254cbdaf27e9ae
The first line contains one integer $$$T$$$ ($$$1 \le T \le 10000$$$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$1 \le n \le 15$$$) — the number of elements in the initial array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^6$$$). It is guaranteed that: the number of test cases having $$$n \ge 5$$$ is not greater than $$$5000$$$; the number of test cases having $$$n \ge 8$$$ is not greater than $$$500$$$; the number of test cases having $$$n \ge 10$$$ is not greater than $$$100$$$; the number of test cases having $$$n \ge 11$$$ is not greater than $$$50$$$; the number of test cases having $$$n \ge 12$$$ is not greater than $$$25$$$; the number of test cases having $$$n \ge 13$$$ is not greater than $$$10$$$; the number of test cases having $$$n \ge 14$$$ is not greater than $$$3$$$; the number of test cases having $$$n \ge 15$$$ is not greater than $$$1$$$.
3,000
For each test case, print the answer as follows: In the first line, print $$$k$$$ — the minimum number of operations you have to perform. Then print $$$k$$$ lines, each containing two indices $$$i$$$ and $$$j$$$ for the corresponding operation. Note that the numeration of elements in the array changes after removing elements from it. If there are multiple optimal sequences of operations, print any one of them.
standard output
PASSED
21c0161ffdd3c08ecc92281709310c89
train_001.jsonl
1587911700
You are given an array $$$a$$$ consisting of $$$n$$$ elements. You may apply several operations (possibly zero) to it.During each operation, you choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$; $$$i \ne j$$$), increase $$$a_j$$$ by $$$a_i$$$, and remove the $$$i$$$-th element from the array (so the indices of all elements to the right to it decrease by $$$1$$$, and $$$n$$$ also decreases by $$$1$$$).Your goal is to make the array $$$a$$$ strictly ascending. That is, the condition $$$a_1 &lt; a_2 &lt; \dots &lt; a_n$$$ should hold (where $$$n$$$ is the resulting size of the array).Calculate the minimum number of actions required to make the array strictly ascending.
512 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class template { public static void main(String[] args) throws Exception { new template().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int asdf = f.nextInt(); int[][][] dp = new int[1 << 15][15][15]; int[][][] prev1 = new int[1 << 15][15][15]; int[][][] prev2 = new int[1 << 15][15][15]; int[][] npos = new int[1 << 15][15]; for(int i = 0; i < 1 << 15; i++) { npos[i][14] = -1; for(int a = 14; a >= 0; a--) if((i & (1 << a)) != 0) npos[i][a] = a; else if(a != 14) npos[i][a] = npos[i][a+1]; } while(asdf-->0) { int[] sum = new int[1 << 15]; int n = f.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = f.nextInt(); LinkedList<Integer> ll = new LinkedList<>(); for(int i = 1; i < 1 << n; i++) { for(int j = 0; j < n; j++) for(int k = 0; k < n; k++) dp[i][j][k] = 2147483647; int pos = -1; for(int b = 0; b < n; b++) if((i&1<<b) != 0) { sum[i] += arr[b]; if(pos == -1) pos = b; } dp[i][0][pos] = sum[i]; prev1[i][0][pos] = i; ll.add(i); ll.add(0); ll.add(pos); } int bj = 0, bk = 0; while(!ll.isEmpty()) { int i = ll.pollFirst(); int j = ll.pollFirst(); int k = ll.pollFirst(); int v = dp[i][j][k]; int m = ((1 << n)-1)^i; int ni = m; while(ni != 0) { if(sum[ni] > v && npos[ni][k] != -1) { if(dp[i|ni][j+1][npos[ni][k]] == 2147483647) { ll.add(i|ni); ll.add(j+1); ll.add(npos[ni][k]); } if(dp[i|ni][j+1][npos[ni][k]] > sum[ni]) { dp[i|ni][j+1][npos[ni][k]] = sum[ni]; prev1[i|ni][j+1][npos[ni][k]] = ni; prev2[i|ni][j+1][npos[ni][k]] = k; } } ni = (ni-1)&m; } if(m == 0) { bj = j; bk = k; } } int bi = (1 << n) - 1; out.println(n-bj-1); int[] pos = new int[n]; for(int i = 0; i < n; i++) pos[i] = i+1; while(bi != 0) { int ni = prev1[bi][bj][bk]; int nk = prev2[bi][bj][bk]; for(int i = 0; i < 15; i++) if((1 << i & ni) != 0 && i != bk) { out.println(pos[i]+ " " + pos[bk]); for(int j = i; j < n; j++) pos[j]--; } bi ^= ni; bj--; bk = nk; } } out.flush(); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 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()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["4\n8\n2 1 3 5 1 2 4 5\n15\n16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1\n2\n3 3\n14\n1 2 3 4 5 6 7 8 9 10 11 12 13 14"]
7 seconds
["3\n6 8\n1 6\n4 1\n7\n1 15\n1 13\n1 11\n1 9\n1 7\n1 5\n1 3\n1\n2 1\n0"]
NoteIn the first test case, the sequence of operations changes $$$a$$$ as follows:$$$[2, 1, 3, 5, 1, 2, 4, 5] \rightarrow [2, 1, 3, 5, 1, 4, 7] \rightarrow [1, 3, 5, 1, 6, 7] \rightarrow [2, 3, 5, 6, 7]$$$.
Java 8
standard input
[ "dp", "bitmasks", "brute force" ]
2ff113d7c71c6e91c8254cbdaf27e9ae
The first line contains one integer $$$T$$$ ($$$1 \le T \le 10000$$$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$1 \le n \le 15$$$) — the number of elements in the initial array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^6$$$). It is guaranteed that: the number of test cases having $$$n \ge 5$$$ is not greater than $$$5000$$$; the number of test cases having $$$n \ge 8$$$ is not greater than $$$500$$$; the number of test cases having $$$n \ge 10$$$ is not greater than $$$100$$$; the number of test cases having $$$n \ge 11$$$ is not greater than $$$50$$$; the number of test cases having $$$n \ge 12$$$ is not greater than $$$25$$$; the number of test cases having $$$n \ge 13$$$ is not greater than $$$10$$$; the number of test cases having $$$n \ge 14$$$ is not greater than $$$3$$$; the number of test cases having $$$n \ge 15$$$ is not greater than $$$1$$$.
3,000
For each test case, print the answer as follows: In the first line, print $$$k$$$ — the minimum number of operations you have to perform. Then print $$$k$$$ lines, each containing two indices $$$i$$$ and $$$j$$$ for the corresponding operation. Note that the numeration of elements in the array changes after removing elements from it. If there are multiple optimal sequences of operations, print any one of them.
standard output
PASSED
c5896bdb8ba077c3ea3fd040764e14ea
train_001.jsonl
1587911700
You are given an array $$$a$$$ consisting of $$$n$$$ elements. You may apply several operations (possibly zero) to it.During each operation, you choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$; $$$i \ne j$$$), increase $$$a_j$$$ by $$$a_i$$$, and remove the $$$i$$$-th element from the array (so the indices of all elements to the right to it decrease by $$$1$$$, and $$$n$$$ also decreases by $$$1$$$).Your goal is to make the array $$$a$$$ strictly ascending. That is, the condition $$$a_1 &lt; a_2 &lt; \dots &lt; a_n$$$ should hold (where $$$n$$$ is the resulting size of the array).Calculate the minimum number of actions required to make the array strictly ascending.
512 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class template { public static void main(String[] args) throws Exception { new template().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int asdf = f.nextInt(); int[][][] dp = new int[1 << 15][15][15]; int[][][] prev1 = new int[1 << 15][15][15]; int[][][] prev2 = new int[1 << 15][15][15]; int[][] npos = new int[1 << 15][15]; for(int i = 0; i < 1 << 15; i++) { npos[i][14] = -1; for(int a = 14; a >= 0; a--) if((i & (1 << a)) != 0) npos[i][a] = a; else if(a != 14) npos[i][a] = npos[i][a+1]; } while(asdf-->0) { int[] sum = new int[1 << 15]; int n = f.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = f.nextInt(); LinkedList<Integer> ll = new LinkedList<>(); for(int i = 1; i < 1 << n; i++) { for(int j = 0; j < n; j++) for(int k = 0; k < n; k++) dp[i][j][k] = 2147483647; int pos = -1; for(int b = 0; b < n; b++) if((i&1<<b) != 0) { sum[i] += arr[b]; if(pos == -1) pos = b; } dp[i][0][pos] = sum[i]; prev1[i][0][pos] = i; ll.add(i); ll.add(0); ll.add(pos); } int bj = 0, bk = 0; while(!ll.isEmpty()) { int i = ll.pollFirst(); int j = ll.pollFirst(); int k = ll.pollFirst(); int v = dp[i][j][k]; int m = ((1 << n)-1)^i; int ni = m; while(ni != 0) { if(sum[ni] > v && npos[ni][k] != -1) { if(dp[i|ni][j+1][npos[ni][k]] == 2147483647) { ll.add(i|ni); ll.add(j+1); ll.add(npos[ni][k]); } if(dp[i|ni][j+1][npos[ni][k]] > sum[ni]) { dp[i|ni][j+1][npos[ni][k]] = sum[ni]; prev1[i|ni][j+1][npos[ni][k]] = ni; prev2[i|ni][j+1][npos[ni][k]] = k; } } ni = (ni-1)&m; } if(m == 0) { bj = j; bk = k; } } int bi = (1 << n) - 1; out.println(n-bj-1); int[] pos = new int[n]; for(int i = 0; i < n; i++) pos[i] = i+1; while(bi != 0) { int ni = prev1[bi][bj][bk]; int nk = prev2[bi][bj][bk]; for(int i = 0; i < 15; i++) if((1 << i & ni) != 0 && i != bk) { out.println(pos[i]+ " " + pos[bk]); for(int j = i; j < n; j++) pos[j]--; } bi ^= ni; bj--; bk = nk; } } out.flush(); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 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()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["4\n8\n2 1 3 5 1 2 4 5\n15\n16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1\n2\n3 3\n14\n1 2 3 4 5 6 7 8 9 10 11 12 13 14"]
7 seconds
["3\n6 8\n1 6\n4 1\n7\n1 15\n1 13\n1 11\n1 9\n1 7\n1 5\n1 3\n1\n2 1\n0"]
NoteIn the first test case, the sequence of operations changes $$$a$$$ as follows:$$$[2, 1, 3, 5, 1, 2, 4, 5] \rightarrow [2, 1, 3, 5, 1, 4, 7] \rightarrow [1, 3, 5, 1, 6, 7] \rightarrow [2, 3, 5, 6, 7]$$$.
Java 8
standard input
[ "dp", "bitmasks", "brute force" ]
2ff113d7c71c6e91c8254cbdaf27e9ae
The first line contains one integer $$$T$$$ ($$$1 \le T \le 10000$$$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$1 \le n \le 15$$$) — the number of elements in the initial array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^6$$$). It is guaranteed that: the number of test cases having $$$n \ge 5$$$ is not greater than $$$5000$$$; the number of test cases having $$$n \ge 8$$$ is not greater than $$$500$$$; the number of test cases having $$$n \ge 10$$$ is not greater than $$$100$$$; the number of test cases having $$$n \ge 11$$$ is not greater than $$$50$$$; the number of test cases having $$$n \ge 12$$$ is not greater than $$$25$$$; the number of test cases having $$$n \ge 13$$$ is not greater than $$$10$$$; the number of test cases having $$$n \ge 14$$$ is not greater than $$$3$$$; the number of test cases having $$$n \ge 15$$$ is not greater than $$$1$$$.
3,000
For each test case, print the answer as follows: In the first line, print $$$k$$$ — the minimum number of operations you have to perform. Then print $$$k$$$ lines, each containing two indices $$$i$$$ and $$$j$$$ for the corresponding operation. Note that the numeration of elements in the array changes after removing elements from it. If there are multiple optimal sequences of operations, print any one of them.
standard output
PASSED
e3cd62a48451d29deb8ee98f43772335
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class pr1118C { static int[][] res = new int[25][25]; static int n; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int[] cnt = new int[1005]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int x = Integer.parseInt(st.nextToken()); cnt[x]++; } } solve(n, cnt, out); out.flush(); out.close(); } static boolean Find4(int x) { for (int i = 1; i <= n/2; i++) { for (int j = 1; j <= n/2; j++) { if(res[i][j] == 0){ res[i][j] = res[n-i+1][j] = res[n-i+1][n-j+1] = res[i][n-j+1] = x; return true; } } } return false; } static boolean Find2(int x) { if(n % 2 == 0) return false; for(int i = 1; i <= n/2; i++) if(res[i][n/2+1] == 0) { res[i][n/2+1]=res[n-i+1][n/2+1]=x; return true; } else if(res[n/2+1][i] == 0) { res[n/2+1][i] = res[n/2+1][n-i+1] = x; return true; } return false; } static boolean Find1(int x) { if(n%2 == 0 || res[n/2+1][n/2+1] != 0) return false; res[n/2+1][n/2+1] = x; return true; } private static void solve(int n, int[] cnt, PrintWriter out) { for (int i = 0; i < 1001; i++) { while(cnt[i] >= 4) { if(!Find4(i)) break; cnt[i] -= 4; } while(cnt[i] >= 2) { if(!Find2(i)) break; cnt[i] -= 2; } while(cnt[i] >0) { if(!Find1(i)) break; cnt[i]--; } if(cnt[i] > 0) { out.print("NO"); return; } } out.println("YES"); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { out.print(res[i][j] + " "); } out.println(); } } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
ac55353a7306d3ab7561abbcf05af91a
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; @SuppressWarnings("unchecked") public class Solution { // 22:25- public static void main(String[] args) throws IOException, InterruptedException { try (PrintStream out = new PrintStream(new BufferedOutputStream(System.out))) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); int n = sc.nextInt(); int[] cnts = new int[1001]; for (int i = 0; i < n * n; i++) cnts[sc.nextInt()]++; List<Integer> fours = new ArrayList<>(); List<Integer> twos = new ArrayList<>(); List<Integer> ones = new ArrayList<>(); for (int i = 0; i < cnts.length; i++) { int x = cnts[i]; for (int j = 0; j < x / 4; j++) fours.add(i); x %= 4; for (int j = 0; j < x / 2; j++) twos.add(i); x %= 2; if (x > 0) ones.add(i); } int[][] ret = new int[n][n]; if (n % 2 == 0) { if (!ones.isEmpty() || !twos.isEmpty()) { out.println("NO"); return; } } else if (ones.size() != 1 || twos.size() > (n / 2) * 2) { out.println("NO"); return; } out.println("YES"); for (int i = 0; i < (n + 1) / 2; i++) { for (int j = 0; j < (n + 1) / 2; j++) { int x; if (i == n / 2 && j == n / 2) { x = ones.remove(0); } else if (i != n / 2 && j != n / 2) { x = fours.remove(fours.size() - 1); } else if ((i == n / 2) ^ (j == n / 2)) { if (twos.isEmpty()) { int y = fours.remove(fours.size() - 1); twos.add(y); twos.add(y); } x = twos.remove(twos.size() - 1); } else { throw new AssertionError(); } ret[i][j] = ret[n - 1 - i][j] = ret[n - 1 - i][n - 1 - j] = ret[i][n - 1 - j] = x; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { out.print(ret[i][j] + " "); } out.println(); } } } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
6fe4fcd6f7d27e6c7fd12b7baa4a64f1
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; @SuppressWarnings("unchecked") public class Solution { // 22:25- public static void main(String[] args) throws IOException, InterruptedException { try (PrintStream out = new PrintStream(new BufferedOutputStream(System.out))) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); int n = sc.nextInt(); int[] cnts = new int[1001]; for (int i = 0; i < n * n; i++) cnts[sc.nextInt()]++; List<Integer> fours = new ArrayList<>(); List<Integer> twos = new ArrayList<>(); List<Integer> ones = new ArrayList<>(); for (int i = 0; i < cnts.length; i++) { int x = cnts[i]; for (int j = 0; j < x / 4; j++) fours.add(i); x %= 4; for (int j = 0; j < x / 2; j++) twos.add(i); x %= 2; if (x > 0) ones.add(i); } int[][] ret = new int[n][n]; if (n % 2 == 0) { if (!ones.isEmpty() || !twos.isEmpty()) { out.println("NO"); return; } } else if (ones.size() != 1 || twos.size() > (n / 2) * 2) { out.println("NO"); return; } out.println("YES"); for (int i = 0; i < (n + 1) / 2; i++) { for (int j = 0; j < (n + 1) / 2; j++) { if (i == n / 2 && j == n / 2) { ret[i][j] = ones.remove(0); } else if (i != n / 2 && j != n / 2) { int x = fours.remove(fours.size() - 1); ret[i][j] = ret[n - 1 - i][j] = ret[n - 1 - i][n - 1 - j] = ret[i][n - 1 - j] = x; } else if (i == n / 2) { if (twos.isEmpty()) { int x = fours.remove(fours.size() - 1); twos.add(x); twos.add(x); } int x = twos.remove(twos.size() - 1); ret[i][j] = ret[i][n - 1 - j] = x; } else if (j == n / 2) { if (twos.isEmpty()) { int x = fours.remove(fours.size() - 1); twos.add(x); twos.add(x); } int x = twos.remove(twos.size() - 1); ret[i][j] = ret[n - 1 - i][j] = x; } else { throw new AssertionError(); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { out.print(ret[i][j] + " "); } out.println(); } } } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
c44e189f999fd40ad6625d8ead531fd2
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.util.Scanner; public class C { static Scanner scanner = new Scanner(System.in); static int[] a; public static void main(String args[]) { int n = scanner.nextInt(); scanner.nextLine(); a = new int[1001]; for (int i = 0; i < n * n; i++) { int x = scanner.nextInt(); a[x]++; if (n == 1) { System.out.println("YES"); System.out.println(x); return; } } int ones = 0; int twos = 0; for (int i = 0; i < 1001; i++) { if (a[i] % 4 != 0) { if (a[i] % 2 == 0) { twos++; } else if (a[i] % 4 == 3) { twos++; ones++; } if (a[i] == 1) { ones++; } } } if (ones > 1) { System.out.println("NO"); return; } int[][] m = new int[n][n]; if (n % 2 == 0) { if (twos > 0) { System.out.println("NO"); return; } for (int i = 0; i < n / 2; i++) { // ROWS for (int j = 0; j < n / 2; j++) { int num = getNumber(); m[i][j] = num; m[n - i - 1][j] = num; m[i][n - j - 1] = num; m[n - i - 1][n - j - 1] = num; if (num != -1) a[num] -= 4; } } } else { int requiredTwos = (n - 1); for (int i = 0; i < n / 2; i++) { // ROWS for (int j = 0; j < n / 2; j++) { int num = getNumber(); m[i][j] = num; m[n - i - 1][j] = num; m[i][n - j - 1] = num; m[n - i - 1][n - j - 1] = num; if (num != -1) a[num] -= 4; } } for (int i = 0; i < n / 2; i++) { int num = getNumber2(); m[i][n / 2] = num; m[n - i - 1][n / 2] = num; a[num] -= 2; } for (int i = 0; i < n / 2; i++) { int num = getNumber2(); m[n / 2][i] = num; m[n / 2][n - i - 1] = num; if (num != -1) a[num] -= 2; } for (int i = 0; i < 1001; i++) { if (a[i] > 0) { m[n / 2][n / 2] = i; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (m[i][j] == -1) { System.out.println("NO"); return; } } } System.out.println("YES"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(m[i][j] + " "); } System.out.println(); } } private static int getNumber2() { for (int i = 0; i < 1001; i++) { if (a[i] >= 2) return i; } return -1; } private static int getNumber() { for (int i = 0; i < 1001; i++) { if (a[i] >= 4) return i; } return -1; } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
1356fceceb9b6a66dbbdf0b3e89a5907
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; /** * @author johnny16 * */ public class PalindromicMatrixMusin { /** * @param args */ static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public static IntIntPair makePair(int first, int second) { return new IntIntPair(first, second); } public IntIntPair(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int n, i, j; n = in.nextInt(); int a[] = new int[n * n]; int count[] = new int[1001]; for (i = 0; i < n * n; i++) { a[i] = in.nextInt(); count[a[i]]++; } List<Set<IntIntPair>> groups = new ArrayList<>(); boolean filled[][] = new boolean[n][n]; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (!filled[i][j]) { int i1 = n - 1 - i; int j1 = n - 1 - j; Set<IntIntPair> group = new HashSet<>(); group.add(IntIntPair.makePair(i, j)); group.add(IntIntPair.makePair(i1, j)); group.add(IntIntPair.makePair(i, j1)); group.add(IntIntPair.makePair(i1, j1)); groups.add(group); filled[i][j] = filled[i1][j] = filled[i][j1] = filled[i1][j1] = true; } } } groups.sort(Comparator.comparingInt(g -> -g.size())); int ans[][] = new int[n][n]; for (Set<IntIntPair> group : groups) { boolean flag = false; for (i = 0; i < count.length; i++) { if (count[i] >= group.size()) { for (IntIntPair p : group) { ans[p.first][p.second] = i; count[i]--; } flag = true; break; } } if (!flag) { System.out.println("NO"); return; } } System.out.println("YES"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { System.out.print(ans[i][j]+" "); } System.out.println(); } } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
61f45483e515fecb4868f95269520620
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; @SuppressWarnings("Duplicates") public class ProblemC { public static void main(String[] args) throws IOException{ Reader sc = new Reader(); PrintWriter pw = new PrintWriter(System.out); //Scanner sc = new Scanner(System.in); //BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int size = sc.nextInt(); int[][] matrix = new int[size][size]; HashMap<Integer,Integer> numbers = new HashMap<>(); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { int aux = sc.nextInt(); numbers.putIfAbsent(aux,0); numbers.computeIfPresent(aux,(integer, integer2) -> integer2+1); } } boolean can = true; boolean used = false; LinkedList<Integer> addMid = new LinkedList<>(); int midRow = (size/2)*2; int mid = -1; for (Map.Entry<Integer, Integer> value : numbers.entrySet()) { if (size%2==1&&(value.getValue() % 4 == 1||value.getValue() % 4 == 3 )&& used){ can=false; } if (size%2==1&&(value.getValue() % 4 == 1||value.getValue() % 4 == 3 )&& !used) { used = true; mid = value.getKey(); value.setValue(value.getValue()-1); } if (size%2==1&&value.getValue() % 4 == 2 && midRow == 0){ can=false; } if (size%2==1&&value.getValue() % 4 == 2 && midRow > 0) { midRow --; addMid.add(value.getKey()); value.setValue(value.getValue()-2); } can = can && value.getValue()%4==0; } if (size%2==1&&can&&used){ LinkedList<Integer> keys = new LinkedList<>(numbers.keySet()); for (int i = midRow; i > 0; i-=2) { while (numbers.get(keys.getFirst())==0){ keys.removeFirst(); } int val =keys.getFirst(); numbers.put(keys.getFirst(),numbers.get(keys.getFirst())-4); addMid.add(val); addMid.add(val); } pw.println("YES"); matrix[size/2][size/2]=mid; for (int i = 0; i < size / 2; i++) { for (int j = 0; j < size / 2; j++) { while (numbers.get(keys.getFirst())==0){ keys.removeFirst(); } int val =keys.getFirst(); numbers.put(keys.getFirst(),numbers.get(keys.getFirst())-4); matrix[i][j] = val; matrix[size-1-i][j]=val; matrix[i][size-1-j]=val; matrix[size-1-i][size-1-j]=val; } } for (int i = 0; i < size / 2; i++) { int val = addMid.removeFirst(); int val2 = addMid.removeFirst(); numbers.put(keys.getFirst(), numbers.get(keys.getFirst()) - 4); matrix[size / 2][i] = val; matrix[size / 2][size - i - 1] = val; matrix[i][size / 2] = val2; matrix[size - 1 - i][size / 2] = val2; } for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { pw.print(matrix[i][j]); if (j==size-1)pw.println(); else pw.print(' '); } } }else if(size%2==0&&can&&!used){ pw.println("YES"); LinkedList<Integer> keys = new LinkedList<>(numbers.keySet()); for (int i = 0; i < (size / 2); i++) { for (int j = 0; j < size / 2; j++) { while (numbers.get(keys.getFirst())==0){ keys.removeFirst(); } int val =keys.getFirst(); numbers.put(keys.getFirst(),numbers.get(keys.getFirst())-4); matrix[i][j] = val; matrix[size-1-i][j]=val; matrix[i][size-1-j]=val; matrix[size-1-i][size-1-j]=val; } } for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { pw.print(matrix[i][j]); if (j==size-1)pw.println(); else pw.print(' '); } } } else pw.println("NO"); pw.flush(); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
1456621c035936f2c24679d66c8c0198
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.util.*; import java.io.*; public class Solution { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main (String[] args) throws IOException { Reader in = new Reader(); int n, i, j, tmp, sq[][], center = -1, v; boolean flag = true; HashMap<Integer, Integer> a = new HashMap<Integer, Integer>(); n = in.nextInt(); sq = new int[n][n]; for(i=0; i<n*n; i++) { tmp = in.nextInt(); if(a.containsKey(tmp)) { a.put(tmp, ((int)a.get(tmp)+1)); } else a.put(tmp, 1); } tmp = 0; if(n%2 == 0) { for(Integer val : a.values()) { if(val%4 != 0) { flag = false; break; } } } else { for(Map.Entry<Integer, Integer> entry : a.entrySet()) { v = entry.getValue(); if((v%4 == 1) || (v%4 == 3)) { if(center == -1) center = entry.getKey(); else { flag = false; break; } } else if(v%4 == 2) { tmp++; if(tmp > (n-1)) { flag = false; break; } } } if(center == -1) flag = false; } System.out.println(flag? "Yes": "No"); if(flag) { if(n%2 == 0) { for(i=0; i<(n/2); i++) { for(j=0; j<(n/2); j++) { for(Map.Entry<Integer, Integer> entry : a.entrySet()) { sq[i][j] = sq[i][n-1-j] = sq[n-1-i][j] = sq[n-1-i][n-1-j] = entry.getKey(); if(entry.getValue()-4 == 0) a.remove(entry.getKey()); else a.put(entry.getKey(), (entry.getValue()-4)); break; } } } } else { sq[n/2][n/2] = center; if(a.get(center) == 1) a.remove(center); else a.put(center, (a.get(center)-1)); for(i=0; i<(n/2); i++) { for(j=0; j<(n/2); j++) { for(Map.Entry<Integer, Integer> entry : a.entrySet()) { if(entry.getValue() > 2) { sq[i][j] = sq[i][n-1-j] = sq[n-1-i][j] = sq[n-1-i][n-1-j] = entry.getKey(); if(entry.getValue()-4 == 0) a.remove(entry.getKey()); else a.put(entry.getKey(), (entry.getValue()-4)); break; } } } } for(i=0; i<(n/2); i++) { for(Map.Entry<Integer, Integer> entry : a.entrySet()) { sq[i][n/2] = sq[n-i-1][n/2] = entry.getKey(); if(entry.getValue()-2 == 0) a.remove(entry.getKey()); else a.put(entry.getKey(), (entry.getValue()-2)); break; } for(Map.Entry<Integer, Integer> entry : a.entrySet()) { sq[n/2][i] = sq[n/2][n-i-1] = entry.getKey(); if(entry.getValue()-2 == 0) a.remove(entry.getKey()); else a.put(entry.getKey(), (entry.getValue()-2)); break; } } } for(i=0; i<n; i++) { for(j=0; j<n; j++) System.out.print(sq[i][j] + " "); System.out.println(); } } } } /* 5 1 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 */
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
2537c37109cfbe50290be581db6b83d5
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.io.*; import java.util.*; public class C { static StringBuilder st = new StringBuilder(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in) ; PrintWriter out = new PrintWriter(System.out) ; int n = sc.nextInt() ; HashSet<Integer> set = new HashSet<>(); int [] freq = new int [1001] ; for(int i = 0 ; i < n*n ;i++) { int x = sc.nextInt() ; set.add(x) ; freq[x]++; } int sq = n / 2 ; if(n % 2 == 0) { boolean allDivs = true ; for(int x : set) allDivs &= freq[x] % 4 == 0 ; if(!allDivs || set.size() > sq * sq) { System.out.println("NO"); return ; } int [][] mat = new int [n][n] ; int [] elements = new int [sq*sq]; int idx = 0 ; for(int x : set) { int cnt = freq[x] / 4 ; while(cnt -->0) elements[idx++] = x ; } idx = 0 ; for(int i = 0 ; i < sq ; i++) for(int j = 0 ; j < sq ; j++) mat[i][j] = elements[idx++]; for(int i = 0 ; i < sq ; i++) for(int j = sq , z = 1; j < n ; j++ , z ++) mat[i][j] = mat[i][sq - z] ; for(int i = sq , z = 1; i < n ; i++, z++) for(int j = 0 ; j < sq ; j++) mat[i][j] = mat[sq - z][j] ; for(int i = sq , z = 1 ; i < n ; i++, z++) for(int j = sq ; j < n ; j++) mat[i][j] = mat[sq - z][j] ; out.println("YES"); for(int [] x : mat) { for(int y : x) out.print(y+" "); out.println(); } } else { int cnt = 0 ; for(int x : set) cnt += freq[x] % 2 ; int [][] mat = new int [n][n] ; if(cnt != 1) { System.out.println("NO"); return ; } for(int x : set) if(freq[x] % 2 == 1) { freq[x]--; mat[n/2][n/2] = x ; if(freq[x] == 0) set.remove(x); break ; } int [] elements = new int [sq*sq] ; int idx = 0 ; for(int x : set) if(freq[x] % 4 == 0 || freq[x] % 4 == 2) { cnt = freq[x]/4 ; while(idx < elements.length && cnt -->0) elements[idx++] = x ; } if(idx < elements.length) { System.out.println("NO"); return ; } for(int x : elements) { freq[x]-= 4; if(freq[x] == 0)set.remove(x) ; } idx = 0 ; for(int i = 0 ;i < sq ; i++) for(int j = 0 ; j < sq ; j++) mat[i][j] = elements[idx ++] ; for(int i = 0 ; i < sq ; i++) for(int j = sq + 1 , z = 1 ; j < n ; j ++ , z ++) mat[i][j] = mat[i][sq - z] ; for(int i = sq + 1 , z = 1; i < n ; i++ , z++) for(int j = 0 ; j < sq ; j ++ ) mat[i][j] = mat[sq - z][j] ; for(int i = sq + 1 , z = 1; i < n ; i++ , z ++) for(int j = sq + 1 ; j < n ; j ++ ) mat[i][j] = mat[sq - z][j] ; idx = 0 ; elements = new int [sq] ; for(int x : set) if(freq[x] % 2 == 0 ) { cnt = freq[x] / 2 ; while(idx < elements.length && cnt -->0)elements[idx++] = x ; } if(idx < elements.length ) { System.out.println("NO");return ; } for(int x : elements) { freq[x]-= 2; if(freq[x] == 0)set.remove(x) ; } idx = 0 ; for(int i = 0 ; i < sq ; i++) mat[i][sq] = elements[idx++]; for(int i = sq + 1 , z = 1; i < n ; i++ , z++) mat[i][sq] = mat[sq - z][sq] ; idx = 0 ; for(int x : set) if(freq[x] % 2 == 0 ) { cnt = freq[x] / 2 ; while(idx < elements.length && cnt -->0)elements[idx++] = x ; } if(idx < elements.length ) { System.out.println("NO");return ; } for(int x : elements) { freq[x]-= 2; if(freq[x] == 0)set.remove(x) ; } idx = 0 ; for(int i = 0 ; i < sq ; i++) mat[sq][i] = elements[idx++]; for(int i = sq + 1 , z = 1; i < n ; i++ , z++) mat[sq][i] = mat[sq][sq - z] ; out.println("YES"); for(int [] x : mat) { for(int y : x) out.print(y+" "); out.println(); } } out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.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());} } static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
ca1192b029458625b72273c493193584
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Scanner; import java.util.Set; public class ProblemC { public static class Number { int num, freq; Number(int num) { this.num = num; this.freq = 1; } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); int n = s.nextInt(); HashMap<Integer, Number> map = new HashMap<>(); for(int i = 0;i<n*n;i++) { int x = s.nextInt(); if(map.containsKey(x)) { Number num = map.get(x); num.freq++; map.put(x, num); } else { map.put(x, new Number(x)); } } int[][] arr = new int[n][n]; Set<Integer> set = map.keySet(); ArrayList<Number> list = new ArrayList<>(); for(Integer i: set) { list.add(map.get(i)); } Collections.sort(list, new myc()); boolean ans = false; if(n%2==0) ans = forEven(arr, 0, list, n, n); else ans = forOdd(arr, 0, list, n, n); if(ans) { System.out.println("YES"); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) System.out.print(arr[i][j]+" "); System.out.println(); } } else { System.out.println("NO"); } } public static boolean forEven(int[][] arr, int row, ArrayList<Number> list, int n, int abs) { if(n == 0) return true; else { //System.out.println(n); for(int i=row;i<abs/2;i++) { int index = search(list, 4); if(index == -1) return false; else { int val = list.get(index).num; list.get(index).freq -= 4; arr[row][i] = val; arr[row][abs-1-i] = val; arr[abs-1-row][i] = val; arr[abs-1-row][abs-1-i] = val; } } for(int i=row + 1;i<abs/2;i++) { int index = search(list, 4); if(index == -1) return false; else { int val = list.get(index).num; list.get(index).freq -= 4; arr[i][row] = val; arr[i][abs-1-row] = val; arr[abs-1-i][row] = val; arr[abs-1-i][abs-1-row] = val; } } return forEven(arr, row+1, list, n-2, abs); } } public static boolean forOdd(int[][] arr, int row, ArrayList<Number> list, int n, int abs) { if(n == 1) { if(search(list, 1)==-1) return false; else { arr[row][row] = list.get(search(list,1)).num; return true; } } else { //System.out.println(n); for(int i=row;i<abs/2;i++) { int index = search(list, 4); if(index == -1) return false; else { int val = list.get(index).num; list.get(index).freq -= 4; arr[row][i] = val; arr[row][abs-1-i] = val; arr[abs-1-row][i] = val; arr[abs-1-row][abs-1-i] = val; } } int index = search(list, 2); if(index == -1) return false; else { arr[row][abs/2] = list.get(index).num; arr[abs-1 - row][abs/2] = list.get(index).num; list.get(index).freq -= 2; } for(int i=row + 1;i<abs/2;i++) { index = search(list, 4); if(index == -1) return false; else { int val = list.get(index).num; list.get(index).freq -= 4; arr[i][row] = val; arr[i][abs-1-row] = val; arr[abs-1-i][row] = val; arr[abs-1-i][abs-1-row] = val; } } index = search(list, 2); if(index == -1) { index = search(list, 3); } if(index == -1) return false; else { arr[abs/2][row] = list.get(index).num; arr[abs/2][abs -1 - row] = list.get(index).num; list.get(index).freq -= 2; } return forOdd(arr, row+1, list, n-2, abs); } } public static int search(ArrayList<Number> num, int freq) { for(int i=0;i<num.size();i++) { if(num.get(i).freq >= freq) return i; } return -1; } public static class myc implements Comparator<Number> { public int compare(Number n1, Number n2) { return n1.freq - n2.freq; } } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
a87f0a2f17da38aefa65d992f4986d5a
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Test77{ PrintWriter pw = new PrintWriter(System.out); InputStream is = System.in; Random rnd = new Random(); int a; void run(){ a = ni(); int k = a*a; TreeMap<Integer, Integer> h = new TreeMap<>(); for(int q=0; q<k; q++){ int c = ni(); h.put(c, h.getOrDefault(c,0)+1); } int[][] o = new int[a][a]; boolean ans = true; if(a%2==0){ int no = 0; for(int u : h.values()) if(u%4!=0) no++; if(no>0) ans = false; else{ for(int q=0; q<a; q++){ for(int w=0; w<a; w++){ if(o[q][w]>0) continue; int c = h.firstKey(); o[q][w] = o[a-q-1][w] = o[q][a-w-1] = o[a-q-1][a-w-1] = c; h.put(c, h.get(c)-4); if(h.get(c)==0) h.remove(c); } } } } else{ int odd = 0, num= -1; for(int u : h.keySet()){ if(h.get(u)%2==1) num = u; odd+=h.get(u)%2; } if(odd!=1) ans = false; else{ o[a/2][a/2] = num; h.put(num, h.get(num)-1); if(h.get(num)==0) h.remove(num); TreeMap<Integer, Integer> dv = new TreeMap<>(); for(int u : h.keySet()) if(h.get(u)%4==2) dv.put(u, h.get(u)); for(int u : dv.keySet()) h.remove(u); if(dv.size()>=a || dv.size()%2==1) ans = false; else{ for(int q=0; q<a; q++){ if(o[q][a/2]>0) continue; if(dv.size()==0) dv.put(h.firstKey(), h.firstEntry().getValue()); int c = dv.firstKey(); o[q][a/2] = o[a-q-1][a/2] = o[q][a-a/2-1] = o[a-q-1][a-a/2-1] = c; if(dv.get(c)%4==0) dv.put(c, dv.get(c)-2); else { h.put(c, dv.get(c) - 2); if (h.get(c) == 0) h.remove(c); dv.remove(c); } } for(int w=0; w<a; w++){ if(o[a/2][w]>0) continue; if(dv.size()==0) dv.put(h.firstKey(), h.firstEntry().getValue()); int c = dv.firstKey(); o[a/2][w] = o[a-a/2-1][w] = o[a/2][a-w-1] = o[a-a/2-1][a-w-1] = c; if(dv.get(c)%4==0) dv.put(c, dv.get(c)-2); else { h.put(c, dv.get(c) - 2); if (h.get(c) == 0) h.remove(c); dv.remove(c); } } for(int q=0; q<a; q++){ for(int w=0; w<a; w++){ if(o[q][w]>0) continue; int c = h.firstKey(); o[q][w] = o[a-q-1][w] = o[q][a-w-1] = o[a-q-1][a-w-1] = c; h.put(c, h.get(c)-4); if(h.get(c)==0) h.remove(c); } } } } } if(!ans) pw.print("NO"); else{ pw.println("YES"); for(int[] p : o){ for(int u : p) pw.print(u+" "); pw.println(); } } pw.flush(); } static class PyraSort { private static int heapSize; public static void sort(int[] a) { buildHeap(a); while (heapSize > 1) { swap(a, 0, heapSize - 1); heapSize--; heapify(a, 0); } } private static void buildHeap(int[] a) { heapSize = a.length; for (int i = a.length / 2; i >= 0; i--) { heapify(a, i); } } private static void heapify(int[] a, int i) { int l = 2 * i + 2; int r = 2 * i + 1; int largest = i; if (l < heapSize && a[i] < a[l]) { largest = l; } if (r < heapSize && a[largest] < a[r]) { largest = r; } if (i != largest) { swap(a, i, largest); heapify(a, largest); } } private static void swap(int[] a, int i, int j) { a[i] ^= a[j] ^= a[i]; a[j] ^= a[i]; } } public static void main(String[] args) { new Test77().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))) { 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(); } } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
3f8df2eb0eeda5b9d39e3aa529bff7a6
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.util.*; import java.io.*; public class Test { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] a = new int[n * n]; int[][] ans = new int[n][n]; int max = 1005; int[] cnt = new int[max]; for(int i = 0; i < n * n; i++){ a[i] = scanner.nextInt(); cnt[a[i]]++; } if(n % 2 == 0){ List<Integer>l = new ArrayList<>(); for(int i = 0; i < max; i++){ if(cnt[i] % 4 != 0){ System.out.println("NO"); return; } for(int j = 0; j < cnt[i] / 4; j++){ l.add(i); } } int ind = 0; for(int i = 0; i < n / 2; i++){ for(int j = 0; j < n / 2; j++){ int num = l.get(ind); ans[i][j] = num; ans[n - 1 - i][j] = num; ans[i][n - 1 - j] = num; ans[n - 1 - i][n - 1 - j] = num; ind++; } } } else{ List<Integer>l1 = new ArrayList<>(); List<Integer>l2 = new ArrayList<>(); List<Integer>l4 = new ArrayList<>(); int count = (n * n - 2 * n + 1) / 4; // System.out.println(count); // System.out.println(cnt[1]); for(int i = 0; i < max && count > 0; i++){ if(cnt[i] >= 4){ int count1 = cnt[i]; for(int j = 0; j < count1 / 4 && count > 0; j++){ // System.out.println("count= " +count); l4.add(i); count--; cnt[i] -= 4; } } } if(l4.size() != (n * n - 2 * n + 1) / 4){ System.out.println("NO"); return; } count = n - 1; for(int i = 0; i < max && count > 0; i++){ if(cnt[i] >= 2){ int count1 = cnt[i]; for(int j = 0; j < count1 / 2 && count > 0; j++){ l2.add(i); count--; cnt[i] -= 2; } } } if(l2.size() != (n - 1)){ System.out.println("NO"); return; } for(int i = 0; i < max; i++){ if(cnt[i] == 1)l1.add(i); } if(l1.size() != 1){ System.out.println("NO"); return; } ans[n / 2][n / 2] = l1.get(0); for(int i = 0; i < l2.size(); i++){ int num = l2.get(i); if(i < n / 2){ ans[i][n / 2] = num; ans[n - 1 - i][n / 2] = num; } else{ ans[n / 2][i - n / 2] = num; ans[n / 2][n - 1 - i + n / 2] = num; } } int ind = 0; for(int i = 0; i < n / 2; i++){ for(int j = 0; j < n / 2; j++){ int num = l4.get(ind); ans[i][j] = num; ans[n - 1 - i][j] = num; ans[i][n - 1 - j] = num; ans[n - 1 - i][n - 1 - j] = num; ind++; } } } System.out.println("YES"); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ System.out.print(ans[i][j] + " "); } System.out.println(); } } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
86cf52be795efbdd37e4cbefb0e1ae36
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class GFG77 { static int mod1 = (int) (1e9 + 7); static class Reader { final private int BUFFER_SIZE = 1 << 16; Scanner scan = new Scanner(new BufferedReader(new InputStreamReader(System.in))); private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString() throws IOException { String str00=scan.next(); return str00; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } public int[] nextArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } } static boolean primeCheck(long num0) { boolean b1 = true; if(num0==1) { b1=false; } else { int num01 = (int) (Math.sqrt(num0)) + 1; me1: for (int i = 2; i < num01; i++) { if (num0 % i == 0) { b1 = false; break me1; } } } return b1; } static int[][] primeDivisor(int pos0,int[][] arr0,int num0) { int count1=0; while(num0%2==0) { count1++; num0/=2; } if(count1>0) { arr0[pos0][2]+=count1; } for(int i=3;i<Math.sqrt(num0)+1;i++) { int count2=0; while(num0%i==0) { count2++; num0/=i; } if(count2>0) { arr0[pos0][i]+=count2; } } if(num0>2) { arr0[pos0][num0]+=1; } return arr0; } static long GCD (long num0,long num00) { BigInteger big1=BigInteger.valueOf(num0); BigInteger big2=BigInteger.valueOf(num00); big1=big1.gcd(big2); long num000=Long.parseLong(big1.toString()); return num000; } static long power1 (long num0,long num00) { long res1 = 1; while (num00 > 0) { if (num00 % 2 != 0) { res1 = (res1 * (num0 % 100006)) % 1000016; } num0 *= num0; num0 %= 1000016; num00 /= 2; } return res1; } static HashSet<Integer> primeDivi(int num0) { HashSet<Integer> hSet1=new HashSet<>(); int num00=(int)Math.sqrt(num0); hSet1.add(1); for(int i=2;i<num00+1;i++) { if(num0%i==0) { hSet1.add(i); hSet1.add(num0/i); } } return hSet1; } static int nCrModp(int n, int r, int p) { int C[]=new int[r+1]; Arrays.fill(C,0); C[0] = 1; for (int i = 1; i <= n; i++) { for (int j = Math.min(i, r); j > 0; j--) { C[j] = (C[j] + C[j - 1]) % p; } } return C[r]; } static long gcd(long num0,long num00) { if(num00==0) { return num0; } return gcd(num00,num0%num00); } static boolean heapCheck(int arr[], int i, int n) { if (i > (n - 2) / 2) { return true; } if (arr[i] >= arr[2 * i + 1] && arr[i] >= arr[2 * i + 2] && heapCheck(arr, 2 * i + 1, n) && heapCheck(arr, 2 * i + 2, n)) { return true; } return false; } static class Node { int data; Node left,right; Node(int data0) { this.data=data0; this.left=null; this.right=null; } } public static void main(String[] args) throws IOException { Reader r = new Reader(); //PrintWriter writer=new PrintWriter(System.out); //Scanner r = new Scanner(new BufferedReader(new InputStreamReader(System.in))); OutputWriter77 out77=new OutputWriter77(System.out); int num1=r.nextInt(); int[] arr1=r.nextArray(num1*num1); HashMap<Integer,Integer> hashMap=new HashMap<>(); int num2=num1*num1; for(int i=0;i<num2;i++) { if (hashMap.containsKey(arr1[i])) { hashMap.put(arr1[i],hashMap.get(arr1[i])+1); } else { hashMap.put(arr1[i],1); } } int[][] res1=new int[num1][num1]; int len1=hashMap.size(); Integer[] arr2=new Integer[len1]; arr2=hashMap.keySet().toArray(arr2); String ans1="YES"; int[] arr3=new int[len1]; me1: for(int i=0;i<len1;i++) { int num3=hashMap.get(arr2[i]); arr3[i]=num3; } if(num1%2==0) { me1: for(int i=0;i<len1;i++) { if(arr3[i]%4!=0) { ans1="NO"; break me1; } } if(ans1.equals("YES")) { int pos1 = 0; for (int i = 0; i < num1 / 2; i++) { for (int j = 0; j < num1 / 2; j++) { res1[i][j] = arr2[pos1]; res1[num1-i-1][j]=arr2[pos1]; res1[i][num1-j-1]=arr2[pos1]; res1[num1-i-1][num1-j-1]=arr2[pos1]; arr3[pos1]-=4; if(arr3[pos1]==0) { pos1++; } } } } out77.print(ans1+"\n"); if(ans1.equals("YES")) { for(int i=0;i<num1;i++) { for(int j=0;j<num1;j++) { out77.print(res1[i][j]+" "); } out77.print("\n"); } } } else { int count1=0; boolean bool1=true; int mid1=0; for(int i=0;i<len1;i++) { if(arr3[i]%2==1) { count1++; mid1=arr2[i]; arr3[i]--; } } if(count1!=1) { ans1="NO"; bool1=false; } if(bool1) { int num3=(num1/2)*(num1/2); int count2=0; for(int i=0;i<len1;i++) { count2+=(arr3[i]/4); } if(count2<num3) { bool1=false; ans1="NO"; } int pos3=0,pos5=0; int[] arr5=new int[(num1*2)-2]; /* for(int i=0;i<len1;i++) { out77.print(arr3[i]+" "); } out77.print("\n"); */ if(bool1) { for(int i=0;i<num1/2;i++) { for(int j=0;j<num1/2;j++) { if(arr3[pos3]>=4) { res1[i][j] = arr2[pos3]; res1[num1-i-1][j]=arr2[pos3]; res1[i][num1-j-1]=arr2[pos3]; res1[num1-i-1][num1-j-1]=arr2[pos3]; arr3[pos3]-=4; } else { pos3++; j--; } } } /* for(int i=0;i<len1;i++) { out77.print(arr3[i]+" "); } */ out77.print("\n"); int pos7=0; for(int i=0;i<len1;i++) { int num003=arr3[i]/2; if(num003!=0) { for (int j = 0; j < num003; j++) { if(pos7<((num1*2)-2)) { arr5[pos7++] = arr2[i]; } else { bool1=false; ans1="NO"; } } } } if(pos7!=(num1/2)*2) { bool1=false; ans1="NO"; } pos7=0; if(bool1) { me2: for(int i=0;i<num1/2;i++) { res1[num1/2][i]=arr5[pos7]; res1[num1/2][num1-i-1]=arr5[pos7++]; } me3: for(int i=0;i<num1/2;i++) { res1[i][num1/2]=arr5[pos7]; res1[num1-i-1][num1/2]=arr5[pos7++]; } } res1[num1/2][num1/2]=mid1; } } out77.print(ans1+"\n"); if(bool1) { for(int i=0;i<num1;i++) { for(int j=0;j<num1;j++) { out77.print(res1[i][j]+" "); } out77.print("\n"); } } } r.close(); out77.close(); } } class OutputWriter77 { BufferedWriter writer; public OutputWriter77(OutputStream stream) { writer = new BufferedWriter(new OutputStreamWriter(stream)); } public void print(int i) throws IOException { writer.write(i + ""); } public void println(int i) throws IOException { writer.write(i + "\n"); } public void print(String s) throws IOException { writer.write(s + ""); } public void println(String s) throws IOException { writer.write(s + "\n"); } public void print(char[] c) throws IOException { writer.write(c); } public void close() throws IOException { writer.flush(); writer.close(); } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
191c6ae96045e4c9cb8c6adbbd653525
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.io.*; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static int oo = (int)1e9; static int mod = 1_000_000_007; static int[] di = {1, 0, 0, -1}; static int[] dj = {0, -1, 1, 0}; static int M = 10005; static double EPS = 1e-5; public static void main(String[] args) throws IOException { int n = in.nextInt(); int[] cnt = new int[M]; for(int i = 0; i < n * n; ++i) { int x = in.nextInt(); cnt[x]++; } int[][] ans = new int[n][n]; for(int i = 0; i < n / 2; ++i) { for(int j = 0; j < n / 2; ++j) { int k = 0; for(; k < M; ++k) { if(cnt[k] >= 4) { break; } } if(k == M) { System.out.println("NO"); return; } ans[i][j] = ans[n-1-i][n-1-j] = ans[i][n-1-j] = ans[n-1-i][j] = k; cnt[k] -= 4; } } if(n % 2 == 1) { for(int i = 0; i < n / 2; ++i) { int k = 0; for(; k < M; ++k) { if(cnt[k] >= 2) break; } if(k == M) { System.out.println("NO"); return; } ans[i][n/2] = ans[n-1-i][n/2] = k; cnt[k] -= 2; } for(int j = 0; j < n / 2; ++j) { int k = 0; for(; k < M; ++k) { if(cnt[k] >= 2) break; } if(k == M) { System.out.println("NO"); return; } ans[n/2][j] = ans[n/2][n-1-j] = k; cnt[k] -= 2; } int k = 0; for(; k < M; ++k) { if(cnt[k] >= 1) break; } if(k == M) { System.out.println("NO"); return; } ans[n/2][n/2] = k; cnt[k]--; } System.out.println("YES"); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { System.out.print(ans[i][j] + " "); } System.out.println(); } out.close(); } static boolean inside(int i, int j, int n, int m) { return i >= 0 && i < n && j >= 0 && j < m; } static long pow(long a, long n, long mod) { if(n == 0) return 1; if(n % 2 == 1) return a * pow(a, n-1, mod) % mod; long x = pow(a, n / 2, mod); return x * x % mod; } static class SegmentTree { int n; char[] a; int[] seg; int DEFAULT_VALUE = 0; public SegmentTree(char[] a, int n) { super(); this.a = a; this.n = n; seg = new int[n * 4 + 1]; build(1, 0, n-1); } private int build(int node, int i, int j) { if(i == j) { int x = a[i] - 'a'; return seg[node] = (1<<x); } int first = build(node * 2, i, (i+j) / 2); int second = build(node * 2 + 1, (i+j) / 2 + 1, j); return seg[node] = combine(first, second); } int update(int k, char value) { return update(1, 0, n-1, k, value); } private int update(int node, int i, int j, int k, char value) { if(k < i || k > j) return seg[node]; if(i == j && j == k) { a[k] = value; int x = a[i] - 'a'; return seg[node] = (1<<x); } int m = (i + j) / 2; int first = update(node * 2, i, m, k, value); int second = update(node * 2 + 1, m + 1, j, k, value); return seg[node] = combine(first, second); } int query(int l, int r) { return query(1, 0, n-1, l, r); } private int query(int node, int i, int j, int l, int r) { if(l <= i && j <= r) return seg[node]; if(j < l || i > r) return DEFAULT_VALUE; int m = (i + j) / 2; int first = query(node * 2, i, m, l, r); int second = query(node * 2 + 1, m+1, j, l, r); return combine(first, second); } private int combine(int a, int b) { return a | b; } } static class DisjointSet { int n; int[] g; int[] h; public DisjointSet(int n) { super(); this.n = n; g = new int[n]; h = new int[n]; for(int i = 0; i < n; ++i) { g[i] = i; h[i] = 1; } } int find(int x) { if(g[x] == x) return x; return g[x] = find(g[x]); } void union(int x, int y) { x = find(x); y = find(y); if(x == y) return; if(h[x] >= h[y]) { g[y] = x; if(h[x] == h[y]) h[x]++; } else { g[x] = y; } } } static int[] getPi(char[] a) { int m = a.length; int j = 0; int[] pi = new int[m]; for(int i = 1; i < m; ++i) { while(j > 0 && a[i] != a[j]) j = pi[j-1]; if(a[i] == a[j]) { pi[i] = j + 1; j++; } } return pi; } static long lcm(long a, long b) { return a * b / gcd(a, b); } static boolean nextPermutation(int[] a) { for(int i = a.length - 2; i >= 0; --i) { if(a[i] < a[i+1]) { for(int j = a.length - 1; ; --j) { if(a[i] < a[j]) { int t = a[i]; a[i] = a[j]; a[j] = t; for(i++, j = a.length - 1; i < j; ++i, --j) { t = a[i]; a[i] = a[j]; a[j] = t; } return true; } } } } return false; } static void shuffle(int[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); int t = a[si]; a[si] = a[i]; a[i] = t; } } static void shuffle(long[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); long t = a[si]; a[si] = a[i]; a[i] = t; } } static int lower_bound(int[] a, int n, int k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int lower_bound(long[] a, int n, long k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { super(); this.first = first; this.second = second; } @Override public int compareTo(Pair o) { return this.first != o.first ? this.first - o.first : this.second - o.second; } // @Override // public int compareTo(Pair o) { // return this.first != o.first ? o.first - this.first : o.second - this.second; // } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
70911664b500e9dca83335c0bc82e341
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package Round540Div3; import java.util.ArrayList; import java.util.Scanner; import java.util.Stack; /** * * @author Hemant Dhanuka */ public class C { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int freq[]=new int[1001]; for(int i=0;i<n*n;i++){ freq[s.nextInt()]++; } int countFor4=0; int countFor2=0; int ans[][]=new int[n][n]; Stack<Integer> al4=new Stack<Integer>(); Stack<Integer> al2=new Stack<Integer>(); for(int i=1;i<=1000;i++){ // countFor4+=freq[i]/4; while(freq[i]>=4 && countFor4<((n/2)*(n/2))){ freq[i]=freq[i]-4; countFor4++; al4.push(i); } while(freq[i]>=2){ freq[i]=freq[i]-2; countFor2++; al2.push(i); } if(freq[i]==1){ ans[n/2][n/2]=i; } } String strAns=""; if(n%2==0){ if(countFor4==(n*n)/4){ strAns="YES"; }else{ strAns="NO"; } }else{ if(countFor4<((n-1)/2)*((n-1)/2)){ strAns="NO"; }else{ if(countFor2==n-1){ strAns="YES"; }else{ strAns="NO"; } } } System.out.println(strAns); if(strAns.equals("YES")){ for(int i=0;i<n/2;i++){ for(int j=0;j<n/2;j++){ int val=al4.pop(); ans[i][j]=ans[i][n-1-j]=ans[n-1-i][j]=ans[n-1-i][n-1-j]=val; } } if(n%2!=0){ for(int i=0;i<n/2;i++){ int val=al2.pop(); ans[i][n/2]=val; ans[n-1-i][n/2]=val; } for(int j=0;j<n/2;j++){ int val=al2.pop(); ans[n/2][j]=val; ans[n/2][n-1-j]=val; } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ System.out.print(ans[i][j]+" "); } System.out.println(); } } } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
2044e0c927f8d02d407ec030ef5509c7
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.util.*; import java.io.*; import java.util.HashMap; import java.util.Map; public class A { public static void main(String ar[]) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); ArrayList<Integer> al4=new ArrayList<Integer>(); ArrayList<Integer> al2=new ArrayList<Integer>(); ArrayList<Integer> al1=new ArrayList<Integer>(); HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); String s1[]=br.readLine().split(" "); for(int i=0;i<n*n;i++) { int u=Integer.parseInt(s1[i]); if(hm.containsKey(u)) hm.put(u,1+hm.get(u)); else hm.put(u,1); if(hm.get(u)==4) { al4.add(u); hm.remove(u); } } for(int i:hm.keySet()) { if(hm.get(i)==3) { al2.add(i); al1.add(i); } else if(hm.get(i)==2) { al2.add(i); } else { al1.add(i); } } boolean bb=true; int a[][]=new int[n][n]; if(n%2==0) { if(al1.size()>0 || al2.size()>0) bb=false; int r=0; for(int i=0;i<n/2 && bb;i++) { for(int j=0;j<n/2 && bb;j++) { int u=al4.get(r); r++; a[i][j]=u; a[n-1-i][j]=u; a[i][n-j-1]=u; a[n-i-1][n-j-1]=u; } } } else { if(al1.size()!=1 || al4.size()<((n-1)*(n-1))/4) bb=false; int r=0; for(int i=0;i<(n-1)/2 && bb;i++) { for(int j=0;j<(n-1)/2 && bb;j++) { int u=al4.get(r); r++; a[i][j]=u; a[n-1-i][j]=u; a[i][n-j-1]=u; a[n-i-1][n-j-1]=u; } } for(int i=r;i<al4.size();i++) { al2.add(al4.get(i)); al2.add(al4.get(i)); } if(al2.size()!=n-1) bb=false; r=0; if(bb) { a[n/2][n/2]=al1.get(0); for(int i=0;i<(n-1)/2;i++) { int u=al2.get(r); r++; a[i][n/2]=u; a[n-i-1][n/2]=u; } for(int j=0;j<(n-1)/2;j++) { int u=al2.get(r); r++; a[n/2][j]=u; a[n/2][n-j-1]=u; } } } if(!bb) System.out.println("NO"); else { System.out.println("YES"); StringBuffer sb=new StringBuffer(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) sb.append(a[i][j]).append(" "); sb.append("\n"); } System.out.println(sb); } } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output
PASSED
d6001ecd99920b18f4b3e61d9192342b
train_001.jsonl
1550586900
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic: The following matrices are not palindromic because they change after the order of rows is reversed: The following matrices are not palindromic because they change after the order of columns is reversed: You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".
256 megabytes
import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; public class C { static class InputReader { private static final int DEFAULT_BUFFER_SIZE = 1 << 16; private static final InputStream DEFAULT_STREAM = System.in; private static final int MAX_DECIMAL_PRECISION = 21; private int c; private byte[] buf; private int bufferSize, bufIndex, numBytesRead; private InputStream stream; private static final byte EOF = -1; private static final byte NEW_LINE = 10; private static final byte SPACE = 32; private static final byte DASH = 45; private static final byte DOT = 46; private char[] charBuffer; private static byte[] bytes = new byte[58]; private static int[] ints = new int[58]; private static char[] chars = new char[128]; static { char ch = ' '; int value = 0; byte _byte = 0; for (int i = 48; i < 58; i++) bytes[i] = _byte++; for (int i = 48; i < 58; i++) ints[i] = value++; for (int i = 32; i < 128; i++) chars[i] = ch++; } private static final double[][] doubles = { {0.0d, 0.00d, 0.000d, 0.0000d, 0.00000d, 0.000000d, 0.0000000d, 0.00000000d, 0.000000000d, 0.0000000000d, 0.00000000000d, 0.000000000000d, 0.0000000000000d, 0.00000000000000d, 0.000000000000000d, 0.0000000000000000d, 0.00000000000000000d, 0.000000000000000000d, 0.0000000000000000000d, 0.00000000000000000000d, 0.000000000000000000000d}, {0.1d, 0.01d, 0.001d, 0.0001d, 0.00001d, 0.000001d, 0.0000001d, 0.00000001d, 0.000000001d, 0.0000000001d, 0.00000000001d, 0.000000000001d, 0.0000000000001d, 0.00000000000001d, 0.000000000000001d, 0.0000000000000001d, 0.00000000000000001d, 0.000000000000000001d, 0.0000000000000000001d, 0.00000000000000000001d, 0.000000000000000000001d}, {0.2d, 0.02d, 0.002d, 0.0002d, 0.00002d, 0.000002d, 0.0000002d, 0.00000002d, 0.000000002d, 0.0000000002d, 0.00000000002d, 0.000000000002d, 0.0000000000002d, 0.00000000000002d, 0.000000000000002d, 0.0000000000000002d, 0.00000000000000002d, 0.000000000000000002d, 0.0000000000000000002d, 0.00000000000000000002d, 0.000000000000000000002d}, {0.3d, 0.03d, 0.003d, 0.0003d, 0.00003d, 0.000003d, 0.0000003d, 0.00000003d, 0.000000003d, 0.0000000003d, 0.00000000003d, 0.000000000003d, 0.0000000000003d, 0.00000000000003d, 0.000000000000003d, 0.0000000000000003d, 0.00000000000000003d, 0.000000000000000003d, 0.0000000000000000003d, 0.00000000000000000003d, 0.000000000000000000003d}, {0.4d, 0.04d, 0.004d, 0.0004d, 0.00004d, 0.000004d, 0.0000004d, 0.00000004d, 0.000000004d, 0.0000000004d, 0.00000000004d, 0.000000000004d, 0.0000000000004d, 0.00000000000004d, 0.000000000000004d, 0.0000000000000004d, 0.00000000000000004d, 0.000000000000000004d, 0.0000000000000000004d, 0.00000000000000000004d, 0.000000000000000000004d}, {0.5d, 0.05d, 0.005d, 0.0005d, 0.00005d, 0.000005d, 0.0000005d, 0.00000005d, 0.000000005d, 0.0000000005d, 0.00000000005d, 0.000000000005d, 0.0000000000005d, 0.00000000000005d, 0.000000000000005d, 0.0000000000000005d, 0.00000000000000005d, 0.000000000000000005d, 0.0000000000000000005d, 0.00000000000000000005d, 0.000000000000000000005d}, {0.6d, 0.06d, 0.006d, 0.0006d, 0.00006d, 0.000006d, 0.0000006d, 0.00000006d, 0.000000006d, 0.0000000006d, 0.00000000006d, 0.000000000006d, 0.0000000000006d, 0.00000000000006d, 0.000000000000006d, 0.0000000000000006d, 0.00000000000000006d, 0.000000000000000006d, 0.0000000000000000006d, 0.00000000000000000006d, 0.000000000000000000006d}, {0.7d, 0.07d, 0.007d, 0.0007d, 0.00007d, 0.000007d, 0.0000007d, 0.00000007d, 0.000000007d, 0.0000000007d, 0.00000000007d, 0.000000000007d, 0.0000000000007d, 0.00000000000007d, 0.000000000000007d, 0.0000000000000007d, 0.00000000000000007d, 0.000000000000000007d, 0.0000000000000000007d, 0.00000000000000000007d, 0.000000000000000000007d}, {0.8d, 0.08d, 0.008d, 0.0008d, 0.00008d, 0.000008d, 0.0000008d, 0.00000008d, 0.000000008d, 0.0000000008d, 0.00000000008d, 0.000000000008d, 0.0000000000008d, 0.00000000000008d, 0.000000000000008d, 0.0000000000000008d, 0.00000000000000008d, 0.000000000000000008d, 0.0000000000000000008d, 0.00000000000000000008d, 0.000000000000000000008d}, {0.9d, 0.09d, 0.009d, 0.0009d, 0.00009d, 0.000009d, 0.0000009d, 0.00000009d, 0.000000009d, 0.0000000009d, 0.00000000009d, 0.000000000009d, 0.0000000000009d, 0.00000000000009d, 0.000000000000009d, 0.0000000000000009d, 0.00000000000000009d, 0.000000000000000009d, 0.0000000000000000009d, 0.00000000000000000009d, 0.000000000000000000009d}}; public InputReader() { this(DEFAULT_STREAM, DEFAULT_BUFFER_SIZE); } public InputReader(int bufferSize) { this(DEFAULT_STREAM, bufferSize); } public InputReader(InputStream stream) { this(stream, DEFAULT_BUFFER_SIZE); } public InputReader(InputStream stream, int bufferSize) { if (stream == null || bufferSize <= 0) throw new IllegalArgumentException(); buf = new byte[bufferSize]; charBuffer = new char[128]; this.bufferSize = bufferSize; this.stream = stream; } private byte read() throws IOException { if (numBytesRead == EOF) throw new IOException(); if (bufIndex >= numBytesRead) { bufIndex = 0; numBytesRead = stream.read(buf); if (numBytesRead == EOF) return EOF; } return buf[bufIndex++]; } private int readJunk(int token) throws IOException { if (numBytesRead == EOF) return EOF; // Seek to the first valid position index do { while (bufIndex < numBytesRead) { if (buf[bufIndex] > token) return 0; bufIndex++; } // reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return EOF; bufIndex = 0; } while (true); } public byte nextByte() throws IOException { return (byte) nextInt(); } public int nextInt() throws IOException { if (readJunk(DASH - 1) == EOF) throw new IOException(); int sgn = 1, res = 0; c = buf[bufIndex]; if (c == DASH) { sgn = -1; bufIndex++; } do { while (bufIndex < numBytesRead) { if (buf[bufIndex] > SPACE) { res = (res << 3) + (res << 1); res += ints[buf[bufIndex++]]; } else { bufIndex++; return res * sgn; } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return res * sgn; bufIndex = 0; } while (true); } public long nextLong() throws IOException { if (readJunk(DASH - 1) == EOF) throw new IOException(); int sgn = 1; long res = 0L; c = buf[bufIndex]; if (c == DASH) { sgn = -1; bufIndex++; } do { while (bufIndex < numBytesRead) { if (buf[bufIndex] > SPACE) { res = (res << 3) + (res << 1); res += ints[buf[bufIndex++]]; } else { bufIndex++; return res * sgn; } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return res * sgn; bufIndex = 0; } while (true); } private void doubleCharBufferSize() { char[] newBuffer = new char[charBuffer.length << 1]; for (int i = 0; i < charBuffer.length; i++) newBuffer[i] = charBuffer[i]; charBuffer = newBuffer; } public String nextLine() throws IOException { try { c = read(); } catch (IOException e) { return null; } if (c == NEW_LINE) return ""; // Empty line if (c == EOF) return null; // EOF int i = 0; charBuffer[i++] = (char) c; do { while (bufIndex < numBytesRead) { if (buf[bufIndex] != NEW_LINE) { if (i == charBuffer.length) doubleCharBufferSize(); charBuffer[i++] = (char) buf[bufIndex++]; } else { bufIndex++; return new String(charBuffer, 0, i); } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return new String(charBuffer, 0, i); bufIndex = 0; } while (true); } public String nextString() throws IOException { if (numBytesRead == EOF) return null; if (readJunk(SPACE) == EOF) return null; for (int i = 0; ; ) { while (bufIndex < numBytesRead) { if (buf[bufIndex] > SPACE) { if (i == charBuffer.length) doubleCharBufferSize(); charBuffer[i++] = (char) buf[bufIndex++]; } else { bufIndex++; return new String(charBuffer, 0, i); } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return new String(charBuffer, 0, i); bufIndex = 0; } } public double nextDouble() throws IOException { String doubleVal = nextString(); if (doubleVal == null) throw new IOException(); return Double.valueOf(doubleVal); } public double nextDoubleFast() throws IOException { c = read(); int sgn = 1; while (c <= SPACE) c = read(); // while c is either: ' ', '\n', EOF if (c == DASH) { sgn = -1; c = read(); } double res = 0.0; // while c is not: ' ', '\n', '.' or -1 while (c > DOT) { res *= 10.0; res += ints[c]; c = read(); } if (c == DOT) { int i = 0; c = read(); // while c is digit and we are less than the maximum decimal precision while (c > SPACE && i < MAX_DECIMAL_PRECISION) { res += doubles[ints[c]][i++]; c = read(); } } return res * sgn; } // Read an array of n byte values public byte[] nextByteArray(int n) throws IOException { byte[] ar = new byte[n]; for (int i = 0; i < n; i++) ar[i] = nextByte(); return ar; } // Read an integer array of size n public int[] nextIntArray(int n) throws IOException { int[] ar = new int[n]; for (int i = 0; i < n; i++) ar[i] = nextInt(); return ar; } // Read a long array of size n public long[] nextLongArray(int n) throws IOException { long[] ar = new long[n]; for (int i = 0; i < n; i++) ar[i] = nextLong(); return ar; } // read an of doubles of size n public double[] nextDoubleArray(int n) throws IOException { double[] ar = new double[n]; for (int i = 0; i < n; i++) ar[i] = nextDouble(); return ar; } // Quickly read an array of doubles public double[] nextDoubleArrayFast(int n) throws IOException { double[] ar = new double[n]; for (int i = 0; i < n; i++) ar[i] = nextDoubleFast(); return ar; } // Read a string array of size n public String[] nextStringArray(int n) throws IOException { String[] ar = new String[n]; for (int i = 0; i < n; i++) { String str = nextString(); if (str == null) throw new IOException(); ar[i] = str; } return ar; } // Read a 1-based byte array of size n+1 public byte[] nextByteArray1(int n) throws IOException { byte[] ar = new byte[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextByte(); return ar; } // Read a 1-based integer array of size n+1 public int[] nextIntArray1(int n) throws IOException { int[] ar = new int[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextInt(); return ar; } // Read a 1-based long array of size n+1 public long[] nextLongArray1(int n) throws IOException { long[] ar = new long[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextLong(); return ar; } // Read a 1-based double array of size n+1 public double[] nextDoubleArray1(int n) throws IOException { double[] ar = new double[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextDouble(); return ar; } // Quickly read a 1-based double array of size n+1 public double[] nextDoubleArrayFast1(int n) throws IOException { double[] ar = new double[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextDoubleFast(); return ar; } // Read a 1-based string array of size n+1 public String[] nextStringArray1(int n) throws IOException { String[] ar = new String[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextString(); return ar; } // Read a two dimensional matrix of bytes of size rows x cols public byte[][] nextByteMatrix(int rows, int cols) throws IOException { byte[][] matrix = new byte[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextByte(); return matrix; } // Read a two dimensional matrix of ints of size rows x cols public int[][] nextIntMatrix(int rows, int cols) throws IOException { int[][] matrix = new int[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextInt(); return matrix; } // Read a two dimensional matrix of longs of size rows x cols public long[][] nextLongMatrix(int rows, int cols) throws IOException { long[][] matrix = new long[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextLong(); return matrix; } // Read a two dimensional matrix of doubles of size rows x cols public double[][] nextDoubleMatrix(int rows, int cols) throws IOException { double[][] matrix = new double[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextDouble(); return matrix; } // Quickly read a two dimensional matrix of doubles of size rows x cols public double[][] nextDoubleMatrixFast(int rows, int cols) throws IOException { double[][] matrix = new double[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextDoubleFast(); return matrix; } // Read a two dimensional matrix of Strings of size rows x cols public String[][] nextStringMatrix(int rows, int cols) throws IOException { String[][] matrix = new String[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextString(); return matrix; } // Read a 1-based two dimensional matrix of bytes of size rows x cols public byte[][] nextByteMatrix1(int rows, int cols) throws IOException { byte[][] matrix = new byte[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextByte(); return matrix; } // Read a 1-based two dimensional matrix of ints of size rows x cols public int[][] nextIntMatrix1(int rows, int cols) throws IOException { int[][] matrix = new int[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextInt(); return matrix; } // Read a 1-based two dimensional matrix of longs of size rows x cols public long[][] nextLongMatrix1(int rows, int cols) throws IOException { long[][] matrix = new long[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextLong(); return matrix; } // Read a 1-based two dimensional matrix of doubles of size rows x cols public double[][] nextDoubleMatrix1(int rows, int cols) throws IOException { double[][] matrix = new double[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextDouble(); return matrix; } // Quickly read a 1-based two dimensional matrix of doubles of size rows x cols public double[][] nextDoubleMatrixFast1(int rows, int cols) throws IOException { double[][] matrix = new double[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextDoubleFast(); return matrix; } // Read a 1-based two dimensional matrix of Strings of size rows x cols public String[][] nextStringMatrix1(int rows, int cols) throws IOException { String[][] matrix = new String[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextString(); return matrix; } // Closes the input stream public void close() throws IOException { stream.close(); } } public static void main(String[] args) throws IOException { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out), true); int n = in.nextInt(); int[] arr = new int[n * n]; for (int i = 0; i < arr.length; ++i) { arr[i] = in.nextInt(); } if (n == 1) { out.println("YES"); out.println(arr[0]); return; } HashMap<Integer, Integer> map = new HashMap<>(); for (int anArr : arr) { if (map.containsKey(anArr)) { int val = map.get(anArr); map.put(anArr, val + 1); } else { map.put(anArr, 1); } } if (n == 2) { if (map.size() > 1) { out.println("NO"); } else { out.println("YES"); out.println(arr[0] + " " + arr[0]); out.println(arr[0] + " " + arr[0]); } return; } int[][] result = new int[n][n]; int top = 0; int bottom = n - 1; while (top <= bottom) { int left = 0; int right = n - 1; if (top == bottom) { while (left <= right) { if (left == right) { int select = 0; for (int x : map.keySet()) { int val = map.get(x); if (val >= 1) { select = x; if (val - 1 == 0) map.remove(x); else map.put(x, val - 1); break; } } if (select == 0) { out.println("NO"); return; } else { result[top][left] = select; result[bottom][left] = select; } break; } int select = 0; for (int x : map.keySet()) { int val = map.get(x); if (val >= 2) { select = x; if (val - 2 == 0) map.remove(x); else map.put(x, val - 2); break; } } if (select == 0) { out.println("NO"); return; } else { result[top][left] = select; result[top][right] = select; result[bottom][left] = select; result[bottom][right] = select; } ++left; --right; } break; } while (left <= right) { if (left == right) { int select = 0; for (int x : map.keySet()) { int val = map.get(x); if (val == 2) { select = x; if (val - 2 == 0) map.remove(x); else map.put(x, val - 2); break; } } if (select == 0) { for (int x : map.keySet()) { int val = map.get(x); if (val >= 2) { select = x; if (val - 2 == 0) map.remove(x); else map.put(x, val - 2); break; } } } if (select == 0) { out.println("NO"); return; } else { result[top][left] = select; result[bottom][left] = select; } break; } int select = 0; for (int x : map.keySet()) { int val = map.get(x); if (val >= 4) { select = x; if (val - 4 == 0) map.remove(x); else map.put(x, val - 4); break; } } if (select == 0) { out.println("NO"); return; } else { result[top][left] = select; result[top][right] = select; result[bottom][left] = select; result[bottom][right] = select; } ++left; --right; } ++top; --bottom; } out.println("YES"); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { out.print(result[i][j] + " "); } out.println(); } } }
Java
["4\n1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1", "3\n1 1 1 1 1 3 3 3 3", "4\n1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1", "1\n10"]
2 seconds
["YES\n1 2 2 1\n8 2 2 8\n8 2 2 8\n1 2 2 1", "YES\n1 3 1\n3 1 3\n1 3 1", "NO", "YES\n10"]
NoteNote that there exist multiple answers for the first two examples.
Java 8
standard input
[ "constructive algorithms", "implementation" ]
20928dd8e512bee2d86c6611c5e76390
The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.
1,700
If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.
standard output