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
a5adf45cf30aef8f66e5d15a4e353bde
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
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.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class D1136 { public static void main(String[] args) throws IOException { // BufferedReader br = new BufferedReader(new FileReader("F:/books/input.txt")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] s = br.readLine().split(" "); int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); int[] q = new int[n]; String[] qs = br.readLine().split(" "); for(int i=0;i<n;i++) { q[i] = Integer.parseInt(qs[i]); } Map<Integer,List<Integer>> mp = new HashMap<Integer,List<Integer>>(); for(int i=0;i<m;i++) { String[] ms = br.readLine().split(" "); int u = Integer.parseInt(ms[0]); int v = Integer.parseInt(ms[1]); insertToMap(mp,u,v); } if(n==1) { System.out.println("0"); return; } int cnt = 0; for(int i=n-2;i>=0;i--) { if(path(i,n-1-cnt,q,mp)) cnt++; } System.out.println(cnt); } private static boolean path(int x, int y, int[] q, Map<Integer, List<Integer>> mp) { List<Integer> l = mp.get(q[x]); if(l==null) return false; for(int i=x+1;i<=y;i++) { if(Collections.binarySearch(l, q[i])<0) return false; } int tmp = q[x]; for(int i=x;i<y;i++) q[i] = q[i+1]; q[y] = tmp; return true; } private static void insertToList(List<Integer> l, int v) { int pos = Collections.binarySearch(l, v); l.add(-pos-1,v); } private static void insertToMap(Map<Integer, List<Integer>> mp, int u, int v) { List<Integer> l = mp.get(u); if(l==null) { l = new ArrayList<Integer>(); mp.put(u, l); } insertToList(l,v); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
5e6693d686b3fe272cf5f44dda37beea
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.util.*; import java.io.*; public class natsya { static class InputReader { private InputStream stream; private byte[] inbuf = new byte[1024]; private int lenbuf = 0; private int ptrbuf = 0; public InputReader(InputStream stream) { this.stream = stream; } private int readByte() { if (lenbuf == -1) throw new UnknownError(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = stream.read(inbuf); } catch (IOException e) { throw new UnknownError(); } 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; } public String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } } public static void main(String args[]) { InputReader sc=new InputReader(System.in); int n,m; n=sc.nextInt(); m=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } List<Integer> l[]=new ArrayList[1000007]; for(int i=0;i<1000007;i++) l[i]=new ArrayList<>(); for(int i=0;i<m;i++) { int x=sc.nextInt(); int y=sc.nextInt(); l[y].add(x); } int ans=0; int c[]=new int[1000007]; for(int i=n-1;i>=0;i--) { if(c[a[i]]==n-1-i-ans && i!=n-1) ans++; else { for(int h:l[a[i]]) c[h]++; } } System.out.println(ans); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
a26e5fc7cd92f14a3cd5b1708bfa955c
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.util.*; public class D { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Solver solver = new Solver(); solver.solve(in, out); out.close(); } private static class Solver { private void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[] p = new int[n]; for (int i = 0; i < n; i++) { p[i] = in.nextInt(); } Set<Integer>[] s = new Set[n + 1]; for (int i = 0; i <= n; i++) s[i] = new HashSet<>(); for (int i = 0; i < m; i++) { int u = in.nextInt(); int v = in.nextInt(); s[v].add(u); } int ans = 0; for (int i = n - 2; i >= 0; i--) { if (s[p[n - 1]].contains(p[i])) { ans++; } else { for (Iterator<Integer> it = s[p[n - 1]].iterator(); it.hasNext();) { if (!s[p[i]].contains(it.next())) { it.remove(); } } } } out.println(ans); } } private static class InputReader { private BufferedReader br; private StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } private String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } private String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
b66432d0a965696033884d3f4aad4da9
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; public class D1136 { static class Scanner { BufferedReader br; StringTokenizer tk=new StringTokenizer(""); public Scanner(InputStream is) { br=new BufferedReader(new InputStreamReader(is)); } public int nextInt() throws IOException { if(tk.hasMoreTokens()) return Integer.parseInt(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextInt(); } public long nextLong() throws IOException { if(tk.hasMoreTokens()) return Long.parseLong(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextLong(); } public String next() throws IOException { if(tk.hasMoreTokens()) return (tk.nextToken()); tk=new StringTokenizer(br.readLine()); return next(); } public String nextLine() throws IOException { tk=new StringTokenizer(""); return br.readLine(); } public double nextDouble() throws IOException { if(tk.hasMoreTokens()) return Double.parseDouble(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextDouble(); } public char nextChar() throws IOException { if(tk.hasMoreTokens()) return (tk.nextToken().charAt(0)); tk=new StringTokenizer(br.readLine()); return nextChar(); } public int[] nextIntArray(int n) throws IOException { int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public int[] nextIntArrayOneBased(int n) throws IOException { int a[]=new int[n+1]; for(int i=1;i<=n;i++) a[i]=nextInt(); return a; } public long[] nextLongArrayOneBased(int n) throws IOException { long a[]=new long[n+1]; for(int i=1;i<=n;i++) a[i]=nextLong(); return a; } } public static void main(String args[]) throws IOException { new Thread(null, new Runnable() { public void run() { try { solve(); } catch(Exception e) { } } }, "1", 1 << 26).start(); } static ArrayList<Integer> g[]; static void solve() throws IOException { Scanner in=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int n = in.nextInt(); int m=in.nextInt(); int p[]=in.nextIntArray(n); HashSet<Integer> h[]=new HashSet[n]; for(int i=0;i<n;i++) h[i]=new HashSet<>(); int revm[]=new int[n+1]; for(int i=0;i<n;i++) revm[p[i]]=i; for(int i=0;i<m;i++){ int u=in.nextInt(); int v=in.nextInt(); h[revm[u]].add(revm[v]); } int ans=0; ArrayList<Integer> a=new ArrayList<>(); a.add(n-1); for(int i=n-2;i>=0;i--){ boolean val=true; for(int x:a) if(!h[i].contains(x)){ val=false; break; } if(val) ans++; else a.add(i); } out.println(ans); out.close(); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
2f1d658f0f2fa1e93449d8bb59252cbc
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static int oo = (int)1e9; // static long oo = (long)1e15; static int mod = 1_000_000_007; // static int mod = 998244353; static int[] di = {-1, 0, 1, 0}; static int[] dj = {0, 1, 0, -1}; static int M = 1000005; static double EPS = 1e-13; public static void main(String[] args) throws IOException { int n = in.nextInt(); int m = in.nextInt(); int[] p = in.nextIntArray(n); HashSet<Integer>[] ok = new HashSet[n+1]; for(int i = 0; i <= n; ++i) { ok[i] = new HashSet<>(); } while(m --> 0) { int u = in.nextInt(); int v = in.nextInt(); ok[u].add(v); } int ans = 0; HashSet<Integer> set = new HashSet<>(); set.add(p[n-1]); for(int i = n-2; i >= 0; --i) { if(ok[p[i]].containsAll(set)) { ans += 1; } else { set.add(p[i]); } } System.out.println(ans); out.close(); } static void update(int[] f, int i) { while(i < f.length) { f[i]++; i += (i & -i); } } static int query(int[] f, int i) { int ret = 0; while(i > 0) { ret += f[i]; i -= (i & -i); } return ret; } static long invmod(long a, long mod) { BigInteger b = BigInteger.valueOf(a); BigInteger m = BigInteger.valueOf(mod); return b.modInverse(m).longValue(); } static int find(int[] g, int x) { return g[x] = g[x] == x ? x : find(g, g[x]); } static void union(int[] g, int[] size, int x, int y) { x = find(g, x); y = find(g, y); if(x == y) return; if(size[x] < size[y]) { g[x] = y; size[y] += size[x]; } else { g[y] = x; size[x] += size[y]; } } static class Segment { Segment left, right; int size; HashSet<Character> set = new HashSet<>(); // int time, lazy; public Segment(char[] a, int l, int r) { super(); if(l == r) { set.add(a[l]); return; } int mid = (l + r) / 2; left = new Segment(a, l, mid); right = new Segment(a, mid+1, r); set.addAll(left.set); set.addAll(right.set); } boolean covered(int ll, int rr, int l, int r) { return ll <= l && rr >= r; } boolean noIntersection(int ll, int rr, int l, int r) { return ll > r || rr < l; } // void lazyPropagation() { // if(lazy != 0) { // if(left != null) { // left.setLazy(this.time, this.lazy); // right.setLazy(this.time, this.lazy); // } // else { // val = lazy; // } // } // } // void setLazy(int time, int lazy) { // if(this.time != 0 && this.time <= time) // return; // this.time = time; // this.lazy = lazy; // } int querySize(int ll, int rr, int l, int r) { // lazyPropagation(); if(noIntersection(ll, rr, l, r)) return 0; if(covered(ll, rr, l, r)) return size; int mid = (l + r) / 2; int leftSize = left.querySize(ll, rr, l, mid); int rightSize = right.querySize(ll, rr, mid+1, r); return leftSize + rightSize; } int query(int k, int l, int r) { Segment trace = this; while(l < r) { int mid = (l + r) / 2; if(trace.left.size > k) { trace = trace.left; r = mid; } else { k -= trace.left.size; trace = trace.right; l = mid + 1; } } return l; } HashSet<Character> querySet(int ll, int rr, int l, int r) { if(noIntersection(ll, rr, l, r)) return new HashSet<>(); if(covered(ll, rr, l, r)) return this.set; int mid = (l + r) / 2; HashSet<Character> leftSet = left.querySet(ll, rr, l, mid); HashSet<Character> rightSet = right.querySet(ll, rr, mid+1, r); HashSet<Character> ret = new HashSet<>(); ret.addAll(leftSet); ret.addAll(rightSet); return ret; } // int queryCnt(int ll, int rr, int x, int l, int r) { // if(noIntersection(ll, rr, l, r)) // return 0; // if(covered(ll, rr, l, r)) { // if(this.gcd % x == 0) // return 0; // if(l == r) { // return 1; // } // int mid = (l + r) / 2; // if(left.gcd % x != 0 && right.gcd % x != 0) { // return 2; // } // if(left.gcd % x != 0) { // return left.queryCnt(ll, rr, x, l, mid); // } // return right.queryCnt(ll, rr, x, mid+1, r); // } // int mid = (l + r) / 2; // int leftCnt = left.queryCnt(ll, rr, x, l, mid); // int rightCnt = right.queryCnt(ll, rr, x, mid+1, r); // return leftCnt + rightCnt; // } // void update(int ll, int rr, int value, int l, int r) { //// lazyPropagation(); // if(noIntersection(ll, rr, l, r)) // return; // if(covered(ll, rr, l, r)) { //// setLazy(time, knight); // this.gcd = value; // return; // } // int mid = (l + r) / 2; // left.update(ll, rr, value, l, mid); // right.update(ll, rr, value, mid+1, r); // this.gcd = gcd(left.gcd, right.gcd); // } } static long pow(long a, long n, long mod) { if(n == 0) return 1; if(n % 2 == 1) return a * pow(a, n-1, mod) % mod; long x = pow(a, n / 2, mod); return x * x % mod; } static int[] getPi(char[] a) { int m = a.length; int j = 0; int[] pi = new int[m]; for(int i = 1; i < m; ++i) { while(j > 0 && a[i] != a[j]) j = pi[j-1]; if(a[i] == a[j]) { pi[i] = j + 1; j++; } } return pi; } static long lcm(long a, long b) { return a * b / gcd(a, b); } static BigInteger lcm2(long a, long b) { long g = gcd(a, b); BigInteger gg = BigInteger.valueOf(g); BigInteger aa = BigInteger.valueOf(a); BigInteger bb = BigInteger.valueOf(b); return aa.multiply(bb).divide(gg); } static boolean nextPermutation(int[] a) { for(int i = a.length - 2; i >= 0; --i) { if(a[i] < a[i+1]) { for(int j = a.length - 1; ; --j) { if(a[i] < a[j]) { int t = a[i]; a[i] = a[j]; a[j] = t; for(i++, j = a.length - 1; i < j; ++i, --j) { t = a[i]; a[i] = a[j]; a[j] = t; } return true; } } } } return false; } static void shuffle(Object[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); Object t = a[si]; a[si] = a[i]; a[i] = t; } } static void shuffle(int[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); int t = a[si]; a[si] = a[i]; a[i] = t; } } static void shuffle(long[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); long t = a[si]; a[si] = a[i]; a[i] = t; } } static int lower_bound(int[] a, int n, int k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int lower_bound(long[] a, int n, long k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static BigInteger gcd(BigInteger a, BigInteger b) { return b.compareTo(BigInteger.ZERO) == 0 ? a : gcd(b, a.mod(b)); } static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { super(); this.first = first; this.second = second; } @Override public int compareTo(Pair o) { return this.first != o.first ? this.first - o.first : this.second - o.second; } // @Override // public int compareTo(Pair o) { // return this.first != o.first ? o.first - this.first : o.second - this.second; // } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
86267c183a1aff2f808c0eede8d7d702
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { static class Task { int NN = 300005; int MOD = 1000000007; int INF = 2000000000; long INFINITY = 2000000000000000000L; int [] pos = new int[NN]; List<Integer> [] g = new ArrayList[NN]; public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); for(int i=1;i<=n;++i) { pos[in.nextInt()] = i; g[i] = new ArrayList<>(); } for(int i=1;i<=m;++i) { int u = pos[in.nextInt()]; int v = pos[in.nextInt()]; g[u].add(v); } Map<Integer, Boolean> removed= new HashMap<>(); int ans = 0; for(int i=n-1;i>=1;--i) { int target = n - i - removed.size(); int cnt = 0; for(int j: g[i]) { if(j <= i || removed.containsKey(j)) continue; ++cnt; } if(cnt == target) { ++ans;removed.put(i, true); } } out.println(ans); } } static void prepareIO(boolean isFileIO) { //long t1 = System.currentTimeMillis(); Task solver = new Task(); // Standard IO if(!isFileIO) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver.solve(in, out); //out.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0); out.close(); } // File IO else { String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in"; String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out"; InputReader fin = new InputReader(IPfilePath); PrintWriter fout = null; try { fout = new PrintWriter(new File(OPfilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } solver.solve(fin, fout); //fout.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0); fout.close(); } } public static void main(String[] args) { prepareIO(false); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public InputReader(String filePath) { File file = new File(filePath); try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
783c661fee81c11d11f83673c8a8c0d0
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
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.Set; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; 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 */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD extends ChelperSolution { public void solve(int testNumber, InputReader in, OutputWriter out) { super.solve(testNumber, in, out); } public void solve(int testNumber) { int n = in.nextInt(); int m = in.nextInt(); int[] positions = in.nextIntArray(n); int[][] swaps = in.nextIntIntArray(m, 2); int[] positionOf = new int[n + 1]; for (int i = 0; i < n; i++) { positionOf[positions[i]] = i; } List<Set<Integer>> rightSideOf = new ArrayList<>(); for (int i = 0; i < n; i++) { rightSideOf.add(new HashSet<>()); } for (int i = 0; i < m; i++) { int l = positionOf[swaps[i][0]]; int r = positionOf[swaps[i][1]]; rightSideOf.get(l).add(r); } int nastya = n - 1; List<Integer> jumpers = new ArrayList<>(); List<Integer> leftovers = new ArrayList<>(); leftovers.add(nastya); for (int i = nastya - 1; i >= 0; i--) { boolean ok = true; for (Integer j : leftovers) { if (!rightSideOf.get(i).contains(j)) { ok = false; break; } } if (ok) { jumpers.add(i); } else { leftovers.add(i); } } out.println(jumpers.size()); } } static class OutputWriter extends PrintWriter { public static OutputWriter toFile(String fileName) { try { return new OutputWriter(fileName); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public void close() { super.close(); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public OutputWriter(OutputStream outputStream) { super(outputStream, true); } public OutputWriter(Writer writer) { super(writer, true); } } static abstract class ChelperSolution implements ChelperCallable { public static final String LOCAL_FILE = "chelper.properties"; public static final String SAVE_RESULT_FILE = "last_test_output.txt"; protected final boolean local = new File(LOCAL_FILE).exists(); protected boolean firstTest = true; protected InputReader in; protected OutputWriter out; protected OutputWriter debug; protected OutputWriter fileOut; protected boolean saveTestResult = true; protected boolean gcj = false; protected void init() { if (local) { debug = new OutputWriter(System.err); if (saveTestResult) { fileOut = OutputWriter.toFile(SAVE_RESULT_FILE); } } else { debug = new OutputWriter(new NullOutputStream()); } } public void solve(int testNumber, InputReader in, OutputWriter out) { if (firstTest) { init(); precalc(); firstTest = false; } this.in = in; if (local && saveTestResult) { this.out = new SplittingOutputWriter(out, fileOut); } else { this.out = out; } preSolve(testNumber); solve(testNumber); postSolve(testNumber); } protected void precalc() { } protected void preSolve(int testNumber) { if (gcj) { out.printf("Case #%d: ", testNumber); } } public abstract void solve(int testNumber); protected void postSolve(int testNumber) { out.flush(); debug.flush(); } } static interface ChelperCallable { } static class NullOutputStream extends OutputStream { public void write(int b) throws IOException { // nothing } } static class SplittingOutputWriter extends OutputWriter { private final OutputWriter[] outputWriters; public SplittingOutputWriter(OutputWriter... outputWriters) { super(new OutputStream() { public void write(int b) throws IOException { for (OutputWriter outputWriter : outputWriters) { outputWriter.write(b); } } }); this.outputWriters = outputWriters; } public void flush() { for (OutputWriter outputWriter : outputWriters) { outputWriter.flush(); } } public void close() { for (OutputWriter outputWriter : outputWriters) { outputWriter.close(); } } } static class InputReader { private BufferedReader br; private StringTokenizer in; public InputReader(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (IOException e) { throw new RuntimeException(e); } } public InputReader(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } private boolean hasMoreTokens() { while (in == null || !in.hasMoreTokens()) { String s = nextLine(); if (s == null) { return false; } in = new StringTokenizer(s); } return true; } public String nextString() { return hasMoreTokens() ? in.nextToken() : null; } public String nextLine() { try { in = null; return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } public int nextInt() { return Integer.parseInt(nextString()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public int[][] nextIntIntArray(int n, int m) { int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = nextInt(); } } return a; } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
670c2bdbc9eed2354bb39c25bea2e20d
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
//package que_b; import java.io.*; import java.util.*; public class utkarsh { InputStream is; PrintWriter out; long mod = (long)(1e9 + 7), inf = (long)(3e18); void solve() { int n = ni(), m = ni(); int a[] = new int[n]; for(int i = 0; i < n; i++) a[i] = ni() - 1; HashSet <Integer> b[] = new HashSet[n]; for(int i = 0; i < n; i++) { b[i] = new HashSet<>(); } for(int i = 0; i < m; i++) { int u = ni()-1, v = ni()-1; b[v].add(u); } int ans = 0; HashSet <Integer> d = b[a[n-1]]; for(int i = n-2; i >= 0; i--) { if(d.isEmpty()) break; if(d.contains(a[i])) ans++; else { d = in(d, b[a[i]]); } } out.println(ans); } HashSet <Integer> in(HashSet <Integer> a, HashSet <Integer> b) { HashSet <Integer> ans = new HashSet<>(); for(int x : a) { if(b.contains(x)) ans.add(x); } return ans; } long mp(long b, long e, long mod) { b %= mod; long r = 1; while(e > 0) { if((e & 1) == 1) { r *= b; r %= mod; } b *= b; b %= mod; e >>= 1; } return r; } //---------- I/O Template ---------- public static void main(String[] args) { new utkarsh().run(); } void run() { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
ebf53956d81734afa3715ff0f1924d61
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.LinkedList; import java.util.ArrayList; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { Reader in = new Reader(); int n = in.nextInt(); int m = in.nextInt(); int[] a = in.na(n); ArrayList<Integer>[] adj = new ArrayList[n+1]; for(int i = 0; i<n+1; i++) adj[i] = new ArrayList<Integer>(); for(int i = 0; i<m; i++) adj[in.nextInt()].add(in.nextInt()); ArrayList<Integer> pass = new ArrayList<Integer>(); pass.add(a[n-1]); int ans = 0; for(int i = n-2; i>=0; i--){ int cur = a[i]; boolean passAll = true; for(int j = 0; j<pass.size()&&passAll; j++) if(!adj[cur].contains(pass.get(j))) passAll = false; if(passAll) ans++; else pass.add(cur); } System.out.println(ans); } static class Reader { static BufferedReader br; static StringTokenizer st; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int nextInt() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Integer.parseInt(st.nextToken()); } public double nextDouble() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Double.parseDouble(st.nextToken()); } public Long nextLong() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Long.parseLong(st.nextToken()); } public String next() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return st.nextToken(); } private static void readLine() { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
63e321a47a8d4a4406aba487a812e0e4
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.LinkedList; import java.util.ArrayList; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { Reader in = new Reader(); int n = in.nextInt(); int m = in.nextInt(); int[] a = in.na(n); /* int[] pos = new int[n+1]; for(int i = 0; i<n; i++) pos[a[i]] = i+1; */ ArrayList<Integer>[] adj = new ArrayList[n+1]; for(int i = 0; i<n+1; i++) adj[i] = new ArrayList<Integer>(); for(int i = 0; i<m; i++) adj[in.nextInt()].add(in.nextInt()); int pos = n-1; ArrayList<Integer> pass = new ArrayList<Integer>(); pass.add(a[n-1]); int ans = 0; for(int i = n-2; i>=0; i--){ int cur = a[i]; boolean passAll = true; for(int j = 0; j<pass.size()&&passAll; j++){ if(!adj[cur].contains(pass.get(j))) passAll = false; } if(passAll){ // System.out.println("Passed: "+cur+""); ans++; }else{ pass.add(cur); } } System.out.println(ans); } static class Reader { static BufferedReader br; static StringTokenizer st; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int nextInt() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Integer.parseInt(st.nextToken()); } public double nextDouble() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Double.parseDouble(st.nextToken()); } public Long nextLong() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Long.parseLong(st.nextToken()); } public String next() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return st.nextToken(); } private static void readLine() { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
17ab6f8c01fba6fda66d89da4c65786c
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * @author anurag.y * @since 13/02/19. */ public class Main { private static InputReader inputReader = new InputReader(); public static void main(String[] args) throws IOException { List<Integer> inputVariables = inputReader.readIntegersFromLine(); int n, m; n = inputVariables.get(0); m = inputVariables.get(1); List<Integer> inputArr = inputReader.readIntegersFromLine(); Set<Integer>[] adjacencyList = new HashSet[n + 1]; Set<Integer>[] reverseAdjacencyList = new HashSet[n + 1]; for (int i = 0; i <= n; i++) { adjacencyList[i] = new HashSet<>(); reverseAdjacencyList[i] = new HashSet<>(); } for (int i = 0; i < m; i++) { List<Integer> temp = inputReader.readIntegersFromLine(); adjacencyList[temp.get(0)].add(temp.get(1)); reverseAdjacencyList[temp.get(1)].add(temp.get(0)); } int count = 0; List<Integer> remainingElement = new ArrayList<>(); remainingElement.add(inputArr.get(n - 1)); for (int i = n - 2;i >= 0; i--) { int value = inputArr.get(i); if (adjacencyList[value].containsAll(remainingElement)) { count++; } else { remainingElement.add(value); } } System.out.println(count); } private static class InputReader { private static BufferedReader bufferedReader; public InputReader() { bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } public String readStringFromLine() throws IOException { return bufferedReader.readLine().trim(); } public int readSingleIntFromLine() throws IOException { return Integer.parseInt(bufferedReader.readLine().trim()); } public List<Integer> readIntegersFromLine() throws IOException { final List<Integer> integerList = new ArrayList<>(); for (String integer : bufferedReader.readLine().trim().split(" ")) { integerList.add(Integer.parseInt(integer)); } return integerList; } public List<Long> readLongsFromLine() throws IOException { final List<Long> integerList = new ArrayList<>(); for (String integer : bufferedReader.readLine().trim().split(" ")) { integerList.add(Long.parseLong(integer)); } return integerList; } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
df423e8fcd6b4f24cce575107891902f
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.util.*; import java.io.*; public class D { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = scanner.nextInt(); int M = scanner.nextInt(); int[] q = new int[N]; ArrayList<Integer>[] graph = new ArrayList[N]; for(int i = 0; i < N; i++) { q[i] = scanner.nextInt()-1; graph[i] = new ArrayList<>(); } while(M-->0) { int u = scanner.nextInt()-1; int v = scanner.nextInt()-1; graph[v].add(u); } int[] cnts = new int[N]; for(int edge: graph[q[N-1]]) { cnts[edge]++; } int ans = 0; int rem = 0; for(int i = N-2; i >= 0; i--) { int tot = N-1-i-rem; if (cnts[q[i]] == tot) { rem++; ans++; } else { for(int edge : graph[q[i]]) cnts[edge]++; } } out.println(ans); out.flush(); } public static class DSU { int[] parent, rank; int size, nSets; public DSU(int ss) { size =ss; nSets = ss; parent = new int[ss]; rank = new int[ss]; for(int i = 0; i < ss; i++) { parent[i] = i; rank[i] = 1; } } public int find(int t) { int prev = t; while(parent[t] != t) t =parent[t]; compress(prev, t); return t; } public void compress(int s, int t) { while(parent[s] != t) { int temp = parent[s]; parent[s] = t; s = temp; } } public boolean union(int a, int b) { int pa = find(a); int pb = find(b); if(pa == pb) return false; nSets--; if (rank[pa] <= rank[pb]) { rank[pb] += rank[pa]; parent[pa] = pb; } else { rank[pa] += rank[pb]; parent[pb] = pa; } return true; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(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 readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
7d09300cf4ed629f9bfdc2c5f158aa56
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.util.*; import java.math.*; // **** D. Nastya Is Buying Lunch **** public class D { static char [] in = new char [10000]; static long HF = 300001L; public static void main (String [] arg) throws Throwable { int n = nextInt(); int m = nextInt(); int [] LINE = new int [n]; //int [] LINEPOS = new int [n+1]; //long [][] pairs = new long [m][2]; //int [] cnt = new int [n+1]; HashSet<Long> canSwitch = new HashSet<Long>(4*m); //int [][] canSwitchAt = int [n+1][]; for (int i = 0; i<n; ++i) { LINE[i] = nextInt(); //LINEPOS[LINE[i]] = i; } for (int i = 0; i<m; ++i) { long L0 = nextInt(); long L1 = nextInt(); //pairs[i][0] = Math.max(L0,L1); //pairs[i][1] = Math.min(L1,L0); canSwitch.add(L0 * HF + L1); //canSwitch.add(L1 * HF + L0); /* int I0 = (int)L0; int I1 = (int)L1; if (I0 < I1) { cnt[I1]++; } else { cnt[I0]++; } */ } /* for (int i = 0; i<n; ++i) canSwitchAt[i] = new int[cnt[i]]; for (int i = 0; i<m; ++i) { int P1 = pairs[i][0]; int P2 = pairs[i][1]; cnt[P2]--; canSwitchAt[P2][cnt[P2]] = P1; } for (int i = 0; i<n; ++i) Arrays.sort(canSwitchAt[i]); */ // Calculate answer int ans = 0; long nastya = LINE[n-1]; int nastya_pos = n-1; //System.err.println("Nastya init at " + nastya_pos); //boolean [] used = new boolean [n]; int pos = n-1; for (pos = n-2; pos >= 0; --pos) { long P1 = LINE[pos]; if (canSwitch.contains( P1 * HF + nastya)) { //System.err.println("Student " + P1 + " Definitely Switches with Nastya"); ans++; nastya_pos--; } else { break; } } //System.err.println("Nastya is now at " + nastya_pos); for (pos = nastya_pos-1; pos>=0; --pos) { boolean can_do = true; long P0 = LINE[pos]; if (!canSwitch.contains(P0 * HF + nastya)) continue; for (int seek_pos = pos+1; seek_pos < nastya_pos && can_do; ++seek_pos) { //if (used[seek_pos]) continue; long P1 = LINE[seek_pos]; if (!canSwitch.contains(P0 * HF + P1)) { //System.err.println("Student " + P0 + " CANT switch with student " + P1); can_do = false; } else { //System.err.println("Student " + P0 + " can switch with student " + P1); } } if (can_do) { //System.err.println("Student " + P0 + " will switch with Nastya"); LINE[pos] = LINE[nastya_pos-1]; nastya_pos--; ans++; } } System.out.println(ans); } /************** FAST IO CODE FOLLOWS *****************/ public static long nextLong() throws Throwable { long i = System.in.read();boolean neg = false;while (i < 45) i = System.in.read();if (i == 45) {neg=true;i=48;}i = i - 48; int j = System.in.read();while (j > 32) {i*=10;i+=j-48;j = System.in.read();}return (neg) ? -i : i; } public static int nextInt() throws Throwable {return (int)nextLong();} public static String next() throws Throwable { int i = 0; while (i < 42 && i != -1) i = System.in.read(); int cptr = 0; while (i >= 42) { in[cptr++] = (char)i; i = System.in.read();} return new String(in, 0,cptr); } /**** LIBRARIES ****/ public static long gcdL(long a, long b) {while (b != 0) {long tmp = b;b = (a % b);a = tmp;}return a;} public static int gcd(int a, int b) {while (b != 0) {int tmp = b;b = (a % b);a = tmp;}return a;} } /* Full Problem Text: At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils. Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward. */
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
81b3329b0e899c8ee03c46a0c5b69a22
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
// No sorceries shall previal. // import java.util.Scanner; import java.io.PrintWriter; import java.util.*; import java.util.Arrays; public class InVoker { public static void main(String args[]) { Scanner inp = new Scanner(System.in); PrintWriter out= new PrintWriter(System.out); int n= inp.nextInt(); int m=inp.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=inp.nextInt()-1; int u[]=new int[m]; int v[]=new int[m]; int adj[][]=new int[n][]; int deg[]=new int[n]; for(int i=0;i<m;i++) { u[i]=inp.nextInt()-1; v[i]=inp.nextInt()-1; deg[u[i]]++; } for(int i=0;i<n;i++) adj[i]=new int[deg[i]]; for(int i=0;i<m;i++) { int x=u[i]; int y=v[i]; adj[x][--deg[x]]=y; } boolean can[]=new boolean[n]; can[a[n-1]]=true; int alive=1,gg=0; for(int i=n-2;i>=0;i--) { int c=0; for(int x:adj[a[i]]) if(can[x]) c++; if(c==alive) gg++; else { alive++; can[a[i]]=true; } } out.println(gg); out.close(); inp.close(); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
48570a0a603e30c8876bc48ee6c6f3e0
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int M = in.nextInt(); int[] perm = new int[N]; ArrayList<Integer>[] arr = new ArrayList[N]; for (int i = 0; i < N; i++) { perm[i] = in.nextInt() - 1; arr[i] = new ArrayList<>(); } for (int i = 0; i < M; i++) { arr[in.nextInt() - 1].add(in.nextInt() - 1); } HashSet<Integer> behind = new HashSet<>(); int res = 0; behind.add(perm[N - 1]); for (int i = N - 2; i >= 0; i--) { int curPas = 0; for (int j : arr[perm[i]]) { if (behind.contains(j)) { curPas++; } } if (curPas == behind.size()) { res++; } else { behind.add(perm[i]); } } out.println(res); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
ade1fc89a3fb43fed2748026a44de30b
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class nastyalunch{ static class Node{ Node next; int data ; Node(){ next=null; data=0; } } static class Graph{ Node start; Node last; int size; Graph(){ start=null; last=null; size=0; } } public static void main(String args[]){ try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] inp = br.readLine().trim().split("\\s+"); int n = Integer.parseInt(inp[0]); int k = Integer.parseInt(inp[1]); int[] arr=new int[n+1]; Graph[] gr = new Graph[n+1]; inp = br.readLine().trim().split("\\s+"); for(int i = 1 ; i<n+1 ; i++){ arr[i] = Integer.parseInt(inp[i-1]); gr[i]=new Graph(); } int[] ar = new int[n+1] ; for(int i = 0 ; i<k ; i++){ inp = br.readLine().trim().split("\\s+"); int y = Integer.parseInt(inp[0]); int x = Integer.parseInt(inp[1]); if(gr[x].size==0){ Node trr = new Node(); trr.data = y; gr[x].start = trr ; gr[x].last = gr[x].start; gr[x].size+=1; } else{ gr[x].size+=1; Node trr = new Node(); trr.data = y; gr[x].last.next=trr; gr[x].last= gr[x].last.next; } } Node tu = gr[arr[n]].start; for(int i=0 ; i<gr[arr[n]].size ; i++){ ar[tu.data]=1; tu=tu.next; } int ans=0; int p = 1; for(int i = n-1 ; i>0 ; i--){ if(ar[arr[i]]==p){ ans+=1; } else{ tu = gr[arr[i]].start; for(int df=0; df<gr[arr[i]].size ; df++){ ar[tu.data]+=1; tu=tu.next; } p+=1; } } System.out.println(ans); /*int flag = 0; int pointer = n-2; int size = 1; int[] gh = new int[n]; for(int kj =0 ; kj<n ;kj++){ gh[kj] = nodes[arr[n-1]-1][kj]; } while(pointer>=0 && flag==0){ //System.out.println(size); if(gh[arr[pointer]-1] == 1 ){ pointer-=1; } else{ for(int kj = 0 ; kj < n ; kj++ ){ if(ar[arr[pointer]-1]==0){ flag=1; break; }else{ gh[kj] = gh[kj]*nodes[arr[pointer]-1][kj]; } } if(flag==0){ size+=1; pointer-=1; } } } System.out.println(n-size-pointer-1);*/ } catch(Exception E){} } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
e3a55695e1de2ab293bfc3de44acaef3
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Iterator; public class Solve4 { public static void main(String[] args) throws IOException { PrintWriter pw = new PrintWriter(System.out); new Solve4().solve(pw); pw.flush(); pw.close(); } public void solve(PrintWriter pw) throws FileNotFoundException, IOException { FastReader sc = new FastReader(); int n = sc.nextInt(), m = sc.nextInt(); HashSet<Integer> p = new HashSet(); HashSet<Integer>[] s = new HashSet[n + 1]; int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = sc.nextInt(); s[i] = new HashSet(); } for (int i = 0; i < m; i++) { s[sc.nextInt()].add(sc.nextInt()); } p.add(a[n]); int ans = 0; for (int i = n - 1; i > 0; i--) { Iterator<Integer> it = s[a[i]].iterator(); int cnt = 0; while (it.hasNext()) { if (p.contains(it.next())) { cnt++; } } if(cnt==p.size()) ans++; else p.add(a[i]); } pw.println(ans); } static public class FastReader { BufferedReader br; StringTokenizer st; public FastReader() throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if (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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { return br.readLine(); } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
2a7150c929f4097fa0ad4faed1e07281
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
//package que_b; import java.io.*; import java.util.*; public class utkarsh { InputStream is; PrintWriter out; long mod = (long)(1e9 + 7), inf = (long)(3e18); void solve() { int n = ni(), m = ni(); int a[] = new int[n]; for(int i = 0; i < n; i++) a[i] = ni() - 1; HashSet <Integer> b[] = new HashSet[n]; for(int i = 0; i < n; i++) { b[i] = new HashSet<>(); } for(int i = 0; i < m; i++) { int u = ni()-1, v = ni()-1; b[v].add(u); } int ans = 0; HashSet <Integer> d = b[a[n-1]]; for(int i = n-2; i >= 0; i--) { if(d.isEmpty()) break; if(d.contains(a[i])) ans++; else { d = in(d, b[a[i]]); } } out.println(ans); } HashSet <Integer> in(HashSet <Integer> a, HashSet <Integer> b) { HashSet <Integer> ans = new HashSet<>(); for(int x : a) { if(b.contains(x)) ans.add(x); } return ans; } long mp(long b, long e, long mod) { b %= mod; long r = 1; while(e > 0) { if((e & 1) == 1) { r *= b; r %= mod; } b *= b; b %= mod; e >>= 1; } return r; } //---------- I/O Template ---------- public static void main(String[] args) { new utkarsh().run(); } void run() { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
21328fec54c3b40a3c6b012778d6bbca
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Set; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.StringTokenizer; import java.util.Map; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author llamaoo7 */ 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); DNastyaIsBuyingLunch solver = new DNastyaIsBuyingLunch(); solver.solve(1, in, out); out.close(); } static class DNastyaIsBuyingLunch { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[] p = new int[n]; for (int i = 0; i < n; i++) p[i] = in.nextInt(); Map<Integer, Set<Integer>> c = new HashMap<>(); for (int i = 0; i < m; i++) { int u = in.nextInt(); int v = in.nextInt(); if (!c.containsKey(u)) c.put(u, new HashSet<>()); c.get(u).add(v); } Set<Integer> cur = new HashSet<>(); cur.add(p[n - 1]); int ret = 0; for (int i = n - 2; i >= 0; i--) { if (c.containsKey(p[i]) && c.get(p[i]).containsAll(cur)) ret++; else cur.add(p[i]); } out.println(ret); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
c4b851ca956d1d8e3e526a8be2758539
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.util.*; public class p1136d { public static void main(String[] args)throws IOException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int arr[] = new int[n]; for(int t = 0; t < n; t++) { arr[t]=in.nextInt()-1; } HashSet<Integer> sets[] = new HashSet[n]; for(int i=0;i<n;i++) sets[i]=new HashSet<Integer>(); for(int i=0;i<m;i++) { int u = in.nextInt()-1; int v = in.nextInt()-1; sets[v].add(u); } int ans = 0; // out.println("sets[n-1] "+sets[n-1]); HashSet<Integer> set = sets[arr[n-1]]; // out.println(set.contains(0)); for(int i=n-2;i>=0;i--) { // out.print("i="+i+";"); if(set.contains(arr[i])) { // out.println(" contains; "); ans++; } else { // out.print(" retained; "); set.retainAll(sets[arr[i]]); } // out.println(set); } out.println(ans); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
dab7bb48fcc36cf69615b8be91d46282
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.util.*; public class p1136d { public static void main(String[] args)throws IOException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int arr[] = new int[n]; for(int t = 0; t < n; t++) arr[t]=in.nextInt()-1; HashSet<Integer> sets[] = new HashSet[n]; for(int i=0;i<n;i++) sets[i]=new HashSet<Integer>(); for(int i=0;i<m;i++) { int u = in.nextInt()-1; int v = in.nextInt()-1; sets[v].add(u); } int ans = 0; HashSet<Integer> set = sets[arr[n-1]]; for(int i=n-2;i>=0;i--) if(set.contains(arr[i])) ans++; else set.retainAll(sets[arr[i]]); out.println(ans); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
4030900ef51b887f3568d4777e5e3f47
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.util.*; public class CF1136D { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] pp = new int[n]; for (int i = 0; i < n; i++) pp[i] = Integer.parseInt(st.nextToken()) - 1; ArrayList[] adj = new ArrayList[n]; for (int u = 0; u < n; u++) adj[u] = new ArrayList<Integer>(); while (m-- > 0) { st = new StringTokenizer(br.readLine()); int u = Integer.parseInt(st.nextToken()) - 1; int v = Integer.parseInt(st.nextToken()) - 1; adj[v].add(u); } HashMap<Integer, Integer> map = new HashMap<>(); ArrayList<Integer> list = adj[pp[n - 1]]; for (int u : list) map.put(u, 1); int ans = 0, cnt = 1; for (int i = n - 2; i >= 0; i--) { int u = pp[i]; if (map.getOrDefault(u, 0) == cnt) ans++; else { cnt++; list = adj[u]; for (int u_ : list) map.put(u_, map.getOrDefault(u_, 0) + 1); } } System.out.println(ans); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
c4afe5f0a1de6d53e901bd6b879adac2
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.util.*; import java.util.function.Function; public class MainD { static int N, M; static int[] P; static int[] U, V; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); N = sc.nextInt(); M = sc.nextInt(); P = sc.nextIntArray(N, -1); U = new int[M]; V = new int[M]; for (int i = 0; i < M; i++) { U[i] = sc.nextInt()-1; V[i] = sc.nextInt()-1; } System.out.println(solve()); } static int solve() { int ans = 0; Set<Integer>[] G = new Set[N]; for (int i = 0; i < M; i++) { int u = U[i]; int v = V[i]; if( G[u] == null ) G[u] = new HashSet<>(); G[u].add(v); } List<Integer> wall = new ArrayList<>(); lo: for (int i = N-2; i >= 0; i--) { int p = P[i]; if( G[p] == null ) { wall.add(p); continue lo; } else { if( !G[p].contains(P[N-1]) ) { wall.add(p); continue; } for (int j = 0; j < wall.size(); j++) { if( !G[p].contains(wall.get(j)) ) { wall.add(p); continue lo; } } ans++; } } return ans; } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static <A> void writeLines(A[] as, Function<A, String> f) { PrintWriter pw = new PrintWriter(System.out); for (A a : as) { pw.println(f.apply(a)); } pw.flush(); } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
0dfd40b8dd06aa95ace50474acab5682
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class D { void solve() throws IOException { int n=nextInt(); int m=nextInt(); int[] p=new int[n]; for(int i=0;i<n;i++)p[i]=nextInt() - 1; HashSet<Integer>[] s=new HashSet[n]; HashSet<Integer> q=new HashSet<>(); for(int i=0;i<n;i++)s[i]=new HashSet<>(); for(int i=0;i<m;i++) { int u=nextInt()-1; int v=nextInt()-1; s[u].add(v); if (v==p[n-1])q.add(u); } int ans=0; int i=n-1; HashSet<Integer> w=new HashSet<>(); while (i>=0) { if (q.contains(p[i])) { boolean good = true; for (Integer x:w) { if (!s[p[i]].contains(x)) { good=false; break; } } if (good) { ans++; } else { w.add(p[i]); } } else { w.add(p[i]); } i--; } out.println(ans); } public static void main(String[] args) throws IOException { new D().run(); } void run() throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); // reader = new BufferedReader(new FileReader("input.txt")); tokenizer = null; out = new PrintWriter(new OutputStreamWriter(System.out)); // out = new PrintWriter(new FileWriter("output.txt")); solve(); reader.close(); out.flush(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } class BitSet { int[] set = new int[10000]; } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
67e40792e7b931da8a071f89731c06e1
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.util.LinkedList; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); r546_D solver = new r546_D(); solver.solve(1, in, out); out.close(); } static class r546_D { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.ni(), m = in.ni(); int[] p = in.na(n); List<Integer>[] g = new List[n]; for (int i = 0; i < n; i++) { g[i] = new LinkedList<>(); } boolean[] canJumpOver = new boolean[n]; int last = p[n - 1] - 1; for (int i = 0; i < m; i++) { int u = in.ni() - 1, v = in.ni() - 1; g[u].add(v); if (v == last) canJumpOver[u] = true; } boolean[] blockers = new boolean[n]; int nBlockers = 0; int ans = 0; for (int i = n - 2; i >= 0; i--) { int no = p[i] - 1; if (!canJumpOver[no]) { blockers[no] = true; nBlockers++; } else { int swaps = 0; for (int v : g[no]) { if (blockers[v]) { swaps++; } } if (swaps == nBlockers) { ans++; } else { blockers[no] = true; nBlockers++; } } } out.println(ans); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int ni() { return Integer.parseInt(ns()); } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
bae44418dc0eccaeefdbba6b9d2fddbf
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
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.Set; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author dmytro.prytula prituladima@gmail.com */ 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); DNastyaIdetVStolovuyu solver = new DNastyaIdetVStolovuyu(); solver.solve(1, in, out); out.close(); } static class DNastyaIdetVStolovuyu { int n; int m; int[] array; IntIntPair[] pairs; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); m = in.nextInt(); array = in.nextIntArray(n); int last = array[array.length - 1]; pairs = in.nextIntPairArray(m); Set<IntIntPair> pairsSet = new HashSet<>(Arrays.asList(pairs)); Map<Integer, Set<Integer>> optimized = new HashMap<>(); for (IntIntPair intIntPair : pairsSet) { int first = intIntPair.getFirst(); int second = intIntPair.getSecond(); optimized.computeIfAbsent(first, k -> new HashSet<>()); optimized.get(first).add(second); } Set<Integer> P = new HashSet<>(); for (int i = array.length - 2; i >= 0; i--) { boolean acceptAll = true; Set<Integer> opt = optimized.get(array[i]); if (opt != null) { for (Integer j : P) { acceptAll &= opt.contains(j); if (!acceptAll) break; } acceptAll &= opt.contains(last); } if (!acceptAll || opt == null) P.add(array[i]); } out.printLine(n - 1 - P.size()); } } 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[] nextIntPairArray(int size) { IntIntPair[] result = new IntIntPair[size]; for (int i = 0; i < size; i++) { result[i] = nextIntPair(); } return result; } public int[] nextIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } public IntIntPair nextIntPair() { int first = nextInt(); int second = nextInt(); return new IntIntPair(first, second); } 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 nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } private 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 int getFirst() { return first; } public int getSecond() { return 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
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
6ed87b95c8e495f136c17c483a083018
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.HashSet; import java.util.List; import java.util.Set; public class Main { private static void solve() { int n = ni(); int m = ni(); int[] a = na(n); for (int i = 0; i < n; i ++) { a[i] --; } List<Set<Integer>> can = new ArrayList<>(); for (int i = 0; i < n; i ++) { can.add(new HashSet<>()); } for (int i = 0; i < m; i ++) { int u = ni() - 1; int v = ni() - 1; can.get(v).add(u); } int me = a[n-1]; int ret = 0; Deque<Integer> q = new ArrayDeque<>(); for (int i = n - 2; i >= 0; i --) { if (!can.get(me).contains(a[i])) { q.add(a[i]); } else { boolean ok = true; for (int v : q) { if (!can.get(v).contains(a[i])) { ok = false; break; } } if (ok) { ret ++; } else { q.add(a[i]); } } } System.out.println(ret); } public static void main(String[] args) { new Thread(null, new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); String debug = args.length > 0 ? args[0] : null; if (debug != null) { try { is = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(debug)); } catch (Exception e) { throw new RuntimeException(e); } } reader = new java.io.BufferedReader(new java.io.InputStreamReader(is), 32768); solve(); out.flush(); tr((System.currentTimeMillis() - start) + "ms"); } }, "", 64000000).start(); } private static java.io.InputStream is = System.in; private static java.io.PrintWriter out = new java.io.PrintWriter(System.out); private static java.util.StringTokenizer tokenizer = null; private static java.io.BufferedReader reader; public static String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new java.util.StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } private static double nd() { return Double.parseDouble(next()); } private static long nl() { return Long.parseLong(next()); } private static int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private static char[] ns() { return next().toCharArray(); } private static long[] nal(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private static int[][] ntable(int n, int m) { int[][] table = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { table[i][j] = ni(); } } return table; } private static int[][] nlist(int n, int m) { int[][] table = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { table[j][i] = ni(); } } return table; } private static int ni() { return Integer.parseInt(next()); } private static void tr(Object... o) { if (is != System.in) System.out.println(java.util.Arrays.deepToString(o)); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
d254be87b72d69defa43847486e106ed
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Vector; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Stack; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Abhas Jain */ 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); DNastyaIsBuyingLunch solver = new DNastyaIsBuyingLunch(); solver.solve(1, in, out); out.close(); } static class DNastyaIsBuyingLunch { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.ni(); int m = in.ni(); int[] ar = new int[n]; for (int i = 0; i < n; ++i) ar[i] = in.ni(); HashSet<Integer>[] hs = new HashSet[n + 1]; for (int i = 1; i <= n; ++i) hs[i] = new HashSet<>(); for (int i = 0; i < m; ++i) { int a = in.ni(); int b = in.ni(); hs[b].add(a); } Stack<Integer> st = new Stack<>(); int ans = 0; outer: for (int i = n - 2; i >= 0; --i) { int cur = ar[i]; Stack<Integer> temp = new Stack<>(); while (!st.isEmpty() && hs[st.peek()].contains(cur)) { temp.add(st.pop()); } boolean f = true; if (st.isEmpty() && hs[ar[n - 1]].contains(cur)) { f = false; ans++; } while (!temp.isEmpty()) { st.add(temp.pop()); } if (f) st.push(cur); } out.print(ans); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
74ab5ada4ca20c9311e98b4ca8c9eba8
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; import java.util.Set; 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 Abhas Jain */ 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); DNastyaIsBuyingLunch solver = new DNastyaIsBuyingLunch(); solver.solve(1, in, out); out.close(); } static class DNastyaIsBuyingLunch { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.ni(); int m = in.ni(); int[] ar = new int[n]; for (int i = 0; i < n; ++i) ar[i] = in.ni(); HashSet<Integer>[] hs = new HashSet[n + 1]; for (int i = 1; i <= n; ++i) hs[i] = new HashSet<>(); for (int i = 0; i < m; ++i) { int a = in.ni(); int b = in.ni(); hs[b].add(a); } Set<Integer> st = new HashSet<>(); int ans = 0; outer: for (int i = n - 2; i >= 0; --i) { int cur = ar[i]; for (int g : st) { if (!hs[g].contains(cur)) { st.add(cur); continue outer; } } if (hs[ar[n - 1]].contains(cur)) ans++; else st.add(cur); } out.print(ans); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
03b5f90c755b641433d29382150ac8cc
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import jdk.nashorn.internal.runtime.regexp.joni.exception.ValueException; import java.io.*; import java.util.*; public class E1066 { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader inp = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver1066D solver = new Solver1066D(); solver.solve(inp, out); out.close(); } static class InputReader { StringTokenizer tokenizer; InputStreamReader sReader; BufferedReader reader; InputReader(InputStream stream) { sReader = new InputStreamReader(stream); reader = new BufferedReader(sReader, 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public List<Integer> intLine(int size) { List<Integer> ls = new ArrayList<>(size); for (int i = 0; i < size; i++) { ls.add(nextInt()); } return ls; } int nextC() { try { return reader.read(); } catch (IOException e) { return -1; } } public int[] intArr(int size) { int[] ls = new int[size]; for (int i = 0; i < size; i++){ ls[i] = nextInt(); } return ls; } } static class Solver1066D { public void solve(InputReader inp, PrintWriter out) { int n = inp.nextInt(), m = inp.nextInt(); int[] ls = new int[n], pointers = new int[n], options = new int[n]; ArrayList<Integer>[] deps = new ArrayList[n]; for (int i = 0; i < n; i++){ int val = inp.nextInt()-1; ls[i] = val; pointers[val] = i; deps[i] = new ArrayList<>(); } for (int i = 0; i < m; i++){ int k = inp.nextInt()-1, l = inp.nextInt()-1; if (pointers[k] < pointers[l]){ deps[l].add(k); options[k]++; } } int important = n-1; for (int i = n-2; i > -1; i--){ int val = ls[i]; if (important == i+options[val]){ for (int d : deps[val]) options[d]--; important-=1; } } out.println(n-important-1); } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
303b5062392a8fce330bd3eda83b6cc3
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.util.*; import java.io.*; public class Main implements Runnable{ FastScanner sc; PrintWriter pw; final class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public long nlo() { return Long.parseLong(next()); } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int ni() { return Integer.parseInt(next()); } public String nli() { String line = ""; if (st.hasMoreTokens()) line = st.nextToken(); else try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } while (st.hasMoreTokens()) line += " " + st.nextToken(); return line; } public double nd() { return Double.parseDouble(next()); } } public static void main(String[] args) throws Exception { new Thread(null,new Main(),"codeforces",1<<28).start(); } public void run() { sc=new FastScanner(); pw=new PrintWriter(System.out); solve(); pw.flush(); pw.close(); } public long gcd(long a,long b) { return b==0L?a:gcd(b,a%b); } public long ppow(long a,long b,long mod) { if(b==0L) return 1L; long tmp=1; while(b>1L) { if((b&1L)==1) tmp*=a; a*=a; a%=mod; tmp%=mod; b>>=1; } return (tmp*a)%mod; } public int gcd(int x,int y) { return y==0?x:gcd(y,x%y); } ////////////////////////////////// ///////////// LOGIC /////////// //////////////////////////////// public void solve() { int n=sc.ni(); int m=sc.ni(); int[] arr=new int[n]; for(int i=0;i<n;i++) arr[i]=sc.ni()-1; HashSet<Integer>[] set=new HashSet[n]; for(int i=0;i<n;i++) set[i]=new HashSet(); for(int i=0;i<m;i++) { int u=sc.ni()-1; int v=sc.ni()-1; set[v].add(u); } int[] map=new int[n]; int ans=0; if(n==1) { pw.println(0); return; } for(int i=n-2;i>=0;i--) { boolean f=true; if(set[arr[n-1]].contains(arr[i])) { f=false; if(map[arr[i]]==(n-2-i-ans)) ans++; else f=true; } if(f) { for(int y:set[arr[i]]) map[y]++; } } pw.println(ans); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
039cdeaecca1ab38e900aa3f9efcf40d
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class bhaa { InputStream is; PrintWriter o; /////////////////// CODED++ BY++ ++ ++ ++ BHAVYA++ ARORA++ ++ ++ ++ FROM++ JAYPEE++ INSTITUTE++ OF++ INFORMATION++ TECHNOLOGY++ //////////////// ///////////////////////// Make it work, make it right, make it fast. Make it work, make it right, make it fast. Make it work, make it right, make it fast. Make it work, make it right, make it fast. ///////////////// void solve() { int n=ni(); int m=ni(); ArrayList<Integer>ad[]=new ArrayList[n+1]; //for(int i=0;i<) ArrayList<Integer>al=new ArrayList<Integer>(); //int arr[]=nia(n); for(int i=0;i<n;i++) { al.add(ni()); } int aage=n-1; int nhijaega=0; for(int i=0;i<=n;i++) { ad[i]=new ArrayList<Integer>(); } for(int i=0;i<m;i++) { ad[ni()].add(ni()); } for(int i=0;i<=n;i++) { Collections.sort(ad[i]); } //boolean chk[]=new boolean[n]; for(int i=n-2;i>=0;i--) { int f=1; int ele=al.get(i); for(int j=i+1;j<al.size();j++) { if(Collections.binarySearch(ad[ele],al.get(j))<0) { f=0; nhijaega++; break; } } if(f==1) { al.remove(i); } } o.println(aage-nhijaega); } //---------- I/O Template ---------- public static void main(String[] args) { new bhaa().run(); } void run() { is = System.in; o = new PrintWriter(System.out); solve(); o.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] nia(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } long[] nla(int n) { long a[] = new long[n]; for(int i = 0; i < n; i++) { a[i] = nl(); } return a; } int [][] nim(int n) { int mat[][]=new int[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { mat[i][j]=ni(); } } return mat; } long [][] nlm(int n) { long mat[][]=new long[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { mat[i][j]=nl(); } } return mat; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } void piarr(int arr[]) { for(int i=0;i<arr.length;i++) { o.print(arr[i]+" "); } o.println(); } void plarr(long arr[]) { for(int i=0;i<arr.length;i++) { o.print(arr[i]+" "); } o.println(); } void pimat(int mat[][]) { for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { o.print(mat[i][j]+" "); } o.println(); } } void plmat(long mat[][]) { for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { o.print(mat[i][j]+" "); } o.println(); } } static class DJset { int n; ty1 arr[]; class ty1 { int rank; int par; ty1(int p,int r) { par=p; rank=r; } } DJset(int nu) { n=nu; arr=new ty1[n]; for(int i=0;i<n;i++) { arr[i]=new ty1(i,1); } } int find(int x) { if(arr[x].par!=x) { arr[x].par=find(arr[x].par); } return arr[x].par; } void union(int x,int y) { x=find(x); y=find(y); if(x!=y) { if(arr[x].rank<arr[y].rank) { arr[x].par=y; } else if(arr[y].rank<arr[x].rank) { arr[y].par=x; } else { arr[x].rank++; arr[y].par=x; } } } public String toString() { String res=""; for(int i=0;i<n;i++) { res+=(arr[i].par+" "); } return res; } public int countsets() { int res=0; for(int i=0;i<n;i++) { if(arr[i].par==i) { res++; } } return res; } } //////////////////////////////////// template finished ////////////////////////////////////// }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
e319268716f9931fee708fa63e6ad424
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.util.*; public class D { // ------------------------ public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); // ------------------------ int n=sc.nextInt(),m=sc.nextInt(); int[]p=new int[n]; for(int i=0;i<n;i++) p[i]=sc.nextInt()-1; HashMap<Integer,HashSet<Integer>>swaps=new HashMap<Integer,HashSet<Integer>>(); for(int i=0;i<n;i++) swaps.put(i,new HashSet<Integer>()); for(int i=0;i<m;i++) swaps.get(sc.nextInt()-1).add(sc.nextInt()-1); HashSet<Integer>blocks=new HashSet<Integer>(); int ans=0; for(int i=n-2;i>=0;i--){ if(swaps.get(p[i]).contains(p[n-1])&&swaps.get(p[i]).size()>blocks.size()){ boolean good=true; for(int b:blocks) if(!swaps.get(p[i]).contains(b)){ good=false; break; } if(good) ans++; else blocks.add(p[i]); }else blocks.add(p[i]); } System.out.println(ans); // ------------------------ out.close(); } //------------------------ public static PrintWriter out; 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
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
7410966a37c4993fea4147243d7de37f
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.Collections; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author cunbidun */ 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); DNastyaIsBuyingLunch solver = new DNastyaIsBuyingLunch(); solver.solve(1, in, out); out.close(); } static class DNastyaIsBuyingLunch { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[] a = in.nextIntArray(n, 1); boolean[] ch = new boolean[n + 1]; ArrayList<Integer>[] adj = new ArrayList[n + 1]; ArrayList<PairII> num = new ArrayList<>(); int[] pos = new int[n + 1]; for (int i = 1; i <= n; i++) { adj[i] = new ArrayList<>(); pos[a[i]] = i; } for (int i = 1; i <= m; i++) { int u = in.nextInt(); int v = in.nextInt(); adj[u].add(v); if (v == a[n]) num.add(new PairII(pos[u], u)); } if (num.size() == 0) { out.println(0); return; } for (int i = 1; i <= n; i++) { if (adj[i].size() != 0) Collections.sort(adj[i]); } Collections.sort(num); int ans = 0; for (int i = num.size() - 1; i >= 0; i--) { int cur = num.get(i).second; if (adj[cur].size() == 0) { out.println(ans); return; } int curPos = num.get(i).first; boolean f = false; for (int j = curPos + 1; j <= n - ans; j++) { if (ch[a[j]]) continue; int bPos = BinarySearch.lowerBound(adj[cur], 0, adj[cur].size() - 1, a[j]); if (bPos == adj[cur].size() || !adj[cur].get(bPos).equals(a[j])) { f = true; break; } } if (!f) { ch[cur] = true; ans++; } } out.println(ans); } } static class BinarySearch { public static int lowerBound(ArrayList<Integer> array, int indexSt, int indexEn, long value) { if (value > array.get(indexEn)) return indexEn + 1; int low = indexSt; int high = indexEn; while (low < high) { final int mid = (low + high) / 2; if (value <= array.get(mid)) { high = mid; } else { low = mid + 1; } } return low; } } static class InputReader extends InputStream { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int length, int stIndex) { int[] arr = new int[length + stIndex]; for (int i = stIndex; i < stIndex + length; i++) arr[i] = nextInt(); return arr; } private static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static class PairII implements Comparable<PairII> { public int first; public int second; public PairII(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; } PairII pair = (PairII) o; return first == pair.first && second == pair.second; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(PairII o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
dd31b4735ef3adb2f5a386af3e8761d0
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n=sc.nextInt(),m=sc.nextInt(); int []p=new int [n]; ArrayList<Integer>[]adj=new ArrayList[n]; for(int i=0;i<n;i++) { p[i]=sc.nextInt()-1; adj[i]=new ArrayList(); } int []a=new int [m],b=new int [m]; boolean []special=new boolean[n]; for(int i=0;i<m;i++) { a[i]=sc.nextInt()-1; b[i]=sc.nextInt()-1; adj[a[i]].add(b[i]); if(b[i]==p[n-1]) special[a[i]]=true; } int ans=0; HashSet<Integer> seen=new HashSet(); for(int i=n-2;i>=0;i--) { int x=p[i]; boolean add=true; if(special[x]) { int cnt=0; for(int v:adj[x]) if(seen.contains(v)) cnt++; if(cnt==seen.size()) { ans++; add=false; } } if(add) seen.add(x); } out.println(ans); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
65dcb51c82adc9ac74ba02493e9c319e
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.util.*; public class Main { class Pair implements Comparable<Pair> { public long first; public Pair(long first, long second) { this.first = first; this.second = second; } public long second; @Override public int compareTo(Pair o) { if (first != o.first) return Long.compare(first, o.first); return Long.compare(second, o.second); } } int[][] steps = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; String fileName = ""; int INF = Integer.MAX_VALUE / 2; long MODULO = 1000000007; private final static Random rnd = new Random(); int n, k; HashSet<Integer>[] graph; void solve() throws IOException { int n = readInt(); int m = readInt(); graph = new HashSet[n]; int[] arr = new int[n]; for (int i=0; i<n; ++i){ arr[i] = readInt() - 1; graph[i] = new HashSet<>(); } for (int i=0; i<m; ++i){ int from = readInt() - 1; int to = readInt() - 1; graph[to].add(from); } int[] count = new int[n]; int me = arr[n - 1]; int ans = 0; int countGood = 0; for (int i=n-2; i>=0; --i){ if (graph[me].contains(arr[i]) && count[arr[i]] == n - 2 - i - countGood){ ans++; countGood++; continue; } for (int to: graph[arr[i]]){ count[to]++; } } out.println(ans); } boolean checkBit(long mask, int bit){ return (mask & (1l << bit)) > 0; } //////////////////////////////////////////////////////////// public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub new Main().run(); } void run() throws NumberFormatException, IOException { solve(); out.close(); }; BufferedReader in; PrintWriter out; StringTokenizer tok; String delim = " "; Main() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } tok = new StringTokenizer(""); } String readLine() throws IOException { return in.readLine(); } String readString() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) { return null; } tok = new StringTokenizer(nextLine); } return tok.nextToken(delim); } int readInt() throws NumberFormatException, IOException { return Integer.parseInt(readString()); } long readLong() throws NumberFormatException, IOException { return Long.parseLong(readString()); } int[] readIntArray (int n) throws NumberFormatException, IOException { int[] a = new int[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } double readDouble() throws NumberFormatException, IOException { return Double.parseDouble(readString()); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
fbba985683f96443226ccf680ca69034
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Scanner; /** * <a href="http://codeforces.com/contests/1136">Codeforces Round #546 (Div. 2)</a> (2019-03-12T00:35:00+08:00) * * @author Klnsyf-Sun */ public class Main { static void solve() throws IOException { int n = nextInt(), m = nextInt(); ArrayList<Integer> line = new ArrayList<>(); for (int index = 0; index < n; index++) { line.add(nextInt()); } HashMap<Integer, LinkedList<Integer>> edges = new HashMap<>(); for (int index = 0; index < m; index++) { int u = nextInt(), v = nextInt(); if (edges.containsKey(u)) { edges.get(u).add(v); } else { edges.put(u, new LinkedList<>()); edges.get(u).add(v); } } int counter = 0; for (int u = n - 2; u >= 0 && line.size() > 1; ) { boolean flag = true; for (int v = u + 1; v < line.size(); v++) { if (!edges.getOrDefault(line.get(u), new LinkedList<>()).contains(line.get(v))) { flag = false; break; } } if (flag) { counter++; line.remove(u); } u--; } System.out.println(counter); } private static StreamTokenizer in; private static Scanner sc; private static PrintWriter out; static { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); sc = new Scanner(new BufferedInputStream(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } public static void main(String[] args) throws IOException { solve(); sc.close(); out.flush(); } private static int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } private static double nextDouble() throws IOException { in.nextToken(); return in.nval; } private static String nextString() throws IOException { in.nextToken(); return in.sval; } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
623e5aaae97ba573c6bdc91b4d753ce4
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class D { static ArrayList adj[]; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int mas[] = new int[n]; int func[] = new int[n]; for (int i = 0; i < n; i++) { mas[i] = in.nextInt() - 1; func[mas[i]] = i; } int kek[] = new int[n]; adj = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList(); } for (int i = 0; i < m; i++) { int x = in.nextInt() - 1, y = in.nextInt() - 1; if (func[x] < func[y]) { kek[x]++; adj[y].add(x); } } int ans = 0; for (int i = n - 2; i >= 0; i--) { int tek = mas[i]; if (kek[tek] == n - 1 - i - ans) { ans++; for (int j = 0; j < adj[tek].size(); j++) { kek[(int) adj[tek].get(j)]--; } } } System.out.println(ans); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
4251273d4f8752f873fe6d3a0b3085fd
train_001.jsonl
1552322100
At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.
256 megabytes
import java.io.*; import java.util.*; public class D { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public void go() throws IOException { StringTokenizer tok = new StringTokenizer(in.readLine()); int n = Integer.parseInt(tok.nextToken()); int m = Integer.parseInt(tok.nextToken()); int[] arr = new int[n]; tok = new StringTokenizer(in.readLine()); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(tok.nextToken()); } HashMap<Integer, HashSet<Integer>> map = new HashMap<>(); for (int i = 0; i < m; i++) { tok = new StringTokenizer(in.readLine()); int a = Integer.parseInt(tok.nextToken()); int b = Integer.parseInt(tok.nextToken()); if (!map.containsKey(a)) { map.put(a, new HashSet<>()); } map.get(a).add(b); } int nat = arr[n-1]; for (int i = n-1; i >= 0; i--) { int j = i; while (j < n-1 && map.containsKey(arr[j]) && map.get(arr[j]).contains(arr[j+1])) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; j++; } } for (int i = 0; i < n; i++) { if (arr[i] == nat) { out.println(n-i-1); } } out.flush(); in.close(); } public static void main(String[] args) throws IOException { new D().go(); } }
Java
["2 1\n1 2\n1 2", "3 3\n3 1 2\n1 2\n3 1\n3 2", "5 2\n3 1 5 4 2\n5 2\n5 4"]
2 seconds
["1", "2", "1"]
NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is change places for pupils with numbers $$$1$$$ and $$$3$$$. change places for pupils with numbers $$$3$$$ and $$$2$$$. change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.
Java 8
standard input
[ "greedy" ]
1716b35de299e88c891ba71f9c368b51
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.
1,800
Print a single integer — the number of places in queue she can move forward.
standard output
PASSED
1316627ceb778a6156b7ebcd4c126979
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static int calculate(int a, int b, int c){ if(b + c <= a) return b + c; if((a ^ b) == 0) return (b - c) + (c >> 1) * 3 + (c & 1); return (a + b + c) / 2; } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pr = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while(t-- > 0){ String input[] = br.readLine().split(" "); int a = Integer.parseInt(input[0]); int b = Integer.parseInt(input[1]); int c = Integer.parseInt(input[2]); int max = Integer.max(Integer.max(a, b), c); int min = Integer.min(Integer.min(a, b), c); int mid = a + b + c - max - min; pr.println(calculate(max, mid, min)); } br.close(); pr.close(); } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
9b59e1a958c2b9d943d598c8d36658c4
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static int calculate(int a, int b, int c){ if(b + c <= a) return b + c; return (a + b + c) / 2; } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pr = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while(t-- > 0){ String input[] = br.readLine().split(" "); int a = Integer.parseInt(input[0]); int b = Integer.parseInt(input[1]); int c = Integer.parseInt(input[2]); int max = Integer.max(Integer.max(a, b), c); int min = Integer.min(Integer.min(a, b), c); int mid = a + b + c - max - min; pr.println(calculate(max, mid, min)); } br.close(); pr.close(); } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
cdef4966a483a5f4853f930a2355cdcc
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.util.*; import java.io.*; public class MyClass { public static void main(String args[]) { FastReader sc = new FastReader(); int t = sc.nextInt(); while(t-->0){ long a[] = new long[3]; for(int i=0;i<3;i++){ a[i]=sc.nextLong(); } Arrays.sort(a); long ans=0; if(a[2]>=(a[0]+a[1])){ System.out.println(a[0]+a[1]); } else{ ans = (long)Math.floor((a[0]+a[1]+a[2])/2); System.out.println(ans); } } } } 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; } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
4d9cb92c86b6dd98a9eee588a9cb182c
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
/* package whatever; // 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 Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int arr[]=new int[3]; for(int i=0;i<3;i++){ arr[i]=sc.nextInt(); } int sum=0; Arrays.sort(arr); if(arr[0]+arr[1]<arr[2]){ sum=arr[0]+arr[1]; } else{ sum=(arr[0]+arr[1]+arr[2])/2; } System.out.println(sum); } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
119c06c1b56b5ea49fc726564f64e55c
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.StringTokenizer; import java.io.PrintWriter; import java.io.*; import java.util.stream.Collectors.*; import java.lang.*; import static java.util.stream.Collectors.*; import static java.util.Map.Entry.*; public class Ideo { 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 class aksh { int x; int y; int moves; public aksh(int a,int b,int c) { x = a; y = b; moves=c; } } static int power(int x,int y) { int res = 1; // Initialize result // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y%2==1) res = (res*x); // y must be even now y = y>>1; // y = y/2 x = (x*x); } return res; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static ArrayList<aksh>[] adj; static int[] vis; static boolean compareSeq(char[] S, int x, int y, int n) { for (int i = 0; i < n; i++) { if (S[x] < S[y]) return true; else if (S[x] > S[y]) return false; x = (x + 1) % n; y = (y + 1) % n; } return true; } static void build(long[] sum,int[] arr,int n) { for(int i=0;i<(1<<n);i++) { long total=0; for(int j=0;j<n;j++) { if((i & (1 << j)) > 0) total+=arr[j]; } sum[i]=total; } } static int count(long arr[], long x, int n) { int l=0; int h=n-1; int res=-1; int mid=-1; while(l<=h) { mid=l+(h-l)/2; if(x==arr[mid]) { res=mid; h=mid-1; } else if(x<arr[mid]) h=mid-1; else l=mid+1; } if(res==-1) return 0; //res is first index and res1 is last index of an element in a sorted array total number of occurences is (res1-res+1) int res1=-1; l=0; h=n-1; while(l<=h) { mid=l+(h-l)/2; if(x==arr[mid]) { res1=mid; l=mid+1; } else if(x<arr[mid]) h=mid-1; else l=mid+1; } if(res1==-1) return 0; if(res!=-1 && res1!=-1) return (res1-res+1); return 0; } static int parity(int a) { a^=a>>16; a^=a>>8; a^=a>>4; a^=a>>2; a^=a>>1; return a&1; } /* PriorityQueue<aksh> pq = new PriorityQueue<>((o1, o2) -> { if (o1.p < o2.p) return 1; else if (o1.p > o2.p) return -1; else return 0; });//decreasing order acc to p*/ static int power(int x, int y, int m) { if (y == 0) return 1; int p = power(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } static int modinv(int a, int m) { int g = gcd(a, m); if (g != 1) return 0; else { return power(a, m - 2, m); } //return 0; } static int[] product(int[] nums) { int[] result = new int[nums.length]; int[] t1 = new int[nums.length]; int[] t2 = new int[nums.length]; t1[0]=1; t2[nums.length-1]=1; //scan from left to right for(int i=0; i<nums.length-1; i++){ t1[i+1] = nums[i] * t1[i]; } //scan from right to left for(int i=nums.length-1; i>0; i--){ t2[i-1] = t2[i] * nums[i]; } for(int i=0;i<nums.length;i++) { System.out.print(t1[i]+" "+t2[i]); System.out.println(); } //multiply for(int i=0; i<nums.length; i++){ result[i] = t1[i] * t2[i]; } return result; } static int getsum(int[] bit,int ind) { int sum=0; while(ind>0) { sum+=bit[ind]; ind-= ind & (-ind); } return sum; } static void update(int[] bit,int max,int ind,int val) { while(ind<=max) { bit[ind]+=val; ind+= ind & (-ind); } } public static void main(String args[] ) throws Exception { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ FastReader sc=new FastReader(); int t=sc.nextInt(); while(t-->0) { int[] a=new int[3]; for(int i=0;i<3;i++) a[i]=sc.nextInt(); Arrays.sort(a); int ans=0; if(a[2]>a[0]+a[1]) ans=a[0]+a[1]; else ans=(a[0]+a[1]+a[2])/2; System.out.println(ans); } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
b6727413cbe2579891a4129a69b6499e
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.io.*; import java.lang.*; import java.util.*; public class Codeforces { public static void main (String[] args) { Scanner sc=new Scanner(System.in); int t =sc.nextInt(); while(t-->0) { int i; int a[]=new int [3]; for(i=0;i<3;i++) a[i]=sc.nextInt(); Arrays.sort(a); int r=a[0]; int g=a[1]; int b=a[2]; if(r==1&& b==1 && g==1){ System.out.println(1); continue;} if((r==0 && b==0) || (r==0&& g==0 )||( g==0 && b==0)){ System.out.println(0); continue;} if(r==0&&g==0&&b==0) { System.out.println(0); continue; } int d=0; int min=a[0]; int mid=a[1]; int max=a[2]; if(max>(min+mid)){ System.out.println((min +mid)); } else System.out.println((min +mid+max)/2); } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
10e98df3cd0df25172b494e541fe8212
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.io.*; import java.util.Arrays; public class SweetProblem { public static void main(String[] args){ try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int cases = Integer.parseInt(br.readLine()); int[] arr = new int[3]; String[] temp; while(cases-->0){ temp = br.readLine().split(" "); arr[0] = Integer.parseInt(temp[0]); arr[1] = Integer.parseInt(temp[1]); arr[2] = Integer.parseInt(temp[2]); if(!(arr[0] <= arr[1] && arr[1] <= arr[2])){ Arrays.sort(arr); } if((arr[0] + arr[1]) < arr[2]){ System.out.println(arr[0] + arr[1]); }else{ System.out.println((arr[0] + arr[1] + arr[2])/2); } } }catch(IOException ioe){ } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
0b90ba746411abcf56cb17d7a277b8b4
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class SweetProblem { static class FastReader4 { BufferedReader br; StringTokenizer st; public FastReader4() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader4 fastReader4 = new FastReader4(); StringBuilder output = new StringBuilder(); int t = fastReader4.nextInt(); for(int i=1;i<=t;i++) { ArrayList<Integer> gg = new ArrayList<>(); gg.add(fastReader4.nextInt()); gg.add(fastReader4.nextInt()); gg.add(fastReader4.nextInt()); Collections.sort(gg); int noOfTimes =0; if(gg.get(0)+gg.get(1)<=gg.get(2)) { noOfTimes = (gg.get(1)+gg.get(0)); output.append(noOfTimes).append("\n"); } else { int sum = gg.get(0) +gg.get(1)+gg.get(2); if(sum%2==0) { noOfTimes = sum/2; } else { noOfTimes = gg.get(0)/2 +gg.get(1)/2+gg.get(2)/2; int y = gg.get(0)%2 +gg.get(1)%2+gg.get(2)%2; if(y%2==0||y==3) noOfTimes++; } if(noOfTimes==0) noOfTimes++; output.append(noOfTimes).append("\n"); } } System.out.println(output.toString()); } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
097d52f6c5c65f1df865cda89a973d99
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void solve(InputReader in) { int n = 3; int a[] = new int[n]; for(int i =0 ; i<n; i++) a[i] = in.readInt(); Arrays.sort(a); if(a[2] >= a[0] + a[1]) { System.out.println(a[0] + a[1]); return; } System.out.println((a[1] + a[0] + a[2])/2); } public static void main(String ...strings) { InputReader in = new InputReader(System.in); int t = in.readInt(); while(t-- > 0) { solve(in); } } } class InputReader{ private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public 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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
a3f60b978524b16464fd3b930c2174f9
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Integer t = Integer.parseInt(sc.nextLine()); for (int i = 0; i < t; i++) { List<Integer> list = new ArrayList<>(); list.add(sc.nextInt()); list.add(sc.nextInt()); list.add(sc.nextInt()); Collections.sort(list); if(list.get(2) <= list.get(1) + list.get(0)) System.out.println((list.get(2) + list.get(1) + list.get(0)) / 2); else System.out.println(list.get(1) + list.get(0)); } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
90d06d8c691e58eedc61018a456e8892
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { Scanner ob = new Scanner(System.in); int N = ob.nextInt(); for(int n = 1; n <= N; n++) { int max = -1, sum = 0, x; for(int i = 0; i < 3; i++) { x = ob.nextInt(); max = Math.max(x, max); sum += x; } int ans = Math.min(sum >> 1, sum - max); System.out.println(ans); } ob.close(); } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
bbaa92f38318781edb5c3c7e1b574259
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.io.*; import java.util.*; public class CF { public static void main(String[] args) throws IOException { int n = nextInt(); for (int i = 0; i < n; i++) { int r = nextInt(); int g = nextInt(); int b = nextInt(); int[] a = {r, g, b}; Arrays.sort(a); if (a[0] + a[1] <= a[2]) { out.println(a[0] + a[1]); } else { out.println((a[0] + a[1] + a[2]) / 2); } } out.close(); } static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter out = new PrintWriter(System.out); static StringTokenizer in = new StringTokenizer(""); public static String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public static long nextLong() throws IOException { return Long.parseLong(nextToken()); } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
f525c7f28637ddebeed1ad2daa1f9ba7
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
// @uthor -: puneet // TimeStamp -: 6:58 PM - 27/11/19 import java.io.*; import java.math.BigInteger; import java.util.*; public class EduQ1 implements Runnable { public void solve() { int t=in.ni(); while(t-->0){ int[] arr=in.intarr(3); Arrays.sort(arr); // int mm=arr[0]; // int ans=arr[0]; // if(arr[0]%2!=0){ // arr[1]-=arr[0]/2; // arr[2]-=arr[0]/2; // arr[2]--; // }else{ // arr[1]-=arr[0]/2; // arr[2]-=arr[0]/2; // } // ans+=Math.min(arr[1],arr[2]); // out.println(ans); int ans=arr[0]; int temp=arr[2]-arr[1]; if(arr[0]<=temp){ arr[2]-=arr[0]; ans+=Math.min(arr[2],arr[1]); }else{ ans=(arr[0]+arr[1]+arr[2])/2; } out.println(ans); } } /* -------------------- Templates and Input Classes -------------------------------*/ @Override public void run() { try { init(); } catch (FileNotFoundException e) { e.printStackTrace(); } solve(); out.flush(); } private FastInput in; private PrintWriter out; public static void main(String[] args) throws Exception { new Thread(null, new EduQ1(), "Main", 1 << 27).start(); } private void init() throws FileNotFoundException { InputStream inputStream = System.in; OutputStream outputStream = System.out; try { if (System.getProperty("user.name").equals("puneet")) { outputStream = new FileOutputStream("/home/puneet/Desktop/output.txt"); inputStream = new FileInputStream("/home/puneet/Desktop/input.txt"); } } catch (Exception ignored) { } out = new PrintWriter(outputStream); in = new FastInput(inputStream); } private void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int object : arr) list.add(object); Collections.sort(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } private void sort(long[] arr) { List<Long> list = new ArrayList<>(); for (long object : arr) list.add(object); Collections.sort(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } public long ModPow(long x, long y, long MOD) { long res = 1L; x = x % MOD; while (y >= 1) { if ((y & 1) > 0) res = (res * x) % MOD; x = (x * x) % MOD; y >>= 1; } return res; } public int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static class FastInput { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastInput(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int peek() { if (numChars == -1) { return -1; } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) { return -1; } } return buf[curChar]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String ns() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { 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 BigInteger readBigInteger() { try { return new BigInteger(ns()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char nc() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public double nd() { 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, ni()); } 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, ni()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String next() { return ns(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] intarr(int n) { int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } public double[] doublearr(int n) { double arr[] = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nd(); } return arr; } public double[][] doublearr(int n, int m) { double[][] arr = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nd(); } } return arr; } public int[][] intarr(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = ni(); } } return arr; } public long[][] longarr(int n, int m) { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nl(); } } return arr; } public long[] longarr(int n) { long arr[] = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
3fb6b5093f34737cfef6e41e05e546f9
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.io.*; import java.util.*; public class C324C { private static StringTokenizer st; public static void nextLine(BufferedReader br) throws IOException { st = new StringTokenizer(br.readLine()); } public static int nextInt() { return Integer.parseInt(st.nextToken()); } public static String next() { return st.nextToken(); } public static long nextLong() { return Long.parseLong(st.nextToken()); } public static double nextDouble() { return Double.parseDouble(st.nextToken()); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); nextLine(br); int t=nextInt(); while(t!=0){ nextLine(br); int r=nextInt(); int g=nextInt(); int b=nextInt(); int max=Math.max(r,Math.max(g,b)); int min=Math.min(r,Math.min(g,b)); int mid=r+g+b-max-min; int ans=0; if(min>=max-mid) System.out.println((r+g+b)/2); else{ ans+=min; ans+=Math.min(max-min,mid); System.out.println(ans); } t--; } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
3f484cc5006c3da35fcbad328e4e8329
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
/****************************************************************************** Online Java Compiler. Code, Compile, Run and Debug java program online. Write your code in this editor and press "Run" button to execute it. *******************************************************************************/ import java.util.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); for (int i = 0; i < t; i++) { int[] arr = new int[3]; arr[0] = input.nextInt(); arr[1] = input.nextInt(); arr[2] = input.nextInt(); Arrays.sort(arr); int ans = 0; int min = Math.min(arr[0], arr[2] -arr[1]); arr[2] -= min; arr[0] -= min; ans += min; if (arr[1] == arr[2]) { int half = arr[0] / 2; ans += half * 2; arr[1] -= half; arr[2] -= half; ans += arr[1]; } else { ans += arr[1]; } System.out.println(ans); } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
5692edd147f509c4ce0ede6cc05d2774
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class contest { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) { int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); PriorityQueue<Integer> p = new PriorityQueue<Integer>(); p.add(a); p.add(b); p.add(c); a = p.poll();b=p.poll();c=p.poll(); int res = 0; if(c==b) { res+=(a/2)*2; res+=b-a/2; } else if(c-b<=a){ res +=c-b ; a-=c-b; c = b; res+=(a/2)*2; res+=b-a/2; }else { res+=Math.min(c-b,a); res+=b; } System.out.println(res); } pw.flush(); pw.close(); } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
630c9b77600c6fbe67e9c5d8446cc9fd
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import static java.lang.Math.max; import static java.lang.Math.min; public class SweetProblem { static BufferedReader br; static StringTokenizer st = new StringTokenizer(""); public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int wheel = nextInt(); for (int i = 0; i < wheel; i++) { int r = nextInt(); int g = nextInt(); int b = nextInt(); int min = min(r, min(g, b)); int max = max(r, max(g, b)); int sum = r + g + b; int mid = sum - max - min; int diff = max - mid; if (diff > min) { pw.println(min(max, sum - max)); } else { min -= diff; mid += diff; int plus = min / 2; pw.println(mid + plus); } } pw.close(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
99d053cca6451fb1cef6054b5dff968f
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.util.*; import java.io.*; public class practice { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-- !=0) { int[]arr=new int[3]; String str=br.readLine(); StringTokenizer st=new StringTokenizer(str); for(int i=0;i<3;i++) { arr[i]=Integer.parseInt(st.nextToken()); } Arrays.sort(arr); int a=arr[2]; int b=arr[1]; int c=arr[0]; if(a>=b+c) { System.out.println(b+c); }else { int ans=0; ans+=(a-b); int diff=a-b; // System.out.println(a+" "+b+" "+c+" "+ans); a=a-diff; c=c-diff; ans+=(b-c); diff=b-c; // System.out.println(a+" "+b+" "+c+" "+ans); b=b-diff; a=a-diff; ans+=(3*a)/2; // System.out.println(a+" "+b+" "+c+" "+ans); System.out.println(ans); } } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
f935af318743141110bb3072f70c6930
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.util.*; public class Main{ public static void main (String args[]){ // write your dream! Twinkle! Scanner in = new Scanner(System.in); int test= in.nextInt(); while (test --!=0){ int r=in.nextInt(),g=in.nextInt(),b=in.nextInt(); int sum = r+g+b; int m = Math.max(r, Math.max(g, b)); int l = Math.min(r, Math.min(g, b)); int middle = sum - m - l; if (m >= sum-m) { System.out.println(sum-m); } else { int rem = (m - middle); System.out.println( l + (middle - (l - rem)/2) - ((l-rem)%2)); } } }}
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
76936ae759c4dc9fde3bdf7ab99647c7
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.util.*; public class problemA { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t!=0){ int[] a=new int[3]; int i; for(i=0;i<3;i++){ a[i]=s.nextInt(); } Arrays.sort(a); int cnt=0; if(a[2]>a[1]+a[0]){ cnt=a[1]+a[0]; } else{ cnt=(a[0]+a[1]+a[2])/2; } System.out.println(cnt); t--; } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
a4f71244b6682732a5a1a16d7d9fde4f
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
//package codeforces.round603div2; import java.io.*; import java.util.*; public class SweetProblem { public static void main(String[] args) { // try { // FastScanner in = new FastScanner(new FileInputStream("src/input.in")); // PrintWriter out = new PrintWriter(new FileOutputStream("src/output.out")); FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int q = in.nextInt(); solve(q, in, out); // } // catch (IOException e) { // e.printStackTrace(); // } } private static void solve(int q, FastScanner in, PrintWriter out) { for(int c = 0; c < q; c++) { Integer[] p = new Integer[3]; p[0] = in.nextInt(); p[1] = in.nextInt(); p[2] = in.nextInt(); Arrays.sort(p, Comparator.reverseOrder()); int d = p[1] - p[2]; p[0] -= d; p[1] -= d; // int sum = p[0] + p[1] + p[2]; // d += sum / 2; if(p[0] == p[1]) { d += p[0] * 3 / 2; } else { if(p[0] < 2 * p[1]) { int diff = p[1] - p[0] / 2; d += diff; p[1] -= diff; p[2] -= diff; } d += 2 * p[1]; } out.println(d); } out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
790510045ddb405e4523c59b3a52338d
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jenish */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); ASweetProblem solver = new ASweetProblem(); solver.solve(1, in, out); out.close(); } static class ASweetProblem { public void solve(int testNumber, ScanReader in, PrintWriter out) { int t = in.scanInt(); while (t-- > 0) { long arr[] = new long[]{in.scanLong(), in.scanLong(), in.scanLong()}; Arrays.sort(arr); long ans = 0; ans = Math.max(ans, Math.min(arr[0] + arr[1], arr[2])); long diff = arr[2] - arr[1]; if (diff >= arr[0]) { arr[2] -= arr[0]; long temp = arr[0]; temp += Math.min(arr[1], arr[2]); arr[2] += arr[0]; ans = Math.max(ans, temp); } else { long temp = diff; arr[0] -= diff; arr[2] = arr[1]; long a = arr[0] / 2; long b = arr[0] - a; long aa = Math.min(arr[1], a); long bb = Math.min(arr[2], b); arr[1] -= aa; arr[2] -= bb; ans = Math.max(ans, temp + aa + bb + Math.min(arr[1], arr[2])); arr[1] += aa; arr[2] += bb; } out.println(ans); } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (INDEX >= TOTAL) { INDEX = 0; try { TOTAL = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (TOTAL <= 0) return -1; } return buf[INDEX++]; } public int scanInt() { int I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } public long scanLong() { long I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
676ab2601578579aa26b77ead2cd833e
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class p603A { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while (t-->0){ int a[]=new int[3]; for (int i=0;i<3;i++) { a[i] = sc.nextInt(); } Arrays.sort(a); if (a[0]+a[1]>=a[2]){ System.out.println((a[0]+a[1]+a[2])/2); }else{ System.out.println(Math.min(a[2],a[0]+a[1])); } } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
a9af52dbbc51d6cfe21d586b5ee2bea0
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class que1 { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); for (int i = 1; i <= n; i++) { int[] arr = new int[3]; for (int l = 0; l < arr.length; l++) { arr[l] = scn.nextInt(); } Arrays.sort(arr); long max=0; int val=arr[2]-arr[1]; if(val>=arr[0]){ System.out.println(arr[0]+Math.min(arr[1], arr[2]-arr[0])); }else{ int diff=arr[2]-arr[1]; int la=(int)Math.ceil(((arr[0]-diff)*1.0)/2); System.out.println((arr[1]-la)+(arr[0]-diff)+diff); } } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
5a083bcaeeb9a836a285b902ddee513b
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class SweetProblem { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while (t-- > 0) { int[] a = new int[3]; for (int i = 0; i < 3; i++) { a[i] = scan.nextInt(); } Arrays.sort(a); if(a[2]>a[1]+a[0]){ System.out.println(a[1]+a[0]); }else{ System.out.println((a[0]+a[1]+a[2])/2); } } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
c39afa459642ecfff4c1a648603dd211
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.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 janit0r */ 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); ASweetProblem solver = new ASweetProblem(); solver.solve(1, in, out); out.close(); } static class ASweetProblem { public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); for (int i = 0; i < t; ++i) { int a[] = new int[3]; a[0] = in.nextInt(); a[1] = in.nextInt(); a[2] = in.nextInt(); Arrays.sort(a); int x = Math.min(a[2], a[0] + a[1]); int d = (a[0] + a[1] - a[2]); if (d > 1) x += d / 2; out.println(x); } } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
c3afc44cf98cff99fa16290eecc920a9
train_001.jsonl
1575038100
You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $$$r$$$ candies in it, the second pile contains only green candies and there are $$$g$$$ candies in it, the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.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 janit0r */ 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); ASweetProblem solver = new ASweetProblem(); solver.solve(1, in, out); out.close(); } static class ASweetProblem { public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); for (int i = 0; i < t; ++i) { int a[] = new int[3]; a[0] = in.nextInt(); a[1] = in.nextInt(); a[2] = in.nextInt(); Arrays.sort(a); int d = a[2] - a[0]; int d1 = Math.abs(a[1] - d); out.println(a[0] + Math.min(a[1], d + d1 / 2)); } } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["6\n1 1 1\n1 2 1\n4 1 1\n7 4 10\n8 1 4\n8 2 8"]
1 second
["1\n2\n2\n10\n5\n9"]
NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Java 8
standard input
[ "math" ]
1f29461c42665523d0a4d56b13f7e480
The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.
1,100
Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.
standard output
PASSED
1ef4b4449cc9e86bfd810ab43884a0d7
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.*; import java.util.*; public class Main { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } static int primes[]; public static void main(String args[]) throws IOException { Scan input=new Scan(); primes=new int[5000001]; sieve(5000001); int prefix[]=new int[5000001]; prefix[0]=primes[0]; for(int i=1;i<5000001;i++) { prefix[i]=prefix[i-1]+primes[i]; } // for(int i=0;i<=100;i++) { // System.out.println(i+"->"+primes[i]); // } int test=input.scanInt(); StringBuilder ans=new StringBuilder(""); for(int t=1;t<=test;t++) { int b=input.scanInt(); int a=input.scanInt(); int tmp=prefix[b]-prefix[a]; ans.append(tmp+"\n"); } System.out.println(ans); } //false for prime number and true for composite number public static void sieve(int n) { boolean sieve[]=new boolean[n]; for(int i=2;i<n;i++) { if(!sieve[i]) { primes[i]++; for(int j=2*i;j<n;j=j+i) { sieve[j]=true; int tmp=j; while(tmp%i==0) { tmp/=i; primes[j]++; } } } } } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 11
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
d6c6e5740b2ad8978e5aebb2f30bd84b
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class SoldierAndNumberGame { InputStream is; PrintWriter pw; String INPUT = ""; int MAXN = 5000001; long factors[] = new long[MAXN]; void solve() { int t = ni(); int lpf[] = enumLowestPrimeFactors(MAXN); for (int i = 2; i < MAXN; i++) { factors[i] = factors[i / lpf[i]] + 1; } for (int i = 1; i < MAXN; i++) { factors[i] += factors[i - 1]; } while (t-- > 0) { int a = ni(), b = ni(); pw.println(factors[a] - factors[b]); } } public static int[] enumLowestPrimeFactors(int n) { int tot = 0; int[] lpf = new int[n + 1]; int u = n + 32; double lu = Math.log(u); int[] primes = new int[(int) (u / lu + u / lu / lu * 1.5)]; for (int i = 2; i <= n; i++) lpf[i] = i; for (int p = 2; p <= n; p++) { if (lpf[p] == p) primes[tot++] = p; int tmp; for (int i = 0; i < tot && primes[i] <= lpf[p] && (tmp = primes[i] * p) <= n; i++) { lpf[tmp] = primes[i]; } } return lpf; } void run() throws Exception { // is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); is = System.in; pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); // int t = ni(); // while (t-- > 0) solve(); pw.flush(); tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new SoldierAndNumberGame().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 11
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
fb5ae4e95bf8de09d7bc52ec5ef1fb7a
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static Integer[] getSmallestPrimeFactorInIntervalInclusive(int maxN) { Integer[] result = new Integer[maxN + 1]; for (int i = 2; i <= maxN; i++) { if (result[i] == null) { for (int j = i; j <= maxN; j += i) { if (result[j] == null) { result[j] = i; } } } } return result; } static FastReader scanner = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static Integer[] primeFactors = getSmallestPrimeFactorInIntervalInclusive(5_000_000); static Integer[] result = new Integer[5_000_001]; public static void main(String[] args) { int t = scanner.nextInt(); result[1] = 0; for (int i = 2; i <= 5_000_000; i++) { result[i] = result[i-1]; int currentNumber = i; while (currentNumber > 1) { result[i]++; currentNumber /= primeFactors[currentNumber]; } } for (int testCase = 0; testCase < t; testCase++) { solve(); } out.close(); } private static void solve() { int a = scanner.nextInt(); int b = scanner.nextInt(); out.println(result[a] - result[b]); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 11
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
f34e4942bec4d70d80727214fc1bc84a
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf546d { public static void main(String[] args) throws IOException { int buf[] = new int[5000005], x[] = new int[5000005], pre[] = new int[5000005]; for(int i = 1; i <= 5000000; ++i) { buf[i] = i; } for(int i = 2; i < 5000000; ++i) { if(buf[i] == i) { x[i] = 1; int mp = i + i; while(mp <= 5000000) { while(buf[mp] % i == 0) { buf[mp] /= i; ++x[mp]; } mp += i; } } } for(int i = 2; i <= 5000000; ++i) { pre[i] = pre[i - 1] + x[i]; } // prln(x); // prln(pre); int t = ri(); while(t --> 0) { int a = rni(), b = ni(); prln(pre[a] - pre[b]); } close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random rand = new Random(); // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 11
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
5ab25ac67f054a00e6f5df23be304bb4
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; // same sol but better sieve given by editorial public class cf546d_2 { public static void main(String[] args) throws IOException { int div[] = new int[5000005], x[] = new int[5000005], pre[] = new int[5000005]; for(int i = 2; i <= 5000000; ++i) { if(div[i] == 0) { div[i] = i; x[i] = 1; int mp = i; while(mp <= 5000000) { div[mp] = i; mp += i; } } else { x[i] = x[i / div[i]] + 1; } } for(int i = 2; i <= 5000000; ++i) { pre[i] = pre[i - 1] + x[i]; } int t = ri(); while(t --> 0) { int a = rni(), b = ni(); prln(pre[a] - pre[b]); } close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random rand = new Random(); // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 11
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
d69c3e7c6373778af1bb31241c2d78ce
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class Main { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int glo = (5*(int)1e6); int prime[] = new int[glo+1]; long dp[] = new long[glo+1]; dp[1]=1; for(int i=2;i<=glo;i++){ if(prime[i]==0){ dp[i]++; for(int j=i*2;j<=glo;j+=i){ int q = j; while(q%i==0){ dp[j]++; q/=i; } prime[j]=1; } } } for(int i=1;i<=glo;i++){ dp[i] += dp[i-1]; } int n = ni(); for(int i=1;i<=n;i++){ int a = ni(); int b = ni(); long ans = dp[a]-dp[b]; out.println(ans); } } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 11
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
af3c35c18339d850a3a374d5dabafd5b
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Problem304D { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); int max = 5000000; int[] spf = smallestPrimeFactor(max); int[] numFactors = new int[spf.length]; numFactors[1] = 0; // 0 prime factors of 1 for (int i = 2; i <= max; i++) { if (spf[i] == i) { // prime numFactors[i] = 1; } else { numFactors[i] = numFactors[i / spf[i]] + 1; } } int[] sum = new int[spf.length]; int count = 0; for (int i = 1; i <= max; i++) { count += numFactors[i]; sum[i] = count; } int tt = Integer.parseInt(reader.readLine()); for (int t = 0; t < tt; t++) { StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int a = Integer.parseInt(tokenizer.nextToken()); int b = Integer.parseInt(tokenizer.nextToken()); int answer = sum[a] - sum[b]; writer.println(answer); } reader.close(); writer.close(); } // spf[0] = spf[1] = -1 // primes: spf[i] = i // O(n log log n) public static int[] smallestPrimeFactor(int n) { int[] spf = new int[n + 1]; // includes 0 spf[0] = -1; spf[1] = -1; for (int i = 2; i <= n; i++) { spf[i] = i; } for (int i = 4; i <= n; i += 2) { spf[i] = 2; } for (int i = 3; i * i <= n; i += 2) { if (spf[i] == i) { // prime for (int j = i * i; j <= n; j += i) { if (spf[j] == j) { spf[j] = i; } } } } return spf; } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 11
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
33090f846c52e9b186af8a6a8efad021
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.*; import java.util.*; public class SoldierNumberGame { public static void main(String[] args)throws Exception{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); // BufferedReader reader = new BufferedReader(new FileReader("sng.in")); // PrintWriter writer = new PrintWriter(new FileWriter("sng.out")); StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int games = Integer.parseInt(tokenizer.nextToken()); int[] spf = smallestPrimeFactor(5000000); int[] totalDivisors = new int[5000001]; for (int i = 2; i < totalDivisors.length; i++){ totalDivisors[i] = totalDivisors[i/spf[i]]+1; } int[] preCompute = new int[5000001]; int sum = 0; for (int i = 0; i < preCompute.length; i++){ sum += totalDivisors[i]; preCompute[i] = sum; } for (int i = 0; i < games; i++){ tokenizer = new StringTokenizer(reader.readLine()); int a = Integer.parseInt(tokenizer.nextToken()); int b = Integer.parseInt(tokenizer.nextToken()); int ans = preCompute[a]-preCompute[b]; writer.println(ans); } reader.close(); writer.close(); } public static int[] smallestPrimeFactor(int n) { int[] spf = new int[n + 1]; spf[0] = -1; spf[1] = -1; for (int i = 2; i <= n; i++) { spf[i] = i; } for (int i = 4; i <= n; i += 2) { spf[i] = 2; } for (int i = 3; i * i <= n; i += 2) { if (spf[i] == i) { // prime for (int j = i * i; j <= n; j += i) { if (spf[j] == j) { spf[j] = i; } } } } return spf; } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 11
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
fb012ccd38476409ca9ac1c5cb81eaf2
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.awt.*; import java.awt.List; import java.io.*; import java.util.*; import java.util.concurrent.BrokenBarrierException; import javax.net.ssl.SSLEngineResult; import javax.swing.*; import javax.swing.text.html.MinimalHTMLWriter; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.sqrt; import java.awt.Toolkit; import java.awt.event.*; import java.util.concurrent.TimeUnit; public class Main { public static void main(String [] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; Integer readFromFile=new Integer(1); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out) ; out.close(); } static class TaskD { void madAdd(Map <Integer, Integer> map, Integer value){ if(map.containsKey(value)){ map.put(value, map.get(value)+1); }else{ map.put(value, 1); } } //I have to try at least two ways to solve this problem, I'll make one of them with ; class Pair implements Comparable<Pair>{ int fist; int second; Pair(int fist, int second){ this.fist = fist; this.second = second; } @Override public int compareTo(Pair arg0) { if(fist!=arg0.fist) { return fist - arg0.fist; }else{ return second - arg0.second; } } } // ArrayList<ArrayList<Integer>> graph = null; // boolean isVisited[] = new boolean[200001]; // int []deap = new int[200001]; // int []valueV = new int[200001]; /* int dfs(int v){ ArrayList<Integer> currentTree = graph.get(v); isVisited[v]=true; for(Integer iter: currentTree){ if(isVisited[iter]==false){ deap[iter]=deap[v]+1; valueV[v] = valueV[v]+dfs(iter); //valueV.set(v, valueV.get(v) + dfs(iter));//= 5;//valueV.get(v)+ (int)dfs(iter, deap); } } return valueV[v]+1; } */ public void solve(int testNumber, InputReader in, PrintWriter out) { int ranger = 5000001; int []prime = new int[ranger]; int sqrtLen = (int)Math.ceil(Math.sqrt(ranger)); for (int i=2; i<sqrtLen; i++){ if(prime[i]==0){ for(int j = i*2; j<ranger; j+=i){ if (prime[j]==0){ prime[j]=i; } } } } int []primeFactor = new int[ranger]; int []prefixSum = new int[ranger]; for (int i=0; i<ranger; i++){ if(prime[i]==0){ primeFactor[i]=1; }else{ primeFactor[i]=primeFactor[i/prime[i]]+1; } } for(int i = 1; i<ranger; i++){ prefixSum[i]=prefixSum[i-1]+primeFactor[i]; } int n = in.nextInt(); for(int i = 0; i<n; i++){ int a = in.nextInt(); int b = in.nextInt(); out.println(prefixSum[a]-prefixSum[b]); } /* int []array = new int[5000]; array[1]=4; array[2]=7; int pow1=2; int dec=10; int r=3; for(int i=1; true; i++){ if(i==r){ pow1*=2; dec*=10; r=i+pow1; } if(4*dec+array[i]==44444444){ break; } array[i+pow1]=4*dec+array[i]; array[i+(pow1*2)]=7*dec+array[i]; } for(int i=1, pow1=1, dec=10; i<100; i+=pow1){ for(int l=i; l<i+pow1*2; l++) { array[l+pow1*2]=4*dec+array[l]; array[l+(pow1*4)]=7*dec+array[l]; } pow1*=2; dec*=10; } */ /* for(int i = 1; i<500; i++){ out.println(i+" "+array[i]); } /* ArrayList<Integer> arrayList = new ArrayList<>(5000); arrayList.add(0); arrayList.add(4); arrayList.add(7); for(int i=1, pow1=1, dec=10; i<500; i+=pow1){ for(int l=i; l<i+pow1*2; l++){ arrayList.add(4*dec+arrayList.get(l)); } for(int l=i; l<i+pow1*2; l++){ arrayList.add(7*dec+arrayList.get(l)); } pow1*=2; dec*=10; } /* int n = in.nextInt(); int k = in.nextInt(); graph = new ArrayList<ArrayList<Integer>> (n+1); //valueV = new ArrayList<Integer>(n+1); for(int i = 0; i<n+1; i++){ graph.add(new ArrayList<>()); // valueV.add(0); } for(int i=0; i<n-1; i++){ int u = in.nextInt(); int v = in.nextInt(); graph.get(u).add(v); graph.get(v).add(u); } dfs(1); ArrayList<Integer> listAnswer = new ArrayList<Integer>(n+1); listAnswer.add(0); for(int i=1; i<n+1; i++){ listAnswer.add(deap[i]-valueV[i]); } listAnswer.remove(0); Collections.sort(listAnswer); Collections.reverse(listAnswer); long answer = 0; for(int i = 0; i<k; i++){ answer+=listAnswer.get(i); } out.println(answer); */ } } static class InputReader { BufferedReader br; StringTokenizer st; String st1; File file = new File("1.txt"); public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public InputReader(int i) { try { br = new BufferedReader( new InputStreamReader(new FileInputStream(file))); } catch (FileNotFoundException e1) { System.out.println("File is not find"); } 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 String nextLine(){ try { st1 = new String(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return st1; } public int nextInt() {return Integer.parseInt(next());} public long nextLong(){ return Long.parseLong(next()); } public Double nextDouble(){ return Double.parseDouble(next()); } public Byte nextByte() { return Byte.parseByte(next()); } private int idx; public Character nextChar() { if(st1==null) { st1 = next(); idx = 0; } if(idx!=(st1.length())-1){ return st1.charAt(idx++); }else{ char c= st1.charAt(idx); st1 = null; return c; } } public void newFile() { try { FileWriter write = new FileWriter(file); write.write("something for cheaking"); write.close(); } catch (IOException e) { e.printStackTrace(); } } public void writeFile1(){ try{ FileWriter write = new FileWriter(file); write.append("100000"+" "); for(int i=0; i<100000; i++){ write.append(new Integer((int)(Math.random()*5000)).toString()+" "); } write.close(); }catch(IOException e){ e.printStackTrace(); } } } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 11
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
c92102512556fe2c651f5dafcd9b7195
train_001.jsonl
1432312200
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
256 megabytes
import java.io.*; import java.util.*; public class Main { static class PairComparator implements Comparator<Pair> { @Override public int compare(Pair x, Pair y) { if (x.val < y.val) return -1; if (x.val > y.val) return 1; if (x.val == y.val) { if (x.ind < y.ind) return -1; if (x.ind > y.ind) return 1; } return 0; } } static class Pair { int ind, val; Pair(int i, int v) { ind = i; val = v; } } static int[] vis; static void func() throws Exception { int maxV = (int)5e6; int[] primes = new int[maxV+1]; for (int i=2;i*i<=maxV;i++){ if (primes[i]!=0)continue; for (int start=i;start<=maxV;start+=i){ if (primes[start]==0)primes[start]=i; } } int[] factors = new int[maxV+1]; for (int i=2;i<=maxV;i++){ if (primes[i]==0)primes[i]=i; factors[i]=1+factors[i/primes[i]]; } long[] prefix = new long[maxV+1]; for (int i=2;i<=maxV;i++){ prefix[i] = prefix[i-1]+factors[i]; } int n = sc.nextInt(); for (int t=0;t<n;t++){ int l = sc.nextInt(); int r =sc.nextInt(); pw.println(prefix[l]-prefix[r]); } } /* * */ static PrintWriter pw; static MScanner sc; public static void main(String[] args) throws Exception { pw = new PrintWriter(System.out); sc = new MScanner(System.in); int tests = 1; // tests =sc.nextInt(); //comment this line while (tests-- > 0) { func(); pw.flush(); } } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(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 int[] intArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public long[] longArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[] in = new Integer[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[] in = new Long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } 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); } } static void shuffle(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * (i + 1)); int tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } static void shuffle(long[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * (i + 1)); long tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } }
Java
["2\n3 1\n6 3"]
3 seconds
["2\n5"]
null
Java 11
standard input
[ "dp", "constructive algorithms", "number theory", "math" ]
79d26192a25cd51d27e916adeb97f9d0
First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.
1,700
For each game output a maximum score that the second soldier can get.
standard output
PASSED
f8b0efcb6083d99e93173cc7ecf7956e
train_001.jsonl
1557671700
$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \leq i \leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \leq j \leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \leq i \leq n$$$ and $$$1 \leq j \leq m$$$. You are given the numbers $$$b_1, \ldots, b_n$$$ and $$$g_1, \ldots, g_m$$$, determine this number.
256 megabytes
import java.util.*; public class Solution { public static void main(String []args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int b[] = new int[n]; int g[] = new int[m]; for(int i = 0 ; i < n ; i++) { b[i] = sc.nextInt(); } for(int i = 0 ; i< m ; i++) { g[i] = sc.nextInt(); } long ans = 0; Arrays.sort(b); Arrays.sort(g); int i = n-1 , j = m-1; int cnt = m; if(b[i] > g[0]) System.out.println("-1"); else { while(i >= 0) { if(j >= 0) { if(b[i] <= g[j]) { if(cnt != 1) { ans += g[j]; cnt--; j--; } else { if(b[i] == g[j]) { ans += b[i]; j--; cnt = m; i--; } else { ans += b[i]; cnt = m; i--; } } } else { ans += (long)cnt*(long)b[i]; i--; cnt = m; } } else { ans += (long)cnt*(long)b[i]; cnt = m; i--; } } System.out.println(ans); } } }
Java
["3 2\n1 2 1\n3 4", "2 2\n0 1\n1 0", "2 3\n1 0\n1 1 2"]
1 second
["12", "-1", "4"]
NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "math", "implementation", "sortings", "binary search" ]
4b4c7e7d9d5c45c8635b403bae997891
The first line contains two integers $$$n$$$ and $$$m$$$, separated with space — the number of boys and girls, respectively ($$$2 \leq n, m \leq 100\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$, separated by spaces — $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \leq b_i \leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \ldots, g_m$$$, separated by spaces — $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \leq g_j \leq 10^8$$$).
1,500
If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.
standard output
PASSED
550fca51171f3076fc6b529bbb25a74b
train_001.jsonl
1557671700
$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \leq i \leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \leq j \leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \leq i \leq n$$$ and $$$1 \leq j \leq m$$$. You are given the numbers $$$b_1, \ldots, b_n$$$ and $$$g_1, \ldots, g_m$$$, determine this number.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static void main() throws Exception{ int n=sc.nextInt(),m=sc.nextInt(); PriorityQueue<Integer>pq=new PriorityQueue<>(Collections.reverseOrder()); for(int i=0;i<n;i++) { int min=sc.nextInt(); pq.add(min); } int maxOfMins=pq.peek(); long ans=0; int minOfMaxs=(int)1e9; for(int i=0;i<m;i++) { int max=sc.nextInt(); ans+=max; if(max<maxOfMins) { pw.println(-1); return; } minOfMaxs=Math.min(minOfMaxs, max); } if(minOfMaxs==maxOfMins) { pq.poll(); } else { ans+=pq.poll(); ans+=(pq.poll()*1l*(m-1)); } while(!pq.isEmpty()) { ans+=pq.poll()*1l*m; } pw.println(ans); } public static void main(String[] args) throws Exception{ pw=new PrintWriter(System.out); sc = new MScanner(System.in); int tc=1; while(tc-->0) main(); pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(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 int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } 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); } } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } }
Java
["3 2\n1 2 1\n3 4", "2 2\n0 1\n1 0", "2 3\n1 0\n1 1 2"]
1 second
["12", "-1", "4"]
NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "math", "implementation", "sortings", "binary search" ]
4b4c7e7d9d5c45c8635b403bae997891
The first line contains two integers $$$n$$$ and $$$m$$$, separated with space — the number of boys and girls, respectively ($$$2 \leq n, m \leq 100\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$, separated by spaces — $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \leq b_i \leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \ldots, g_m$$$, separated by spaces — $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \leq g_j \leq 10^8$$$).
1,500
If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.
standard output
PASSED
21d7076d65a7e3a51276dfd1cae6763a
train_001.jsonl
1557671700
$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \leq i \leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \leq j \leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \leq i \leq n$$$ and $$$1 \leq j \leq m$$$. You are given the numbers $$$b_1, \ldots, b_n$$$ and $$$g_1, \ldots, g_m$$$, determine this number.
256 megabytes
import java.util.*; import java.io.*; public class A559 { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); long [] b = new long[n]; long [] g = new long[m]; for (int i = 0; i < n; i++) b[i] = sc.nextLong(); for (int i = 0; i < m; i++) g[i] = sc.nextLong(); Arrays.sort(b); Arrays.sort(g); if (g[0] < b[n - 1]) { out.println(-1); } else { long base = 0; long max = 0; for (int i = 0; i < n; i++) { base = base + m * b[i]; max = Math.max(max, b[i]); } for (int i = 1; i < m; i++) base += (g[i] - max); if (max != g[0]) base += (g[0] - b[n - 2]); out.println(base); } out.close(); } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3 2\n1 2 1\n3 4", "2 2\n0 1\n1 0", "2 3\n1 0\n1 1 2"]
1 second
["12", "-1", "4"]
NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "math", "implementation", "sortings", "binary search" ]
4b4c7e7d9d5c45c8635b403bae997891
The first line contains two integers $$$n$$$ and $$$m$$$, separated with space — the number of boys and girls, respectively ($$$2 \leq n, m \leq 100\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$, separated by spaces — $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \leq b_i \leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \ldots, g_m$$$, separated by spaces — $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \leq g_j \leq 10^8$$$).
1,500
If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.
standard output
PASSED
c2ca68db90a354db145b4e01074660e2
train_001.jsonl
1557671700
$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \leq i \leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \leq j \leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \leq i \leq n$$$ and $$$1 \leq j \leq m$$$. You are given the numbers $$$b_1, \ldots, b_n$$$ and $$$g_1, \ldots, g_m$$$, determine this number.
256 megabytes
import java.io.*; import java.util.*; public class Main { static class PairComparator implements Comparator<Pair> { @Override public int compare(Pair x, Pair y) { if (x.val < y.val)return -1; if (x.val > y.val)return 1; if (x.val == y.val){ if (x.ind < y.ind)return -1; if (x.ind > y.ind)return 1; } return 0; } } static class Pair{ int ind, val; Pair(int i, int v){ ind=i; val=v; } } static int[] vis; static void func() throws Exception { int n = sc.nextInt(); int m = sc.nextInt(); int[] b= sc.intArr(n); int[] g= sc.intArr(m); int maxB = 0; int minG = Integer.MAX_VALUE; for (int i=0;i<n;i++){ maxB= Math.max(maxB, b[i]); } for (int i=0;i<m;i++){ minG= Math.min(minG, g[i]); } if (minG<maxB){ pw.println(-1); return; } Arrays.sort(b); long sum = 0; for (int i=0;i<n-2;i++){ sum+= (long)(b[i])*(long)m; } for (int i=0;i<m;i++){ sum+= (long)g[i]; } if (minG==maxB){ if (n-2>=0){ sum+=(long)b[n-2]*(long)m; } } else{ if (n-2>=0){ sum+=(long)b[n-2]*(long)(m-1); } sum+=b[n-1]; } pw.println(sum); } /* * */ static PrintWriter pw; static MScanner sc; public static void main(String[] args) throws Exception { pw = new PrintWriter(System.out); sc = new MScanner(System.in); int tests = 1; // tests =sc.nextInt(); //comment this line while (tests-- > 0){ func(); pw.flush(); } } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(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 int[] intArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public long[] longArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[] in = new Integer[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[] in = new Long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } 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); } } static void shuffle(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * (i+1)); int tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } static void shuffle(long[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * (i+1)); long tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } }
Java
["3 2\n1 2 1\n3 4", "2 2\n0 1\n1 0", "2 3\n1 0\n1 1 2"]
1 second
["12", "-1", "4"]
NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$.
Java 11
standard input
[ "greedy", "constructive algorithms", "two pointers", "math", "implementation", "sortings", "binary search" ]
4b4c7e7d9d5c45c8635b403bae997891
The first line contains two integers $$$n$$$ and $$$m$$$, separated with space — the number of boys and girls, respectively ($$$2 \leq n, m \leq 100\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$, separated by spaces — $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \leq b_i \leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \ldots, g_m$$$, separated by spaces — $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \leq g_j \leq 10^8$$$).
1,500
If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.
standard output
PASSED
c2b77c4ae5062f8424895001eebfdeb4
train_001.jsonl
1489851300
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.Arrays; import java.util.InputMismatchException; import java.util.*; import java.io.*; import java.math.*; public class Main5{ static class Pair { long x; int y; public Pair(long x, int y) { this.x = x; this.y = y; } } static class Compare { static void compare(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.x>p2.x) { return 1; } else if(p2.x>p1.x) { return -1; } else { if(p1.y>p2.y) { return 1; } else if(p1.y<p2.y) { return -1; } else return 0; } } }); } } public static long pow(long a, long b) { long result=1; while(b>0) { if (b % 2 != 0) { result=(result*a); b--; } a=(a*a); b /= 2; } return result; } public static long fact(long num) { long value=1; int i=0; for(i=2;i<num;i++) { value=((value%mod)*i%mod)%mod; } return value; } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } public static long lcm(int a,int b) { return a * (b / gcd(a, b)); } public static long sum(int h) { return (h*(h+1)/2); } public static void dfs(int parent,boolean[] visited) { ArrayList<Integer> arr=new ArrayList<Integer>(); arr=graph.get(parent); visited[parent]=true; // ts.add(parent); for(int i=0;i<arr.size();i++) { int num=arr.get(i); edges++; if(visited[num]==false) { dfs(num,visited); } } count++; } static long edges=0,count=0; static TreeSet<Integer> ts; static int f=0; static long mod=1000000007L; static ArrayList<ArrayList<Integer>> graph; static int[] color; public static void bfs(int num,boolean[] visited) { Queue<Integer> q=new LinkedList<>(); q.add(num); visited[num]=true; while(!q.isEmpty()) { int x=q.poll(); ArrayList<Integer> al=graph.get(x); for(int i=0;i<al.size();i++) { int y=al.get(i); if(visited[y]==false) { q.add(y); visited[y]=true; } } } } public static void main(String args[])throws IOException { // InputReader in=new InputReader(System.in); // OutputWriter out=new OutputWriter(System.out); // long a=pow(26,1000000005); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); ArrayList<Integer> ar=new ArrayList<>(); ArrayList<Integer> ar1=new ArrayList<>(); ArrayList<Integer> ar2=new ArrayList<>(); ArrayList<Integer> ar3=new ArrayList<>(); ArrayList<Integer> ar4=new ArrayList<>(); TreeSet<Integer> ts1=new TreeSet<>(); TreeSet<String> pre=new TreeSet<>(); HashMap<Long,Long> hash=new HashMap<>(); //HashMap<Long,Integer> hash1=new HashMap<Long,Integer>(); HashMap<Long,Integer> hash2=new HashMap<Long,Integer>(); /* boolean[] prime=new boolean[10001]; for(int i=2;i*i<=10000;i++) { if(prime[i]==false) { for(int j=2*i;j<=10000;j+=i) { prime[j]=true; } } }*/ int n=i(); int m=i(); int[] a=new int[m]; int[] b=new int[m]; graph=new ArrayList<>(); for(int i=0;i<n;i++) { graph.add(new ArrayList<>()); } for(int i=0;i<m;i++) { a[i]=i()-1; b[i]=i()-1; graph.get(a[i]).add(b[i]); graph.get(b[i]).add(a[i]); } boolean[] visited=new boolean[n]; edges=0; count=0; int flag=0; for(int i=0;i<n;i++) { if(visited[i]==false) { dfs(i,visited); long tmp=count*(count-1); if((edges-tmp)!=0) { flag=1; break; } edges=0; count=0; } } if(flag==1) { pln("NO"); } else pln("YES"); } /**/ static InputReader in=new InputReader(System.in); static OutputWriter out=new OutputWriter(System.out); public static long l() { String s=in.String(); return Long.parseLong(s); } public static void pln(String value) { System.out.println(value); } public static int i() { return in.Int(); } public static String s() { return in.String(); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars== -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int Int() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String String() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return String(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.Int(); return array; } }
Java
["4 3\n1 3\n3 4\n1 4", "4 4\n3 1\n2 3\n3 4\n1 2", "10 4\n4 3\n5 10\n8 9\n1 2", "3 2\n1 2\n2 3"]
1 second
["YES", "NO", "YES", "NO"]
NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
1173d89dd3af27b46e579cdeb2cfdfe5
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
1,500
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
standard output
PASSED
3341057e96f435642f1f1570b1296bbb
train_001.jsonl
1489851300
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.Arrays; import java.util.InputMismatchException; import java.util.*; import java.io.*; import java.math.*; public class Main5{ static class Pair { long x; int y; public Pair(long x, int y) { this.x = x; this.y = y; } } static class Compare { static void compare(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.x>p2.x) { return 1; } else if(p2.x>p1.x) { return -1; } else { if(p1.y>p2.y) { return 1; } else if(p1.y<p2.y) { return -1; } else return 0; } } }); } } public static long pow(long a, long b) { long result=1; while(b>0) { if (b % 2 != 0) { result=(result*a); b--; } a=(a*a); b /= 2; } return result; } public static long fact(long num) { long value=1; int i=0; for(i=2;i<num;i++) { value=((value%mod)*i%mod)%mod; } return value; } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } public static long lcm(int a,int b) { return a * (b / gcd(a, b)); } public static long sum(int h) { return (h*(h+1)/2); } public static void dfs(int parent,boolean[] visited) { ArrayList<Integer> arr=new ArrayList<Integer>(); arr=graph.get(parent); visited[parent]=true; ts.add(parent); for(int i=0;i<arr.size();i++) { int num=arr.get(i); edges++; if(visited[num]==false) { dfs(num,visited); } } count++; } static long edges=0,count=0; static TreeSet<Integer> ts; static int f=0; static long mod=1000000007L; static ArrayList<ArrayList<Integer>> graph; static int[] color; public static void bfs(int num,boolean[] visited) { Queue<Integer> q=new LinkedList<>(); q.add(num); visited[num]=true; while(!q.isEmpty()) { int x=q.poll(); ArrayList<Integer> al=graph.get(x); for(int i=0;i<al.size();i++) { int y=al.get(i); if(visited[y]==false) { q.add(y); visited[y]=true; } } } } public static void main(String args[])throws IOException { // InputReader in=new InputReader(System.in); // OutputWriter out=new OutputWriter(System.out); // long a=pow(26,1000000005); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); ArrayList<Integer> ar=new ArrayList<>(); ArrayList<Integer> ar1=new ArrayList<>(); ArrayList<Integer> ar2=new ArrayList<>(); ArrayList<Integer> ar3=new ArrayList<>(); ArrayList<Integer> ar4=new ArrayList<>(); TreeSet<Integer> ts1=new TreeSet<>(); TreeSet<String> pre=new TreeSet<>(); HashMap<Long,Long> hash=new HashMap<>(); //HashMap<Long,Integer> hash1=new HashMap<Long,Integer>(); HashMap<Long,Integer> hash2=new HashMap<Long,Integer>(); /* boolean[] prime=new boolean[10001]; for(int i=2;i*i<=10000;i++) { if(prime[i]==false) { for(int j=2*i;j<=10000;j+=i) { prime[j]=true; } } }*/ int n=i(); int m=i(); int[] a=new int[m]; int[] b=new int[m]; graph=new ArrayList<>(); for(int i=0;i<n;i++) { graph.add(new ArrayList<>()); } for(int i=0;i<m;i++) { a[i]=i()-1; b[i]=i()-1; graph.get(a[i]).add(b[i]); graph.get(b[i]).add(a[i]); } boolean[] visited=new boolean[n]; edges=0; count=0; int flag=0; for(int i=0;i<n;i++) { if(visited[i]==false) { ts=new TreeSet<Integer>(); dfs(i,visited); long tmp=(long)ts.size()*((long)ts.size()-1); if((edges-tmp)!=0) { flag=1; break; } edges=0; count=0; } } if(flag==1) { pln("NO"); } else pln("YES"); } /**/ static InputReader in=new InputReader(System.in); static OutputWriter out=new OutputWriter(System.out); public static long l() { String s=in.String(); return Long.parseLong(s); } public static void pln(String value) { System.out.println(value); } public static int i() { return in.Int(); } public static String s() { return in.String(); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars== -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int Int() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String String() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return String(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.Int(); return array; } }
Java
["4 3\n1 3\n3 4\n1 4", "4 4\n3 1\n2 3\n3 4\n1 2", "10 4\n4 3\n5 10\n8 9\n1 2", "3 2\n1 2\n2 3"]
1 second
["YES", "NO", "YES", "NO"]
NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
1173d89dd3af27b46e579cdeb2cfdfe5
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
1,500
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
standard output
PASSED
ed6f04d946c7b401236d2d3338b6c61c
train_001.jsonl
1489851300
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
256 megabytes
import java.io.*; import java.util.*; public class A771 { public static void main(String args[])throws IOException { Reader sc=new Reader(); int n=sc.nextInt(); int m=sc.nextInt(); HashMap<Integer,HashSet<Integer>> map=new HashMap<>(); int size[]=new int[n+1]; for(int i=1;i<=n;i++) { map.put(i,new HashSet<>()); } for(int i=1;i<=m;i++) { int x=sc.nextInt(); int y=sc.nextInt(); size[x]++;size[y]++; map.get(x).add(y); map.get(y).add(x); } boolean vis[]=new boolean[n+1];int f=0; for(int i=1;i<=n;i++) { if(!vis[i]) { Stack st=new Stack(); st.push(i); vis[i]=true; long edge=0,vert=0; while(st.size()!=0) { int a=(Integer)st.pop(); vert++; for(int j:map.get(a)) { edge++; if(!vis[j]) { st.push(j);vis[j]=true; } } } //System.out.println(edge+" "+vert); if(edge!=(1L*vert*(vert-1))) { f=1; break; } } } if(f==0) System.out.println("YES"); else System.out.println("NO"); } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte [] buffer; private int bufferPointer, bytesRead; public Reader () { din = new DataInputStream (System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader (String file_name) throws IOException { din = new DataInputStream (new FileInputStream (file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine () throws IOException { byte [] buf = new byte[1024]; int cnt = 0, c; while ((c = read ()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String (buf, 0, cnt); } public int nextInt () throws IOException { int ret = 0; byte c = read (); while (c <= ' ') c = read (); boolean neg = (c == '-'); if (neg) c = read (); do { ret = ret * 10 + c - '0'; } while ((c = read ()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong () throws IOException { long ret = 0; byte c = read (); while (c <= ' ') c = read (); boolean neg = (c == '-'); if (neg) c = read (); do { ret = ret * 10 + c - '0'; } while ((c = read ()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble () throws IOException { double ret = 0, div = 1; byte c = read (); while (c <= ' ') c = read (); boolean neg = (c == '-'); if (neg) c = read (); do { ret = ret * 10 + c - '0'; } while ((c = read ()) >= '0' && c <= '9'); if (c == '.') while ((c = read ()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer () throws IOException { bytesRead = din.read (buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read () throws IOException { if (bufferPointer == bytesRead) fillBuffer (); return buffer[bufferPointer++]; } public void close () throws IOException { if (din == null) return; din.close (); } }
Java
["4 3\n1 3\n3 4\n1 4", "4 4\n3 1\n2 3\n3 4\n1 2", "10 4\n4 3\n5 10\n8 9\n1 2", "3 2\n1 2\n2 3"]
1 second
["YES", "NO", "YES", "NO"]
NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
1173d89dd3af27b46e579cdeb2cfdfe5
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
1,500
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
standard output
PASSED
6e32c19b820f226d0524486b45f92e56
train_001.jsonl
1489851300
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { static class Graph { private int V;// No. of vertices private Long dfsVertices, dfsEdges; public Long getDfsEdges() { return dfsEdges; } public Long getDfsVertices() { return dfsVertices; } private ArrayList<Integer> adj[]; // Adjacency List //Constructor Graph(int v) { V = v; adj = new ArrayList[v]; for (int i=0; i<v; ++i) adj[i] = new ArrayList(); reSet(); } // Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); adj[w].add(v); } public void reSet() { dfsVertices = dfsEdges = 0L; } public void dfs(boolean[] visited, int u) { visited[u] = true; dfsVertices ++;///total vertices in the connected component dfsEdges += adj[u].size();//total edges in the connected component for(int i = 0; i<adj[u].size(); i++) { if(visited[adj[u].get(i)] == false) { dfs(visited,adj[u].get(i)); } } } } public static void main(String[] args) { MyScanner cin = new MyScanner(); PrintWriter cout = new PrintWriter(new BufferedOutputStream(System.out)); int v,e,x,y; v = cin.nextInt();e = cin.nextInt(); v++; Graph g = new Graph(v); for(int i= 0; i<e; i++) { x = cin.nextInt(); y = cin.nextInt(); g.addEdge(x,y); } boolean[] visited = new boolean[v]; for(int i = 0; i<v; i++) { if(visited[i] == false) { g.dfs(visited,i); } if(g.getDfsEdges() != (g.getDfsVertices()-1)*(g.getDfsVertices())) { cout.println("NO"); cout.close(); return ; } g.reSet(); } cout.println("YES"); cout.close(); } 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 3\n1 3\n3 4\n1 4", "4 4\n3 1\n2 3\n3 4\n1 2", "10 4\n4 3\n5 10\n8 9\n1 2", "3 2\n1 2\n2 3"]
1 second
["YES", "NO", "YES", "NO"]
NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
1173d89dd3af27b46e579cdeb2cfdfe5
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
1,500
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
standard output
PASSED
08f9f490144e692adc1844342e31f6a6
train_001.jsonl
1489851300
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
256 megabytes
import java.io.*; import java.util.*; public class A771 { static int n, m; static List<Integer>[] graph; static boolean[] visited; static List<List<Integer>> finallist; static List<Integer> list; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] ss = br.readLine().trim().split("\\s+"); n = Integer.parseInt(ss[0]); m = Integer.parseInt(ss[1]); graph = new ArrayList[n+1]; Arrays.setAll(graph, i -> new ArrayList<>()); for (int i=0; i<m; i++) { ss = br.readLine().split("\\s+"); int a = Integer.parseInt(ss[0]); int b = Integer.parseInt(ss[1]); graph[a].add(b); graph[b].add(a); } visited = new boolean[n+1]; list = new ArrayList<>(); finallist = new ArrayList<>(); for (int i=1; i<=n; i++) { if (!visited[i]) { dfs(i); finallist.add(list); list = new ArrayList<>(); } } boolean isClique = true; for (List<Integer> l : finallist) { long vertices = l.size(); long edges = 0; for (int i : l) { edges += graph[i].size(); } edges /= 2; //System.out.println(vertices + " " + edges); if (edges != (((long)vertices*((long)vertices-1)) / 2)) { isClique = !isClique; break; } } System.out.println(isClique ? "YES" : "NO"); } static void dfs(int i) { visited[i] = true; list.add(i); for (int v : graph[i]) { if (!visited[v]) { dfs(v); } } } }
Java
["4 3\n1 3\n3 4\n1 4", "4 4\n3 1\n2 3\n3 4\n1 2", "10 4\n4 3\n5 10\n8 9\n1 2", "3 2\n1 2\n2 3"]
1 second
["YES", "NO", "YES", "NO"]
NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
1173d89dd3af27b46e579cdeb2cfdfe5
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
1,500
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
standard output
PASSED
1677239788cc966b416690edcb478cf8
train_001.jsonl
1489851300
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class B { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); HashSet<Integer>[] graph = (HashSet<Integer>[]) new HashSet[n]; for(int i=0;i<n;i++) graph[i] = new HashSet<>(); long ar[] = new long[n]; for(int i=0;i<n;i++) ar[i] += i; for(int i=0;i<m;i++){ int a = ni() - 1, b = ni() - 1; graph[a].add(b); graph[b].add(a); ar[a] += b; ar[b] += a; } out.println(fun(n, m, graph, ar) ? "YES" : "NO"); } static boolean fun(int n, int m, HashSet<Integer>[] graph, long ar[]){ boolean visited[] = new boolean[n]; for(int i=0;i<n;i++){ if(!visited[i]){ int deg = graph[i].size(); visited[i] = true; if(deg==0) continue; for(int v: graph[i]){ if(graph[v].size() != deg) return false; if(visited[v]) return false; if(ar[i]!=ar[v]) return false; visited[v] = true; } } } return true; } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new B().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["4 3\n1 3\n3 4\n1 4", "4 4\n3 1\n2 3\n3 4\n1 2", "10 4\n4 3\n5 10\n8 9\n1 2", "3 2\n1 2\n2 3"]
1 second
["YES", "NO", "YES", "NO"]
NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
1173d89dd3af27b46e579cdeb2cfdfe5
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
1,500
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
standard output
PASSED
a37a7141095e54564ad2ecec6a853212
train_001.jsonl
1489851300
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
256 megabytes
/* HARSH KHATRI DA-IICT */ import java.io.*; import java.util.*; import java.lang.*; import java.util.Scanner; import java.util.Arrays; import java.util.List; import java.util.ArrayList; public class CF771A { static FasterScanner in = new FasterScanner(); static int n = in.nextInt(), m = in.nextInt(); static ArrayList<ArrayList<Integer>> makeUndir(int v, int e) { ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); for(int i =0; i<v; i++) { adj.add(new ArrayList<Integer>()); } int x, y; for(int i=0; i<e; i++) { x = in.nextInt(); y = in.nextInt(); (adj.get(x-1)).add(y-1); (adj.get(y-1)).add(x-1); } return adj; } static long Choose(int n, int r) { long ans = 1; int i, j; for(i=1; i<=r; i++) { ans = (ans*(n-i+1)); ans /= i; } return ans; } static boolean[] vis; static ArrayList<ArrayList<Integer>> adj = makeUndir(n, m); static int dfs(int i) { int nodes = 0; if(!vis[i]) { nodes++; vis[i] = true; for(int x : adj.get(i)) { nodes += dfs(x); } } return nodes; } public static void main(String[] args) { long sum = 0; int k; vis = new boolean[n]; for(int i=0; i<n; i++) { if(!vis[i]) { k = dfs(i); sum += Choose(k, 2); } } System.out.println( (m==sum) ? "YES" : "NO" ); } } class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public double nextDouble() { return Double.parseDouble(this.nextString()); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
Java
["4 3\n1 3\n3 4\n1 4", "4 4\n3 1\n2 3\n3 4\n1 2", "10 4\n4 3\n5 10\n8 9\n1 2", "3 2\n1 2\n2 3"]
1 second
["YES", "NO", "YES", "NO"]
NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
1173d89dd3af27b46e579cdeb2cfdfe5
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
1,500
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
standard output
PASSED
eea835f0aa1addfff542ef0d86edb0ac
train_001.jsonl
1489851300
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
256 megabytes
import java.util.*; import java.io.*; public class Test { public static long numberOfVertices=0,numberOfEdges=0; public static boolean[] visited; public static LinkedList<Integer>[] adj; public static void main(String[] args) { boolean possible=true; int x,y; FastReader scan=new FastReader(); PrintWriter out = new PrintWriter(System.out); int n=scan.nextInt(); visited=new boolean[n]; adj=new LinkedList[n]; for (int i = 0; i <n ; i++) { adj[i]=new LinkedList(); } int m=scan.nextInt(); while (m-->0){ int a=scan.nextInt()-1; int b=scan.nextInt()-1; adj[a].add(b); adj[b].add(a); } for(x=0;x<n;x++){ numberOfVertices=0; numberOfEdges=0; if(!visited[x]) { BFS(x); if (1L*numberOfVertices * (numberOfVertices - 1) != numberOfEdges) { possible = false; break; } } } out.println(possible?"YES":"NO"); out.close(); } static void BFS(int s) { LinkedList<Integer> queue = new LinkedList<Integer>(); visited[s] = true; queue.add(s); numberOfVertices++; numberOfEdges+=adj[s].size(); while (queue.size() != 0) { s = queue.poll(); Iterator<Integer> i = adj[s].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { numberOfVertices++; numberOfEdges+=adj[n].size(); visited[n] = true; queue.add(n); } } } } 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; } } }
Java
["4 3\n1 3\n3 4\n1 4", "4 4\n3 1\n2 3\n3 4\n1 2", "10 4\n4 3\n5 10\n8 9\n1 2", "3 2\n1 2\n2 3"]
1 second
["YES", "NO", "YES", "NO"]
NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
1173d89dd3af27b46e579cdeb2cfdfe5
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
1,500
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
standard output
PASSED
36cd34eee05cac09a576e3b487ff3e46
train_001.jsonl
1489851300
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.*; import java.util.*; public class Main { static int N = 150005; static int[] f = new int[N]; static int[] s = new int[N]; static int[] e = new int[N]; private static int getf(int x) { return f[x] == x ? x : (f[x] = getf(f[x])); } public static void main(String[] args) { MyScanner in = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = in.nextInt() , m = in.nextInt(); for (int i = 0 ; i < n ; ++ i) { f[i] = i; s[i] = 1; e[i] = 0; } for (int i = 0 ; i < m ; ++ i) { int x = in.nextInt() - 1, y = in.nextInt() - 1; if (getf(x) != getf(y)) { s[getf(y)] += s[getf(x)]; e[getf(y)] += e[getf(x)]; f[getf(x)] = getf(y); } ++ e[getf(x)]; } for (int i = 0 ; i < n ; ++ i) { if (getf(i) == i && e[i] != (long)s[i] * (s[i] - 1) / 2) { System.out.println("NO"); return; } } System.out.println("YES"); } 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 3\n1 3\n3 4\n1 4", "4 4\n3 1\n2 3\n3 4\n1 2", "10 4\n4 3\n5 10\n8 9\n1 2", "3 2\n1 2\n2 3"]
1 second
["YES", "NO", "YES", "NO"]
NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
Java 8
standard input
[ "dsu", "dfs and similar", "graphs" ]
1173d89dd3af27b46e579cdeb2cfdfe5
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
1,500
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
standard output
PASSED
4139f32d3293b67fa1b7389da9f6804b
train_001.jsonl
1305299400
On an IT lesson Valera studied data compression. The teacher told about a new method, which we shall now describe to you.Let {a1, a2, ..., an} be the given sequence of lines needed to be compressed. Here and below we shall assume that all lines are of the same length and consist only of the digits 0 and 1. Let's define the compression function: f(empty sequence) = empty string f(s) = s. f(s1, s2) =  the smallest in length string, which has one of the prefixes equal to s1 and one of the suffixes equal to s2. For example, f(001, 011) = 0011, f(111, 011) = 111011. f(a1, a2, ..., an) = f(f(a1, a2, an - 1), an). For example, f(000, 000, 111) = f(f(000, 000), 111) = f(000, 111) = 000111. Valera faces a real challenge: he should divide the given sequence {a1, a2, ..., an} into two subsequences {b1, b2, ..., bk} and {c1, c2, ..., cm}, m + k = n, so that the value of S = |f(b1, b2, ..., bk)| + |f(c1, c2, ..., cm)| took the minimum possible value. Here |p| denotes the length of the string p.Note that it is not allowed to change the relative order of lines in the subsequences. It is allowed to make one of the subsequences empty. Each string from the initial sequence should belong to exactly one subsequence. Elements of subsequences b and c don't have to be consecutive in the original sequence a, i. e. elements of b and c can alternate in a (see samples 2 and 3).Help Valera to find the minimum possible value of S.
256 megabytes
import java.util.NavigableSet; import java.util.Map; import java.util.Collections; import java.util.HashMap; import java.util.InputMismatchException; import java.math.BigInteger; import java.util.*; import java.util.Collection; import java.util.ArrayList; import java.util.List; import java.util.Comparator; import java.io.*; import java.util.Iterator; import java.util.Arrays; import java.util.NoSuchElementException; /** * Generated by Contest helper plug-in * Actual solution is at the bottom */ public class Main { public static void main(String[] args) { InputReader in = new StreamInputReader(System.in); PrintWriter out = new PrintWriter(System.out); run(in, out); } public static void run(InputReader in, PrintWriter out) { Solver solver = new TaskE(); solver.solve(1, in, out); Exit.exit(in, out); } } abstract class InputReader { private boolean finished = false; public abstract int read(); public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); 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; } public void setFinished(boolean finished) { this.finished = finished; } public abstract void close(); } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public StreamInputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public void close() { try { stream.close(); } catch (IOException ignored) { } } } interface Solver { public void solve(int testNumber, InputReader in, PrintWriter out); } class Exit { private Exit() { } public static void exit(InputReader in, PrintWriter out) { in.setFinished(true); in.close(); out.close(); } } class CollectionUtils { public static<T extends Comparable<T>> T minElement(Iterable<T> collection) { T result = null; for (T element : collection) { if (result == null || result.compareTo(element) > 0) result = element; } return result; } } abstract class ReadOnlyIterator<T> implements Iterator<T> { public final void remove() { throw new UnsupportedOperationException(); } } class ArrayUtils { public static void fill(int[][] array, int value) { for (int[] row : array) Arrays.fill(row, value); } } class IOUtils { public static<T> void printCollection(Iterable<T> collection, PrintWriter out, String delimiter) { boolean isFirst = true; for (T element : collection) { if (isFirst) isFirst = false; else out.print(delimiter); out.print(element); } out.println(); } } abstract class AbstractSequence<T> implements Sequence<T> { public Iterator<T> iterator() { return new ReadOnlyIterator<T>() { private int index = 0; public boolean hasNext() { return index != size(); } public T next() { if (!hasNext()) throw new NoSuchElementException(); return get(index++); } }; } public String toString() { StringWriter writer = new StringWriter(); IOUtils.printCollection(this, new PrintWriter(writer), ","); return "[" + writer.toString().substring(0, writer.toString().length() - 1) + "]"; } } abstract class AbstractWritableSequence<T> extends AbstractSequence<T> implements WritableSequence<T> { } abstract class ArrayWrapper<T> extends AbstractWritableSequence<T> { public static WritableSequence<Integer> wrap(int...array) { return new IntArrayWrapper(array); } protected static class IntArrayWrapper extends ArrayWrapper<Integer> { protected final int[] array; protected IntArrayWrapper(int[] array) { this.array = array; } public int size() { return array.length; } public Integer get(int index) { return array[index]; } } } interface Sequence<T> extends Iterable<T> { public int size(); public T get(int index); } interface WritableSequence<T> extends Sequence<T> { } class TaskE implements Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int count = in.readInt(); int length = 0; int[] values = new int[count]; for (int i = 0; i < count; i++) { String string = in.readString(); length = string.length(); values[i] = Integer.parseInt(string, 2); } int[][] delta = new int[length + 1][]; for (int i = 0; i <= length; i++) delta[i] = new int[1 << i]; ArrayUtils.fill(delta, length); int totalLength = length; for (int i = 1; i < count; i++) { int bestShift = 0; int last = values[i - 1]; int current = values[i]; for (int k = 1; k <= length; k++) { if ((last & ((1 << k) - 1)) == (current >> (length - k))) bestShift = k; } totalLength += length - bestShift; int bestValue = length; for (int k = 0; k <= length; k++) { int prefix = (current >> (length - k)); bestValue = Math.min(bestValue, delta[k][prefix] - k); } bestValue += bestShift; for (int k = 0; k <= length; k++) { int suffix = (last & ((1 << k) - 1)); delta[k][suffix] = Math.min(delta[k][suffix], bestValue); } } totalLength += Math.min(0, CollectionUtils.minElement(ArrayWrapper.wrap(delta[length]))); out.println(totalLength); } }
Java
["3\n01\n10\n01", "4\n000\n111\n110\n001", "5\n10101\n01010\n11111\n01000\n10010"]
2 seconds
["4", "8", "17"]
NoteDetailed answers to the tests: The best option is to make one of the subsequences empty, and the second one equal to the whole given sequence. |f(01, 10, 01)| = |f(f(01, 10), 01)| = |f(010, 01)| = |0101| = 4. The best option is: b = {000, 001}, c = {111, 110}. S = |f(000, 001)| + |f(111, 110)| = |0001| + |1110| = 8. The best option is: b = {10101, 01010, 01000}, c = {11111, 10010}. S = |10101000| + |111110010| = 17.
Java 8
standard input
[ "dp", "bitmasks" ]
d65ca3fb4853031304cb829c3cda3462
The first line of input data contains an integer n — the number of strings (1 ≤ n ≤ 2·105). Then on n lines follow elements of the sequence — strings whose lengths are from 1 to 20 characters, consisting only of digits 0 and 1. The i + 1-th input line contains the i-th element of the sequence. Elements of the sequence are separated only by a newline. It is guaranteed that all lines have the same length.
2,800
Print a single number — the minimum possible value of S.
standard output
PASSED
31b2b2ddb834b8141c95a1c0d7667800
train_001.jsonl
1305299400
On an IT lesson Valera studied data compression. The teacher told about a new method, which we shall now describe to you.Let {a1, a2, ..., an} be the given sequence of lines needed to be compressed. Here and below we shall assume that all lines are of the same length and consist only of the digits 0 and 1. Let's define the compression function: f(empty sequence) = empty string f(s) = s. f(s1, s2) =  the smallest in length string, which has one of the prefixes equal to s1 and one of the suffixes equal to s2. For example, f(001, 011) = 0011, f(111, 011) = 111011. f(a1, a2, ..., an) = f(f(a1, a2, an - 1), an). For example, f(000, 000, 111) = f(f(000, 000), 111) = f(000, 111) = 000111. Valera faces a real challenge: he should divide the given sequence {a1, a2, ..., an} into two subsequences {b1, b2, ..., bk} and {c1, c2, ..., cm}, m + k = n, so that the value of S = |f(b1, b2, ..., bk)| + |f(c1, c2, ..., cm)| took the minimum possible value. Here |p| denotes the length of the string p.Note that it is not allowed to change the relative order of lines in the subsequences. It is allowed to make one of the subsequences empty. Each string from the initial sequence should belong to exactly one subsequence. Elements of subsequences b and c don't have to be consecutive in the original sequence a, i. e. elements of b and c can alternate in a (see samples 2 and 3).Help Valera to find the minimum possible value of S.
256 megabytes
import java.util.*; import static java.lang.Math.*; public class E { public static void main(String[] args){ Scanner in = new Scanner(System.in); N = in.nextInt(); int[] V = new int[N]; K = -1; for(int i = 0; i < N;i++){ String s = in.next(); K = s.length(); V[i] = Integer.valueOf(s, 2); } cost = new int[K+1][]; set = new int[K+1][]; for(int len = 0; len <= K;len++){ cost[len] = new int[1<<len]; set[len] = new int[1<<len]; Arrays.fill(set[len], -1); } adjcost = new int[N]; adjcost[0] = 0; for(int i = 1; i < N;i++){ int c = K; for(int len = 1; len <= K;len++) if(prefix(V[i-1], len) == suffix(V[i], len)) c = K-len; adjcost[i] = adjcost[i-1] + c; } // for(int len = 0; len <= K;len++){ // cost[len][prefix(V[0], len)] = K; // set[len][prefix(V[0], len)] = 0; // } cost[0][0] = K; set[0][0] = 0; // int ans = Integer.MAX_VALUE; for(int at = 1; at < N;at++){ int best = Integer.MAX_VALUE; for(int len = 0; len <= K; len++){ int suffix = suffix(V[at], len); if(set[len][suffix] == -1) continue; int score = getcost(len, suffix, at) + (K-len); best = min(best, score); } // System.out.println(at+" "+best); for(int len = 0; len <= K; len++){ int prefix = prefix(V[at-1], len); if(set[len][prefix] == -1 || best < getcost(len, prefix, at+1)){ // System.out.println("\tSET: "+len+" "+Integer.toBinaryString(prefix)+" "+best); set[len][prefix] = at; cost[len][prefix] = best; } } // System.out.println(); // if(at == N-1) // ans = best; } int ans = Integer.MAX_VALUE; for(int len = 0; len <= K; len++){ for(int value = 0; value < 1<<len; value++){ if(set[len][value] != -1) ans = min(ans, getcost(len, value, N)); } } System.out.println(ans); } private static int getcost(int len, int suffix, int at) { return cost[len][suffix] + adjcost[at-1]-adjcost[set[len][suffix]]; } static int[] adjcost; static int[][] cost, set; static int N, K; static int suffix(int v, int len){ return v >> (K-len); } static int prefix(int v, int len){ return v & ((1<<len)-1); } }
Java
["3\n01\n10\n01", "4\n000\n111\n110\n001", "5\n10101\n01010\n11111\n01000\n10010"]
2 seconds
["4", "8", "17"]
NoteDetailed answers to the tests: The best option is to make one of the subsequences empty, and the second one equal to the whole given sequence. |f(01, 10, 01)| = |f(f(01, 10), 01)| = |f(010, 01)| = |0101| = 4. The best option is: b = {000, 001}, c = {111, 110}. S = |f(000, 001)| + |f(111, 110)| = |0001| + |1110| = 8. The best option is: b = {10101, 01010, 01000}, c = {11111, 10010}. S = |10101000| + |111110010| = 17.
Java 6
standard input
[ "dp", "bitmasks" ]
d65ca3fb4853031304cb829c3cda3462
The first line of input data contains an integer n — the number of strings (1 ≤ n ≤ 2·105). Then on n lines follow elements of the sequence — strings whose lengths are from 1 to 20 characters, consisting only of digits 0 and 1. The i + 1-th input line contains the i-th element of the sequence. Elements of the sequence are separated only by a newline. It is guaranteed that all lines have the same length.
2,800
Print a single number — the minimum possible value of S.
standard output
PASSED
569114371381cac7e541a1e2dc7cd90b
train_001.jsonl
1305299400
On an IT lesson Valera studied data compression. The teacher told about a new method, which we shall now describe to you.Let {a1, a2, ..., an} be the given sequence of lines needed to be compressed. Here and below we shall assume that all lines are of the same length and consist only of the digits 0 and 1. Let's define the compression function: f(empty sequence) = empty string f(s) = s. f(s1, s2) =  the smallest in length string, which has one of the prefixes equal to s1 and one of the suffixes equal to s2. For example, f(001, 011) = 0011, f(111, 011) = 111011. f(a1, a2, ..., an) = f(f(a1, a2, an - 1), an). For example, f(000, 000, 111) = f(f(000, 000), 111) = f(000, 111) = 000111. Valera faces a real challenge: he should divide the given sequence {a1, a2, ..., an} into two subsequences {b1, b2, ..., bk} and {c1, c2, ..., cm}, m + k = n, so that the value of S = |f(b1, b2, ..., bk)| + |f(c1, c2, ..., cm)| took the minimum possible value. Here |p| denotes the length of the string p.Note that it is not allowed to change the relative order of lines in the subsequences. It is allowed to make one of the subsequences empty. Each string from the initial sequence should belong to exactly one subsequence. Elements of subsequences b and c don't have to be consecutive in the original sequence a, i. e. elements of b and c can alternate in a (see samples 2 and 3).Help Valera to find the minimum possible value of S.
256 megabytes
import java.util.NavigableSet; import java.util.Map; import java.util.Collections; import java.util.HashMap; import java.util.InputMismatchException; import java.math.BigInteger; import java.util.*; import java.util.Collection; import java.util.ArrayList; import java.util.List; import java.util.Comparator; import java.io.*; import java.util.Iterator; import java.util.Arrays; import java.util.NoSuchElementException; /** * Generated by Contest helper plug-in * Actual solution is at the bottom */ public class Main { public static void main(String[] args) { InputReader in = new StreamInputReader(System.in); PrintWriter out = new PrintWriter(System.out); run(in, out); } public static void run(InputReader in, PrintWriter out) { Solver solver = new TaskE(); solver.solve(1, in, out); Exit.exit(in, out); } } abstract class InputReader { private boolean finished = false; public abstract int read(); public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); 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; } public void setFinished(boolean finished) { this.finished = finished; } public abstract void close(); } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public StreamInputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public void close() { try { stream.close(); } catch (IOException ignored) { } } } interface Solver { public void solve(int testNumber, InputReader in, PrintWriter out); } class Exit { private Exit() { } public static void exit(InputReader in, PrintWriter out) { in.setFinished(true); in.close(); out.close(); } } class CollectionUtils { public static<T extends Comparable<T>> T minElement(Iterable<T> collection) { T result = null; for (T element : collection) { if (result == null || result.compareTo(element) > 0) result = element; } return result; } } abstract class ReadOnlyIterator<T> implements Iterator<T> { public final void remove() { throw new UnsupportedOperationException(); } } class ArrayUtils { public static void fill(int[][] array, int value) { for (int[] row : array) Arrays.fill(row, value); } } class IOUtils { public static<T> void printCollection(Iterable<T> collection, PrintWriter out, String delimiter) { boolean isFirst = true; for (T element : collection) { if (isFirst) isFirst = false; else out.print(delimiter); out.print(element); } out.println(); } } abstract class AbstractSequence<T> implements Sequence<T> { public Iterator<T> iterator() { return new ReadOnlyIterator<T>() { private int index = 0; public boolean hasNext() { return index != size(); } public T next() { if (!hasNext()) throw new NoSuchElementException(); return get(index++); } }; } public String toString() { StringWriter writer = new StringWriter(); IOUtils.printCollection(this, new PrintWriter(writer), ","); return "[" + writer.toString().substring(0, writer.toString().length() - 1) + "]"; } } abstract class AbstractWritableSequence<T> extends AbstractSequence<T> implements WritableSequence<T> { } abstract class ArrayWrapper<T> extends AbstractWritableSequence<T> { public static WritableSequence<Integer> wrap(int...array) { return new IntArrayWrapper(array); } protected static class IntArrayWrapper extends ArrayWrapper<Integer> { protected final int[] array; protected IntArrayWrapper(int[] array) { this.array = array; } public int size() { return array.length; } public Integer get(int index) { return array[index]; } } } interface Sequence<T> extends Iterable<T> { public int size(); public T get(int index); } interface WritableSequence<T> extends Sequence<T> { } class TaskE implements Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int count = in.readInt(); int length = 0; int[] values = new int[count]; for (int i = 0; i < count; i++) { String string = in.readString(); length = string.length(); values[i] = Integer.parseInt(string, 2); } int[][] delta = new int[length + 1][]; for (int i = 0; i <= length; i++) delta[i] = new int[1 << i]; ArrayUtils.fill(delta, length); int totalLength = length; for (int i = 1; i < count; i++) { int bestShift = 0; int last = values[i - 1]; int current = values[i]; for (int k = 1; k <= length; k++) { if ((last & ((1 << k) - 1)) == (current >> (length - k))) bestShift = k; } totalLength += length - bestShift; int bestValue = length; for (int k = 0; k <= length; k++) { int prefix = (current >> (length - k)); bestValue = Math.min(bestValue, delta[k][prefix] - k); } bestValue += bestShift; for (int k = 0; k <= length; k++) { int suffix = (last & ((1 << k) - 1)); delta[k][suffix] = Math.min(delta[k][suffix], bestValue); } } totalLength += Math.min(0, CollectionUtils.minElement(ArrayWrapper.wrap(delta[length]))); out.println(totalLength); } }
Java
["3\n01\n10\n01", "4\n000\n111\n110\n001", "5\n10101\n01010\n11111\n01000\n10010"]
2 seconds
["4", "8", "17"]
NoteDetailed answers to the tests: The best option is to make one of the subsequences empty, and the second one equal to the whole given sequence. |f(01, 10, 01)| = |f(f(01, 10), 01)| = |f(010, 01)| = |0101| = 4. The best option is: b = {000, 001}, c = {111, 110}. S = |f(000, 001)| + |f(111, 110)| = |0001| + |1110| = 8. The best option is: b = {10101, 01010, 01000}, c = {11111, 10010}. S = |10101000| + |111110010| = 17.
Java 6
standard input
[ "dp", "bitmasks" ]
d65ca3fb4853031304cb829c3cda3462
The first line of input data contains an integer n — the number of strings (1 ≤ n ≤ 2·105). Then on n lines follow elements of the sequence — strings whose lengths are from 1 to 20 characters, consisting only of digits 0 and 1. The i + 1-th input line contains the i-th element of the sequence. Elements of the sequence are separated only by a newline. It is guaranteed that all lines have the same length.
2,800
Print a single number — the minimum possible value of S.
standard output
PASSED
906eaa3fafeb63fb27045e3c2bf80206
train_001.jsonl
1305299400
On an IT lesson Valera studied data compression. The teacher told about a new method, which we shall now describe to you.Let {a1, a2, ..., an} be the given sequence of lines needed to be compressed. Here and below we shall assume that all lines are of the same length and consist only of the digits 0 and 1. Let's define the compression function: f(empty sequence) = empty string f(s) = s. f(s1, s2) =  the smallest in length string, which has one of the prefixes equal to s1 and one of the suffixes equal to s2. For example, f(001, 011) = 0011, f(111, 011) = 111011. f(a1, a2, ..., an) = f(f(a1, a2, an - 1), an). For example, f(000, 000, 111) = f(f(000, 000), 111) = f(000, 111) = 000111. Valera faces a real challenge: he should divide the given sequence {a1, a2, ..., an} into two subsequences {b1, b2, ..., bk} and {c1, c2, ..., cm}, m + k = n, so that the value of S = |f(b1, b2, ..., bk)| + |f(c1, c2, ..., cm)| took the minimum possible value. Here |p| denotes the length of the string p.Note that it is not allowed to change the relative order of lines in the subsequences. It is allowed to make one of the subsequences empty. Each string from the initial sequence should belong to exactly one subsequence. Elements of subsequences b and c don't have to be consecutive in the original sequence a, i. e. elements of b and c can alternate in a (see samples 2 and 3).Help Valera to find the minimum possible value of S.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.text.*; import java.util.Random; public class Main { static int res; static int n,prefix[][],suffix[][]; static int f[][],a[],L,sum[]; public static void put(int id,int best) { if (id>=0)res = Math.min(res, best+sum[n-1]); if (-1 == id) { f[0][L]=best; return; } for (int i = 0;i < L+1;++i) f[suffix[id][i]][i] = Math.min(f[suffix[id][i]][i],best); } public static int distance(int a,int b) { if (-1 == a || b >= n) return L; for (int i = 0;i < L;++i) if (suffix[a][i] == prefix[b][i]) return i; return L; } public static void main(String[] args) { Scanner cin=new Scanner(System.in); n = cin.nextInt(); a = new int[n+10]; String buf; for (int i = 0;i < n;++i) { buf = cin.next(); L = buf.length(); a[i] = 0; for (int j = 0;j < L;++j) a[i] = a[i] * 2 + (buf.charAt(j) - '0'); } if (n == 1) { System.out.println(L); return; } prefix = new int[n+10][L+1]; suffix = new int[n+10][L+1]; sum = new int[n+10]; f = new int[1<<L][L+1]; int dp[] = new int[n+10]; for (int i = 0;i < n;++i) { for (int j = 0;j < L+1;++j) { suffix[i][j] = a[i] & ((1 << (L-j))-1); prefix[i][j] = a[i] >> j; } } for (int i = 0;i < (1<<L);++i) for (int j = 0;j < L+1;++j) f[i][j] = 0x7f7f7f7f; sum[0] = 0; // System.out.println("ll"); for (int i = 1;i < n;++i) { sum[i] = distance(i-1,i); if (i > 0) sum[i] += sum[i-1]; // System.out.println(sum[i]); } sum[n] = sum[n-1]; res = 0x7f7f7f7f; put(-1,0); for (int i = 0;i < n;++i) { int step = 0x7f7f7f7f; for (int j = 0;j < L+1;++j) step = Math.min(step, f[prefix[i][j]][j] + j + sum[Math.max(0,i-1)]); put(i-1,step-sum[i]); // System.out.println(step); if (i == n-1) res = Math.min(res,step); } System.out.println(res); } }
Java
["3\n01\n10\n01", "4\n000\n111\n110\n001", "5\n10101\n01010\n11111\n01000\n10010"]
2 seconds
["4", "8", "17"]
NoteDetailed answers to the tests: The best option is to make one of the subsequences empty, and the second one equal to the whole given sequence. |f(01, 10, 01)| = |f(f(01, 10), 01)| = |f(010, 01)| = |0101| = 4. The best option is: b = {000, 001}, c = {111, 110}. S = |f(000, 001)| + |f(111, 110)| = |0001| + |1110| = 8. The best option is: b = {10101, 01010, 01000}, c = {11111, 10010}. S = |10101000| + |111110010| = 17.
Java 6
standard input
[ "dp", "bitmasks" ]
d65ca3fb4853031304cb829c3cda3462
The first line of input data contains an integer n — the number of strings (1 ≤ n ≤ 2·105). Then on n lines follow elements of the sequence — strings whose lengths are from 1 to 20 characters, consisting only of digits 0 and 1. The i + 1-th input line contains the i-th element of the sequence. Elements of the sequence are separated only by a newline. It is guaranteed that all lines have the same length.
2,800
Print a single number — the minimum possible value of S.
standard output
PASSED
265d9f0e5cd3b57adb70d49eff037c90
train_001.jsonl
1305299400
On an IT lesson Valera studied data compression. The teacher told about a new method, which we shall now describe to you.Let {a1, a2, ..., an} be the given sequence of lines needed to be compressed. Here and below we shall assume that all lines are of the same length and consist only of the digits 0 and 1. Let's define the compression function: f(empty sequence) = empty string f(s) = s. f(s1, s2) =  the smallest in length string, which has one of the prefixes equal to s1 and one of the suffixes equal to s2. For example, f(001, 011) = 0011, f(111, 011) = 111011. f(a1, a2, ..., an) = f(f(a1, a2, an - 1), an). For example, f(000, 000, 111) = f(f(000, 000), 111) = f(000, 111) = 000111. Valera faces a real challenge: he should divide the given sequence {a1, a2, ..., an} into two subsequences {b1, b2, ..., bk} and {c1, c2, ..., cm}, m + k = n, so that the value of S = |f(b1, b2, ..., bk)| + |f(c1, c2, ..., cm)| took the minimum possible value. Here |p| denotes the length of the string p.Note that it is not allowed to change the relative order of lines in the subsequences. It is allowed to make one of the subsequences empty. Each string from the initial sequence should belong to exactly one subsequence. Elements of subsequences b and c don't have to be consecutive in the original sequence a, i. e. elements of b and c can alternate in a (see samples 2 and 3).Help Valera to find the minimum possible value of S.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class E implements Runnable { final int INF = 1 << 30; int m; int[] a; private void solve() throws Exception { int n = in.nextInt(); int[] s = new int[n+1]; a = new int[n+1]; s[0] = 0; for (int i = 1; i <= n; ++i) { String ss = in.next(); m = ss.length(); int x = 0; for (int j = 0; j < m; ++j) x = (x << 1) + (int)(ss.charAt(j) - '0'); a[i] = x; s[i] = s[i-1] + merge(i-1, i); } int[] f = new int[n+1]; int[][] b = new int[m+1][1 << m]; for (int i = 0; i < b.length; ++i) Arrays.fill(b[i], INF); int ans = s[n]; for (int i = 1; i < n; ++i) { f[i] = s[i] + m; for (int j = 0; j <= m; ++j) { int tmp = b[j][ a[i+1] >> (m-j) ] + m - j + s[i]; if (tmp < f[i]) f[i] = tmp; } int now = s[n] - s[i+1] + f[i]; if (now < ans) ans = now; now = f[i] - s[i+1]; for (int j = 0; j <= m; ++j) { if (now < b[j][ a[i] & ((1<<j)-1) ]) b[j][ a[i] & ((1<<j)-1) ] = now; } } out.println(ans); } public int merge(int p, int q) { if (p == 0) return m; for (int i = m; i >= 0; --i) if ((a[p] & ((1<<i)-1)) == (a[q] >> (m-i))) return m - i; return 0; } public static void main(String args[]) { new E().run(); } InputReader in; PrintWriter out; public void run() { try { in = new InputReader(System.in); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream in) throws IOException { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } void close() throws IOException { reader.close(); } String next() throws IOException { while (null == tokenizer || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
Java
["3\n01\n10\n01", "4\n000\n111\n110\n001", "5\n10101\n01010\n11111\n01000\n10010"]
2 seconds
["4", "8", "17"]
NoteDetailed answers to the tests: The best option is to make one of the subsequences empty, and the second one equal to the whole given sequence. |f(01, 10, 01)| = |f(f(01, 10), 01)| = |f(010, 01)| = |0101| = 4. The best option is: b = {000, 001}, c = {111, 110}. S = |f(000, 001)| + |f(111, 110)| = |0001| + |1110| = 8. The best option is: b = {10101, 01010, 01000}, c = {11111, 10010}. S = |10101000| + |111110010| = 17.
Java 6
standard input
[ "dp", "bitmasks" ]
d65ca3fb4853031304cb829c3cda3462
The first line of input data contains an integer n — the number of strings (1 ≤ n ≤ 2·105). Then on n lines follow elements of the sequence — strings whose lengths are from 1 to 20 characters, consisting only of digits 0 and 1. The i + 1-th input line contains the i-th element of the sequence. Elements of the sequence are separated only by a newline. It is guaranteed that all lines have the same length.
2,800
Print a single number — the minimum possible value of S.
standard output
PASSED
282a49bed26b3614fac8489c11615e7c
train_001.jsonl
1439483400
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static void main(String[] args) { //int a[] = new int[1000000000]; Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int cit[] = new int[n]; int v[][] = new int[m][n]; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ //System.out.println(i + " " + j); v[i][j] = in.nextInt(); } } for(int i = 0; i <m; i++){ int max = 0; int ind = -1; for(int j = 0; j < n; j++){ int a = v[i][j]; if(a > max){ max = a; ind = j; } } if(ind == -1){ ind = 0; } cit[ind]++; } int max = 0; int ind = -1; for(int j = 0; j < n; j++){ int a = cit[j]; if(a > max){ max = a; ind = j; } } if(ind == -1){ ind = 0; } System.out.println(ind+1); } } // 1466166051744
Java
["3 3\n1 2 3\n2 3 1\n1 2 1", "3 4\n10 10 3\n5 1 6\n2 2 2\n1 5 7"]
1 second
["2", "1"]
NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.
Java 8
standard input
[ "implementation" ]
b20e98f2ea0eb48f790dcc5dd39344d3
The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.
1,100
Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.
standard output
PASSED
949b87986c3c957d053bbf6bfc57fb0d
train_001.jsonl
1439483400
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class ATM { public static void main(String[] args) { Scanner s = new Scanner(System.in); long candidates = s.nextLong(); long cities = s.nextLong(); long winnerIndex = 1; Map<Long, Integer> finalList = new HashMap<>(); for (int i = 0; i < cities; i++) { long winner = -1; for (int j = 0; j < candidates; j++) { long nextWinner = s.nextLong(); if (winner == -1) { winner = nextWinner; winnerIndex = j + 1; } else if (winner < nextWinner) { winner = nextWinner; winnerIndex = j + 1; } } Integer winnerCounter = finalList.get(winnerIndex); if (winnerCounter != null) finalList.put(winnerIndex, winnerCounter + 1); else { finalList.put(winnerIndex, 1); } } long winnervalue = 1; for (Map.Entry<Long, Integer> key : finalList.entrySet()) { if (winnervalue < key.getValue()) { winnervalue = key.getValue(); winnerIndex = key.getKey(); } else if (winnervalue == key.getValue() && winnerIndex > key.getKey()) { winnerIndex = key.getKey(); } } System.out.println(winnerIndex); } }
Java
["3 3\n1 2 3\n2 3 1\n1 2 1", "3 4\n10 10 3\n5 1 6\n2 2 2\n1 5 7"]
1 second
["2", "1"]
NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.
Java 8
standard input
[ "implementation" ]
b20e98f2ea0eb48f790dcc5dd39344d3
The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.
1,100
Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.
standard output
PASSED
d8e612d2d8a384dda972d5a6a45705c2
train_001.jsonl
1439483400
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class ProblemA { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int m = s.nextInt(); int[] wins = new int[n]; Arrays.fill(wins, 0); for(int i = 0; i < m ; i++) { int max = 0, idx = 0; for(int j = 0; j < n; j++) { int v = s.nextInt(); if(v > max) { max = v; idx = j; } } wins[idx]++; } int max = 0, idx = 0; for(int i = 0; i < n; i++) { if(wins[i] > max) { max = wins[i]; idx = i; } } System.out.print(idx+1); } }
Java
["3 3\n1 2 3\n2 3 1\n1 2 1", "3 4\n10 10 3\n5 1 6\n2 2 2\n1 5 7"]
1 second
["2", "1"]
NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.
Java 8
standard input
[ "implementation" ]
b20e98f2ea0eb48f790dcc5dd39344d3
The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.
1,100
Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.
standard output
PASSED
9c16bb9aec6a34dd3c576600dcb92e9e
train_001.jsonl
1439483400
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.
256 megabytes
import java.util.Scanner; public class Vibori { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] kandidat = new int[n]; int max = -1; int [] WinnerOfCity = new int[m]; int [] KandidatScores = new int[n + 1]; int winner = 0; for(int k = 0;k < m;k++) { for(int i = 0;i < n;i++) kandidat[i] = in.nextInt(); for(int j = 0;j < n;j++) { if(kandidat[j] > max){ max = kandidat[j]; WinnerOfCity[k] = j+1;} } max = -1; } for(int j = 1;j < n + 1;j++) { for(int i = 0;i < m;i++) { if(WinnerOfCity[i] == j) KandidatScores[j]++; } } max = 0; for(int j = 1;j < n + 1;j++) { if(KandidatScores[j] > max) { max = KandidatScores[j]; winner = j; } } System.out.println(winner); } }
Java
["3 3\n1 2 3\n2 3 1\n1 2 1", "3 4\n10 10 3\n5 1 6\n2 2 2\n1 5 7"]
1 second
["2", "1"]
NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.
Java 8
standard input
[ "implementation" ]
b20e98f2ea0eb48f790dcc5dd39344d3
The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.
1,100
Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.
standard output
PASSED
ae5a307e5497a2202f236855e0c57707
train_001.jsonl
1439483400
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.
256 megabytes
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int people = scan.nextInt(), k=0, city = scan.nextInt(), max = -1; int[] winner = new int[people]; for(int i=0; i<city; i++){ for(int j=0; j<people; j++){ int temp = scan.nextInt(); if(temp>max){ max = temp; k = j; } } winner[k]++; max=-1; } max = -1; k =0; for(int i=0; i<people; i++){ if(winner[i]>max){ max = winner[i]; k = i; } } System.out.println(k+1); } }
Java
["3 3\n1 2 3\n2 3 1\n1 2 1", "3 4\n10 10 3\n5 1 6\n2 2 2\n1 5 7"]
1 second
["2", "1"]
NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.
Java 8
standard input
[ "implementation" ]
b20e98f2ea0eb48f790dcc5dd39344d3
The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.
1,100
Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.
standard output
PASSED
e252d32ee1119db78aeda98d5c9d08f8
train_001.jsonl
1439483400
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.
256 megabytes
/*input 3 3 0 1 0 0 0 1 0 0 0 */ import java.io.*; import java.util.*; public class Main { public static void main(String []args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); StringTokenizer srt = new StringTokenizer(line); // n candidates // m cities int n = Integer.parseInt(srt.nextToken()); int m = Integer.parseInt(srt.nextToken()); int [][]arr = new int[m][n]; int max = 0, index = 0; int [] cand = new int[n]; for (int i = 0; i < arr.length; ++i) { srt = new StringTokenizer(br.readLine()); max = 0; for (int j = 0; j < arr[i].length; ++j) { arr[i][j] = Integer.parseInt(srt.nextToken()); if (max == 0 && arr[i][j] != 0) { max = arr[i][j]; index = j; } if (max < arr[i][j]) { max = arr[i][j]; index = j; } } if (max == 0) index = 0; // System.out.println("index->"+index); cand[index]++; } max = 0; for (int i = 0; i < cand.length; i++) { if (max < cand[i]) { max = cand[i]; index = i; } } System.out.println(index+1); // System.out.println(Arrays.toString(cand)); } }
Java
["3 3\n1 2 3\n2 3 1\n1 2 1", "3 4\n10 10 3\n5 1 6\n2 2 2\n1 5 7"]
1 second
["2", "1"]
NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.
Java 8
standard input
[ "implementation" ]
b20e98f2ea0eb48f790dcc5dd39344d3
The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.
1,100
Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.
standard output