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
e9d2f1d6415354918ff6a93a89ff7b9d
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * @author pvasilyev * @since 30 Mar 2017 */ public class A277 { public static void main(String[] args) throws IOException { final Scanner reader = new Scanner(new InputStreamReader(System.in)); final PrintWriter writer = new PrintWriter(System.out); solve(reader, writer); writer.close(); reader.close(); } private static void solve(final Scanner reader, final PrintWriter writer) { final int n = reader.nextInt(); final int m = reader.nextInt(); final DSU dsu = new DSU(n + m); for (int i = 1; i <= n + m; ++i) { dsu.makeSet(i); } for (int i = 1; i <= n; ++i) { int k = reader.nextInt(); for (int j = 0; j < k; ++j) { int lang = reader.nextInt() + n; dsu.union(i, lang); } } if (noOneKnowsNoLangs(dsu, n, m)) { writer.println(n); } else { Set<Integer> set = new HashSet<>(); for (int i = 1; i <= n; ++i) { set.add(dsu.findSet(i)); } writer.println(set.size() - 1); } } private static boolean noOneKnowsNoLangs(DSU dsu, int n, int m) { for (int i = n + 1; i <= n + m; ++i) { if (dsu.findSet(i) != i) { return false; } } return true; } private static class DSU { private int[] p; private DSU(int n) { p = new int[n + 1]; } private void makeSet(int u) { p[u] = u; } private int findSet(int u) { if (p[u] == u) return u; int parent = findSet(p[u]); p[u] = parent; return parent; } private void union(int u, int v) { int a = findSet(u); int b = findSet(v); if (a != b) { if (b < a) { int t = a; a = b; b = t; } p[b] = a; } } } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
894dcafacd2d3b04abd7fd6f8a43205a
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.util.ArrayList; import java.util.Scanner; import java.util.TreeSet; public class Learning_Languages { static boolean vis[]; static ArrayList<Integer> [] adj; public static void dfs(int x) { vis[x]=true; for(int y:adj[x]) { if(!vis[y]) { dfs(y); } } } public static void main(String [] arga) { Scanner sc=new Scanner (System.in); int n=sc.nextInt(); int m=sc.nextInt(); boolean flag=true; vis=new boolean [n]; int cost=0; ArrayList<Integer> [] tsarr=new ArrayList[n]; adj=new ArrayList [n]; for(int i=0;i<n;i++) { tsarr[i]=new ArrayList<Integer>(); adj[i]=new ArrayList<Integer>(); } for(int i=0;i<n;i++) { int k=sc.nextInt(); if(k!=0) { flag=false; } for(int j=0;j<k;j++) { tsarr[i].add(sc.nextInt()); } } for(int i=0;i<n;i++) { for(int x:tsarr[i]) { for(int j=0;j<n;j++) { if(j!=i) { for(int y:tsarr[j]) { if(y==x ) { adj[i].add(j); } } } } } } // for(int i=0;i<n;i++) { // for(int x:adj[i]) { // System.out.print(x+" "); // } // System.out.println(); // } int c=-1; for(int i=0;i<n;i++) { if(!vis[i]) { c++; dfs(i); } } if(!flag) { System.out.println(c); } else { System.out.println(n); } } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
d5acf529b5001f1f8c15223548e7e987
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
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) throws IOException{ InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); A170 solver = new A170(); solver.solve(1, in, out); out.close(); } static class A170 { int[][] graph = new int[102][102]; boolean[] visited = new boolean[102]; public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException { StringTokenizer st = new StringTokenizer(in.nextLine()); int aris = Integer.parseInt(st.nextToken()); int n = Integer.parseInt(st.nextToken()); int[] hash = new int[102]; int count = 0; boolean enter = false; for (int i = 0; i < aris; i++) { String[] s = in.nextLine().split(" "); int cur = Integer.parseInt(s[0]); if (cur == 0) { count++; } else { enter = true; int aux = Integer.parseInt(s[1]); hash[aux]++; for (int j = 1; j < cur; j++) { int ac = Integer.parseInt(s[j + 1]); hash[ac]++; graph[aux][ac] = 1; graph[ac][aux] = 1; aux = ac; } } } if (enter) { for (int i = 1; i <= aris; i++) { if (!visited[i] && hash[i] > 0) { dfs(i); count++; } } out.println(count - 1); } else out.println(aris); } void dfs(int nod) { visited[nod] = true; for (int i = 0; i < graph[nod].length; i++) { if (!visited[i] && graph[nod][i] == 1) { dfs(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 nextLine() throws IOException { return reader.readLine(); } } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
a287b6a677d432c0c15196b61be740e5
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int m = in.nextInt(); boolean any = false; boolean[][] know = new boolean[n][m]; for (int i = 0; i < n; i++) { int from = i; int cnt = in.nextInt(); for (int j = 0; j < cnt; j++) { int to = in.nextInt() - 1; know[from][to] = true; any = true; } } if (!any) { out.println(n); return; } UFDS set = new UFDS(n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { if (know[i][k] && know[j][k]) { set.connect(i, j); } } } } int count = set.getConnectedComponents(); out.println(count - 1); } } static class UFDS { public int n; public int[] rank; public int[] parent; public UFDS(int n) { this.n = n; this.rank = new int[n]; this.parent = new int[n]; for (int i = 0; i < n; i++) { rank[i] = 1; parent[i] = i; } } public int root(int i) { return parent[i] == i ? i : (parent[i] = root(parent[i])); } public void connect(int i, int j) { int X = root(i); int Y = root(j); if (X != Y) { if (rank[X] < rank[Y]) { parent[Y] = X; } else { parent[X] = Y; if (rank[X] == rank[Y]) { rank[Y]++; } } } } public int getConnectedComponents() { int count = 0; for (int i = 0; i < n; i++) { if (i == root(i)) { count++; } } return count; } } static class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
c7d6acda3741d588b88467e777e4de84
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int m = in.nextInt(); boolean any = false; boolean[][] know = new boolean[n][m]; for (int i = 0; i < n; i++) { int from = i; int cnt = in.nextInt(); for (int j = 0; j < cnt; j++) { int to = in.nextInt() - 1; know[from][to] = true; any = true; } } if (!any) { out.println(n); return; } boolean[][] g = new boolean[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { if (know[i][k] && know[j][k]) { g[i][j] = true; } } } } for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { g[i][j] |= (g[i][k] && g[k][j]); } } } int res = 0; boolean[] mark = new boolean[n]; for (int i = 0; i < n; i++) { if (!mark[i]) { res++; for (int j = 0; j < n; j++) { if (g[i][j]) { mark[j] = true; } } } } out.println(res - 1); } } static class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
c9da6b5e312cb2776c926931a9bcb645
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { private int V; private boolean[] was; private ArrayList[] g; public void solve(int testNumber, FastScanner in, FastPrinter out) { int P = in.nextInt(); int L = in.nextInt(); V = P + L; g = createGraph(V); int E = 0; for (int i = 0; i < P; i++) { int from = i; int n = in.nextInt(); for (int j = 0; j < n; j++) { int lang = in.nextInt() - 1; int to = P + lang; addEdge(from, to); E++; } } if (E == 0) { out.println(P); return; } int count = 0; was = new boolean[V]; for (int i = 0; i < P; i++) { if (!was[i]) { dfs(i); count++; } } out.println(count - 1); } private void dfs(int u) { was[u] = true; ArrayList<Integer> next = g[u]; for (Integer v : next) { if (!was[v]) { dfs(v); } } } private ArrayList[] createGraph(int V) { ArrayList[] g = new ArrayList[V]; for (int i = 0; i < V; i++) { g[i] = new ArrayList<Integer>(); } return g; } private void addEdge(int from, int to) { g[from].add(to); g[to].add(from); } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } static class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
455bb2366f0cb4985a16f4328fc0e3c0
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int m = in.nextInt(); boolean anyEdge = false; boolean[][] know = new boolean[n][m]; for (int i = 0; i < n; i++) { int from = i; int cnt = in.nextInt(); for (int j = 0; j < cnt; j++) { int to = in.nextInt() - 1; know[from][to] = true; anyEdge = true; } } if (!anyEdge) { out.println(n); return; } boolean[][] g = new boolean[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { if (know[i][k] && know[j][k]) { g[i][j] = true; } } } } for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { g[i][j] |= (g[i][k] & g[k][j]); } } } int result = 0; boolean[] mark = new boolean[n]; for (int i = 0; i < n; i++) { if (!mark[i]) { result++; for (int j = 0; j < n; j++) { if (g[i][j]) { mark[j] = true; } } } } out.println(result - 1); } } static class FastScanner { public BufferedReader br; public StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
603ee0c711c6e92e23ef881d9ce785c7
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.util.* ; import java.io.*; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pr = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); HashSet<Integer> [] adjSet = new HashSet[n]; for (int i = 0; i < n ; i++) adjSet[i] = new HashSet(); int numOfSets = 0 ; int zeros = 0 ; int ans = 0 ; int totalSets = 0 ; while(n-->0) { int num = sc.nextInt(); if(num==0){ zeros++ ; continue ; } Set<Integer> set = new HashSet<>(); while(num-->0) set.add(sc.nextInt()); ArrayList<Integer> lst = new ArrayList(); for (int i = 0; i < numOfSets ; i++) { HashSet<Integer> s = new HashSet<>(adjSet[i]); s.retainAll(set); if(s.size()>0) lst.add(i); } if(lst.size()>0) { for (int i = 1 ; i < lst.size() ; i++) { adjSet[lst.get(0)].addAll(adjSet[lst.get(i)]); adjSet[lst.get(i)].clear(); totalSets-- ; } adjSet[lst.get(0)].addAll(set); } else{ adjSet[numOfSets++].addAll(set); totalSets++ ; } // System.out.println("totalSets = " + totalSets); } ans += zeros ; if(totalSets>0) ans += totalSets-1 ; pr.println(ans); sc.close(); pr.close(); } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
b80d981c37d94b0340e5e984ff85492c
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.util.* ; import java.io.*; /** * @author mostafa */ public class A { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pr = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int [] first = new int[m]; Arrays.fill(first, -1); Graph graph = new Graph(n); int zeros = 0 ; for(int i = 0 ; i < n ; i++) { st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken()); if( x == 0 ) zeros++ ; while(x-->0) { int u = Integer.parseInt(st.nextToken())-1; if(first[u]!=-1) graph.addEdge(first[u], i); else first[u] = i ; } } int count = new CC(graph).count(); if(count==zeros) pr.println(count); else pr.println(count-1); br.close(); pr.close(); } } class Graph { private final int V ; private ArrayList<Integer> adjList[] ; public Graph(int V) { this.V = V ; adjList = new ArrayList[V]; for (int i = 0; i < V ; i++) adjList[i] = new ArrayList(); } public int V() { return V ; } public void addEdge(int u , int v) { adjList[u].add(v); adjList[v].add(u); } public Iterable<Integer> adj(int v) { return adjList[v]; } } class CC { private boolean [] marked ; private int count ; public CC(Graph G) { marked = new boolean [G.V()]; for (int v = 0; v < G.V() ; v++) if(!marked[v]) { dfs(G, v); count++ ; } } private void dfs(Graph G , int v) { marked[v] = true ; for(int w : G.adj(v)) if(!marked[w]) dfs(G, w); } public int count() { return count ; } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
2623395150249a5b2b00b880f8400e2c
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.util.ArrayList; import java.util.Scanner; // public class LearningLanguages { int[] parents; public static void main(String[] args) { Scanner input = new Scanner(System.in); LearningLanguages obj = new LearningLanguages(); int n = input.nextInt(); int m = input.nextInt(); obj.parents = new int[m + 1]; int temp, numOfZero = 0, numOfSets; ArrayList<Integer>[] data = new ArrayList[n]; for (int i = 0; i < n; i++) { temp = input.nextInt(); data[i] = new ArrayList<Integer>(); if (temp == 0) { numOfZero++; data[i].add(0); } else { for (int j = 0; j < temp; j++) { data[i].add(input.nextInt()); } obj.control(data[i]); } } numOfSets = obj.solve(); System.out.println(numOfSets + numOfZero); } private void control(ArrayList<Integer> employee) { int parent = employee.get(0); if (employee.size() == 1) { if (parents[parent]==0){ parents[parent]=parent; } } else { for (int i = 1; i < employee.size(); i++) { union(parent, employee.get(i)); } } } private int getRoot(int x) { if (parents[x] == 0) { parents[x] = x; } return parents[x]; } private void union(int x, int y) { int parentX = getRoot(x); int parentY = getRoot(y); if (parentY != parentX) { for (int i = 0; i < parents.length; i++) { if (parents[i] == parentY) { parents[i] = parentX; } } } } // private int solve() { int ans = 0; boolean visited[] = new boolean[parents.length]; for (int i = 1; i < parents.length; i++) { visited[parents[i]] = true; } for (int i = 1; i < parents.length; i++) { if (visited[i]) { ans++; } } if (ans>0){ ans--; } return ans; } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
541565a8dd732c564315d5edc40ae95a
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class LearningLanguages { int[] parents; public static void main(String[] args) { Scanner input = new Scanner(System.in); LearningLanguages obj = new LearningLanguages(); int n = input.nextInt(); int m = input.nextInt(); obj.parents = new int[m + 1]; int temp, numOfZero = 0, numOfSets; ArrayList<Integer>[] data = new ArrayList[n]; for (int i = 0; i < n; i++) { temp = input.nextInt(); data[i] = new ArrayList<Integer>(); if (temp == 0) { numOfZero++; data[i].add(0); } else { for (int j = 0; j < temp; j++) { data[i].add(input.nextInt()); } obj.control(data[i]); } } numOfSets = obj.solve(); System.out.println(numOfSets + numOfZero); } private void control(ArrayList<Integer> employee) { int parent = employee.get(0); if (employee.size() == 1) { if (parents[parent]==0){ parents[parent]=parent; } } else { for (int i = 1; i < employee.size(); i++) { union(parent, employee.get(i)); } } } private int getRoot(int x) { if (parents[x] == 0) { parents[x] = x; } return parents[x]; } private void union(int x, int y) { int parentX = getRoot(x); int parentY = getRoot(y); if (parentY != parentX) { for (int i = 0; i < parents.length; i++) { if (parents[i] == parentY) { parents[i] = parentX; } } } } private int solve() { int ans = 0; boolean visited[] = new boolean[parents.length]; for (int i = 1; i < parents.length; i++) { visited[parents[i]] = true; } for (int i = 1; i < parents.length; i++) { if (visited[i]) { ans++; } } if (ans>0){ ans--; } return ans; } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
4f56ce8305c9f97b22a1505e0f3f4edc
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class LearningLanguages { int[] parents; public static void main(String[] args) { Scanner input = new Scanner(System.in); LearningLanguages obj = new LearningLanguages(); int n = input.nextInt(); int m = input.nextInt(); obj.parents = new int[m + 1]; int temp, numOfZero = 0, numOfSets; ArrayList<Integer>[] data = new ArrayList[n]; for (int i = 0; i < n; i++) { temp = input.nextInt(); data[i] = new ArrayList<Integer>(); if (temp == 0) { numOfZero++; data[i].add(0); } else { for (int j = 0; j < temp; j++) { data[i].add(input.nextInt()); } obj.control(data[i]); } } numOfSets = obj.solve(); System.out.println(numOfSets + numOfZero); } private void control(ArrayList<Integer> employee) { int parent = employee.get(0); if (employee.size() == 1) { if (parents[parent]==0){ parents[parent]=parent; } } else { for (int i = 1; i < employee.size(); i++) { union(parent, employee.get(i)); } } } private int getRoot(int x) { if (parents[x] == 0) { parents[x] = x; } return parents[x]; } private void union(int x, int y) { int parentX = getRoot(x); int parentY = getRoot(y); if (parentY != parentX) { for (int i = 0; i < parents.length; i++) { if (parents[i] == parentY) { parents[i] = parentX; } } } } // private int solve() { int ans = 0; boolean visited[] = new boolean[parents.length]; for (int i = 1; i < parents.length; i++) { visited[parents[i]] = true; } for (int i = 1; i < parents.length; i++) { if (visited[i]) { ans++; } } if (ans>0){ ans--; } return ans; } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
b7119e92f19415b95b1d57e3224f63b7
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.io.*; import java.util.*; public class LearningLanguages { static int n, m; static int[] parent; static int find(int x) { return (x == parent[x] ? (x) : (parent[x] = find(parent[x]))); } static void union(int a, int b) { int p1 = find(a); int p2 = find(b); if(p1 != p2) { parent[p1] = p2; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); parent = new int[m+1]; HashSet<Integer> h = new HashSet<Integer>(); for(int i = 1; i <= m; i++) parent[i] = i; for(int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); int k = Integer.parseInt(st.nextToken()); if(k == 0) parent[0]++; else if(k == 1) { int first = Integer.parseInt(st.nextToken()); h.add(first); } else if(k > 1) { int first = Integer.parseInt(st.nextToken()); h.add(first); for(int j = 1; j < k; j++) { int next = Integer.parseInt(st.nextToken()); union(first, next); h.add(next); } } } //System.out.println(Arrays.toString(parent)); int ret = parent[0]; HashSet<Integer> hset = new HashSet<Integer>(); boolean b = true; //System.out.println(Arrays.toString(parent)); for(int i = 1; i <= m; i++) { int par = find(i); //System.out.println(i + " " + par); if(!hset.contains(par) && h.contains(par)) { //System.out.println(i); if(b) { ret--; b = false; } hset.add(par); ret++; } } System.out.println(ret); } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
b7b4739be163fa30607c5e7d4770f42b
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; import java.util.TreeMap; public class Test1 { static ArrayList<Integer>[] adjList; static boolean[] visited; static boolean yes; static void dfs(int a) { visited[a] = true; for (int x : adjList[a]) if (!visited[x]) { dfs(x); yes = true; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); adjList = new ArrayList[100111]; for (int i = 0; i < adjList.length; i++) { adjList[i] = new ArrayList<Integer>(); } HashSet<Integer> hs = new HashSet<Integer>(); boolean f = false; for (int i = 1; i <= n; i++) { int k = sc.nextInt(); hs.add(i*1001); int[] tmp = new int[k]; if(k>0) f = true; for (int j = 0; j < k; j++) { tmp[j] = sc.nextInt() ; } for (int j = 0; j < k; j++) { adjList[i * 1001].add(tmp[j]); adjList[tmp[j]].add(i * 1001); } } visited = new boolean[adjList.length]; int c = 0; for (int i = 0; i <visited.length ; i++) { if (!visited[i] && hs.contains(i)) { dfs(i); c++; } } System.out.println(f?c - 1:c); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
b82fb9e6c44cb67454425a15dc39dbea
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.io.*; import java.util.*; public class test1 { static ArrayList<Integer>[] d; static int []M; static boolean[]vis; public static void main(String[] args) throws IOException, InterruptedException { Scanner sc=new Scanner (System.in); int n=sc.nextInt(); int m=sc.nextInt(); vis=new boolean[n]; M=new int[n]; d=new ArrayList[n]; for(int i=0;i<n;i++) d[i]=new ArrayList(); TreeSet <Integer>[]h=new TreeSet[n]; for(int i=0;i<n;i++) h[i]=new TreeSet(); for(int i=0;i<n;i++) { int y=sc.nextInt(); for(int j=0;j<y;j++) { h[i].add(sc.nextInt()); } } int v=0; for(int o=0;o<n;o++) if(h[o].size()==0) v++; for(int i=0;i<n-1;i++) { for(int w:h[i]) { for(int j=i+1;j<n;j++) { if(h[j].contains(w)) { d[i].add(j); d[j].add(i); } }} } int money=-1; for(int i=0;i<n;i++) if(!vis[i]) { dfs(i); money++;} if(v!=n) System.out.println(money); else System.out.println(n); } public static void dfs(int u) { vis[u]=true; for(int r:d[u]) { if(!vis[r]) { dfs(r); } } } static class Scanner{ StringTokenizer st; BufferedReader br; public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));} public Scanner(String file) throws Exception {br = new BufferedReader(new FileReader(file));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine()throws IOException{return br.readLine();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public char nextChar()throws IOException{return next().charAt(0);} public Long nextLong()throws IOException{return Long.parseLong(next());} public boolean ready() throws IOException{return br.ready();} public void waitForInput() throws InterruptedException {Thread.sleep(3000);} } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
a4e7eda69c900e8ab412e0d1b44eed91
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
256 megabytes
import java.util.*; public final class Test1 { public static void dfs(int graph[][],int start,int n,boolean visited[]){ visited[start]=true; for(int i=0;i<n;i++){ if(graph[start][i]==1 && !visited[i]){ dfs(graph,i,n,visited); } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); ArrayList<Integer> arr[]=new ArrayList[n]; int count=0; for(int i=0;i<n;i++){ arr[i]=new ArrayList(); int k=sc.nextInt(); count+=k; for(int j=0;j<k;j++){ arr[i].add(sc.nextInt()); } } int graph[][]=new int[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ graph[i][j]=0; } } for(int i=0;i<n;i++){ int size=arr[i].size(); for(int j=0;j<size;j++){ int x=arr[i].get(j); for(int k=0;k<n;k++){ if(i!=k && arr[k].contains(x)){ graph[i][k]=1; } } } } boolean visited[]=new boolean[n]; int connected=0; for(int i=0;i<n;i++){ if(!visited[i]){ connected++; dfs(graph,i,n,visited); } } /* for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ System.out.print(graph[i][j]+" "); } System.out.println(); }*/ if(count==0) System.out.println(connected); else System.out.println(connected-1); } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
e15b163be1c043809ed6ffefe18fba9e
train_000.jsonl
1362065400
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
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. */ /** * * @author dipankar12 */ import java.io.*; import java.util.*; public class r277a { public static void main(String args[]) { fastio in=new fastio(System.in); PrintWriter pw=new PrintWriter(System.out); r277a1 ob=new r277a1(); int n=in.nextInt(); int m=in.nextInt(); int count=0; for(int i=0;i<n;i++) { int num=in.nextInt(); if(num==0) count++; else if(num==1) { int x=in.nextInt(); if(ob.findset(x)==-100) ob.makeset(x); } else { int lang=in.nextInt(); if(ob.findset(lang)==-100) ob.makeset(lang); for(int j=0;j<num-1;j++) { int lang1=in.nextInt(); if(ob.findset(lang1)==-100) ob.makeset(lang1); ob.union(lang, lang1); lang=lang1; } //System.out.println("Hello for "+(i+1)); } } HashSet<Long> hs=new HashSet<Long>(); for(int i=0;i<m;i++) { long x=ob.findset(i+1); //System.out.println("x is "+x+" for "+(i+1)); if(x!=-100) hs.add(x); } //System.out.println("size is"+hs.size()+" hs is "+hs+"count is "+count); int size=hs.size(); if(size!=0) size--; pw.println(size+count); pw.close(); } static class fastio { private final InputStream stream; private final byte[] buf = new byte[8192]; private int cchar, snchar; private SpaceCharFilter filter; public fastio(InputStream stream) { this.stream = stream; } public int nxt() { if (snchar == -1) throw new InputMismatchException(); if (cchar >= snchar) { cchar = 0; try { snchar = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snchar <= 0) return -1; } return buf[cchar++]; } public int nextInt() { int c = nxt(); while (isSpaceChar(c)) { c = nxt(); } int sgn = 1; if (c == '-') { sgn = -1; c = nxt(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = nxt(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = nxt(); while (isSpaceChar(c)) { c = nxt(); } int sgn = 1; if (c == '-') { sgn = -1; c = nxt(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = nxt(); } 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 = nxt(); while (isSpaceChar(c)) { c = nxt(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nxt(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = nxt(); while (isSpaceChar(c)) c = nxt(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nxt(); } 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); } } } class r277a2 { long data; r277a2 parent; int rank; } class r277a1 { private HashMap<Long,r277a2> hm=new HashMap<Long,r277a2>(); public void makeset(long data) { r277a2 ob=new r277a2(); ob.data=data; ob.parent=ob; ob.rank=0; hm.put(data, ob); } boolean union(long data1,long data2) { r277a2 ob1=hm.get(data1); r277a2 ob2=hm.get(data2); r277a2 parent1=findset(ob1); r277a2 parent2=findset(ob2); if(parent1.data==parent2.data) return false; if(parent1.rank>=parent2.rank) { parent1.rank=(parent1.rank==parent2.rank)?parent1.rank+1:parent1.rank; parent2.parent=parent1; //System.out.println("Making union of"+parent2.data+" "+parent1.data); } else parent1.parent=parent2; return true; } public long findset(long data) { if(hm.get(data)==null) return -100; return findset(hm.get(data)).data; } r277a2 findset(r277a2 ob) { r277a2 parent=ob.parent; if(parent==ob) return parent; ob.parent=findset(ob.parent); return ob.parent; } void print() { System.out.println(hm); } }
Java
["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"]
2 seconds
["0", "2", "1"]
NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Java 8
standard input
[ "dsu", "dfs and similar" ]
e2836276aee2459979b232e5b29e6d57
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.
1,400
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
standard output
PASSED
af08f6067868eb5cdb6b5c646b154ed9
train_000.jsonl
1459182900
Limak is a big polar bear. He prepared n problems for an algorithmic contest. The i-th problem has initial score pi. Also, testers said that it takes ti minutes to solve the i-th problem. Problems aren't necessarily sorted by difficulty and maybe harder problems have smaller initial score but it's too late to change it — Limak has already announced initial scores for problems. Though it's still possible to adjust the speed of losing points, denoted by c in this statement.Let T denote the total number of minutes needed to solve all problems (so, T = t1 + t2 + ... + tn). The contest will last exactly T minutes. So it's just enough to solve all problems.Points given for solving a problem decrease linearly. Solving the i-th problem after x minutes gives exactly points, where is some real constant that Limak must choose.Let's assume that c is fixed. During a contest a participant chooses some order in which he or she solves problems. There are n! possible orders and each of them gives some total number of points, not necessarily integer. We say that an order is optimal if it gives the maximum number of points. In other words, the total number of points given by this order is greater or equal than the number of points given by any other order. It's obvious that there is at least one optimal order. However, there may be more than one optimal order.Limak assumes that every participant will properly estimate ti at the very beginning and will choose some optimal order. He also assumes that testers correctly predicted time needed to solve each problem.For two distinct problems i and j such that pi &lt; pj Limak wouldn't be happy to see a participant with strictly more points for problem i than for problem j. He calls such a situation a paradox.It's not hard to prove that there will be no paradox for c = 0. The situation may be worse for bigger c. What is the maximum real value c (remember that ) for which there is no paradox possible, that is, there will be no paradox for any optimal order of solving problems?It can be proved that the answer (the maximum c as described) always exists.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; /** * @author Pavel Mavrin */ public class D { private static final double EPS = 1e-9; private void solve() throws IOException { int n = nextInt(); Problem[] problems = new Problem[n]; for (int i = 0; i < n; i++) { problems[i] = new Problem(); } for (int i = 0; i < n; i++) { problems[i].p = nextInt(); } for (int i = 0; i < n; i++) { problems[i].t = nextInt(); } Arrays.sort(problems); int l = 0; long tt = 0; while (l < n) { int r = l + 1; while (r < n) { long d = problems[r].p * problems[l].t - problems[l].p * problems[r].t; if (d != 0) break; r++; } for (int i = l; i < r; i++) { problems[i].minTime = tt + problems[i].t; } for (int i = l; i < r; i++) { tt += problems[i].t; } for (int i = l; i < r; i++) { problems[i].maxTime = tt; } l = r; } Arrays.sort(problems, new Comparator<Problem>() { @Override public int compare(Problem o1, Problem o2) { return Long.compare(o1.p, o2.p); } }); // for (Problem problem : problems) { // System.out.println(problem.p + " " +problem.t + " " +problem.minTime + " " + problem.maxTime); // } double[] x = new double[2 * n + 2]; double[] y = new double[2 * n + 2]; int m = 2; x[0] = 1; x[1] = 0; double[] aa = new double[2 * n + 2]; double[] bb = new double[2 * n + 2]; double res = 1; l = 0; while (l < n) { int r = l + 1; while (r < n && problems[r].p == problems[l].p) { r++; } for (int i = l; i < r; i++) { double b = problems[i].p; double a = -1.0 * problems[i].p * problems[i].maxTime / tt; int ll = -1; int rr = m; while (rr > ll + 1) { int mm = (ll + rr) / 2; double v = a * x[mm] + b; if (v < y[mm] - EPS) { ll = mm; } else { rr = mm; } } // System.out.println(a + " " + b); // System.out.println(problems[i].p + " " + problems[i].t + " " + ll); if (ll == -1) { continue; } if (rr == m) { res = 0; continue; } double xx = (bb[ll] - b) / (a - aa[ll]); if (xx < 0) xx = 0; if (xx > 1) xx = 1; // System.out.println(problems[i].p + " " + problems[i].t + " " + xx); if (Double.isNaN(xx)) continue; res = Math.min(res, xx); } for (int i = l; i < r; i++) { double b = problems[i].p; double a = -1.0 * problems[i].p * problems[i].minTime / tt; while (m > 0 && y[m - 1] < a * x[m - 1] + b + EPS) { m--; } if (m == 0) { x[0] = 1; y[0] = a + b; aa[0] = a; bb[0] = b; m++; } else { double xx = (bb[m - 1] - b) / (a - aa[m - 1]); double yy = a * xx + b; if (xx < 0) xx = 0; if (xx > 1) xx = 1; x[m] = xx; y[m] = yy; aa[m] = a; bb[m] = b; m++; } x[m] = 0; y[m] = b; m++; } // for (int i = 0; i < m; i++) { // System.out.println("(" + x[i] + " " + y[i] + " " + aa[i] + " " + bb[i] + ")"); // } l = r; } out.println(res); } class Problem implements Comparable<Problem> { long t, p; long minTime, maxTime; @Override public int compareTo(Problem o) { long d = o.p * t - p * o.t; if (d != 0) { return Long.signum(d); } else { return Long.compare(p, o.p); } } } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; PrintWriter out = new PrintWriter(System.out); String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } public static void main(String[] args) throws IOException { new D().run(); } private void run() throws IOException { solve(); out.close(); } }
Java
["3\n4 3 10\n1 1 8", "4\n7 20 15 10\n7 20 15 10", "2\n10 20\n10 1"]
3.5 seconds
["0.62500000000", "0.31901840491", "1.00000000000"]
NoteIn the first sample, there are 3 problems. The first is (4, 1) (initial score is 4 and required time is 1 minute), the second problem is (3, 1) and the third one is (10, 8). The total time is T = 1 + 1 + 8 = 10.Let's show that there is a paradox for c = 0.7. Solving problems in order 1, 2, 3 turns out to give the best total score, equal to the sum of: solved 1 minute after the start: solved 2 minutes after the start: solved 10 minutes after the start: So, this order gives 3.72 + 2.58 + 3 = 9.3 points in total and this is the only optimal order (you can calculate total scores for other 5 possible orders too see that they are lower). You should check points for problems 1 and 3 to see a paradox. There is 4 &lt; 10 but 3.72 &gt; 3. It turns out that there is no paradox for c = 0.625 but there is a paradox for any bigger c.In the second sample, all 24 orders are optimal.In the third sample, even for c = 1 there is no paradox.
Java 8
standard input
[ "binary search", "sortings", "math" ]
2dfeceace9a820a2e68ca2b8fe69b7cb
The first line contains one integer n (2 ≤ n ≤ 150 000) — the number of problems. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 108) — initial scores. The third line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 108) where ti is the number of minutes needed to solve the i-th problem.
2,800
Print one real value on a single line — the maximum value of c that and there is no optimal order with a paradox. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if .
standard output
PASSED
87aa99d17b01d3297c55638b655b3b9d
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); scanner.nextLine(); while (t-- > 0) { int n = scanner.nextInt(); int lMax = 0; int rMin = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { lMax = Math.max(lMax, scanner.nextInt()); rMin = Math.min(rMin, scanner.nextInt()); } System.out.println(Math.max(lMax - rMin, 0)); } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
d9dbe026f5244ec6061d2bf1bbc17a60
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int tc = 0; tc < t; tc++) { int n = sc.nextInt(); int[] l = new int[n]; int[] r = new int[n]; for (int i = 0; i < n; i++) { l[i] = sc.nextInt(); r[i] = sc.nextInt(); } System.out.println(solve(l, r)); } sc.close(); } static int solve(int[] l, int[] r) { return Math.max(0, Arrays.stream(l).max().getAsInt() - Arrays.stream(r).min().getAsInt()); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
fdce72ed40c307d52ff5af9ef1bb74ca
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class c1 { public static MyScanner scan; public static PrintWriter out; public static void main(String[] args) { scan=new MyScanner(); out=new PrintWriter(new BufferedOutputStream(System.out)); // int t=1; int t=scan.nextInt(); while(t-->0) { int n=scan.nextInt(); int minb=Integer.MAX_VALUE,maxa=0; for(int c=0;c<n;c++) { int a=scan.nextInt(); int b=scan.nextInt(); if(a>maxa) maxa=a; if(b<minb) minb=b; } out.println(Math.max(0,maxa-minb)); } out.close(); } //-----------------------------------------------------COMP-SPACE----------------------------------------------------- //-------------------------------------------------------------------------------------------------------------------- //util public static int gcd(int a, int b) { if (b == 0) return a; if (a == 0) return b; return (a > b) ? gcd(a % b, b) : gcd(a, b % a); } public static int lcm(int a, int b) { return a * b / gcd(a, b); } public static ArrayList<Integer> getPrimes(int n) { boolean prime[]=new boolean[n+1]; Arrays.fill(prime,true); for (int p=2;p*p<=n;p++) { if (prime[p]) { for (int i=p*2;i<=n;i+=p) { prime[i]=false; } } } ArrayList<Integer> primeNumbers=new ArrayList<Integer>(); for (int i = 2; i <= n; i++) { if (prime[i]) { primeNumbers.add(i); } } return primeNumbers; } public static boolean isPrime(int a) { if (a == 0 || a == 1) { return false; } if (a == 2) { return true; } for (int i = 2; i < Math.sqrt(a) + 1; i++) { if (a % i == 0) { return false; } } return true; } public static ArrayList<Integer> getDivisors(int n) { ArrayList<Integer> div = new ArrayList<Integer>(); for (int i=1;i*i<=n;i++) { if (n%i==0) { div.add(i); if (n/i!=i) div.add(n/i); } } return div; } //scanner 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
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
28a785ce2d36788b592f7fc0c1a82d8a
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.*; 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; public class Kotlin { public static void main(String[] args) throws IOException { Scanner sc = new Scanner (System.in); PrintWriter pw = new PrintWriter (System.out); int t = sc.nextInt(); for (int p = 0 ; p < t ; p ++ ) { int l = sc.nextInt(); int [] arr = new int [l] ; int [] arr2 = new int [l] ; for (int i = 0 ; i < l ; i ++ ) { arr[i] = sc.nextInt(); arr2[i] = sc.nextInt(); }if (l == 1 ) {pw.println(0) ; }else { Arrays.sort(arr); Arrays.sort(arr2); if (arr[l-1] <= arr2[0] ) {pw.println(0);}else { int n = Math.abs(arr2[0] - arr[l-1]) ; int m = Math.abs(arr2[l-1] - arr[0]) ; int max = (n > m) ? m : n ; pw.println(max); }}} pw.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } 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 { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
9eeef3f9050489a058093943a79363ac
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.Scanner; public class Main { final static int N=(int)(1e5+10); static int t; static String s; static int[] a=new int[N]; static int[] b=new int[N]; public static void main(String[] args) { Scanner sc=new Scanner(System.in); t=sc.nextInt(); for(int i =0;i<t;i++) { int n=sc.nextInt(); int min=(int)(1e9); int max=0; for(int j=0;j<n;j++) { a[j]=sc.nextInt(); b[j]=sc.nextInt(); max=a[j]>max? a[j]:max; min=b[j]<min? b[j]:min; } if(n==1) { System.out.println(0); continue; } System.out.println((max-min)>0? max-min:0); } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
1f1ee857eb255bad859b74aec252d9a8
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; public class MathProblem { static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); public static void main(String args[]) { int t = sc.nextInt(); while (t-- > 0) { solve(); } } private static void solve() { int n = sc.nextInt(); int leftEnd = Integer.MAX_VALUE; int rightStart = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { int l = sc.nextInt(); int r = sc.nextInt(); leftEnd = Math.min(leftEnd, r); rightStart = Math.max(rightStart, l); } int ans = 0; if (leftEnd >= rightStart) { ans = 0; } else { ans = rightStart - leftEnd; } System.out.println(ans); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
2c52dded8b5d8d7995342954345c548c
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; /** * Created by Ринат on 26.09.2018. */ public class B { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new BufferedInputStream(System.in)); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); for (int i = 0; i <n; i++) { int m = in.nextInt(); int[]a = new int[m]; int[]b = new int[m]; for (int j = 0; j <m ; j++) { a[j] = in.nextInt(); b[j] = in.nextInt(); } Arrays.sort(a); Arrays.sort(b); int x = a[m-1]-b[0]; if(x<0)x=0; out.println(x); } out.close(); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
a29e6cc71d394d0ea6e1b5b01c74c05a
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.*; import java.io.*; public final class Codechef { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int x = 0; int y = Integer.MAX_VALUE; for(int i = 0; i<n; i++) { x = Math.max(x, sc.nextInt()); y = Math.min(y, sc.nextInt()); } System.out.println(Math.max(x-y, 0)); } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
fe6e170d68617ac6cf786cc1df99e90a
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.Scanner; public class Jonny { static Scanner in=new Scanner(System.in); public static void main(String args[]){ int t=in.nextInt(); for(int i=0;i<t;i++) { int n=in.nextInt(); int[][] a=new int[n][2]; for(int j=0;j<n;j++) for(int k=0;k<2;k++)a[j][k]=in.nextInt(); //Arrays.sort(a, Comparator.comparingInt(arr -> arr[1])); int max=0; int min=a[0][1]; for(int j=0;j<n;j++) { if(a[j][1]<min)min=a[j][1]; if(a[j][0]>max)max=a[j][0]; } if(max-min<0)System.out.println(0); else System.out.println(max-min); } }}
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
66c9d4ad2947b5f4dab521996b500cd7
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.awt.event.MouseAdapter; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws Exception { new Main().run(); } int p = 0,l; char a[]; long readLong(){ long s = 0; while(p<l&&a[p]>='0'&&a[p]<='9'){ s = s*10L+ (a[p]-'0'); p++; } return s; } void solve() { // String n = ns(); // int x = ni(); // // if(x>0){ // // for(int i=0;i< n.length();++i){ // // } // // // // // } int trie[][] = new int[4500][10]; int d[] = new int[4500]; Arrays.fill(d,10000001); int ct = 1; int t =ni(); while(t-->0){ int n = ni(); int p[][] = new int[n][2]; for(int i=0;i<n;++i) { p[i][0] = ni(); p[i][1] = ni(); } Arrays.sort(p,(int[] x,int[] y)->{ return x[1]-y[1]; }); int a = p[0][1]; int b = a; for(int i=1;i<n;++i){ b = Math.max(b,p[i][0]); } println(b-a); } // // for(int i=0;i<1000000;++i){ // r = mul(r,a,k); // if(Arrays.equals(r,a)){ // println(i+1);return; // } // } // println(-1); // int n = ni(); // int p = ni(); // // int h[] = new int[n+1]; // Arrays.fill(h,-1); // int to[] = new int[2*n+5]; // int ne[] = new int[2*n+5]; // int ct = 0; // // for(int i=0;i<p;i++){ // int x = ni(); // int y = ni(); // to[ct] = x; // ne[ct] = h[y]; // h[y] = ct++; // // to[ct] = y; // ne[ct] = h[x]; // h[x] = ct++; // // } // // println(go(1,h,ne,to,-1)); // int n= ni(); // //int m = ni(); // int l = 2*n; // // String s[] = new String[2*n+1]; // // long a[] = new long[2*n+1]; // for(int i=1;i<=n;++i){ // s[i] = ns(); // s[i+n] = s[i]; // a[i] = ni(); // a[i+n] = a[i]; // } // // long dp[][] = new long[l+1][l+1]; // long dp1[][] = new long[l+1][l+1]; // // for(int i = l;i>=1;--i) { // // Arrays.fill(dp[i],-1000000000); // Arrays.fill(dp1[i],1000000000); // } // // for(int i = l;i>=1;--i) { // dp[i][i] = a[i]; // dp1[i][i] = a[i]; // } // // // // for(int i = l;i>=1;--i) { // // for (int j = i+1; j <= l&&j-i+1<=n; ++j) { // // // for(int e=i;e<j;++e){ // if(s[e+1].equals("t")){ // dp[i][j] = Math.max(dp[i][j], dp[i][e]+dp[e+1][j]); // dp1[i][j] = Math.min(dp1[i][j], dp1[i][e]+dp1[e+1][j]); // }else{ // // long f[] = {dp[i][e]*dp[e+1][j],dp1[i][e]*dp1[e+1][j],dp[i][e]*dp1[e+1][j],dp1[i][e]*dp[e+1][j]}; // // for(long u:f) { // dp[i][j] = Math.max(dp[i][j], u); // dp1[i][j] = Math.min(dp1[i][j], u); // } // } // // // } // // } // } // long ma = -100000000; // List<Integer> li = new ArrayList<>(); // for (int j = 1; j <= n; ++j) { // if(dp[j][j+n-1]==ma){ // li.add(j); // }else if(dp[j][j+n-1]>ma){ // ma = dp[j][j+n-1]; // li.clear(); // li.add(j); // } // // } // println(ma); // for(int u:li){ // print(u+" "); // } // println(); // println(get(490)); // int num =1; // while(true) { // int n = ni(); // int m = ni(); // if(n==0&&m==0) break; // int p[] = new int[n]; // int d[] = new int[n]; // for(int j=0;j<n;++j){ // p[j] = ni(); // d[j] = ni(); // } // int dp[][] = new int[8001][22]; // int choose[][] = new int[8001][22]; // // for(int v=0;v<=8000;++v){ // for(int u=0;u<=21;++u) { // dp[v][u] = -100000; // choose[v][u] =-1; // } // } // dp[4000][0] = 0; // // for(int j=0;j<n;++j){ // for(int g = m-1 ;g>=0; --g){ // if(p[j] - d[j]>=0) { // for (int v = 4000; v >= -4000; --v) { // if (v + 4000 + p[j] - d[j] >= 0 && v + 4000 + p[j] - d[j] <= 8000 && dp[v + 4000][g] >= 0) { // int ck1 = dp[v + 4000 + p[j] - d[j]][g + 1]; // if (ck1 < dp[v + 4000][g] + p[j] + d[j]) { // dp[v + 4000 + p[j] - d[j]][g + 1] = dp[v + 4000][g] + p[j] + d[j]; // choose[v + 4000 + p[j] - d[j]][g + 1] = j; // } // } // // } // }else{ // for (int v = -4000; v <= 4000; ++v) { // if (v + 4000 + p[j] - d[j] >= 0 && v + 4000 + p[j] - d[j] <= 8000 && dp[v + 4000][g] >= 0) { // int ck1 = dp[v + 4000 + p[j] - d[j]][g + 1]; // if (ck1 < dp[v + 4000][g] + p[j] + d[j]) { // dp[v + 4000 + p[j] - d[j]][g + 1] = dp[v + 4000][g] + p[j] + d[j]; // choose[v + 4000 + p[j] - d[j]][g + 1] = j; // } // } // // } // // // // // // } // } // } // int big = 0; // int st = 0; // boolean ok = false; // for(int v=0;v<=4000;++v){ // int v1 = -v; // if(dp[v+4000][m]>0){ // big = dp[v+4000][m]; // st = v+4000; // ok = true; // } // if(dp[v1+4000][m]>0&&dp[v1+4000][m]>big){ // big = dp[v1+4000][m]; // st = v1+4000; // ok = true; // } // if(ok){ // break; // } // } // int f = 0; // int s = 0; // List<Integer> res = new ArrayList<>(); // while(choose[st][m]!=-1){ // int j = choose[st][m]; // res.add(j+1); // f += p[j]; // s += d[j]; // st -= p[j]-d[j]; // m--; // } // Collections.sort(res); // println("Jury #"+num); // println("Best jury has value " + f + " for prosecution and value " + s + " for defence:"); // for(int u=0;u<res.size();++u){ // print(" "); // print(res.get(u)); // } // println(); // println(); // num++; // } // int n = ni(); // int m = ni(); // // int dp[][] = new int[n][4]; // // for(int i=0;i<n;++i){ // for(int j=0;j<m;++j){ // for(int c = 0;c<4;++c){ // if(c==0){ // dp[i][j][] = // } // } // } // } } static void pushdown(int num, int le, int ri) { } long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } InputStream is; PrintWriter out; void run() throws Exception { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } 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 char ncc() { int b = readByte(); return (char) b; } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private String nline() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[][] nm(int n, int m) { char[][] a = new char[n][]; for (int i = 0; i < n; i++) a[i] = ns(m); return a; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); 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 << 3) + (num << 1) + (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(); } } void print(Object obj) { out.print(obj); } void println(Object obj) { out.println(obj); } void println() { out.println(); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
a11b2748328c517bfce0c37dd694336a
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.Scanner; /** * * @author Hp */ public class JavaApplication141 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int t= in.nextInt(); while(t-->0){ int n=in.nextInt(); long min = 1000000000; int max = 0; for (int i=0; i<n ;i++) { int x = in.nextInt() ; max = Math.max(max, x); //4 int y = in.nextInt() ; min = Math.min(min,y ); //0 } System.out.println(Math.max(max-min,0)); }}}
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
4a4580310411a0f14a39bd7513ae12a8
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.io.*; import java.util.*; public class __Solution { static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; public static void main(String[] args) { new __Solution().run(); } BufferedReader in; PrintWriter out; StringTokenizer tok; void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } tok = new StringTokenizer(""); } void run() { try { long timeStart = System.currentTimeMillis(); init(); solve(); out.close(); long timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeStart)); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } String readLine() throws IOException { return in.readLine(); } String delimiter = " "; String readString() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(delimiter); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } void solve() throws IOException { int t = readInt(); for(int j = 0; j < t; ++j){ int n = readInt(); int amn = readInt(); int bmx = readInt(); for(int i = 1; i < n; ++i){ int a = readInt(); int b = readInt(); if(a > amn){ amn = a; } if(b < bmx){ bmx = b; } } if(amn - bmx < 0){ out.println(0); } else{ out.println(amn - bmx); } } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
dac89892505fe96424cb3bb039207a4b
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.text.*; import java.io.*; public final class Solution { static PrintWriter out = new PrintWriter(System.out); static void flush() { out.flush(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } static boolean isPalindrome(String str1, String str2) { String str3 = str1+str2; int i = 0, j = str3.length()-1; while(i < j) { char a = str3.charAt(i), b = str3.charAt(j); if(a != b) return false; i++;j--; } return true; } static boolean isPalindrome(String str) { int i = 0, j = str.length()-1; while(i < j) { char a = str.charAt(i), b = str.charAt(j); if(a != b) return false; i++;j--; } return true; } 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());} static int fact(int n) { if(n == 1) return 1; return n * fact(n-1); } public int[] readIntArray(int n) { int[] arr = new int[n]; for(int i=0; i<n; ++i) arr[i]=nextInt(); return arr; } public int[][] readIntArray(int m, int n){ int[][] arr = new int[m][n]; for(int i = 0;i<m;i++) for(int j = 0;j<n;j++) arr[i][j] = nextInt(); return arr; } public String[] readStringArray(int n) { String[] arr = new String[n]; for(int i=0; i<n; ++i) arr[i]= nextLine(); return arr; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } double nextDouble() {return Double.parseDouble(next());} String nextLine() { String str = ""; try{str = br.readLine();} catch (IOException e) {e.printStackTrace();} return str;} } static int solve(int[] l, int[] r, int n) { int x = Integer.MAX_VALUE, y = Integer.MIN_VALUE, min = Integer.MAX_VALUE, max = -1; // if(n == 1) { // return 0; // } for(int i = 1;i<n;i++) { min = Math.min(min, r[i-1]); max = Math.max(max, l[i-1]); if(l[i] > min) { x = Math.min(x, min); y = Math.max(y, l[i]); } else if(r[i] < max) { x = Math.min(x, r[i]); y = Math.max(y, max); } } if(x == Integer.MAX_VALUE && y == Integer.MIN_VALUE){ return 0; } return (Math.abs(y-x)); } public static void main(String args[]) throws Exception { FastReader sc = new FastReader(); long start = System.currentTimeMillis(); int t = sc.nextInt(); while(t-- > 0 ) { int n = sc.nextInt(); int[] l = new int[n]; int[] r = new int[n]; for(int i =0;i<n;i++) { l[i]= sc.nextInt(); r[i] = sc.nextInt(); } out.println(solve(l,r,n)); } flush(); long end = System.currentTimeMillis(); NumberFormat formatter = new DecimalFormat("#0.00000"); //System.out.print("Execution time is " + formatter.format((end - start) / 1000d) + " seconds"); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
cd51e5836244c8a863fbf3f3654b6667
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.io.*; import java.util.*; public class Solver { static ArrayList<Integer> graph[]; static boolean used[]; static int mt[]; static boolean prime[]; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = nextInt(); for (int i = 0; i < t; i++) { int n = nextInt(); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int j = 0; j < n; j++) { int a = nextInt(); int b = nextInt(); if (a > max){ max = a; } if (min > b){ min = b; } } if(max <= min)pw.println(0); else pw.println(Math.abs(max - min)); } pw.close(); } static StringTokenizer st = new StringTokenizer(""); static BufferedReader br; static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
b30e6edd17a094749354d96b9f169d7c
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.io.*; import java.util.*; public class Main { String fileName = ""; public void solve() throws IOException { // code here int n = nextInt(); int ansA = Integer.MIN_VALUE; int ansB = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int a = nextInt(); int b = nextInt(); ansA = Math.max(ansA, a); ansB = Math.min(ansB, b); } //System.out.println("v " + ansA + " " + ansB); if (ansA > ansB) { out.println(ansA - ansB); } else { out.println(0); } } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Main().run(); } private void run() { try { if (fileName.equals("")) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { br = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } int t = nextInt(); for (int i = 0; i < t; i++) { solve(); } out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } 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()); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
7d09d0b70ecd4410e6b4d3560902367d
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(bf.readLine()); while(t-->0) { int n=Integer.parseInt(bf.readLine()); int cmin=Integer.MAX_VALUE; // int c=0; int dmax=Integer.MIN_VALUE; // int d=0; for(int i=0;i<n;i++) { String s[]=bf.readLine().split(" "); int a=Integer.parseInt(s[0]); int b=Integer.parseInt(s[1]); if(b<cmin) { cmin=b; // c=b; } if(a>dmax) { dmax=a; // d=b; } } // System.out.println(dmax+" "+cmin); System.out.println(Math.max((dmax-cmin),0)); } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
e72b48c63bc5ab816c03be663d6983f9
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import sun.security.jgss.TokenTracker; public class myFile { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int query = sc.nextInt(); int start,end; List<MyClass> classList = new ArrayList<MyClass>(); while(query>0 && sc.hasNextInt()) { start = 1123456789; end = 0; query--; int n = sc.nextInt(); classList.clear(); for(int i=1;i<=n;i++) { int x1 = sc.nextInt(); int y1 = sc.nextInt(); MyClass obj = new MyClass(x1,y1); start = Math.min(start, y1); end = Math.max(end, x1); classList.add(obj); } long ans = Math.abs(end-start); int count=0; for(int i=0;i<classList.size();i++) { int u = classList.get(i).getStart(); int v = classList.get(i).getEnd(); if(start>=u && end<=v) count++; } if(count==classList.size())ans=0; System.out.println(ans); } } } class MyClass { int start; int end; public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } public MyClass(int start, int end) { super(); this.start = start; this.end = end; } @Override public String toString() { return "MyClass [start=" + start + ", end=" + end + "]"; } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
a5534dc35b6f21a49378d494cd3cb3f5
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
//package code_; import java.io.*; import java.util.*; public class A_ { public static void main(String[] args) { Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt(); int minr = 2147483647; int maxl = -1; for (int j = 0; j < n; j++) { int l = in.nextInt(); int r = in.nextInt(); minr = Math.min(minr, r); maxl = Math.max(maxl, l); } out.println(Math.max(maxl - minr, 0)); } out.close(); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
a56ff2d5ba1635610dc2adf375c5f652
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
//package main; import java.io.*; import java.util.*; public final class Main { BufferedReader br; StringTokenizer stk; public static void main(String[] args) throws Exception { new Main().run(); } { stk = null; br = new BufferedReader(new InputStreamReader(System.in)); } long mod = 1000_000_000 + 7; void run() throws Exception { int t = ni(); while(t-- > 0) { int n = ni(); List<Pair> pairs = new ArrayList<>(n); for(int i=0; i<n; i++) { pairs.add(new Pair(ni(), ni())); } int minr = Integer.MAX_VALUE; int maxl = Integer.MIN_VALUE; for(Pair p : pairs) { minr = Math.min(minr, p.right); maxl = Math.max(maxl, p.left ); } System.out.println(Math.max(0, maxl - minr)); } } class Pair { int left, right; public Pair(int left, int right) { this.left = left; this.right = right; } @Override public String toString() { return "[" + left + ", " + right + "]"; } } //Reader & Writer String nextToken() throws Exception { if (stk == null || !stk.hasMoreTokens()) { stk = new StringTokenizer(br.readLine(), " "); } return stk.nextToken(); } String nt() throws Exception { return nextToken(); } int ni() throws Exception { return Integer.parseInt(nextToken()); } long nl() throws Exception { return Long.parseLong(nextToken()); } double nd() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
cf4543474703d0c2d8dc6ffe7ffc27bd
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for(int j = 0;j<t;j++) { int n = in.nextInt(); int l[] = new int[n]; int r[] = new int[n]; int minR = Integer.MAX_VALUE; int maxL = -1; for(int i = 0;i<n;i++) { l[i] = in.nextInt(); if(l[i]>maxL) { maxL = l[i]; } r[i] = in.nextInt(); if(r[i]<minR) { minR = r[i]; } } if(maxL>minR) { System.out.println(maxL-minR); } else { System.out.println(0); } } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
8b87eb25bf204af2dbb7b11966491069
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args){ InputReader in = new InputReader(System.in); int t = in.nextInt(); while(t-- > 0){ int n = in.nextInt(); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int l, r; if(n == 1){ l = in.nextInt(); r = in.nextInt(); System.out.println(0); continue; } while(n-- > 0){ l = in.nextInt(); r = in.nextInt(); if(l > max){ max = l; } if(r < min){ min = r; } } if(max - min > 0){ System.out.println(max - min); }else{ System.out.println(0); } } } } 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()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
d29a726b2f5c6c46c0f00f9dfefc74ec
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author John Martin */ 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); AMathProblem solver = new AMathProblem(); solver.solve(1, in, out); out.close(); } static class AMathProblem { public void solve(int testNumber, InputReader c, OutputWriter w) { int tc = c.readInt(); while (tc-- > 0) { int n = c.readInt(); IntIntPair p[] = c.readIntPairArray(n); Arrays.sort(p); int l = p[0].second; for (int i = 0; i < n; i++) { l = Math.min(l, p[i].second); } int r = p[n - 1].first; int res = Math.max(0, r - l); w.printLine(res); } } } static 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 close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public IntIntPair[] readIntPairArray(int size) { IntIntPair[] result = new IntIntPair[size]; for (int i = 0; i < size; i++) { result[i] = readIntPair(); } return result; } public IntIntPair readIntPair() { int first = readInt(); int second = readInt(); return new IntIntPair(first, second); } 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); } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int 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); } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
25bce082e8cb80542d7f399eeddd33ff
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
/* MOHD SADIQ */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; import java.util.ArrayList; public class Main { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private long longVal() throws IOException{ return Long.parseLong(br.readLine().trim()); } private int intVal() throws IOException{ return Integer.parseInt(br.readLine().trim()); } private double doubleVal() throws IOException{ return Double.parseDouble(br.readLine().trim()); } private int[] intArr() throws IOException{ String[] s = br.readLine().trim().split(" "); int n = s.length; int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(s[i]); } return a; } private long[] longArr() throws IOException { String[] s = br.readLine().trim().split(" "); int n = s.length; long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = Long.parseLong(s[i]); } return a; } private double[] doubleArr() throws IOException { String[] s = br.readLine().trim().split(" "); int n = s.length; double[] a = new double[n]; for (int i = 0; i < n; i++) { a[i] = Double.parseDouble(s[i]); } return a; } private String[] stringArr() throws IOException{ String[] s = br.readLine().trim().split(" "); return s; } private char[] charArr() throws IOException{ return br.readLine().trim().toCharArray(); } private static String solve() throws IOException { Main obj = new Main(); int n = obj.intVal(); int[][] arr = new int[n][2]; for(int i=0;i<n;i++) arr[i] = obj.intArr(); Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { if(Integer.compare(o1[0],o2[0])==0) return Integer.compare(o1[1],o2[1]); return Integer.compare(o1[0],o2[0]); } }); // for(int[] i:arr) { // for (int j : i) { // System.out.print(j + " "); // } // System.out.println(); // } int ans = 0; int l = arr[0][0] ,r = arr[0][1]; for(int i=1;i<n;i++){ // System.out.println(l+" "+r); if(arr[i][0]>r){ // System.out.println(l +" "+r); ans += arr[i][0]-r; l = arr[i][0]; r = arr[i][0]; } else { l = Math.max(l,arr[i][0]); r = Math.min(r,arr[i][1]); } } return String.valueOf(ans); } public static void main(String[] args) throws IOException { Main ob = new Main(); int total_test_case = ob.intVal(); // int total_test_case = 1; StringBuffer ans = new StringBuffer(); String k ; for(int test_case =0;test_case<total_test_case;test_case++){ k = solve(); // System.out.println(k); ans.append(k+"\n"); } System.out.print(ans); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
0993d381ba07ac59be4f12d6d81806e3
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.StringTokenizer; public class TaskA { public static String doMain(Reader reader) throws IOException { MyReader in = new MyReader(reader); int i = in.nextInt(); StringBuilder sb = new StringBuilder(); for (int j = 0; j < i; j++) { sb.append(task(in)); sb.append("\n"); } return sb.toString(); } private static String task(MyReader in) throws IOException { int n = in.nextInt(); int minr = 1_000_000_001; int maxl = -1; for (int i = 0; i < n; i++) { int l = in.nextInt(); int r = in.nextInt(); minr = Math.min(minr, r); maxl = Math.max(maxl, l); } return "" + Math.max(0, maxl - minr); } public static void main(String[] args) throws IOException { String result = doMain(new InputStreamReader(System.in)); System.out.println(result); } static class MyReader { BufferedReader bf; StringTokenizer st; String last; MyReader(Reader reader) throws IOException { bf = new BufferedReader(reader); readNextLine(); } String nextToken() throws IOException { while (!st.hasMoreTokens()) { readNextLine(); } return st.nextToken(); } void readNextLine() throws IOException { last = bf.readLine(); if (last == null) last = ""; st = new StringTokenizer(last); } String nextLine() throws IOException { String s = last; readNextLine(); return s; } long nextLong() throws IOException { return Long.parseLong(nextToken()); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int[] readIntArray(int n) throws IOException { int[] answer = new int[n]; for (int i = 0; i < n; ++i) { answer[i] = nextInt(); } return answer; } long[] readLongArray(int n) throws IOException { long[] answer = new long[n]; for (int i = 0; i < n; ++i) { answer[i] = nextLong(); } return answer; } double[] readDoubleArray(int n) throws IOException { double[] answer = new double[n]; for (int i = 0; i < n; ++i) { answer[i] = nextDouble(); } return answer; } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
ef501dde67f5e5c4f1e81c1184e9e888
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer; import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t-->0){ int n=s.nextInt(); int y=Integer.MAX_VALUE; int cnt=0; for (int i=0;i<n;i++) { cnt = Math.max(cnt, s.nextInt()); y = Math.min(y, s.nextInt()); } System.out.println(Math.max(cnt-y,0)); } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
d58aa358eb00a56e556e12a8e3601d90
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.*; import java.io.*; import java.text.DecimalFormat; public class Exam { public static long mod = (long)Math.pow(10, 9)+7 ; public static double epsilon=0.00000000008854;//value of epsilon public static InputReader sc = new InputReader(System.in); public static PrintWriter pw = new PrintWriter(System.out); public static void d(int n,int s,int a[],String ans){ if(a[0]==1){ return; } if(n<=0){ if(Math.sqrt(s)-(int)Math.sqrt(s)==0) { a[0]=1; pw.println(ans); } return; } for(int i=1;i<10;i++){ d(n-1,s+i*i,a,ans+i); } } public static int gr(int s,int e,int a[][],int k,int dp[][]){ int t=0; if(dp[s][k]!=0) return dp[s][k]; if(s==e&&k==0){ dp[s][k]=1; return 1; } if(k<=0){ dp[s][k]=0; return 0; } for(int i=0;i<a[s].length;i++){ if(a[s][i]==1){ t+=gr(i,e,a,k-1,dp); } } dp[s][k]=t; return t; } public static int f(int n,int k,int v[],int dp[][]){ if(n==0) return 0; if(n<0||k<=0) return -1; if(dp[n][k]!=0){ return dp[n][k]; } int c=f(n-k,k,v,dp); if(c==-1){ dp[n][k]=f(n, k-1, v, dp); } else{ dp[n][k]=Math.max(c+v[k-1],f(n, k-1, v, dp)); } return dp[n][k]; } public static int f1(int n,int v[],int dp[]){ if(n==0) return v[0]; else if(n==1) return Math.max(v[0],v[1]); if(dp[n]!=0) return dp[n]; else{ dp[n]=Math.max(f1(n-2,v,dp)+v[n], f1(n-1,v,dp)); return dp[n]; } } public static double dis(int x,int y,int x1[],int y1[],int x2[],int y2[],int x3[],int y3[]){ double d1[]=new double [x1.length]; double d2[]=new double [x2.length]; Arrays.fill(d2,Long.MAX_VALUE); for(int i=0;i<x1.length;i++){ d1[i]=Math.sqrt(Math.pow(x1[i]-x, 2)+Math.pow(y1[i]-y, 2)); } for(int i=0;i<x2.length;i++){ for(int j=0;j<x3.length;j++){ d2[i]=Math.min(Math.sqrt(Math.pow(x2[i]-x3[j], 2)+Math.pow(y2[i]-y3[j], 2)), d2[i]); } } double min=Long.MAX_VALUE; for(int i=0;i<x1.length;i++){ for(int j=0;j<x2.length;j++){ min=Math.min(d1[i]+d2[j]+Math.sqrt(Math.pow(x1[i]-x2[j], 2)+Math.pow(y1[i]-y2[j], 2)), min); } } return min; } public static int check(int b,int c,int a[][],int f[]){ int d=0,in=-1; for(int i=0;i<a.length;i++){ if(i!=f[0]){ if(b==a[i][0]||b==a[i][1]||b==a[i][2]){ if(c==a[i][0]||c==a[i][1]||c==a[i][2]){ in=i; f[0]=in; break; } } } } if(in!=-1){ for(int i=0;i<3;i++){ if(a[in][i]!=b&&a[in][i]!=c) d=a[in][i]; } } return d; } public static long dp(int n,int k,int m,long dp[][],long a[]){ if(k==0&&n>=-1) return 0; if(n-m==-1&&k==1){ dp[n][k]=a[n]; } else if(n-m<0){ dp[n][k]=0; } else if(dp[n][k]!=-1) return dp[n][k]; else{ dp[n][k]=Math.max((long)a[n]+dp(n-m,k-1,m,dp,a), dp(n-1,k,m,dp,a)); } return dp[n][k]; } public static void main(String[] args) { // code starts.. int q=sc.nextInt(); while(q-->0){ int n=sc.nextInt(); int l=Integer.MAX_VALUE,r=0; for(int i=0;i<n;i++){ r=Math.max(sc.nextInt(), r); l=Math.min(sc.nextInt(), l); } if(r-l<=0){ pw.println(0); } else pw.println(Math.abs(r-l)); } // Code ends... pw.flush(); pw.close(); } static class tripletL implements Comparable<tripletL> { Long x, y, z; tripletL(long x, long y, long z) { this.x = x; this.y = y; this.z = z; } public int compareTo(tripletL o) { int result = x.compareTo(o.x); if (result == 0) result = y.compareTo(o.y); if (result == 0) result = z.compareTo(o.z); return result; } public boolean equlas(Object o) { if (o instanceof tripletL) { tripletL p = (tripletL) o; return (x - p.x == 0) && (y - p.y ==0 ) && (z - p.z == 0); } return false; } public String toString() { return x + " " + y + " " + z; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode() + new Long(z).hashCode(); } } public static String Doubleformate(double a){ DecimalFormat f =new DecimalFormat("#.00"); return f.format(a); } public static Comparator<Integer[]> column(int i){ return new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { Integer quantityOne = o1[i]; Integer quantityTwo = o2[i]; return quantityOne.compareTo(quantityTwo); } }; } public static Comparator<Integer[]> pair(){ return new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { int result=o1[0].compareTo(o2[0]); if(result==0) result=o1[1].compareTo(o2[1]); return result; } }; } public static Comparator<Integer[]> Triplet(){ return new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { for(int i=0;i<3;i++){ for(int j=i+1;j<3;j++){ for(int k=0;k<3;k++){ for(int p=k+1;p<3;p++){ if((o1[i]==o2[k]&&o1[j]==o2[p])||(o1[j]==o2[k]&&o1[i]==o2[p])){ } } } } } int result=o1[0].compareTo(o2[0]); if(result==0) result=o1[1].compareTo(o2[1]); if(result==0) result=o1[2].compareTo(o2[2]); return result; } }; } public static String reverseString(String s){ StringBuilder input1 = new StringBuilder(); input1.append(s); input1 = input1.reverse(); return input1.toString(); } public static int[] scanArray(int n){ int a[]=new int [n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); return a; } public static long[] scanLongArray(int n){ long a[]=new long [n]; for(int i=0;i<n;i++) a[i]=sc.nextLong(); return a; } public static String [] scanStrings(int n){ String a[]=new String [n]; for(int i=0;i<n;i++) a[i]=sc.nextLine(); return a; } 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
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
09db85a18244c298fdd05340b27271ac
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.TreeSet; import java.util.Collections; import java.util.Scanner; import java.util.StringTokenizer; public class taskA { public static void main(String[] args) { Scanner in = new Scanner(new BufferedInputStream(System.in)); PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); StringTokenizer st; st = new StringTokenizer(in.nextLine(), " "); int t = Integer.parseInt(st.nextToken()); TreeSet<Integer> points = new TreeSet<>(); TreeSet<Integer> start = new TreeSet<>(); TreeSet<Integer> end = new TreeSet<>(); for (int i = 0; i < t; i++) { points.clear(); start.clear(); end.clear(); st = new StringTokenizer(in.nextLine(), " "); int n = Integer.parseInt(st.nextToken()); for (int j = 0; j < n; j++) { st = new StringTokenizer(in.nextLine(), " "); int l = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); start.add(l); end.add(r); if (!points.contains(l)) { points.add(l); } if (!points.contains(r)) { points.add(r); } } if (points.size() == 1) { pw.println(0); } else { int ans1 = -1; int ans2 = -1; for (int x : points) { if (ans1 == -1 && end.contains(x)) { ans1 = x; } while (start.contains(x)) { start.remove(x); } if (start.size() == 0) { if (ans1 != -1) { ans2 = x; } break; } } pw.println(ans2 - ans1); } } pw.close(); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
a91e6f3ce19dff3f0c07ae456c6ebd94
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.io.BufferedReader; // import java.io.FileInputStream; // import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Random; import java.util.StringTokenizer; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.round; import static java.util.Arrays.copyOf; import static java.util.Arrays.fill; import static java.util.Arrays.sort; import static java.util.Collections.reverseOrder; import static java.util.Collections.sort; public class Solution { FastScanner in; PrintWriter out; private void solve() throws IOException { int n = in.nextInt(); int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { max = max(max, in.nextInt()); min = min(min, in.nextInt()); } out.println(max(0, max - min)); } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); for (int t = in.nextInt(); t-- > 0; ) solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Solution().run(); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
f8d720926ee3cde0a366590395c09622
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
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 * * @author anand.oza */ 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); AMathProblem solver = new AMathProblem(); solver.solve(1, in, out); out.close(); } static class AMathProblem { public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); for (int i = 0; i < t; i++) { solve(in, out); } } private void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int[] l = new int[n]; int[] r = new int[n]; for (int i = 0; i < n; i++) { l[i] = in.nextInt(); r[i] = in.nextInt(); } int answer = Util.max(l) - Util.min(r); answer = Math.max(0, answer); out.println(answer); } } 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()); } } static class Util { public static int max(int... x) { int max = Integer.MIN_VALUE; for (int i : x) { max = Math.max(i, max); } return max; } public static int min(int... x) { int min = Integer.MAX_VALUE; for (int i : x) { min = Math.min(i, min); } return min; } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
956b1e55f83efd59e3418d8a459ca102
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.Scanner; import java.util.*; import java.io.*; public class CodeForcesFormat { public static void main(String args[]){ Scanner input = new Scanner(System.in); int t = input.nextInt(); while(t>0){ int n = input.nextInt(); int max = 0 ; int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++){ max = Math.max(max, input.nextInt()); min = Math.min(min, input.nextInt()); } System.out.println(Math.max(max-min, 0)); t--; } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
0cd249ac2168a96d9d4c3f52afbe8c96
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.Scanner; public class A1227 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int t=0; t<T; t++) { int N = in.nextInt(); int minR = Integer.MAX_VALUE; int maxL = Integer.MIN_VALUE; for (int n=0; n<N; n++) { int L = in.nextInt(); int R = in.nextInt(); minR = Math.min(minR, R); maxL = Math.max(maxL, L); } int answer = Math.max(0, maxL-minR); System.out.println(answer); } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
6629c7d76c24676c2e37ee9f04787b4c
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Day9 { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); int t = Integer.parseInt(reader.readLine()); for(int q = 0; q < t; ++q){ int n = Integer.parseInt(reader.readLine()); ArrayList<Integer> s = new ArrayList<>(); ArrayList<Integer> f = new ArrayList<>(); for(int i =0; i < n; ++i){ StringTokenizer st = new StringTokenizer(reader.readLine()); s.add(Integer.parseInt(st.nextToken())); f.add(Integer.parseInt(st.nextToken())); } Collections.sort(s); Collections.sort(f); writer.println(Math.max(0, s.get(s.size() - 1) - f.get(0))); } writer.close(); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
0ccc8fd8a92f87faab067c429d5d9e31
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(bf.readLine()); while(t-->0) { int n=Integer.parseInt(bf.readLine()); int cmin=Integer.MAX_VALUE; // int c=0; int dmax=Integer.MIN_VALUE; // int d=0; for(int i=0;i<n;i++) { String s[]=bf.readLine().split(" "); int a=Integer.parseInt(s[0]); int b=Integer.parseInt(s[1]); if(b<cmin) { cmin=b; // c=b; } if(a>dmax) { dmax=a; // d=b; } } // System.out.println(dmax+" "+cmin); System.out.println(Math.max((dmax-cmin),0)); } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
bcd5a6dc9b865328891827300595a4ae
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.*; public class CodeForces1227A{ public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); for(int i = 0;i<t;i++){ int n = input.nextInt(); int x = 0; int y = Integer.MAX_VALUE; for(int j = 0;j<n;j++){ x = Math.max(x,input.nextInt()); y = Math.min(y,input.nextInt()); } System.out.println(Math.max(x-y,0)); } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
66f19e1ebeb8badec0aeb343b5262cf7
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class A { public static void main(String[] args) throws Exception { // FileInputStream inputStream = new FileInputStream("input.txt"); // FileOutputStream outputStream = new FileOutputStream("output.txt"); InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); int t = in.nextInt(); // int t = 1; for (int i = 0 ; i < t ; i++) { solver.solve(1, in, out); } out.close(); } static class Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int resultL = Integer.MAX_VALUE; int resultR = Integer.MIN_VALUE; for (int i = 0 ; i < n ; i++) { int l = in.nextInt(); int r = in.nextInt(); resultL = Math.min(resultL, r); resultR = Math.max(resultR, l); } out.println(Math.max(0, resultR - resultL)); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
9ef4109e7ec41535c64cce465a334ddc
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
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 Practice_1100; import java.io.*; /** * * @author Akhilesh */ public class A1227 { public static void main(String[] args) throws IOException { BufferedReader scan = new BufferedReader(new InputStreamReader(System.in)); int test = Integer.parseInt(scan.readLine().trim()); test: while (test-- > 0) { int n = Integer.parseInt(scan.readLine().trim()), min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { String str[] = scan.readLine().split("\\s+"); int a = Integer.parseInt(str[0]); int b = Integer.parseInt(str[1]); min = Math.min(min, b); max = Math.max(max, a); } System.out.println(max - min > 0 ? max - min : 0); } } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
c478ed49c13d353343ee8f863b5bcc43
train_000.jsonl
1574582700
Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.
256 megabytes
import java.awt.*; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; import java.lang.String; import static java.lang.Math.*; public class Main { long mod = (long) 1e9 + 7; void run() throws IOException { int q = nextInt(); while (q-- > 0) { int n = nextInt(); long min_r = Long.MAX_VALUE; long max_l = 0; for (int i = 0; i < n; i++) { int l = nextInt(); int r = nextInt(); min_r = min(r, min_r); max_l = max(l, max_l); } if (n == 1) { pw.println(0); continue; } if (max_l >= min_r) pw.println(max_l - min_r); else pw.println(0); } pw.close(); } class Point { int x, y; public Point(int a, int b) { x = a; y = b; } } class PointComp implements Comparator<Point> { @Override public int compare(Point o1, Point o2) { if (o1.x == o2.x) return Integer.compare(o1.y, o2.y); return Long.compare(o1.x, o2.x); } } class Touple { int x; int from, to; public Touple(int a, int b, int c) { x = a; from = b; to = c; } } class ToupleComp implements Comparator<Touple> { @Override public int compare(Touple o1, Touple o2) { if (o1.x == o2.x && o1.from == o2.from) return Integer.compare(o1.to, o2.to); if (o1.x == o2.x) return Integer.compare(o1.from, o2.from); return Long.compare(o1.x, o2.x); } } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); PrintWriter pw = new PrintWriter(System.out); int nextInt() throws IOException { return Integer.parseInt(next()); } String next() throws IOException { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public Main() throws FileNotFoundException { } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1"]
2 seconds
["2\n4\n0\n0"]
NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.
Java 8
standard input
[ "math" ]
f8a8bda80a75ed430465605deff249ca
The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.
1,100
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.
standard output
PASSED
6a2b721770b4a005b57ab101f9e38780
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.util.*; import java.io.*; public class Main{ BufferedReader in; StringTokenizer str = null; PrintWriter out; private String next() throws Exception{ while(str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return str.nextToken(); } private int nextInt() throws Exception{ return Integer.parseInt(next()); } private long nextLong() throws Exception{ return Long.parseLong(next()); } int n, vtx = 1, root = 0; long []a, prefix; int tree[][]; final static long oo = Long.MAX_VALUE/2; public void run() throws Exception{ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); n = nextInt(); a = new long[n]; for(int i=0;i<n;i++){ a[i] = nextLong(); } long ret = 0; prefix = new long[n+1]; for(int i=1;i<=n;i++){ prefix[i] = prefix[i-1] ^ a[i-1]; ret = Math.max(ret, prefix[i]); } //System.out.println(Arrays.toString(prefix)); tree = new int[4000000][2]; for(int i=0;i<tree.length;i++){ Arrays.fill(tree[i], -1); } add(0); long suffix = 0; for(int i=n-1;i>=0;i--){ suffix^=a[i]; ret = Math.max(ret, suffix); add(suffix); //System.out.println("suffix is " + suffix); long s = get(prefix[i]); //System.out.println("prefix is " + prefix[i] + "; s is " + s); ret = Math.max(ret, s); } out.println(ret); out.close(); } private void add(long x){ int v = root; for(int i=60;i>=0;i--){ if ((x & (1L << i)) > 0){ if(tree[v][1] == -1){ tree[v][1] = vtx++; } v = tree[v][1]; }else{ if (tree[v][0] == -1){ tree[v][0] = vtx++; } v = tree[v][0]; } } } private long get(long x){ long ret = 0; int v = root; for(int i=60;i>=0;i--){ if((x & (1L << i)) > 0){ if (tree[v][0] != -1){ v = tree[v][0]; }else{ v = tree[v][1]; ret|=1L << i; } }else{ if (tree[v][1] != -1){ v = tree[v][1]; ret|=1L << i; }else{ v = tree[v][0]; } } } return ret ^ x; } public static void main(String args[]) throws Exception{ new Main().run(); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
919ebc469f95e4863586c546aea5bca3
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
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.StringTokenizer; public class E { static StringTokenizer st; static BufferedReader in; static int[][]t; static int[]c, res; static int cnt; 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(); long[]a = new long[n+1]; for (int i = 1; i <= n; i++) { a[i] = nextLong(); } long[]xor = new long[n+1]; long ans = 0; for (int i = 1; i <= n; i++) { xor[i] = xor[i-1] ^ a[i]; ans = Math.max(ans, xor[i]); } c = new int[60]; res = new int[60]; long tail = 0; t = new int[60*n+1][2]; t[0][0] = t[0][1] = -1; for (int i = n-1; i >= 1; i--) { tail ^= a[i+1]; ans = Math.max(ans, tail); add(tail); long s = get(xor[i]); ans = Math.max(ans, s); } System.out.println(ans); pw.close(); } private static long get(long s) { int v = 0; for (int i = 59; i >= 0; i--) { c[i] = (int) (s % 2); s /= 2; } for (int i = 0; i < 60; i++) { if (t[v][1-c[i]] != -1) { v = t[v][1-c[i]]; res[i] = 1; } else { v = t[v][c[i]]; res[i] = 0; } } s = 0; for (int i = 0; i < 60; i++) { s = s*2+res[i]; } return s; } private static void add(long s) { for (int i = 59; i >= 0; i--) { c[i] = (int) (s % 2); s /= 2; } int v = 0; for (int i = 0; i < 60; i++) { if (t[v][c[i]]==-1) { t[v][c[i]] = ++cnt; t[cnt][0] = t[cnt][1] = -1; } v = t[v][c[i]]; } } 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
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
4897db440ba8ff2748b965469f7efa65
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { static final int MAXBIT = 45; public void solve() throws Exception { int n = sc.nextInt(); long a [] = new long [n + 2]; long b [] = new long [n + 2]; for (int i = 1; i <= n; i++) { a[i] = sc.nextLong(); } long num = 0; for (int i = n + 1; i >= 0; i--) { num ^= a[i]; b[i] = num; } num = 0; for (int i = 0; i <= n + 1; i++) { num ^= a[i]; a[i] = num; } Arrays.sort(b); long c [] = new long [n + 2]; long d [] = new long [n + 2]; long result = 0; long mask = 0; for (int bit = MAXBIT - 1; bit >= 0; bit--) { mask |= (1L << bit); result ^= (1L << bit); for (int i = 0; i <= n + 1; i++) { c[i] = a[i] & mask; d[i] = b[i] & mask; } boolean good = false; for (int i = 0; i <= n; i++) { long check = c[i] ^ result; int l = -1; int r = n + 2; while (r - l > 1) { int mid = (r + l) >> 1; if (check <= d[mid]) r = mid; else l = mid; } if (r != n + 2 && check == d[r]) { good = true; break; } } if (!good) result ^= (1L << bit); } out.println(result); } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; @Override public void run() { try { // in = new BufferedReader(new FileReader(".in")); // out = new PrintWriter(new FileWriter(".out")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); solve(); } catch (Throwable uncaught) { Solution.uncaught = uncaught; } finally { out.close(); } } public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Solution(), "", (1 << 26)); thread.start(); thread.join(); if (Solution.uncaught != null) { throw Solution.uncaught; } } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
be0249086c5e6c0cd9ebd6a55fd4c92d
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); long[] mas = new long[n]; for (int i = 0; i < n; ++i) mas[i] = in.readLong(); long[] prefix = new long[n]; long value = 0; for (int i = 0; i < n; ++i) { value ^= mas[i]; prefix[i] = value; } PrefixTree tree = new PrefixTree(2); long best = 0; final int MAX_LOG = 50; value = 0; for (int pos = n - 1; pos >= -1; --pos) { int[] array = new int[MAX_LOG]; for (int i = MAX_LOG - 1; i >= 0; --i) array[MAX_LOG - 1 - i] = (int) ((value >> i) & 1); tree.add(array); long ans = 0; PrefixTree.Node v = tree.root; long pref = 0; if (pos > -1) pref = prefix[pos]; for (int i = MAX_LOG - 1; i >= 0; --i) { int bit = (int) ((pref >> i) & 1); if (v.next[bit ^ 1] != null) { ans ^= (1L << i); v = v.next[bit ^ 1]; } else { v = v.next[bit]; } } best = Math.max(best, ans); if (pos > -1) value ^= mas[pos]; } out.printLine(best); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 13]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private 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 long readLong() { 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream), 1 << 13)); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class PrefixTree { public final class Node { public Node[] next; public boolean terminal = false; public Node() { next = new Node[alphabetSize]; } } private int alphabetSize; public Node root; public PrefixTree(int alphabetSize) { this.alphabetSize = alphabetSize; root = new Node(); } public void add(int... array) { Node current = root; for (int i = 0; i < array.length; ++i) { if (current.next[array[i]] == null) current.next[array[i]] = new Node(); current = current.next[array[i]]; } current.terminal = true; } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
ebf694cb10fa99f48de4ce307eac9c65
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class CF282E { public static void main(String[] args) throws Exception { new CF282E().solve(); } private void solve() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] sl = br.readLine().split(" "); long[] a = new long[n]; long leftXor = 0; for (int i = 0; i < n; i++) { a[i] = Long.parseLong(sl[i]); leftXor ^= a[i]; } BitTrie trie = new BitTrie(40); trie.insert(0); long rightXor = 0; long max = leftXor; for (int i = n - 1; i >= 0; i--) { leftXor ^= a[i]; rightXor ^= a[i]; trie.insert(rightXor); max = Math.max(max, leftXor ^ trie.findNearest(~leftXor)); } System.out.println(max); } static class BitTrie { BitTrie[] children = new BitTrie[2]; final int childBit; public BitTrie(int childBit) { this.childBit = childBit; } void insert(long v) { if (childBit < 0) return; int ch = (v & (1L << childBit)) == 0 ? 0 : 1; if (children[ch] == null) children[ch] = new BitTrie(childBit - 1); children[ch].insert(v); } long findNearest(long v) { int ch = (v & (1L << childBit)) == 0 ? 0 : 1; if (children[ch] == null) ch ^= 1; return (ch == 0 ? 0 : (1L << childBit)) + (childBit >= 0 ? children[ch].findNearest(v) : 0); } } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
d96f9dd2667896c2d153108b85f19fa0
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; public class E { /** * @param args */ public static void main(String[] args) { BitSausage bs = new BitSausage(); bs.solve(); bs.print(); } } class BitSausage { BitSausage() { Scanner scr = new Scanner(new BufferedReader(new InputStreamReader(System.in))); n = scr.nextInt(); s = new long[n+1]; for (int i = 1; i <= n; i++){ s[i] = scr.nextLong(); } app = new long[n+1]; } void solve() { for (int i = 1; i <= n; i++){ app[i] = s[i] ^ app[i-1]; } xor = app[n]; Arrays.sort(app); int maxbits = 0; long maxapp = app[n]; while (maxapp > 0) { maxapp = maxapp >> 1; maxbits++; } long [] appp = new long[n+1]; long y = 0; long test; int ind = -1; long xork; for (int k = maxbits-1; k >= 0; k--){ for (int i = 0; i <= n; i++){ appp[i] = (app[i] >> k); } xork = xor >> k; for (int i = 0; i <= n; i++){ test = appp[i] ^ xork ^ ((y << 1) + 1); ind = Arrays.binarySearch(appp, test); if (ind >= 0) { break; } } if (ind >= 0) { y = (y << 1) + 1; } else { y = (y << 1); } } maxp = y; } void print() { System.out.println(maxp); } long xor; long maxp; long[] app; long[] s; int n; }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
b0969a2b9ed2f804e30cdf28f274069f
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class SausageMaxRedo { public static void main(String[] args){ FastScanner sc = new FastScanner(); int n = sc.nextInt(); long[] a = new long[n]; for(int i=0; i<n; i++){ a[i] = sc.nextLong(); } //i is one-based. if 0, 0. long[] delLeft = new long[n+1]; delLeft[0] = 0; delLeft[1] = a[0]; long curXor = a[0]; for(int i=1; i<n;i++){ curXor ^= a[i]; delLeft[i+1] = curXor; } Long[] delRight = new Long[n+1]; delRight[0] = (long) 0; delRight[1] = a[n-1]; curXor = a[n-1]; for(int i=1; i<n;i++){ curXor ^= a[n-i-1]; delRight[i+1] = curXor; } Arrays.sort(delRight); //for each left, find right that max {leftVal ^ rightVal} //it's ok if right overlaps with left, because xor will cancel them out, and we //are taking the max including cases where left does not overlap with right long max = 0; for(int left=0;left<=n;left++){ //2^40 >= (2^10)^4 > 1000^4 = 10^12 long rightVal = 0; //inv: arr[lo] <= rightVal <= arr[hi] and arr[lo] matches arr[hi] for the left 40..40-i digits int lo = 0; int hi = n; //fill bits for rightVal one by one starting from highest bit for(long i=40; i>=0; i--){ long sep = rightVal + (((long)1)<<i); int ind = binSearch(delRight, lo, hi, sep); if(ind == -1){ //everybody has bit = 1, so no choice but to make this bit =1 too rightVal = sep; }else if(ind == hi){ //everybody has bit = 0, so we have to choose 0 and leave rightVal untouched }else{ //some have 0, some have 1 //ind+1 points to the first guy who has 1 int leftBit = (int) ((delLeft[left] >> i) & 1); if(leftBit == 0){ //to max xor, gotta add 1 to this bit rightVal = sep; lo = ind+1; }else{ //leftBit =1, make this bit = 0 hi = ind; } } } max = Math.max(max, delLeft[left] ^ rightVal); } System.out.println(max); } //@return highest index where arr[lo]<s public static int binSearch(Long[] arr, int lo, int hi, long s){ if(arr[lo]>=s){ lo = -1; }else{ while(lo < hi){ int mid = lo + (hi-lo+1)/2; if(arr[mid] >= s){ hi = mid-1; }else{ lo = mid; } } } return lo; } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } 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(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
e10c1bf8528f72e1e097a2a9c8873268
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class Node{ Node t1; Node t0; public Node(){ } public static void add(Node tree,long val){ Node current = tree; for(int i = 40;i >= 0;i--){ if(((1L << i) & val) != 0){ if(current.t1 == null){ current.t1 = new Node(); } current = current.t1; } else { if(current.t0 == null){ current.t0 = new Node(); } current = current.t0; } } } } static long findMax(long res,Node tree){ Node current = tree; long ans = 0; for(int i = 40;i >= 0;i--){ if(((1L << i) & res )== 0){ if(current.t1 != null){ ans |= (1L << i); current = current.t1; } else current = current.t0; } else{ if(current.t0 != null){ ans |= (1L << i); current = current.t0; } else current = current.t1; } } return ans; } public static void main(String [] args)throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); long array[] = new long[n]; StringTokenizer st = new StringTokenizer(br.readLine()); long totxor = 0; for(int i = 0;i < n;i++){ totxor ^= (array[i] = Long.parseLong(st.nextToken())); } Node tree = new Node(); long remxor = 0; long ans = totxor; tree.add(tree,0); for(int k = n - 1;k >= 0;k--){ totxor ^= array[k]; remxor ^= array[k]; Node curr = tree; curr.add(tree,remxor); ans = Math.max(ans,findMax(totxor,curr)); } System.out.println(ans); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
9186761345da1730a4187096d00e3a37
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class Node{ Node t1; Node t0; public Node(){ } public static void add(Node tree,long val){ Node current = tree; for(int i = 40;i >= 0;i--){ if(((1L << i) & val) != 0){ if(current.t1 == null){ current.t1 = new Node(); } current = current.t1; } else { if(current.t0 == null){ current.t0 = new Node(); } current = current.t0; } } } } static long findMax(long res,Node tree){ Node current = tree; long ans = 0; for(int i = 40;i >= 0;i--){ if(((1L << i) & res )== 0){ if(current.t1 != null){ ans |= (1L << i); current = current.t1; } else current = current.t0; } else{ if(current.t0 != null){ ans |= (1L << i); current = current.t0; } else current = current.t1; } } return ans; } public static void main(String [] args)throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); long array[] = new long[n]; StringTokenizer st = new StringTokenizer(br.readLine()); long totxor = 0; for(int i = 0;i < n;i++){ totxor ^= (array[i] = Long.parseLong(st.nextToken())); } Node tree = new Node(); long remxor = 0; long ans = totxor; tree.add(tree,0); for(int k = n - 1;k >= 0;k--){ totxor ^= array[k]; remxor ^= array[k]; tree.add(tree,remxor); ans = Math.max(ans,findMax(totxor,tree)); } System.out.println(ans); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
34bd92dc6081a8ba5324b67692cb5a0b
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Round173_E { class Node { Node zero, one; public Node() { zero = null; one = null; } } Node root; public void add(Node node, long val, int bit) { if (bit == -1) return; boolean zero = (val & (1L << bit)) == 0; if (zero) { if (node.zero == null) node.zero = new Node(); add(node.zero, val, bit - 1); } else { if (node.one == null) node.one = new Node(); add(node.one, val, bit - 1); } } // must add before match query public long maxMatch(Node node, long val, int bit) { if (bit == -1) return 0; boolean zero = (val & (1L << bit)) == 0; if ((zero && node.one != null)) { return (1L << bit) + maxMatch(node.one, val, bit - 1); } else if ((!zero && node.zero != null)) return (1L << bit) + maxMatch(node.zero, val, bit - 1); else if (zero) return maxMatch(node.zero, val, bit - 1); else return maxMatch(node.one, val, bit - 1); } int N; public void solve() throws Exception { InputReader in = new InputReader(); N = in.nextInt(); long[] a = new long[N]; for (int i = 0; i < N; i++) { a[i] = in.nextLong(); } long left[] = new long[N]; left[0] = a[0]; long ans = left[0]; for (int i = 1; i < N; i++) { left[i] = a[i] ^ left[i - 1]; ans = Math.max(ans,left[i]); } root = new Node(); long right = 0; for (int i = N - 1; i > -1; i--) { right ^= a[i]; add(root, right, 40); ans = Math.max(ans,right); ans = Math.max(ans, maxMatch(root, left[i], 40)); } System.out.println(ans); } public static void main(String[] args) throws Exception { new Round173_E().solve(); } static class InputReader { BufferedReader in; StringTokenizer st; public InputReader() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(in.readLine()); } public String next() throws IOException { while (!st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
3008e1ccb8be339a7d22c6cf9fb53a9b
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.*; import java.util.*; public class Main { long X; long[] pxor; long[] s; void run() throws Exception{ int N = nextInt(); s = new long[N + 1]; for (int i = 1; i <= N; i++){ s[i] = nextLong(); } pxor = new long[N + 1]; for (int i = 1; i <= N; i++){ pxor[i] = s[i] ^ pxor[i-1]; } X = pxor[N]; Arrays.sort(pxor); int maxl = 0; long maxp = pxor[N]; while (maxp > 0) { maxp = maxp >> 1; maxl++; } long [] trie = new long[N + 1]; long rside = 0; long lside; int t = -1; for (int k = maxl - 1; k >= 0; k--){ for (int i = 0; i <= N; i++){ trie[i] = (pxor[i] >> k); } long K = X >> k; int i = 0; outer: for (i = 0; i <= N; i++){ lside = trie[i] ^ K ^ ((rside << 1) + 1); t = Arrays.binarySearch(trie, lside); if (t >= 0) { rside = (rside << 1) + 1; break; } } if(i == N + 1) rside = (rside << 1 ); } System.out.println(rside); } public static void main(String args[]) throws Exception { new Main().run(); // read rsideom stdin/stdout // new Main("prog.in", "prog.out").run(); // or use file i/o } BufferedReader in; PrintStream out; StringTokenizer st; Main() throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = System.out; } Main(String is, String os) throws Exception { in = new BufferedReader(new FileReader(new File(is))); out = new PrintStream(new File(os)); } long nextLong() throws Exception { return Long.parseLong(next()); } int nextInt() throws Exception { return Integer.parseInt(next()); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
498665763dc3a2ea799369f8f194e4de
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Sausage { static class Trie{ Trie zero; Trie one; void add(long n, int bit){ if (bit<0)return; boolean isOne = (n&(1L<<bit))!=0; if (isOne){ if (one==null) one = new Trie(); one.add(n,bit-1); } else { if (zero==null) zero = new Trie(); zero.add(n, bit-1); } } long get(long n, int bit){ if (bit<0) return n; boolean isOne = (n&(1L<<bit))!=0; if(isOne){ if(one!=null){ return one.get(n,bit-1); } else { return zero.get(n&(~(1L<<bit)),bit-1); } } else { if(zero!=null){ return zero.get(n,bit-1); } else { return one.get(n|(1L<<bit),bit-1); } } } } public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); int n = sc.nextInt(); long[] nums = new long[n]; for(int i =0; i<n; i++){ nums[i] = sc.nextLong(); } long[] toRight = new long[n+1]; long[] toLeft = new long[n+1]; toRight[0] = 0; for(int i =1; i<n+1; i++){ toRight[i] = toRight[i-1]^nums[i-1]; } Trie t = new Trie(); int len = 42; toLeft[n] = 0; for(int i=n-1; i>=0; i--){ toLeft[i] = toLeft[i+1]^nums[i]; t.add(toLeft[i], len); //Add toLeft[i+1] to the Trie } long max = Long.MIN_VALUE; for(int i=n; i>=0; i--){ long close = t.get((toRight[i]^0xFFFFFFFFFFL),len); // Look for the closest to the complement of toRight i in the Trie max = Math.max(max, toRight[i]^close); } System.out.println(max); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } 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; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
70dfa8e5cc1129fe0e7d95b3884bc7e4
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.util.Scanner; public class Sausage { static class Trie{ Trie zero; Trie one; void add(long n, int bit){ if (bit<0)return; boolean isOne = (n&(1L<<bit))!=0; if (isOne){ if (one==null){ one = new Trie(); } one.add(n,bit-1); } else { if (zero==null){ zero = new Trie(); } zero.add(n, bit-1); } } long get(long n, int bit){ if (bit<0) return n; boolean isOne = (n&(1L<<bit))!=0; if(isOne){ if(one!=null){ return one.get(n,bit-1); } else { return zero.get(n&(~(1L<<bit)),bit-1); } } else { if(zero!=null){ return zero.get(n,bit-1); } else { return one.get(n|(1L<<bit),bit-1); } } } @Override public String toString() { return "(" + zero + ", " + one + ")"; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long[] nums = new long[n]; for(int i =0; i<n; i++){ nums[i] = sc.nextLong(); } long[] toRight = new long[n+1]; long[] toLeft = new long[n+1]; toRight[0] = 0; for(int i =1; i<n+1; i++){ toRight[i] = toRight[i-1]^nums[i-1]; } toLeft[n] = 0; for(int i=n-1; i>=0; i--){ toLeft[i] = toLeft[i+1]^nums[i]; } long max = Long.MIN_VALUE; Trie t = new Trie(); int len = 42; for(int i=n; i>=0; i--){ t.add(toLeft[i], len); //Add toLeft[i+1] to the Trie long close = t.get((toRight[i]^0xFFFFFFFFFFL),len); // Look for the closest to the complement of toRight i in the Trie max = Math.max(max, toRight[i]^close); } System.out.println(max); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
8ce2acdb4c7361e64fb33b655a4d6015
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Sausage { static class Trie{ Trie zero; Trie one; void add(long n, int bit){ if (bit<0)return; boolean isOne = (n&(1L<<bit))!=0; if (isOne){ if (one==null){ one = new Trie(); } one.add(n,bit-1); } else { if (zero==null){ zero = new Trie(); } zero.add(n, bit-1); } } long get(long n, int bit){ if (bit<0) return n; boolean isOne = (n&(1L<<bit))!=0; if(isOne){ if(one!=null){ return one.get(n,bit-1); } else { return zero.get(n&(~(1L<<bit)),bit-1); } } else { if(zero!=null){ return zero.get(n,bit-1); } else { return one.get(n|(1L<<bit),bit-1); } } } @Override public String toString() { return "(" + zero + ", " + one + ")"; } } public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); int n = sc.nextInt(); long[] nums = new long[n]; for(int i =0; i<n; i++){ nums[i] = sc.nextLong(); } long[] toRight = new long[n+1]; long[] toLeft = new long[n+1]; toRight[0] = 0; for(int i =1; i<n+1; i++){ toRight[i] = toRight[i-1]^nums[i-1]; } toLeft[n] = 0; for(int i=n-1; i>=0; i--){ toLeft[i] = toLeft[i+1]^nums[i]; } long max = Long.MIN_VALUE; Trie t = new Trie(); int len = 42; for(int i=n; i>=0; i--){ t.add(toLeft[i], len); //Add toLeft[i+1] to the Trie long close = t.get((toRight[i]^0xFFFFFFFFFFL),len); // Look for the closest to the complement of toRight i in the Trie max = Math.max(max, toRight[i]^close); // Update the maxTot } System.out.println(max); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } 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; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
9c1eafe453fd5fb31267a20d4e15ee2e
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Round_173_E { static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } 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; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } } static class Trie { Trie[] edges = new Trie[2]; void insert(long x) { Trie t = this; for (int idx = 40; idx >= 0; idx--) { int b = (int) (x >> idx & 1); if (t.edges[b] == null) t.edges[b] = new Trie(); t = t.edges[b]; } } long query(long x) { long ans = 0; Trie t = this; for (int idx = 40; idx >= 0; idx--) { int b = (int) (x >> idx & 1); long bL = (long) b; if (t.edges[b] != null) { // Good match ans |= bL << idx; t = t.edges[b]; } else { ans |= (bL^1) << idx; t = t.edges[b^1]; } } return ans; } } public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); int n = sc.nextInt(); long[] A = new long[n]; for (int i = 0; i < n; i++) A[i] = sc.nextLong(); Trie t = new Trie(); long l = 0; t.insert(l); for (int i = 0; i < n; i++) { l ^= A[i]; t.insert(l); } long r = 0; long mask = 0xffffffffffL; long m = r ^ t.query(r ^ mask); for (int i = n-1; i >= 0; i--) { r ^= A[i]; m = Math.max(m, r ^ t.query(r ^ mask)); } System.out.println(m); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
e9411c8a866199ea6016a3c1c891935c
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.*; import java.util.*; public class E { final String filename = new String("E").toLowerCase(); void solve() throws Exception { int n = nextInt(); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } long[] pref = new long[n + 1]; long[] suf = new long[n + 1]; pref[0] = suf[n] = 0; for (int i = 0; i < n; i++) { pref[i + 1] = a[i] ^ pref[i]; } for (int i = n - 1; i >= 0; i--) { suf[i] = suf[i + 1] ^ a[i]; } Arrays.sort(suf); long ans = 0; for (long x : pref) { long mask = 1L << 40; long cur = 0; for (int bit = 39; bit >= 0; bit--) { mask >>>= 1; long tmp = cur; if ((x & mask) == 0) { tmp |= mask; } int id = Arrays.binarySearch(suf, tmp); if (id < 0) { id = (-id - 1); if (id > n || Long.highestOneBit(suf[id] ^ tmp) >= mask) { tmp ^= mask; } } cur = tmp; } ans = Math.max(ans, cur ^ x); } out.println(ans); } public void run() { try { // in = new BufferedReader(new FileReader("gen.out")); // out = new PrintWriter("output.txt"); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } BufferedReader in; PrintWriter out; StringTokenizer st; String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(nextToken()); } long nextLong() throws Exception { return Long.parseLong(nextToken()); } double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } public static void main(String[] args) { new E().run(); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
9df51d2b4f11bff6d93e55a090eb129f
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.InputMismatchException; public class E { public static void main(String[] args) { InputReader in = new InputReader(System.in); int n = in.readInt(); long[] A = new long[n]; long pre = 0; for (int i = 0; i < n; i++) pre ^= A[i] = in.readLong(); long suf = 0; long ans = pre; Trie T = new Trie(); T.insert(0); for (int i = n - 1; i >= 0; i--) { suf ^= A[i]; pre ^= A[i]; T.insert(suf); long v = T.search(pre); ans = Math.max(ans, pre ^ v); } System.out.println(ans); } } class Trie { Trie[] next; public Trie() { next = new Trie[2]; } public void insert(long x) { insert(x, 40); } private void insert(long x, int bit) { if (bit == -1) return; int current = (x & (1l << bit)) == 0 ? 0 : 1; if (next[current] == null) next[current] = new Trie(); next[current].insert(x, bit - 1); } public long search(long x) { return search(x, 40); } private long search(long x, int bit) { if (bit == -1) return 0; int current = (x & (1l << bit)) == 0 ? 1 : 0; if (next[current] != null) return ((long) current << bit) | next[current].search(x, bit - 1); else return ((long) (1 - current) << bit) | next[current ^ 1].search(x, bit - 1); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private 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 long readLong() { 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 String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { 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, readInt()); 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, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
f2c72f8dae71671e91bd3313c4b0febf
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.*; public class Solver { public static void main(String[] Args) throws NumberFormatException, IOException { new Solver().Run(); } PrintWriter pw; StringTokenizer Stok; BufferedReader br; public String nextToken() throws IOException { while (Stok == null || !Stok.hasMoreTokens()) { Stok = new StringTokenizer(br.readLine()); } return Stok.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } final int KOL_BITS=41; int n; long[] a; long result=0; TrieTree tree; class Node{ Node zero; Node one; public Node(){ zero=null; one=null; } } class TrieTree{ Node root; public TrieTree(){ root=new Node(); } public void addLong(long zn){ StringBuilder sb=new StringBuilder(Long.toBinaryString(zn)); int len=sb.length(); for (int i=0; i<KOL_BITS-len; i++){ sb.insert(0, '0'); } Node curNode=root; for (int i=0; i<KOL_BITS; i++){ if (sb.charAt(i)=='0'){ if (curNode.zero==null) curNode.zero=new Node(); curNode=curNode.zero; } else { if (curNode.one==null) curNode.one=new Node(); curNode=curNode.one; } } } public long getMaxZn(long zn){ int[] dig=new int[KOL_BITS]; int[] digZn=new int[KOL_BITS]; for (int i=KOL_BITS-1; i>=0; i--){ digZn[i]=(int) (zn & 1); zn=(zn>>1); } Node curNode=root; int prefDig; long result=0; for (int i=0; i<KOL_BITS; i++){ prefDig=1-digZn[i]; if (prefDig==0){ if (curNode.zero!=null){ dig[i]=1; curNode=curNode.zero; } else { dig[i]=0; curNode=curNode.one; } } else { if (curNode.one!=null){ dig[i]=1; curNode=curNode.one; } else { dig[i]=0; curNode=curNode.zero; } } result=(result<<1)|dig[i]; } return result; } } public void genInput() throws FileNotFoundException{ PrintWriter pw2=new PrintWriter("input.txt"); pw2.println(100000); Random rn=new Random(); for (int i=0; i<100000; i++){ pw2.print(Math.abs(rn.nextLong() % (long)1e12)); pw2.print(' '); } pw2.flush(); pw2.close(); } public void Run() throws NumberFormatException, IOException { //genInput(); //return; //br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter("output.txt"); br=new BufferedReader(new InputStreamReader(System.in)); pw=new PrintWriter(new OutputStreamWriter(System.out)); n=nextInt(); a=new long[n]; Random rn=new Random(); for (int i=0; i<n; i++){ a[i]=nextLong(); } long curZn=0; tree=new TrieTree(); tree.addLong(curZn); for (int i=n-1; i>=0; i--){ curZn=(curZn ^ a[i]); tree.addLong(curZn); } curZn=0; result=tree.getMaxZn(curZn); long curres; for (int i=0; i<n; i++){ curZn=(curZn ^ a[i]); curres=tree.getMaxZn(curZn); if (curres>result) result=curres; } pw.println(result); pw.flush(); pw.close(); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
58b6578cdd1b0cbe5652551738e9185e
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import static java.lang.Math.*; import java.util.*; import java.io.*; public class sausage { public static void main(String [] argv) { Kattio io = new Kattio(System.in, System.out); int n =io.getInt(); long [] A = new long[n]; long [] xors = new long[n+1]; for (int i=0; i<n; i++) { A[i] = io.getLong(); xors[i+1] = A[i]^xors[i]; } long xorAll = xors[n]; // now find max (XOR_{i=j}^{k} A[i]) XOR xorAll XorTrie2 xt2 = new XorTrie2(); int d = 60; xt2.add(0, d); long best = xorAll; for (int j=0; j<n; j++) { best = max(best, xt2.query(xorAll^xors[j+1], d)); xt2.add(xors[j+1], d); } io.println(best); io.close(); } } // @@@@@@@@@@@@@ KATTIO.JAVA class Kattio extends PrintWriter { public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } // ################ XORTRIE2.JAVA @@@@@@@@@@@@@ class XorTrie2 { XorTrie2 [] n; // adds the 'mx' last bits of 'x' to the trie public void add(long x, int mx) { if (mx == 0) return; else { // you get the 'mx':th bit by (1<<(mx-1)) int b = (x & (1L<<(mx-1))) == 0 ? 0 : 1; if (n == null) n = new XorTrie2[2]; if (n[b] == null) n[b] = new XorTrie2(); n[b].add(x, mx-1); } } // queries the trie for the // maximal possible (mx(x) ^ q) // among all 'x' in the trie // where mx(x) is the 'mx' least // significant bits of 'x' // (so, mx(x) = (1<<mx)-1) public long query(long q, int mx) { if (mx == 0) return 0; else { int b = (q&(1L<<(mx-1))) == 0 ? 1 : 0; if (n==null) throw new Error("This should never happen!"); else if (n[b] != null) return (1L<<(mx-1)) | n[b].query(q, mx-1); else return n[b^1].query(q, mx-1); } } public static void main(String [] argv) { XorTrie2 xt = new XorTrie2(); xt.add(0,3); // 000 //xt.add(3,3); // 011 xt.add(2,3); // 010 xt.add(5,3); // 101 //System.out.println("\n" + xt.query()); //xt.add(9); // 1001 //xt.add(12); // 1100 //xt.add(1); // 1 //xt.add(5);// 101 System.out.println(xt.query(4, 3)); // 100 //xt.add(2); //xt.add(7); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
e152f523cc3ea3b056654cdbf7709735
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class E_Round_173_Div2 { public static long MOD = 1000000007; static long re; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); long[] data = new long[n]; long[] post = new long[n]; for (int i = 0; i < n; i++) { data[i] = in.nextLong(); } long result = 0; Node root = new Node(40, 0); for (int i = n - 1; i >= 0; i--) { post[i] = data[i]; if (i + 1 < n) { post[i] ^= post[i + 1]; } if (result < post[i]) { result = post[i]; } insert(post[i], root); } long pre = 0; for (int i = 0; i < n - 1; i++) { pre ^= data[i]; // System.out.println(Long.toBinaryString(pre) + " " + pre); remove(post[i], root); re = 0; getMax(pre, root); if (re < pre) { re = pre; } if (re > result) { result = re; } } out.println(result); out.close(); } static void getMax(long val, Node node) { while (true) { int bit = ((1L << node.bit) & val) == 0 ? 0 : 1; if (bit == 1 && node.val == 1) { val ^= (1L << node.bit); } else if (node.val == 1) { val |= (1L << node.bit); } if (node.bit == 0) { re = val; return; } bit = ((1L << (node.bit - 1)) & val) == 0 ? 0 : 1; if (bit == 0) { if (node.right != null && node.right.count > 0) { node = node.right; } else if (node.left != null && node.left.count > 0) { node = node.left; } else { re = val; } } else { if (node.left != null && node.left.count > 0) { node = node.left; } else if (node.right != null && node.right.count > 0) { node = node.right; } else { re = val; break; } } } } static void remove(long val, Node node) { while (true) { node.count--; if (node.bit == 0) { return; } long nxt = val & (1L << (node.bit - 1)); if (nxt != 0) { node = node.right; } else { node = node.left; } } } static void insert(long val, Node node) { while (true) { node.count++; if (node.bit == 0) { return; } long nxt = val & (1L << (node.bit - 1)); if (nxt != 0) { if (node.right == null) { node.right = new Node(node.bit - 1, 1); } node = node.right; } else { if (node.left == null) { node.left = new Node(node.bit - 1, 0); } node = node.left; } } } static class Node { int bit; int val; int count; Node left, right; public Node(int bit, int val) { super(); this.bit = bit; this.val = val; } } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new // BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new // FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
3480df17268a1da535e723cf9ecae1ac
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.Random; import java.util.StringTokenizer; public class CF173D2E implements CodeforcesSolver { public void solve(InputStream is) { FastScanner in = new FastScanner(is); int n = in.nextInt(); long[] a = new long[n]; for(int i : Range.zeroTo(n)) a[i] = in.nextLong(); // n = 100000; // a = new long[n]; // for(int i : Range.zeroTo(n)) // a[i] = new Random().nextLong() % 1000000000000L; long left = xorAll(a); long right = 0; long max = 0; final MutableMapFactoryForOneKeyType<Boolean> mf = MutableMapFactoryForBooleanKey.create(); Trie<Boolean> trie = new Trie<Boolean>(new TrieNodeFactory<Boolean>() { public TrieNode<Boolean> create() { return new TrieNode<Boolean>() { TrieNode<Boolean> zero, one; public void putChild(Boolean ch, TrieNode<Boolean> node) { if(ch) one = node; else zero = node; } public boolean hasChild(Boolean ch) { if(ch) return one != null; else return zero != null; } public Iterable<Boolean> getEdges() { throw new RuntimeException(); } public int getChildCount() { throw new RuntimeException(); } public TrieNode<Boolean> getChild(Boolean ch) { if(ch) return one; else return zero; } public TrieNode<Boolean> getChild(Boolean ch, TrieNode<Boolean> def) { TrieNode<Boolean> r = getChild(ch); if(r != null) return r; else return def; } }; } }); trie.add(toarray(0)); for(int i=n; i>= 0; i--) { TrieNode<Boolean> cur = trie.getRoot(); long best = 0; for(int j=63;j>=0;j--) { boolean leftbit = (left & (1L<<j)) > 0; // TODO LongBitUtil?? ??????. boolean prefer = !leftbit; if(cur.hasChild(prefer)) { cur = cur.getChild(prefer); best |= (1L<<j); } else { cur = cur.getChild(!prefer); } } // System.out.println("L " + left); // System.out.println(trie); max = Math.max(max, best); if(i-1 >= 0) { left ^= a[i-1]; right ^= a[i-1]; Array<Boolean> array = toarray(right); trie.add(array); } } System.out.println(max); } private long xorAll(long[] a) { long r = 0; for(long v : a) r ^= v; return r; } private Array<Boolean> toarray(long right) { Boolean[] r = new Boolean[64]; for(int j=63;j>=0;j--) r[63-j] = (right & (1L<<j)) > 0; return new MutableArrayUsingJavaArray(r); } public static void main(String[] args) throws Exception { CodeforcesSolverLauncher.launch(new CodeforcesSolverFactory() { public CodeforcesSolver create() { return new CF173D2E(); } }, "E1.txt", "E2.txt", "E3.txt", "E4.txt"); } } interface CodeforcesSolver { void solve(InputStream is); } interface CodeforcesSolverFactory { CodeforcesSolver create(); } class CodeforcesSolverLauncher { public static void launch(CodeforcesSolverFactory factory, String... inputFilePath) throws FileNotFoundException, IOException { if(System.getProperty("ONLINE_JUDGE", "false").equals("true")) { factory.create().solve(System.in); } else { for(String path : inputFilePath) { FileInputStream is = new FileInputStream(new File(path)); factory.create().solve(is); is.close(); System.out.println(); } } } } class FastScanner { private StringTokenizer tokenizer; public FastScanner(InputStream is) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(1024*1024); byte[] buf = new byte[1024*1024]; while(true) { int read = is.read(buf); if(read == -1) break; bos.write(buf, 0, read); } tokenizer = new StringTokenizer(new String(bos.toByteArray())); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(tokenizer.nextToken()); } public long nextLong() { return Long.parseLong(tokenizer.nextToken()); } public String next() { return tokenizer.nextToken(); } } class Range { public static Iterable<Integer> zeroTo(int end) { return fromTo(0, end); } public static Iterable<Integer> fromTo(int begin, int end) { return IntSequenceIterable.create(begin, 1, end-begin); } } class IntSequenceIterable { public static Iterable<Integer> create(final int from, final int step, final int size) { return new Iterable<Integer>() { public Iterator<Integer> iterator() { return new ReadOnlyIterator<Integer>() { int nextIndex = 0; public boolean hasNext() { return nextIndex < size; } public Integer next() { return from + step * (nextIndex++); } }; } }; } } abstract class ReadOnlyIterator<T> implements Iterator<T> { public final void remove() { throw new UnsupportedOperationException(); } } interface Array<T> extends Collection<T> { T get(int index); } interface Collection<T> extends Iterable<T> { int size(); boolean isEmpty(); } interface MutableMapFactoryForOneKeyType<K> { <V> MutableMap<K, V> create(); } interface MutableMap<K, V> extends Collection<MutableEntry<K, V>> { // TODO ���������̽� �̱�. void clear(); void put(K key, V value); void remove(K key); boolean containsKey(K key); V get(K key); V get(K key, V def); Iterable<V> values(); Iterable<K> keys(); } interface MutableEntry<K, V> { // TODO �̰͵� �׳� Entry�� �־�� �ұ�? K getKey(); V getValue(); void setValue(V v); } class MutableArrayUsingJavaArray<T> implements MutableArray<T> { // TODO �̸��ٲٱ� ArrayUsingJavaArray staticarray~�� �����ϴ°ŵ� �� �ٲ���. final private T[] a; final private int start; final private int end; public MutableArrayUsingJavaArray(T[] a) { this.a = a; start = 0; end = a.length-1; } public MutableArrayUsingJavaArray(T[] a, int start, int end) { this.a = a; this.start = start; this.end = end; } public MutableArrayUsingJavaArray(T[] a, int n) { this.a = a; this.start = 0; this.end = n-1; } public T get(int arg0) { return a[start+arg0]; } public void set(int arg0, T arg1) { a[start+arg0] = arg1; } public int size() { return end-start+1; } public final boolean isEmpty() { return size() == 0; } public final Iterator<T> iterator() { return ArrayIterator.create(this); } public final String toString() { return IterableToString.toString(this); } } class IterableToString { public static <T> String toString(Iterable<T> iterable) { StringBuilder sb = new StringBuilder(); sb.append('('); boolean first = true; for(T v : iterable) { if(first) first = false; else sb.append(','); sb.append(v); } sb.append(')'); return sb.toString(); } } class ArrayIterator { public static <T> Iterator<T> create(final Array<T> a) { return new ReadOnlyIterator<T>() { int p = 0; public boolean hasNext() { return p < a.size(); } public T next() { return a.get(p++); } }; } } interface MutableArray<T> extends Array<T> { void set(int index, T value); } class MutableMapFactoryForBooleanKey { public static MutableMapFactoryForOneKeyType<Boolean> create() { return new MutableMapFactoryForOneKeyType<Boolean>() { public <T> MutableMap<Boolean, T> create() { return new MutableMap<Boolean, T>() { T falseValue = null; T trueValue = null; public void clear() { falseValue = null; trueValue= null; } public boolean containsKey(Boolean key) { if(key) return trueValue != null; else return falseValue != null; } public T get(Boolean key) { T r = get(key, null); if(r == null) throw new RuntimeException(); return r; } public T get(Boolean key, T def) { T r; if(key) r = trueValue; else r = falseValue; if(r != null) return r; else return def; } public boolean isEmpty() { return trueValue == null && falseValue != null; } public Iterator<MutableEntry<Boolean, T>> iterator() { return ConvertedDataIterable.create(keys(), new DataConverter<Boolean, MutableEntry<Boolean, T>>() { public MutableEntry<Boolean, T> convert(final Boolean key) { return new MutableEntry<Boolean, T>() { public Boolean getKey() { return key; } public T getValue() { return get(key); } public void setValue(T value) { put(key, value); } }; } }).iterator(); } public Iterable<Boolean> keys() { return FilteringIterable.create(ArrayIterable.create(false, true), new DataFilter<Boolean>() { public boolean isAccepted(Boolean v) { if(v) return trueValue != null; else return falseValue != null; } }); } public int size() { return (trueValue!=null?1:0) + (falseValue!=null?1:0); } public void put(Boolean key, T value) { if(key) trueValue = value; else falseValue = value; } public void remove(Boolean key) { put(key, null); } public Iterable<T> values() { return ConvertedDataIterable.create(keys(), new DataConverter<Boolean, T>() { public T convert(final Boolean key) { return get(key); } }); } }; } }; } } class ConvertedDataIterable { public static <T1, T2> Iterable<T2> create(final Iterable<T1> outerIterable, final DataConverter<T1, T2> converter) { return new Iterable<T2>() { public Iterator<T2> iterator() { return ConvertedDataIterator.create(outerIterable.iterator(), converter); } }; } } class ConvertedDataIterator { public static <T1, T2> Iterator<T2> create(final Iterator<T1> original, final DataConverter<T1, T2> converter) { return new ReadOnlyIterator<T2>() { public boolean hasNext() { return original.hasNext(); } public T2 next() { return converter.convert(original.next()); } }; } } interface DataConverter<T1, T2> { T2 convert(T1 v); } interface DataFilter<T> { boolean isAccepted(T v); } class FilteringIterable { public static <T> Iterable<T> create(final Iterable<? extends T> original, final DataFilter<T> filter) { return new Iterable<T>() { public Iterator<T> iterator() { return new ReadOnlyIterator<T>() { Iterator<? extends T> cursor = original.iterator(); boolean hasNext = false; T next; public boolean hasNext() { ensureNext(); return hasNext; } public T next() { ensureNext(); hasNext = false; return next; } private void ensureNext() { if(!hasNext) { while(cursor.hasNext()) { T value = cursor.next(); if(filter.isAccepted(value)) { next = value; hasNext = true; break; } } } } }; } }; } } class ArrayIterable { public static <T> Iterable<T> create(final T... data) { return ConvertedDataIterable.create(Range.zeroTo(data.length), new DataConverter<Integer, T>() { public T convert(Integer v) { return data[v]; } }); } } class Trie<T> { private TrieNodeFactory<T> nodeFactory; private final TrieNode<T> root; public Trie(TrieNodeFactory<T> nodeFactory) { this.nodeFactory = nodeFactory; root = nodeFactory.create(); } public void add(Iterable<T> sequence) { TrieNode<T> cur = root; for(T v : sequence) { TrieNode<T> subTrie = cur.getChild(v, null); if(subTrie == null) { subTrie = nodeFactory.create(); cur.putChild(v, subTrie); } cur = subTrie; } } public TrieNode<T> getRoot() { return root; } public String toString() { StringBuilder sb = new StringBuilder(); toString(root, 0, sb); return sb.toString(); } private void toString(TrieNode<T> node, int level, StringBuilder sb) { for(T c : node.getEdges()) { for(@SuppressWarnings("unused") int i : Range.zeroTo(level)) sb.append(" "); sb.append(c + "\n"); toString(node.getChild(c), level+1, sb); } } } interface TrieNode<T> { int getChildCount(); boolean hasChild(T ch); TrieNode<T> getChild(T ch, TrieNode<T> def); TrieNode<T> getChild(T ch); Iterable<T> getEdges(); void putChild(T ch, TrieNode<T> node); } interface TrieNodeFactory<T> { TrieNode<T> create(); }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
de45a6f98c5dbfd6e1bc54efdb8af497
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.StringTokenizer; public class CF173D2E implements CodeforcesSolver { // public void solve(InputStream is) { FastScanner in = new FastScanner(is); int n = in.nextInt(); long[] a = new long[n]; for(int i : ZeroTo.get(n)) a[i] = in.nextLong(); long leftsum = xorAll(a); long rightsum = 0; long max = 0; Trie<Boolean> trie = new Trie<Boolean>(TrieNodeFactoryForBooleanKey.getInstance()); trie.add(getBitSequence(0)); for(int i=n; i>= 0; i--) { TrieNode<Boolean> cur = trie.getRoot(); long best = 0; for(int j=63;j>=0;j--) { boolean prefer = !LongBitUtil.get(leftsum, j); if(cur.hasChild(prefer)) { cur = cur.getChild(prefer); best = LongBitUtil.set(best, j); } else { cur = cur.getChild(!prefer); } } max = Math.max(max, best); if(i >= 1) { leftsum ^= a[i-1]; rightsum ^= a[i-1]; trie.add(getBitSequence(rightsum)); } } System.out.println(max); } private long xorAll(long[] a) { long r = 0; for(long v : a) r ^= v; return r; } private Iterable<Boolean> getBitSequence(final long v) { return ConvertedDataIterable.create(IntSequenceIterable.create(63, -1, 64), new DataConverter<Integer, Boolean>() { public Boolean convert(Integer i) { return LongBitUtil.get(v, i); } }); } public static void main(String[] args) throws Exception { CodeforcesSolverLauncher.launch(new CodeforcesSolverFactory() { public CodeforcesSolver create() { return new CF173D2E(); } }, "E1.txt", "E2.txt", "E3.txt", "E4.txt"); } } interface CodeforcesSolver { void solve(InputStream is); } interface CodeforcesSolverFactory { CodeforcesSolver create(); } class CodeforcesSolverLauncher { public static void launch(CodeforcesSolverFactory factory, String... inputFilePath) throws FileNotFoundException, IOException { if(System.getProperty("ONLINE_JUDGE", "false").equals("true")) { factory.create().solve(System.in); } else { for(String path : inputFilePath) { FileInputStream is = new FileInputStream(new File(path)); factory.create().solve(is); is.close(); System.out.println(); } } } } class FastScanner { private StringTokenizer tokenizer; public FastScanner(InputStream is) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(1024*1024); byte[] buf = new byte[1024*1024]; while(true) { int read = is.read(buf); if(read == -1) break; bos.write(buf, 0, read); } tokenizer = new StringTokenizer(new String(bos.toByteArray())); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(tokenizer.nextToken()); } public long nextLong() { return Long.parseLong(tokenizer.nextToken()); } public String next() { return tokenizer.nextToken(); } } class ConvertedDataIterable { public static <T1, T2> Iterable<T2> create(final Iterable<T1> outerIterable, final DataConverter<T1, T2> converter) { return new Iterable<T2>() { public Iterator<T2> iterator() { return ConvertedDataIterator.create(outerIterable.iterator(), converter); } }; } private ConvertedDataIterable() { } } class ConvertedDataIterator { public static <T1, T2> Iterator<T2> create(final Iterator<T1> original, final DataConverter<T1, T2> converter) { return new ReadOnlyIterator<T2>() { public boolean hasNext() { return original.hasNext(); } public T2 next() { return converter.convert(original.next()); } }; } private ConvertedDataIterator() { } } interface DataConverter<T1, T2> { T2 convert(T1 v); } abstract class ReadOnlyIterator<T> implements Iterator<T> { public final void remove() { throw new UnsupportedOperationException(); } } class IntSequenceIterable { public static Iterable<Integer> create(final int from, final int step, final int size) { return new Iterable<Integer>() { public Iterator<Integer> iterator() { return new ReadOnlyIterator<Integer>() { int nextIndex = 0; public boolean hasNext() { return nextIndex < size; } public Integer next() { return from + step * (nextIndex++); } }; } }; } private IntSequenceIterable() { } } class ZeroTo { public static Iterable<Integer> get(int end) { return FromTo.get(0, end); } } class FromTo { public static Iterable<Integer> get(int begin, int end) { return IntSequenceIterable.create(begin, 1, end-begin); } } class Trie<T> { private final TrieNodeFactory<T> factory; private final TrieNode<T> root; public Trie(TrieNodeFactory<T> nodeFactory) { this.factory = nodeFactory; root = factory.create(); } public void add(Iterable<T> sequence) { TrieNode<T> cur = root; for(T v : sequence) { TrieNode<T> subTrie = cur.getChild(v, null); if(subTrie == null) { subTrie = factory.create(); cur.putChild(v, subTrie); } cur = subTrie; } } public TrieNode<T> getRoot() { return root; } public String toString() { StringBuilder sb = new StringBuilder(); toString(root, 0, sb); return sb.toString(); } private void toString(TrieNode<T> node, int level, StringBuilder sb) { for(T c : node.getEdges()) { for (@SuppressWarnings("unused") int i : ZeroTo.get(level)) sb.append(" "); sb.append(c + "\n"); toString(node.getChild(c), level+1, sb); } } } interface TrieNode<T> { int getChildCount(); boolean hasChild(T ch); TrieNode<T> getChild(T ch, TrieNode<T> def); TrieNode<T> getChild(T ch); Iterable<T> getEdges(); void putChild(T ch, TrieNode<T> node); } interface TrieNodeFactory<T> { TrieNode<T> create(); } final class TrieNodeFactoryForBooleanKey { // specialized in speed for boolean keyed nodes. public static TrieNodeFactory<Boolean> getInstance() { return new TrieNodeFactory<Boolean>() { public TrieNode<Boolean> create() { return new BooleanTrieNode(); } }; } private static class BooleanTrieNode implements TrieNode<Boolean> { private TrieNode<Boolean> zero, one; public void putChild(Boolean ch, TrieNode<Boolean> node) { if(ch) one = node; else zero = node; } public boolean hasChild(Boolean ch) { return (ch?one:zero) != null; } public Iterable<Boolean> getEdges() { return FilteredIterable.create(ArrayIterable.create(false, true), new DataFilter<Boolean>() { // slow. improve when need. public boolean isAccepted(Boolean v) { return hasChild(v); } }); } public int getChildCount() { return (one==null?0:1) + (zero==null?0:1); } public TrieNode<Boolean> getChild(Boolean ch) { TrieNode<Boolean> cand = getChild(ch, null); if(cand == null) throw new RuntimeException(); return cand; } public TrieNode<Boolean> getChild(Boolean ch, TrieNode<Boolean> def) { TrieNode<Boolean> cand = ch ? one : zero; if(cand != null) return cand; else return def; } } private TrieNodeFactoryForBooleanKey() {} } class ArrayIterable { public static <T> Iterable<T> create(final T... data) { return ConvertedDataIterable.create(ZeroTo.get(data.length), new DataConverter<Integer, T>() { public T convert(Integer v) { return data[v]; } }); } private ArrayIterable() { } } interface DataFilter<T> { boolean isAccepted(T v); } class FilteredIterable { public static <T> Iterable<T> create(final Iterable<? extends T> original, final DataFilter<T> filter) { return new Iterable<T>() { public Iterator<T> iterator() { return new FilteredIterator<T>(filter, original); } }; } private static final class FilteredIterator<T> extends ReadOnlyIterator<T> { private final DataFilter<T> filter; private final Iterator<? extends T> cursor; private T next = null; private FilteredIterator(DataFilter<T> filter, Iterable<? extends T> original) { this.filter = filter; cursor = original.iterator(); } public boolean hasNext() { tryToStepNext(); return next != null; } public T next() { tryToStepNext(); T r = next; next = null; return r; } private void tryToStepNext() { if (next == null) { while(cursor.hasNext()) { T value = cursor.next(); if(filter.isAccepted(value)) { next = value; break; } } } } } private FilteredIterable() { } } class LongBitUtil { static long set(long v, int pos) { return v | (1L<<pos); } public static boolean get(long v, int pos) { return (v & (1L<<pos)) > 0; } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
7506c292c7c47814187a8369e65ecca9
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.StringTokenizer; public class CF173D2E implements CodeforcesSolver { // public void solve(InputStream is) { FastScanner in = new FastScanner(is); int n = in.nextInt(); long[] a = new long[n]; for(int i : Range.zeroTo(n)) a[i] = in.nextLong(); long leftsum = xorAll(a); long rightsum = 0; long max = 0; Trie<Boolean> trie = new Trie<Boolean>(TrieNodeFactoryForBooleanKey.create()); trie.add(toarray(0)); for(int i=n; i>= 0; i--) { TrieNode<Boolean> cur = trie.getRoot(); long best = 0; for(int j=63;j>=0;j--) { boolean prefer = !LongBitUtil.get(leftsum, j); if(cur.hasChild(prefer)) { cur = cur.getChild(prefer); best = LongBitUtil.set(best, j); } else { cur = cur.getChild(!prefer); } } max = Math.max(max, best); if(i-1 >= 0) { leftsum ^= a[i-1]; rightsum ^= a[i-1]; trie.add(toarray(rightsum)); } } System.out.println(max); } private long xorAll(long[] a) { long r = 0; for(long v : a) r ^= v; return r; } private Iterable<Boolean> toarray(final long v) { return ConvertedDataIterable.create(IntSequenceIterable.create(63, -1, 64), new DataConverter<Integer, Boolean>() { public Boolean convert(Integer i) { return LongBitUtil.get(v, i); } }); // Boolean[] r = new Boolean[64]; // for(int j=63;j>=0;j--) // r[63-j] = LongBitUtil.get(right, j); // return MutableArrayUsingJavaArray.create(r); } public static void main(String[] args) throws Exception { CodeforcesSolverLauncher.launch(new CodeforcesSolverFactory() { public CodeforcesSolver create() { return new CF173D2E(); } }, "E1.txt", "E2.txt", "E3.txt", "E4.txt"); } } interface CodeforcesSolver { void solve(InputStream is); } interface CodeforcesSolverFactory { CodeforcesSolver create(); } class CodeforcesSolverLauncher { public static void launch(CodeforcesSolverFactory factory, String... inputFilePath) throws FileNotFoundException, IOException { if(System.getProperty("ONLINE_JUDGE", "false").equals("true")) { factory.create().solve(System.in); } else { for(String path : inputFilePath) { FileInputStream is = new FileInputStream(new File(path)); factory.create().solve(is); is.close(); System.out.println(); } } } } class FastScanner { private StringTokenizer tokenizer; public FastScanner(InputStream is) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(1024*1024); byte[] buf = new byte[1024*1024]; while(true) { int read = is.read(buf); if(read == -1) break; bos.write(buf, 0, read); } tokenizer = new StringTokenizer(new String(bos.toByteArray())); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(tokenizer.nextToken()); } public long nextLong() { return Long.parseLong(tokenizer.nextToken()); } public String next() { return tokenizer.nextToken(); } } class ConvertedDataIterable { public static <T1, T2> Iterable<T2> create(final Iterable<T1> outerIterable, final DataConverter<T1, T2> converter) { return new Iterable<T2>() { public Iterator<T2> iterator() { return ConvertedDataIterator.create(outerIterable.iterator(), converter); } }; } } class ConvertedDataIterator { public static <T1, T2> Iterator<T2> create(final Iterator<T1> original, final DataConverter<T1, T2> converter) { return new ReadOnlyIterator<T2>() { public boolean hasNext() { return original.hasNext(); } public T2 next() { return converter.convert(original.next()); } }; } } interface DataConverter<T1, T2> { T2 convert(T1 v); } abstract class ReadOnlyIterator<T> implements Iterator<T> { public final void remove() { throw new UnsupportedOperationException(); } } class IntSequenceIterable { public static Iterable<Integer> create(final int from, final int step, final int size) { return new Iterable<Integer>() { public Iterator<Integer> iterator() { return new ReadOnlyIterator<Integer>() { int nextIndex = 0; public boolean hasNext() { return nextIndex < size; } public Integer next() { return from + step * (nextIndex++); } }; } }; } } class Range { public static Iterable<Integer> zeroTo(int end) { return fromTo(0, end); } public static Iterable<Integer> fromTo(int begin, int end) { return IntSequenceIterable.create(begin, 1, end-begin); } } interface Array<T> extends Collection<T> { T get(int index); } interface Collection<T> extends Iterable<T> { int size(); boolean isEmpty(); } class MutableArrayUsingJavaArray { public static <T> MutableArray<T> create(T[] a) { return new Impl<T>(a, 0, a.length); } private static class Impl<T> implements MutableArray<T> { final private T[] a; final private int start; final private int end; public Impl(T[] a, int start, int end) { this.a = a; this.start = start; this.end = end; } public T get(int p) { return a[start + p]; } public void set(int p, T v) { a[start + p] = v; } public int size() { return end - start; } public final boolean isEmpty() { return start == end; } public final Iterator<T> iterator() { return ArrayIterator.create(this); } public final String toString() { return IterableToString.toString(this); } } } class IterableToString { public static <T> String toString(Iterable<T> iterable) { StringBuilder sb = new StringBuilder(); sb.append('('); boolean first = true; for(T v : iterable) { if(first) first = false; else sb.append(','); sb.append(v); } sb.append(')'); return sb.toString(); } } class ArrayIterator { public static <T> Iterator<T> create(final Array<T> a) { return new ReadOnlyIterator<T>() { int p = 0; public boolean hasNext() { return p < a.size(); } public T next() { return a.get(p++); } }; } } interface MutableArray<T> extends Array<T> { void set(int index, T value); } class LongBitUtil { static long set(long v, int pos) { return v | (1L<<pos); } public static boolean get(long v, int pos) { return (v & (1L<<pos)) > 0; } } class Trie<T> { private final TrieNodeFactory<T> nodeFactory; private final TrieNode<T> root; public Trie(TrieNodeFactory<T> factory) { this.nodeFactory = factory; root = factory.create(); } public void add(Iterable<T> sequence) { TrieNode<T> cur = root; for(T v : sequence) { TrieNode<T> subTrie = cur.getChild(v, null); if(subTrie == null) { subTrie = nodeFactory.create(); cur.putChild(v, subTrie); } cur = subTrie; } } public TrieNode<T> getRoot() { return root; } public String toString() { StringBuilder sb = new StringBuilder(); toString(root, 0, sb); return sb.toString(); } private void toString(TrieNode<T> node, int level, StringBuilder sb) { for(T c : node.getEdges()) { for(@SuppressWarnings("unused") int i : Range.zeroTo(level)) sb.append(" "); sb.append(c + "\n"); toString(node.getChild(c), level+1, sb); } } } interface TrieNode<T> { int getChildCount(); boolean hasChild(T ch); TrieNode<T> getChild(T ch, TrieNode<T> def); TrieNode<T> getChild(T ch); Iterable<T> getEdges(); void putChild(T ch, TrieNode<T> node); } interface TrieNodeFactory<T> { TrieNode<T> create(); } class TrieNodeFactoryForBooleanKey { // speed specialized for boolean keyed nodes. public static TrieNodeFactory<Boolean> create() { return new TrieNodeFactory<Boolean>() { public TrieNode<Boolean> create() { return new Node(); } }; } private static class Node implements TrieNode<Boolean> { private TrieNode<Boolean> zero, one; public void putChild(Boolean ch, TrieNode<Boolean> node) { if(ch) one = node; else zero = node; } public boolean hasChild(Boolean ch) { return (ch?one:zero) != null; } public Iterable<Boolean> getEdges() { return FilteredIterable.create(ArrayIterable.create(false, true), new DataFilter<Boolean>() { // slow. improve when need. public boolean isAccepted(Boolean v) { return hasChild(v); } }); } public int getChildCount() { return (one==null?0:1) + (zero==null?0:1); } public TrieNode<Boolean> getChild(Boolean ch) { TrieNode<Boolean> cand = getChild(ch, null); if(cand == null) throw new RuntimeException(); return cand; } public TrieNode<Boolean> getChild(Boolean ch, TrieNode<Boolean> def) { TrieNode<Boolean> cand = ch ? one : zero; if(cand != null) return cand; else return def; } } } interface DataFilter<T> { boolean isAccepted(T v); } class FilteredIterable { public static <T> Iterable<T> create(final Iterable<? extends T> original, final DataFilter<T> filter) { return new Iterable<T>() { public Iterator<T> iterator() { return new ReadOnlyIterator<T>() { Iterator<? extends T> cursor = original.iterator(); T next = null;; public boolean hasNext() { ensureNext(); return next != null; } public T next() { ensureNext(); T r = next; next = null; return r; } private void ensureNext() { if (next == null) { while(cursor.hasNext()) { T value = cursor.next(); if(filter.isAccepted(value)) { next = value; break; } } } } }; } }; } } class ArrayIterable { public static <T> Iterable<T> create(final T... data) { return ConvertedDataIterable.create(Range.zeroTo(data.length), new DataConverter<Integer, T>() { public T convert(Integer v) { return data[v]; } }); } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
7c56938be57524f61511f9810132fef4
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class E { public static void main(String[] args) throws Exception { int cnt = nextInt(); long[] leftXor = new long[cnt + 1]; leftXor[0] = 0; long[] ar = new long[cnt]; for (int i = 0; i < cnt; i++) { ar[i] = nextLong(); leftXor[i + 1] = leftXor[i] ^ ar[i]; } Trie trie = new Trie(); long cur = 0; for (int i = cnt - 1; i >= 0; i--) { trie.addWord(cur, 39, i + 1); cur ^= ar[i]; } trie.addWord(cur, 39, 0); long res = 0; for (int i = 0; i < leftXor.length; i++) { Trie current = trie; long tmp = 0; for (int j = 39; j >= 0; j--) { if (((1l << j) | leftXor[i]) == leftXor[i]) { if (current.edges[0] != null && current.edges[0].maxIdx >= i) { current = current.edges[0]; tmp |= (1l << j); } else { current = current.edges[1]; } } else { if (current.edges[1] != null && current.edges[1].maxIdx >= i) { current = current.edges[1]; tmp |= (1l << j); } else { current = current.edges[0]; } } } res = Math.max(res, tmp); } System.out.println(res); } static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer tokenizer = new StringTokenizer(""); static int nextInt() throws Exception { return Integer.parseInt(next()); } static long nextLong() throws Exception { return Long.parseLong(next()); } static double nextDouble() throws Exception { return Double.parseDouble(next()); } static String next() throws Exception { while (true) { if (tokenizer.hasMoreTokens()) { return tokenizer.nextToken(); } String s = br.readLine(); if (s == null) { return null; } tokenizer = new StringTokenizer(s); } } static class Trie { int maxIdx; Trie[] edges; public Trie() { maxIdx = 0; edges = new Trie[2]; } public void addWord(long word, int wordIdx, int idx) { maxIdx = Math.max(maxIdx, idx); if (wordIdx == -1) { return; } int branch = ((word & (1l << wordIdx)) == 0) ? 0 : 1; if (edges[branch] == null) { edges[branch] = new Trie(); } edges[branch].addWord(word, wordIdx - 1, idx); } } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
02b6aea7707aa73e4181313dffbc0397
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.util.Scanner; // http://codeforces.com/contest/282/problem/E public class SausageMaximization { static class PrefixTreeNode { PrefixTreeNode left; PrefixTreeNode right; } static PrefixTreeNode root = new PrefixTreeNode(); static final int HIGH = 40; public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); long[] a = new long[n]; long left = 0; for (int i = 0; i < n; i++) { a[i] = s.nextLong(); left ^= a[i]; } long ans = left; long right = 0; add(0); for (int i = n - 1; i >= 0; i--) { left ^= a[i]; right ^= a[i]; long match = search(left); ans = Math.max(ans, left ^ match); add(right); } System.out.println(ans); } static long search(long num) { PrefixTreeNode cur = root; long match = 0; for (int i = HIGH; i >= 0; i--) { long ii = (1L << i); if ((ii & num) == 0) { if (cur.right != null) { cur = cur.right; match |= ii; } else { cur = cur.left; } } else { if (cur.left != null) { cur = cur.left; } else { cur = cur.right; match |= ii; } } } return match; } static void add(long num) { PrefixTreeNode cur = root; for (int i = HIGH; i >= 0; i--) { long ii = (1L << i); if ((ii & num) == 0) { if (cur.left == null) { cur.left = new PrefixTreeNode(); } cur = cur.left; } else { if (cur.right == null) { cur.right = new PrefixTreeNode(); } cur = cur.right; } } } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
e135d1e856675ca0d2202131b51a4526
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class Main { private static final int bits = 40; private static int nodeCnt = 1; public static void insert(TrieNode[] trie, long num){ int k = 0; for (int i = bits; i >= 0; i--){ int pos = ((num & (1L << i)) != 0) ? 1 : 0; if (trie[k].children[pos] == -1) { trie[nodeCnt] = new TrieNode(); trie[k].children[pos] = nodeCnt++; } k = trie[k].children[pos]; } } public static long findMaxXor(TrieNode[] trie, long num){ int k = 0; long result = 0; for (int i = bits; i >= 0; i--){ int pos = ((num & (1L << i)) != 0) ? 0 : 1; if (trie[k].children[pos] != -1) { result += (1L << i); k = trie[k].children[pos]; } else { k = trie[k].children[pos ^ 1]; } } return result; } public static void main(String[] args) { // Scanner in = new Scanner(System.in); // int n = in.nextInt(); // long[] numsArr = new long[n]; // for(int i = 0; i < n; i++){ // numsArr[i] = in.nextLong(); // } // in.close(); InputReader in = new InputReader(System.in); int n = in.nextInt(); long[] numsArr = new long[n]; for(int i = 0; i < n; i++){ numsArr[i] = in.nextLong(); } // System.out.println((int) Math.pow(2, 51)); TrieNode[] trie = new TrieNode[41 * 100000]; trie[0] = new TrieNode(); long[] suffixXor = new long[n]; for (int i = n - 1; i >= 0; i--){ if (i == n - 1){ suffixXor[i] = numsArr[i]; continue; } suffixXor[i] = suffixXor[i + 1] ^ numsArr[i]; // System.out.println(i+":\t"+suffixXor[i]); } long[] prefixXor = new long[n]; for (int i = 0; i < n; i++){ if (i == 0){ prefixXor[i] = numsArr[i]; continue; } prefixXor[i] = prefixXor[i - 1] ^ numsArr[i]; } long maxXor = suffixXor[0]; // System.out.println("\t"+maxXor); long suffixValue = 0; insert(trie, 0); for (int i = 0; i < n; i++){ insert(trie, prefixXor[i]); // System.out.println("insert:\t"+prefixXor[i]); suffixValue = (i + 1 < n) ? suffixXor[i+1] : 0; // System.out.println(suffixValue+"\t"+trie.findMaxXor(suffixValue)); maxXor = Math.max(findMaxXor(trie, suffixValue), maxXor); } System.out.println(maxXor); } // public static void main(String[] args) { // // TODO Auto-generated method stub // // InputReader cin = new InputReader(System.in); // PrintWriter cout = new PrintWriter(new OutputStreamWriter(System.out)); // // // // cout.flush(); // } private static class InputReader { public BufferedReader rea; public StringTokenizer tok; public InputReader(InputStream stream) { rea = new BufferedReader(new InputStreamReader(stream), 32768); tok = null; } public String next() { while (tok == null || !tok.hasMoreTokens()) { try { tok = new StringTokenizer(rea.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tok.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } } class TrieNode { public int[] children; public TrieNode() { children = new int[2]; children[0] = children[1] = -1; } }
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
9153c8b3076a4cba4dc804339b148ab5
train_000.jsonl
1363188600
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
256 megabytes
import java.io.*; import java.util.*; public class E { public static void main(String[] args) { try { new E().solve(); } catch (Exception e) { e.printStackTrace(); } } void solve() throws IOException { // Scanner sc = new Scanner(System.in); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] sp; int n = Integer.parseInt(in.readLine()); long[] a = new long[n]; sp = in.readLine().split(" "); long amax = 0; for (int i = 0; i < n; i++) { a[i] = Long.parseLong(sp[i]); amax = Math.max(amax, a[i]); } // K,root K = 1; while (amax >> K != 0) { K++; } root = new BitTree(); add(0); // xor long xor1 = 0; long xor2 = 0; for (int i = 0; i < n; i++) { xor1 ^= a[i]; } // max long max = 0; for (int i = n - 1; i >= 0; i--) { max = Math.max(max, xor1 ^ find(~xor1)); xor1 ^= a[i]; xor2 ^= a[i]; add(xor2); } max = Math.max(max, xor1 ^ find(~xor1)); System.out.println(max); } int K; BitTree root; void add(long v) { BitTree bt = root; for (int k = K - 1; k >= 0; k--) { int i = (int) (v >> k & 1); if (bt.child[i] == null) { bt.child[i] = new BitTree(); } bt = bt.child[i]; } } long find(long v) { BitTree bt = root; long ret = 0; for (int k = K - 1; k >= 0; k--) { int i = (int) (v >> k & 1); if (bt.child[i] == null) { i = 1 - i; } bt = bt.child[i]; ret |= ((long) i) << k; } return ret; } class BitTree { BitTree[] child = new BitTree[] { null, null }; } } // // // // // // // // // // // // // // // // // // // // // // // // //
Java
["2\n1 2", "3\n1 2 3", "2\n1000 1000"]
2 seconds
["3", "3", "1000"]
null
Java 7
standard input
[ "data structures", "bitmasks", "trees" ]
02588d1e94595cb406d92bb6e170ded6
The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,200
Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.
standard output
PASSED
7b34e1052bfc5c666fe2e74ef87e6ff6
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
import java.util.Scanner; public class FlagDay { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int m = input.nextInt(); int[] dancer = new int[3]; int[] res = new int[n]; for (int i = 0; i < n; ++i) { res[i] = -1; } boolean[] visited = new boolean[3]; int idx; for (int i = 0; i < m; ++i) { for (int j = 0; j < 3; ++j) { visited[j] = false; } for (int j = 0; j < 3; ++j) { dancer[j] = input.nextInt(); if (res[dancer[j] - 1] != -1) { visited[res[dancer[j] - 1] - 1] = true; } } idx = 0; for (int j = 0; j < 3; ++j) { if (res[dancer[j] - 1] == -1) { while (visited[idx]) { ++idx; } visited[idx] = true; res[dancer[j] - 1] = idx + 1; } } } for (int i = 0; i < n; ++i) { System.out.print(res[i]); if (i == n - 1) { System.out.println(); } else { System.out.print(" "); } } } }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
57e2088444918fd02aed59d10b19b68f
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; public class palin { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(System.out); Scanner scan = new Scanner(System.in); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(), a[] = new int[n]; for (int i = 0; i < m; i++) { int p = in.nextInt() - 1, q = in.nextInt() - 1, r = in.nextInt() - 1; if (a[p] == 0) { if (a[q] != 1 && a[r] != 1) { a[p] = 1; } else { if (a[q] != 2 && a[r] != 2) { a[p] = 2; } else { a[p] = 3; } } } if (a[q] == 0) { if (a[p] != 1 && a[r] != 1) { a[q] = 1; } else { if (a[p] != 2 && a[r] != 2) { a[q] = 2; } else { a[q] = 3; } } } if (a[r] == 0) { if (a[q] != 1 && a[p] != 1) { a[r] = 1; } else { if (a[q] != 2 && a[p] != 2) { a[r] = 2; } else { a[r] = 3; } } } } for (int i = 0; i < a.length; i++) { out.print(a[i]); if (i < a.length - 1) { out.print(" "); } } } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public float nextFloat() { return Float.parseFloat(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
c5dc069b242b0ee2866bbd2c3ad00c56
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
import java.io.*; public class B { public static void main(String[] args) throws IOException { Parser in = new Parser(System.in); PrintStream out = new PrintStream(System.out); int n = in.nextInt(); int[] d = new int[n+1]; int m = in.nextInt(); for (int i = 0; i < m; i++) { int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); if (d[a] == 0) { if (d[b] == 0) { if (d[c] == 0) { d[a] = 1; d[b] = 2; d[c] = 3; } else if (d[c] == 1) { d[a] = 2; d[b] = 3; } else if (d[c] == 2) { d[a] = 1; d[b] = 3; } else if (d[c] == 3) { d[a] = 1; d[b] = 2; } } else if (d[b] == 1) { d[a] = 2; d[c] = 3; } else if (d[b] == 2) { d[a] = 1; d[c] = 3; } else if (d[b] == 3) { d[a] = 1; d[c] = 2; } } else if (d[a] == 1) { d[b] = 2; d[c] = 3; } else if (d[a] == 2) { d[b] = 1; d[c] = 3; } else if (d[a] == 3) { d[b] = 1; d[c] = 2; } } for (int i = 1; i <= n; i++) System.out.print(d[i] + " "); } } class Parser { public Parser (InputStream in) { this.in = new DataInputStream(in); } public int nextInt() throws IOException { int c; while ((c = in.read()) != '-' && (c > '9' || c < '0')); boolean neg = c == '-'; if (neg) c = in.read(); int r = 0; while (c <= '9' && c >= '0') { r = r*10 + c - '0'; c = in.read(); } return r; } public String nextName() throws IOException { int c; while (((c = in.read()) > 'Z' || c < 'A') && (c < 'a' || c > 'z')); String s = ""; while (c <= 'Z' && c >= 'A' || c >= 'a' && c <= 'z') { s += (char)c; c = in.read(); } return s; } DataInputStream in; }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
9b576d94ff43df21007893c8ef4adf93
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) { } new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); private void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(); int m = nextInt(); int a[][] = new int[m][3]; int ok[] = new int[n+1]; fill(ok,0); for(int i = 0;i < m;i++){ a[i][0] = nextInt(); a[i][1] = nextInt(); a[i][2] = nextInt(); } for(int i = 0;i < m;i++){ if((ok[a[i][0]]==0)&&(ok[a[i][1]]==0)&&(ok[a[i][2]]==0)){ ok[a[i][0]]=1; ok[a[i][1]]= 2; ok[a[i][2]]=3; } else{ if((ok[a[i][0]]!=0)){ ok[a[i][1]]= (ok[a[i][0]])%3+1; ok[a[i][2]]=(ok[a[i][0]]+1)%3+1; } else{ if((ok[a[i][1]]!=0)){ ok[a[i][0]]= (ok[a[i][1]])%3+1; ok[a[i][2]]=(ok[a[i][1]]+1)%3+1;; } else{ ok[a[i][0]]= (ok[a[i][2]])%3+1; ok[a[i][1]]=(ok[a[i][2]]+1)%3+1;; } } } } for(int i = 1;i <n;i++){ out.print(ok[i]+" "); } out.print(ok[n]); in.close(); out.close(); } void chk(boolean b) { if (b) return; System.out.println(new Error().getStackTrace()[1]); exit(999); } void deb(String fmt, Object... args) { System.out.printf(Locale.US, fmt + "%n", args); } String nextToken() throws IOException { while (!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()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
21199a123290e57da57e377d1e7715c7
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
import java.util.Scanner; public class B { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int m = s.nextInt(); int[] c = new int[n+1]; for(int i = 0; i < m; i++) { int d1 = s.nextInt(); int d2 = s.nextInt(); int d3 = s.nextInt(); if(c[d1] != 0) { c[d2] = (c[d1]+1)%3+1; c[d3] = (c[d2]+1)%3+1; } else if(c[d2] != 0) { c[d3] = (c[d2]+1)%3+1; c[d1] = (c[d3]+1)%3+1; } else if(c[d3] != 0) { c[d1] = (c[d3]+1)%3+1; c[d2] = (c[d1]+1)%3+1; } else { c[d1] = 1; c[d2] = 2; c[d3] = 3; } } for(int i = 1; i <= n; i++) System.out.print(c[i] + " "); } }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
285f28bbf455afce6c7d08d8b1efce39
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package programminginjava; import java.io.*; import java.util.*; /** * * @author vijit */ public class jeff2 { static String[] lines; static boolean debug; public static void assignColor(int[] arr, int person, int[] colorArr){ if(colorArr[person] != -1) return; for(int i=0; i<3; i++){ if(arr[i] == 0){ colorArr[person] = i; arr[i] = 1; return; } } } public static void main(String [] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); // BufferedReader f = new BufferedReader(new FileReader("concom.in")); // out = new PrintWriter(new BufferedWriter(new FileWriter("prefix.out"))); lines = f.readLine().split(" ") ; int n = Integer.parseInt(lines[0]); int m = Integer.parseInt(lines[1]); int[] colorArr = new int[n + 1]; for(int i=0; i<=n; i++){ colorArr[i] = -1; } int a,b,c; debug = false; for(int i=0; i<m; i++){ //if(i==16) debug = true; //else debug = false; int[] arr = {0,0,0}; lines = f.readLine().split(" "); a = Integer.parseInt(lines[0]); if(colorArr[a] != -1){arr[colorArr[a]] = 1;} b = Integer.parseInt(lines[1]); if(colorArr[b] != -1){arr[colorArr[b]] = 1;} c = Integer.parseInt(lines[2]); if(colorArr[c] != -1){arr[colorArr[c]] = 1;} if(debug) System.out.println(Arrays.toString(arr)); assignColor(arr, a, colorArr); if(debug) System.out.println(Arrays.toString(arr)); assignColor(arr, b, colorArr); if(debug) System.out.println(Arrays.toString(arr)); assignColor(arr, c, colorArr); } for(int i=1; i<=n; i++){ System.out.print(colorArr[i] + 1); if(i!=n) System.out.print(" "); } System.out.print("\n"); //out.close(); System.exit(0); } }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
d83f915f13938a46ed2f472c1e5dc9f3
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
//package hash13; import java.io.IOException; import java.util.Arrays; import java.util.Scanner; public class cf207b { public static void main(String args[]) throws IOException { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); int dance[] = new int[n]; int arr[][] = new int[m][3]; for(int i=0;i<m;i++) { for(int j=0;j<3;j++) { arr[i][j] = scan.nextInt(); } } Arrays.fill(dance, 0); dance[arr[0][0]-1] = 1; dance[arr[0][1]-1] = 2; dance[arr[0][2]-1] = 3; for(int i=1;i<m;i++) { int colour[] = new int[3]; Arrays.fill(colour, 0); if(dance[arr[i][0]-1] !=0) { colour[dance[arr[i][0]-1]-1] = 1; } if(dance[arr[i][1]-1] !=0) { colour[dance[arr[i][1]-1]-1] = 1; } if(dance[arr[i][2]-1] !=0) { colour[dance[arr[i][2]-1]-1] = 1; } for(int j=0;j<3;j++) { if(dance[arr[i][j]-1] !=0) continue; else { int k=0; while(k<3) { if(colour[k]==1) { k++; continue; } else { dance[arr[i][j]-1] = k+1; colour[k] = 1; break; } } } } } for(int i=0;i<n;i++) { System.out.print(dance[i]+" "); } } }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
ae3269524badb324853fc1a209b08e2e
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; import java.lang.*; import java.nio.charset.Charset; public class B { public static void main(String[] args) { B a = new B(); a.run(); } void run(){ Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); int[] v = new int[100010]; for (int i = 1; i <= m; i++){ int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); if ((v[a] == 0) && (v[b] != 1) && (v[c] != 1)){ v[a] = 1; } else { if ((v[a] == 0) && (v[b] != 2) && (v[c] != 2)) v[a] = 2; else { if (v[a] == 0) v[a] = 3; } } if ((v[b] == 0) && (v[a] != 1) && (v[c] != 1)){ v[b] = 1; } else { if ((v[b] == 0) && (v[a] != 2) && (v[c] != 2)) v[b] = 2; else { if (v[b] == 0) v[b] = 3; } } if ((v[c] == 0) && (v[b] != 1) && (v[a] != 1)){ v[c] = 1; } else { if ((v[c] == 0) && (v[b] != 2) && (v[a] != 2)) v[c] = 2; else { if (v[c] == 0) v[c] = 3; } } } for (int i = 1; i<= n; i++){ out.print(v[i] + " "); } out.flush(); } }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
8b1f9905a2f5cdd1598e2d4894eaadbb
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeSet; public class B { public static final int MAX = 1001; public static int min_cost(int[] count, int size, int c1, int c2){ int sum_cost = 0; //boolean fst = true; for(int i = 0; i < size; i++){ if(count[i] > 0){ sum_cost += Math.min(c2, c1 * count[i]); } } return sum_cost; } public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); final int n = sc.nextInt(); final int m = sc.nextInt(); int[][] dances = new int[m][3]; for(int i = 0; i < m; i++){ for(int j = 0; j < 3; j++){ dances[i][j] = sc.nextInt() - 1; } } int[] ans = new int[n]; Arrays.fill(ans, -1); for(int i = 0; i < m; i++){ final boolean fst = ans[dances[i][0]] == -1; final boolean snd = ans[dances[i][1]] == -1; final boolean thd = ans[dances[i][2]] == -1; final int fst_n = ans[dances[i][0]]; final int snd_n = ans[dances[i][1]]; final int thd_n = ans[dances[i][2]]; if(fst && snd && thd){ ans[dances[i][0]] = 0; ans[dances[i][1]] = 1; ans[dances[i][2]] = 2; }else if(fst && snd){ ans[dances[i][0]] = (thd_n + 1) % 3; ans[dances[i][1]] = (thd_n + 2) % 3; }else if(fst && thd){ ans[dances[i][0]] = (snd_n + 2) % 3; ans[dances[i][2]] = (snd_n + 1) % 3; }else if(snd && thd){ ans[dances[i][1]] = (fst_n + 1) % 3; ans[dances[i][2]] = (fst_n + 2) % 3; }else if(fst){ for(int t = 0; t < 3; t++){ if(t != snd_n && t != thd_n){ ans[dances[i][0]] = t; break; } } }else if(snd){ for(int t = 0; t < 3; t++){ if(t != fst_n && t != thd_n){ ans[dances[i][1]] = t; break; } } }else if(thd){ for(int t = 0; t < 3; t++){ if(t != fst_n && t != snd_n){ ans[dances[i][2]] = t; break; } } }else{ } } boolean first = true; for(int i = 0; i < n; i++){ if(first){ first = false; }else{ System.out.print(" "); } System.out.print(ans[i] + 1); } System.out.println(); } public static class Scanner { private BufferedReader br; private StringTokenizer tok; public Scanner(InputStream is) throws IOException{ br = new BufferedReader(new InputStreamReader(is)); getLine(); } private void getLine() throws IOException{ while(tok == null || !tok.hasMoreTokens()){ tok = new StringTokenizer(br.readLine()); } } private boolean hasNext(){ return tok.hasMoreTokens(); } public String next() throws IOException{ if(hasNext()){ return tok.nextToken(); }else{ getLine(); return tok.nextToken(); } } public int nextInt() throws IOException{ if(hasNext()){ return Integer.parseInt(tok.nextToken()); }else{ getLine(); return Integer.parseInt(tok.nextToken()); } } public long nextLong() throws IOException{ if(hasNext()){ return Long.parseLong(tok.nextToken()); }else{ getLine(); return Long.parseLong(tok.nextToken()); } } public double nextDouble() throws IOException{ if(hasNext()){ return Double.parseDouble(tok.nextToken()); }else{ getLine(); return Double.parseDouble(tok.nextToken()); } } } }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
6b3d50706f050e4cfa7caa6eae308a6d
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
import java.util.Scanner; public class Codeforces357B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] colors = new int[n+1]; for(int i = 0; i < m; i++){ int a = sc.nextInt(); int c = sc.nextInt(); int b = sc.nextInt(); if(colors[a] != 0){ if(colors[a] == 2){ colors[b] = 1; colors[c] = 3; } else{ colors[b] = 4 - colors[a]; colors[c] = 2; } } else if(colors[b] != 0){ if(colors[b] == 2){ colors[a] = 1; colors[c] = 3; } else{ colors[a] = 4 - colors[b]; colors[c] = 2; } } else{ if(colors[c] % 2 == 0){ colors[c] = 2; colors[a] = 1; colors[b] = 3; } else{ colors[a] = 4 - colors[c]; colors[b] = 2; } } } System.out.print(colors[1]); for(int i = 2; i <= n; i++){ System.out.printf(" %d",colors[i]); } System.out.println(); } }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
40ec7c940728a46ab98162b28a21868d
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
import java.util.*; import java.io.*; public class solution { public static int tonumb(String a) { return Integer.parseInt(a); } public static void toint(int arr[],String a) { String s[] = a.split(" "); int i; for(i=0;i<s.length;i++) { arr[i] = tonumb(s[i]); } return; } public static void print(int a) { System.out.println(a); } public static void print(String a) { System.out.println(a); } public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int temp[] = new int[3]; toint(temp,br.readLine()); int n = temp[0]; int m = temp[1]; int colors[] = new int[n+1]; boolean assigned[]= new boolean[n+1]; int i; int dance[][] = new int[n][3]; for(i=0;i<m;i++) { toint(dance[i],br.readLine()); } boolean valid = false; int j; for(i=1;i<=3;i++) { Arrays.fill(assigned,false); for(j=0;j<m;j++) { if(j==0) { colors[dance[j][0]] = i; assigned[dance[j][0]] = true; assignexc(0,dance,colors,j,assigned); } else { if(assigned[dance[j][0]]) assignexc(0,dance,colors,j,assigned); else if(assigned[dance[j][1]]) assignexc(1,dance,colors,j,assigned); else if(assigned[dance[j][2]]) assignexc(2,dance,colors,j,assigned); else assignexc(-1,dance,colors,j,assigned); } } break; } for(i=1;i<=n;i++) { System.out.print(colors[i]+" "); } } public static void assignexc(int n, int dance[][], int colors[], int j,boolean assigned[]) { if(n==-1) { assigned[dance[j][0]] = true; assigned[dance[j][1]] = true; assigned[dance[j][2]] = true; colors[dance[j][0]] = 1; colors[dance[j][1]] = 2; colors[dance[j][2]] = 3; } else if(n==0) { int x = colors[dance[j][0]]; assigned[dance[j][1]] = true; assigned[dance[j][2]] = true; if(x==1) { colors[dance[j][1]] = 2; colors[dance[j][2]] = 3; } else if(x==2) { colors[dance[j][1]] = 1; colors[dance[j][2]] = 3; } else { colors[dance[j][1]] = 1; colors[dance[j][2]] = 2; } } else if(n==1) { int x = colors[dance[j][1]]; assigned[dance[j][0]] = true; assigned[dance[j][2]] = true; if(x==1) { colors[dance[j][0]] = 2; colors[dance[j][2]] = 3; } else if(x==2) { colors[dance[j][0]] = 1; colors[dance[j][2]] = 3; } else { colors[dance[j][0]] = 1; colors[dance[j][2]] = 2; } } else { int x = colors[dance[j][2]]; assigned[dance[j][0]] = true; assigned[dance[j][1]] = true; if(x==1) { colors[dance[j][0]] = 2; colors[dance[j][1]] = 3; } else if(x==2) { colors[dance[j][0]] = 1; colors[dance[j][1]] = 3; } else { colors[dance[j][0]] = 1; colors[dance[j][1]] = 2; } } } }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
4dd407e3d62e4408fc195ed60a527c18
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws IOException { B solver = new B(); solver.solve(); } private Set<Integer>[] g; private int[] colors; private void solve() throws IOException { FastScanner sc = new FastScanner(System.in); // sc = new FastScanner("7 3\n" + // "1 2 3\n" + // "4 5 6\n" + // "1 4 7\n"); // sc = new FastScanner("7 3\n" + // "1 2 3\n" + // "1 4 5\n" + // "4 6 7\n"); // sc = new FastScanner("5 2\n" + // "4 1 5\n" + // "3 1 2\n"); int n = sc.nextInt(); int m = sc.nextInt(); g = new HashSet[n]; for (int i = 0; i < n; i++) { g[i] = new HashSet<Integer>(); } for (int i = 0; i < m; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; int c = sc.nextInt() - 1; g[a].add(b); g[a].add(c); g[b].add(a); g[b].add(c); g[c].add(a); g[c].add(b); } colors = new int[n]; for (int i = 0; i < n; i++) { if (colors[i] == 0) { dfs(i); } } StringBuilder sb = new StringBuilder(); for (int c : colors) { sb.append(c); sb.append(' '); } System.out.println(sb.toString()); } private boolean dfs(int v) { if (colors[v] > 0) return true; int[] trycolors = {1, 2, 3}; NEXT_COLOR: for (int c : trycolors) { for (int u : g[v]) { if (colors[u] == c) continue NEXT_COLOR; } colors[v] = c; boolean res = true; for (int u : g[v]) { res &= dfs(u); if (!res) break; } if (res) return true; colors[v] = 0; } return false; } public static class FastScanner { private BufferedReader br; private StringTokenizer st; public FastScanner(InputStream in) throws IOException { br = new BufferedReader(new InputStreamReader(in)); } public FastScanner(File file) throws IOException { br = new BufferedReader(new FileReader(file)); } public FastScanner(String s) { br = new BufferedReader(new StringReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); return ""; } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
d36bd5ea6aa945ff0d8dfdc1f328a07a
train_000.jsonl
1381838400
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
256 megabytes
import java.util.*; public class FlagDay357B { public static void main(String[] args) { // Set up scanner Scanner sc = new Scanner(System.in); // System.out.println("Enter n"); int n = sc.nextInt(); // System.out.println("Enter m"); int m = sc.nextInt(); ArrayList<Integer> one23 = new ArrayList<Integer>(); one23.add(1); one23.add(2); one23.add(3); int[] dancercolor = new int[n+1]; for (int i=0; i<m; i++) { // System.out.println("Input first dancer"); int one = sc.nextInt(); // System.out.println("Input second dancer"); int two = sc.nextInt(); // System.out.println("Input third dancer"); int three = sc.nextInt(); int onecolor = dancercolor[one]; int twocolor = dancercolor[two]; int threecolor = dancercolor[three]; if (onecolor != 0) // Dancer one has already danced { one23.remove(new Integer(onecolor)); dancercolor[two] = one23.get(0); dancercolor[three] = one23.get(1); one23.add(onecolor); } else if (twocolor != 0) { one23.remove(new Integer(twocolor)); dancercolor[one] = one23.get(0); dancercolor[three] = one23.get(1); one23.add(twocolor); } else if (threecolor != 0) { one23.remove(new Integer(threecolor)); dancercolor[one] = one23.get(0); dancercolor[two] = one23.get(1); one23.add(threecolor); } else // All three are new--assign at random { dancercolor[one] = one23.get(0); dancercolor[two] = one23.get(1); dancercolor[three] = one23.get(2); } } StringBuilder sb = new StringBuilder(); for (int i=1; i<=n; i++) { sb.append(dancercolor[i] + " "); } System.out.println(sb); } }
Java
["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"]
1 second
["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"]
null
Java 6
standard input
[ "constructive algorithms", "implementation" ]
ee523bb4da5cb794e05fb62b7da8bb89
The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
1,400
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
standard output
PASSED
3f3c505fe6ddd83656013ea364d9c2b8
train_000.jsonl
1448636400
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int bSearch(int num,Integer[] arr){ int low=0; int high=arr.length-1; if(num<arr[low]){ return 0; }else if(num>=arr[high]){ return arr.length; } while(low<high){ int mid=(low+high)/2; if(arr[mid]==num){ if(mid+1<arr.length && arr[mid+1]==num ){ low=mid; }else { return mid + 1; } }else if(arr[mid]>num){ high=mid; }else{ low=mid; } if(Math.abs(high-low)==1){ return low+1; } } return low; } public static void main(String[] args) throws IOException { FastReader ip = new FastReader(); OutputStream output = System.out; PrintWriter out = new PrintWriter(output); int n=ip.nextInt(); int m=ip.nextInt(); Integer[] arr1=new Integer[n]; int[] arr2=new int[m]; for(int i=0;i<n;i++){ arr1[i]=ip.nextInt(); } for(int i=0;i<m;i++){ arr2[i]=ip.nextInt(); } Arrays.sort(arr1); for(int i=0;i<m;i++){ int pos=bSearch(arr2[i],arr1); out.print(pos+" "); } out.close(); } }
Java
["5 4\n1 3 5 7 9\n6 4 2 8", "5 5\n1 2 1 2 5\n3 1 4 1 5"]
2 seconds
["3 2 1 4", "4 2 4 2 5"]
null
Java 11
standard input
[ "data structures", "two pointers", "binary search", "sortings" ]
e9a519be33f25c828bae787330c18dd4
The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109). The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).
1,300
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
standard output
PASSED
a7bf1fed28775762bacce0f5c2c79218
train_000.jsonl
1448636400
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args) { Scanner s=new Scanner(System.in); // int a=s.nextInt(); int b=s.nextInt(); Integer arr1[]=new Integer[a]; int i,j; for(i=0;i<a;i++){ arr1[i]=s.nextInt(); } Arrays.sort(arr1); for(i=0;i<b;i++){ System.out.print(binSearch(arr1,s.nextInt())+" "); } // } private static int binSearch(Integer arr[],int number){ int left=0,right=arr.length-1,mid=(left+right)/2,ind=0; while(left<=right){ if(arr[mid]<=number){ ind=mid+1; left=mid+1; } else right=mid-1; mid=(left+right)/2; } return ind; } }
Java
["5 4\n1 3 5 7 9\n6 4 2 8", "5 5\n1 2 1 2 5\n3 1 4 1 5"]
2 seconds
["3 2 1 4", "4 2 4 2 5"]
null
Java 11
standard input
[ "data structures", "two pointers", "binary search", "sortings" ]
e9a519be33f25c828bae787330c18dd4
The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109). The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).
1,300
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
standard output
PASSED
564e554075d4c684aeff32be35aeb792
train_000.jsonl
1448636400
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int n, m; static Num[] arr1; static int[] arr2; public static void main(String args[]) throws Exception { FastReader cin = new FastReader(); n = cin.nextInt(); m = cin.nextInt(); arr1 = new Num[n]; arr2 = new int[m]; for (int i = 0; i < n; i++) { int val = cin.nextInt(); arr1[i] = new Num(val, i); } Arrays.parallelSort(arr1, new ValCmp()); for (int i = 0; i < m; i++) { arr2[i] = cin.nextInt(); } for (int i = 0; i < m; i++) { search(arr1, arr2[i]); } } public static void search(Num[] arr1, int target) { int low = 0; int high = n - 1; while (low <= high) { int mid = (low + high) / 2; if (arr1[mid].val == target) { if (mid == n - 1) { System.out.println(mid + 1 + " "); return; } else { low = mid + 1; } } if (arr1[mid].val < target) { low = mid + 1; } if (arr1[mid].val > target) { if (mid - 1 >= 0 && arr1[mid - 1].val <= target) { System.out.print(mid + " "); return; } else { high = mid - 1; } } } System.out.println(low); } } class ValCmp implements Comparator<Num> { public int compare(Num a, Num b) { return a.val - b.val; } } class Num { int val, index; public Num(int val, int index) { this.val = val; this.index = index; } }
Java
["5 4\n1 3 5 7 9\n6 4 2 8", "5 5\n1 2 1 2 5\n3 1 4 1 5"]
2 seconds
["3 2 1 4", "4 2 4 2 5"]
null
Java 11
standard input
[ "data structures", "two pointers", "binary search", "sortings" ]
e9a519be33f25c828bae787330c18dd4
The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109). The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).
1,300
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
standard output
PASSED
bed180b1a0acadb6b510f3c3b0083396
train_000.jsonl
1448636400
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
256 megabytes
import java.util.*; public class queries{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); long n = scan.nextLong(); long m = scan.nextLong(); long[] arrA = new long[(int)n]; for(int i = 0;i<n;i++){ arrA[i] = scan.nextLong(); } merge(arrA,0,n-1); for(int i = 0;i<m;i++){ System.out.print(binary(arrA,scan.nextLong(),0,(int)n-1)+" "); } } static int binary(long[] arrA,long target,int low,int high){ while(low<=high){ int mid = (low+high)/2; if(arrA[mid]<=target){ low = mid+1; } else{ high = mid-1; } } return high+1; } public static void merge(long[] arr,long left,long right){ if(left<right){ long mid = (left+right)/2; merge(arr,left,mid); merge(arr,mid+1,right); mergeSort(arr,left,mid,right); } } public static void mergeSort(long[] arr,long l,long m,long r){ long n1 = m-l+1; long n2 = r-m; long[] left = new long[(int)n1]; long[] right = new long[(int)n2]; for(int i = 0;i<n1;i++){ left[i] = arr[(int)l+i]; } for(int j = 0;j<n2;j++){ right[j] = arr[(int)m+1+j]; } int i = 0; int j = 0; long k = l; while(i<n1 && j<n2){ if(left[i]<right[j]){ arr[(int)k] = left[i]; i++; } else{ arr[(int)k] = right[j]; j++; } k++; } while(i<n1){ arr[(int)k] = left[i]; i++; k++; } while(j<n2){ arr[(int)k] = right[j]; j++; k++; } } }
Java
["5 4\n1 3 5 7 9\n6 4 2 8", "5 5\n1 2 1 2 5\n3 1 4 1 5"]
2 seconds
["3 2 1 4", "4 2 4 2 5"]
null
Java 11
standard input
[ "data structures", "two pointers", "binary search", "sortings" ]
e9a519be33f25c828bae787330c18dd4
The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109). The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).
1,300
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
standard output
PASSED
40056a87f796e307df3951c1bf03423e
train_000.jsonl
1448636400
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
256 megabytes
import java.util.Scanner; public class queries { public static void main(String[] args) { int max = Integer.MIN_VALUE; Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int ar[] = new int[n]; for (int i = 0; i < n; i++) { ar[i] = sc.nextInt(); if (ar[i] > max) max = ar[i]; } int br[] = new int[m]; for (int i = 0; i < m; i++) { br[i] = sc.nextInt(); } sort(ar,0,ar.length-1); for (int i = 0; i < m; i++) { int t = br[i]; if (t >= max) { br[i] = ar.length; } else { int start = 0, end = ar.length - 1; while (start < end) { int mid = (start + end) / 2; if (ar[mid] > t) { end = mid; } else { start = mid + 1; } } br[i] = start; } } for (int i = 0; i <m ; i++) { System.out.print(br[i]+" "); } } public static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int [n1]; int R[] = new int [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() public static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } }
Java
["5 4\n1 3 5 7 9\n6 4 2 8", "5 5\n1 2 1 2 5\n3 1 4 1 5"]
2 seconds
["3 2 1 4", "4 2 4 2 5"]
null
Java 11
standard input
[ "data structures", "two pointers", "binary search", "sortings" ]
e9a519be33f25c828bae787330c18dd4
The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109). The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).
1,300
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
standard output