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
c10ca91b91b4f816cc21bdf968fc9fe5
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class E{ final int mod = 998244353; final int maxn = -1; final double eps = 1e-9; void main(){ // freopen("in"); int n = nextInt(); List<Long> a = new ArrayList<Long>(); for(int i = 0; i < n; ++i){ a.add((long)(i + 1) * (n - i) * nextInt()); } List<Integer> b = new ArrayList<Integer>(); for(int i = 0; i < n; ++i){ b.add(nextInt()); } Collections.sort(a); Collections.sort(b, (x, y) -> Integer.compare(y, x)); int ans = 0; for(int i = 0; i < n; ++i){ ans = (int)(ans + a.get(i) % mod * b.get(i) % mod) % mod; } printf("%d\n", ans); } final double pi = Math.acos(-1.0); final long infl = 0x3f3f3f3f3f3f3f3fl; final int inf = 0x3f3f3f3f; final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; boolean zero(double x){ return x < eps; } PrintWriter out = new PrintWriter(System.out); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 1 << 15); StringTokenizer tokens = new StringTokenizer(""); E(){ Locale.setDefault(Locale.US); // imprime double com ponto main(); out.close(); } void freopen(String s){ try{ reader = new BufferedReader(new InputStreamReader(new FileInputStream(s)), 1 << 15); } catch(FileNotFoundException e){ throw new RuntimeException(e); } } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String next(){ readTokens(); return tokens.nextToken(); } String nextLine(){ readTokens(); return tokens.nextToken("\n"); } void readTokens(){ while(!tokens.hasMoreTokens()) // lΓͺ os dados, ignorando linhas vazias try{ tokens = new StringTokenizer(reader.readLine()); } catch(IOException e){ throw new RuntimeException(e); } } void printf(String s, Object... o){ out.printf(s, o); } void debug(String s, Object... o){ if(!ONLINE_JUDGE) System.err.printf((char)27 + "[91m" + s + (char)27 + "[0m", o); } public static void main(String[] args){ new E(); } }
Java
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer β€” the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
588179f7c7bf2ae6d286d6f3d40eb723
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import java.util.*; //1165E public class Main{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); Long[] A=new Long[n]; Long[] B=new Long[n]; for(int i=0;i<n;i++) A[i]=sc.nextLong(); for(int i=0;i<n;i++) B[i]=sc.nextLong(); new Main().solve(n,A,B); } long mod=998244353; void solve(int n,Long[] A,Long[] B){ Long[] C=new Long[n]; for(int i=0;i<n;i++){ C[i]=A[i]*(i+1)*(n-i); } Arrays.sort(C,Collections.reverseOrder()); Arrays.sort(B); long ret=0; for(int i=0;i<n;i++){ ret+=(B[i]%mod)*(C[i]%mod); ret%=mod; } System.out.println(ret); } }
Java
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer β€” the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
281109d02840f81e2a9d312ebd9726a0
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import javafx.scene.layout.Priority; import java.io.*; import java.lang.reflect.Array; import java.net.Inet4Address; import java.util.*; import java.lang.*; import java.util.HashMap; import java.util.PriorityQueue; public class templ implements Runnable { static class pair implements Comparable { int f; int s; pair(int fi,int se) { f=fi; s=se; } public int compareTo(Object o) { pair pr=(pair)o; if(s>pr.s) return 1; if(s==pr.s) { if(f<pr.f) return 1; else return -1; } else return -1; } public boolean equals(Object o) { pair ob=(pair)o; int ff; int ss; if(o!=null) { ff=ob.f; ss=ob.s; if((ff==this.f)&&(ss==this.s)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s).hashCode(); } } public class triplet implements Comparable { int f,t; int s; triplet(int f,int s,int t) { this.f=f; this.s=s; this.t=t; } public boolean equals(Object o) { triplet ob=(triplet)o; int ff; int ss; int tt; if(o!=null) { ff=ob.f; ss=ob.s; tt=ob.t; if((ff==this.f)&&(ss==this.s)&&(tt==this.t)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s+" "+this.t).hashCode(); } public int compareTo(Object o) { triplet tr=(triplet)o; if(t>tr.t) return 1; else return -1; } } public static void main(String args[])throws Exception { new Thread(null,new templ(),"templ",1<<27).start(); } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); long n=in.nl(); long M=998244353; PriorityQueue<Long>a=new PriorityQueue<>(); PriorityQueue<Long>b=new PriorityQueue<>(); for(long i=1;i<=n;i++) { long x=in.nl(); x=((x*i)*(n-i+1)); x=-1*x; a.add(x); } for(int j=1;j<=n;j++) { b.add(in.nl()); } long ans=0; while(!a.isEmpty()) { long x=Math.abs(a.remove()); long y=b.remove(); ans=(ans+(x%M*y%M)%M)%M; } out.println(ans%M); out.close(); } catch(Exception e){ return; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer β€” the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
36dea4ed1ab825c9346e0aa8fddee815
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class template { public static void main(String[] args) throws Exception { new template().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = f.nextInt(); ArrayList<Long> a1 = new ArrayList<>(); ArrayList<Long> a2 = new ArrayList<>(); for(int i = 0; i < n; i++) a1.add(f.nextLong() * (i+1) * (n-i)); for(int i = 0; i < n; i++) a2.add(f.nextLong()); Collections.sort(a1); Collections.sort(a2, Collections.reverseOrder()); long ans = 0; for(int i = 0; i < n; i++) ans = (ans + a1.get(i) % MOD * a2.get(i) % MOD) % MOD; out.println(ans); out.flush(); } public static final long MOD = 998244353; static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer β€” the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
37b51391577fc60767aabe966f2d09cb
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); //Scanner sc = new Scanner(); Reader in = new Reader(); Main solver = new Main(); solver.solve(out, in); out.flush(); out.close(); } static int INF = 998244353 ; static int maxn = (int)2e5+5; static long mod=(int)1e9+7 ; static int n,m,k,t,q; static long x,y; void solve(PrintWriter out, Reader in) throws IOException{ n = in.nextInt(); ArrayList<Long> a = new ArrayList<>(); ArrayList<Long> b = new ArrayList<>(); for(long i=0;i<n;i++) { long tmp= (i+1)*(n-1-i); tmp+=i+1; a.add(in.nextLong()*tmp); } for(int i=0;i<n;i++) b.add(in.nextLong()); long ans =0; Collections.sort(a); Collections.sort(b); Collections.reverse(b); for(int i=0;i<n;i++){ long haha = ((a.get(i)%INF)*(b.get(i)%INF))%INF; ans= (ans+haha)%INF; } out.println(ans); } //<> static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer β€” the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
5482e3a93bb0c43389e7dde74f06fc6e
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import java.io.*; import java.math.*; import java.text.*; import java.util.*; import java.util.regex.*; public class Solution { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter w = new PrintWriter(System.out); int n = Integer.parseInt(in.readLine()); ArrayList<Long> al = new ArrayList<Long>(); ArrayList<Long> bl = new ArrayList<Long>(); String[] sa = in.readLine().trim().split("\\s+"); String[] sb = in.readLine().trim().split("\\s+"); long mod = 998244353L; for(int i=0;i<n;i++) { al.add(Long.parseLong(sa[i])); bl.add(Long.parseLong(sb[i])); } ArrayList<Long> pro = new ArrayList<Long>(); for(int i=0;i<n;i++) { long times = ((long)n-(long)i)*((long)i+1L); pro.add(al.get(i)*times); } Collections.sort(pro); Collections.sort(bl); long sum = 0; for(int i=0;i<n;i++) { sum = ((sum%mod)+((((bl.get(n-1-i)%mod)*(pro.get(i)%mod))%mod)%mod))%mod; } w.println(sum); w.close(); } }
Java
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer β€” the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
a912df836bfddeb392e227a3d896e139
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.*; public class TaskE { int n; Integer[] a, b; static long MOD = 998244353; void solve() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 327680); StringTokenizer sk = new StringTokenizer(br.readLine()); n = Integer.parseInt(sk.nextToken()); a = new Integer[(int)n]; b = new Integer[(int)n]; sk = new StringTokenizer(br.readLine()); for(int i=0; i<n; ++i){ a[i] = Integer.parseInt(sk.nextToken()); } sk = new StringTokenizer(br.readLine()); for(int i=0; i<n; ++i){ b[i] = Integer.parseInt(sk.nextToken()); } long[] pps = new long[(int)n]; for(int i=0; i<n; ++i){ pps[i] = a[i]*(long)(i+1)*(n-i); } Arrays.parallelSort(pps); Arrays.parallelSort(b); // Arrays.sort(pps); // Arrays.sort(b); long res = 0; for(int i=0; i<n; i++){ res += b[i] * (pps[(int)n-i-1]%MOD); res %= MOD; } System.out.println(res%MOD); System.out.flush(); } public static void main(String[] args) throws Exception{ //System.setIn(new FileInputStream("inputs/e.in")); TaskE s = new TaskE(); s.solve(); } }
Java
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer β€” the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
e8a5283a6c6e26b7af1e3a8c366769bc
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.*; public class TaskE { int n; Integer[] a, b; static long MOD = 998244353; void solve() throws Exception { Scanner sc = new Scanner(System.in); n = sc.nextInt(); a = new Integer[(int)n]; b = new Integer[(int)n]; for(int i=0; i<n; ++i){ a[i] = sc.nextInt(); } for(int i=0; i<n; ++i){ b[i] = sc.nextInt(); } long[] pps = new long[(int)n]; for(int i=0; i<n; ++i){ pps[i] = a[i]*(long)(i+1)*(n-i); } Arrays.parallelSort(pps); Arrays.parallelSort(b); // Arrays.sort(pps); // Arrays.sort(b); long res = 0; for(int i=0; i<n; i++){ res += b[i] * (pps[(int)n-i-1]%MOD); res %= MOD; } System.out.println(res%MOD); System.out.flush(); } public static void main(String[] args) throws Exception{ //System.setIn(new FileInputStream("inputs/e.in")); TaskE s = new TaskE(); s.solve(); } }
Java
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer β€” the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
5d61cf5c502031ac606cf7dc79980137
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.*; public class TaskE { int n; ArrayList<Integer> a, b; static long MOD = 998244353; void solve() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 327680); StringTokenizer sk = new StringTokenizer(br.readLine()); n = Integer.parseInt(sk.nextToken()); a = new ArrayList<>(n); b = new ArrayList<>(n); for(int i=0; i<n; i++){ a.add(0); b.add(0); } sk = new StringTokenizer(br.readLine()); for(int i=0; i<n; ++i){ int aa = Integer.parseInt(sk.nextToken()); a.set(i, aa); } sk = new StringTokenizer(br.readLine()); for(int i=0; i<n; ++i){ int bb = Integer.parseInt(sk.nextToken()); b.set(i, bb); } ArrayList<Long> pps = new ArrayList<>(n); for(int i=0; i<n; ++i){ pps.add(a.get(i)*(long)(i+1)*(n-i)); } Collections.sort(pps); Collections.sort(b); // Arrays.sort(pps); // Arrays.sort(b); long res = 0; for(int i=0; i<n; i++){ res += b.get(i) * (pps.get((int)n-i-1)%MOD); res %= MOD; } System.out.println(res%MOD); System.out.flush(); } public static void main(String[] args) throws Exception{ //System.setIn(new FileInputStream("inputs/e.in")); TaskE s = new TaskE(); s.solve(); } }
Java
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer β€” the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
2c68a3350dec4ae9c14c4754945cc663
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
import java.io.*; import java.math.*; import java.security.KeyStore.Entry; import java.util.*; public class CODEFORCES { private InputStream is; private PrintWriter out; class ST { int n; int arr[]; ST(int a) { n = a; arr = new int[n + 1]; } void u(int ind, int val) { ind++; while (ind <= n) { arr[ind] += val; ind += (ind & (-ind)); } } int an(int l, int r) { return ans(r) - ans(l - 1); } int ans(int ind) { int sum = 0; ind++; while (ind > 0) { sum += arr[ind]; ind -= (ind & (-ind)); } return sum; } } void solve() { int n = ni(), q = ni(); int sq = (int) Math.sqrt(n); ST s[] = new ST[sq + 2]; for (int i = 0; i < s.length; i++) s[i] = new ST(n); int block[] = new int[n], a[] = new int[n], index[] = new int[n]; for (int i = 0; i < n; i++) { block[i] = i / sq; a[i] = i; index[i] = i; s[block[i]].u(i, 1); } long ans = 0; while (q-- > 0) { int l = ni() - 1, r = ni() - 1; if (l > r) { int di = l; l = r; r = di; } if (l == r) { out.println(ans); continue; } int ml = 0; for (int i = block[a[l]] + 1; i < block[a[r]]; i++) ml += s[i].an(l + 1, r - 1); ans += ml * 2; ml = 0; for (int i = block[a[r]] + 1; i < block[a[l]]; i++) ml += s[i].an(l + 1, r - 1); ans -= ml * 2; ml = 0; if (block[a[l]] == block[a[r]]) { int jk = 2; if (a[r] < a[l]) jk = -2; for (int i = Math.min(a[l], a[r]) + 1; i < Math.max(a[l], a[r]); i++) { if (index[i] > l && index[i] < r) ans += jk; } } else { if (a[l] < a[r]) { int jk = 2; for (int i = a[l] + 1; i < (block[a[l]] + 1) * sq; i++) { if (index[i] > l && index[i] < r) ans += jk; } for (int i = block[a[r]] * sq; i < a[r]; i++) { if (index[i] > l && index[i] < r) ans += jk; } } else { int jk = -2; for (int i = a[r] + 1; i < (block[a[r]] + 1) * sq; i++) { if (index[i] > l && index[i] < r) ans += jk; } for (int i = block[a[l]] * sq; i < a[l]; i++) { if (index[i] > l && index[i] < r) ans += jk; } } } if (a[l] < a[r]) ans++; else ans--; s[block[a[l]]].u(l, -1); s[block[a[r]]].u(r, -1); s[block[a[l]]].u(r, +1); s[block[a[r]]].u(l, +1); index[a[l]] = r; index[a[r]] = l; ml = a[l]; a[l] = a[r]; a[r] = ml; out.println(ans); } } void soln() { is = System.in; 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 CODEFORCES().soln(); } // To Get Input // Some Buffer Methods private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' // ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
747c749f873c8e564376337376ce676b
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 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.Collection; import java.util.Random; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jialin Ouyang (Jialin.Ouyang@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; QuickScanner in = new QuickScanner(inputStream); QuickWriter out = new QuickWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { int n; int q; int[] perm; int[] permIdx; int[] lower; int[] upper; QuickWriter out; int sqrtQ; int sqrtQ2; int[] nxtMobileIdx; IntArrayList mobileIdx; IntArrayList mobileValue; int[][] forward; int[][] backward; long res; int m; public void solve(int testNumber, QuickScanner in, QuickWriter out) { this.out = out; n = in.nextInt(); q = in.nextInt(); perm = new int[n]; permIdx = new int[n]; for (int i = 0; i < n; ++i) { perm[i] = i; permIdx[i] = i; } lower = new int[q]; upper = new int[q]; for (int i = 0; i < q; ++i) { lower[i] = in.nextInt() - 1; upper[i] = in.nextInt() - 1; } calc(); } void calc() { sqrtQ = 1; for (; sqrtQ * sqrtQ < q; ++sqrtQ) { } sqrtQ2 = sqrtQ << 1; nxtMobileIdx = new int[n]; mobileIdx = new IntArrayList(sqrtQ2); mobileValue = new IntArrayList(sqrtQ2); forward = new int[sqrtQ2][sqrtQ2]; backward = new int[sqrtQ2][sqrtQ2]; res = 0; for (int fromIdx = 0, toIdx = sqrtQ; fromIdx < q; fromIdx += sqrtQ, toIdx += sqrtQ) { calc(fromIdx, Math.min(toIdx, q)); } } void calc(int fromIdx, int toIdx) { mobileIdx.clear(); for (int i = fromIdx; i < toIdx; ++i) { mobileIdx.add(lower[i]); mobileIdx.add(upper[i]); } mobileIdx.sortAndUnique(); mobileValue.clear(); for (int i = 0; i < mobileIdx.size; ++i) { mobileValue.add(perm[mobileIdx.get(i)]); } mobileValue.sort(); m = mobileValue.size; //System.out.printf("====[%d, %d)====\n", fromIdx, toIdx); //System.out.printf("\tmobileId:%s\n", mobileIdx.toString()); //System.out.printf("\tmobileValue:%s\n", mobileValue.toString()); //System.out.printf("\tperm:%s\n", IntArrayUtils.toString(perm)); //System.out.printf("\tpermIdx:%s\n", IntArrayUtils.toString(permIdx)); calcForward(); calcBackward(); for (int i = fromIdx; i < toIdx; ++i) { res -= calcInvs(lower[i], upper[i]); swap(lower[i], upper[i]); res += calcInvs(lower[i], upper[i]); out.println(res); } } void calcForward() { Arrays.fill(nxtMobileIdx, -1); for (int i = 0; i < m; ++i) { nxtMobileIdx[mobileIdx.get(i)] = i; Arrays.fill(forward[i], 0, m, 0); } for (int i = n - 2; i >= 0; --i) if (nxtMobileIdx[i] < 0) { nxtMobileIdx[i] = nxtMobileIdx[i + 1]; } //System.out.printf("\tnxtMobileIdx:%s\n", IntArrayUtils.toString(nxtMobileIdx, 0, n)); //for (int i = 0; i < m; ++i) System.out.printf("\t%s\n", IntArrayUtils.toString(forward[i], 0, m)); int from = n, to; for (int i = m - 1; i >= 0; --i) { to = from; from = mobileValue.get(i); for (int j = from + 1; j < to; ++j) { int idx = permIdx[j]; int nxtIdx = nxtMobileIdx[idx]; //if (idx == nxtIdx) System.out.printf("\t+ value:%d idx:%d [nxtIdx:%d][i:%d]\n", j, idx, nxtIdx, i); if (nxtIdx >= 0) { ++forward[nxtIdx][i]; } } } for (int i = 0; i < m; ++i) for (int j = m - 1; j >= 0; --j) { if (i > 0) forward[i][j] += forward[i - 1][j]; if (j + 1 < m) forward[i][j] += forward[i][j + 1]; if (i > 0 && j + 1 < m) forward[i][j] -= forward[i - 1][j + 1]; } //System.out.printf("\tforward\n"); //for (int i = 0; i < m; ++i) System.out.printf("\t%s\n", IntArrayUtils.toString(forward[i], 0, m)); } void calcBackward() { Arrays.fill(nxtMobileIdx, -1); for (int i = 0; i < m; ++i) { nxtMobileIdx[mobileIdx.get(i)] = i; Arrays.fill(backward[i], 0, m, 0); } for (int i = 1; i < n; ++i) if (nxtMobileIdx[i] < 0) { nxtMobileIdx[i] = nxtMobileIdx[i - 1]; } //System.out.printf("\tnxtMobileIdx:%s\n", IntArrayUtils.toString(nxtMobileIdx, 0, n)); //for (int i = 0; i < m; ++i) System.out.printf("\t%s\n", IntArrayUtils.toString(forward[i], 0, m)); int from, to = -1; for (int i = 0; i < m; ++i) { from = to; to = mobileValue.get(i); for (int j = from + 1; j < to; ++j) { int idx = permIdx[j]; int nxtIdx = nxtMobileIdx[idx]; if (nxtIdx >= 0) { //System.out.printf("\t+ value:%d idx:%d [nxtIdx:%d][i:%d]\n", j, idx, nxtIdx, i); ++backward[nxtIdx][i]; } } } for (int i = m - 1; i >= 0; --i) for (int j = 0; j < m; ++j) { if (i + 1 < m) backward[i][j] += backward[i + 1][j]; if (j > 0) backward[i][j] += backward[i][j - 1]; if (i + 1 < m && j > 0) backward[i][j] -= backward[i + 1][j - 1]; } //System.out.printf("\tbackward\n"); //for (int i = 0; i < m; ++i) System.out.printf("\t%s\n", IntArrayUtils.toString(backward[i], 0, m)); } int calcInvs(int lower, int upper) { return calcInv(lower, perm[lower]) + calcInv(upper, perm[upper]) - (perm[Math.min(lower, upper)] > perm[Math.max(lower, upper)] ? 1 : 0); } int calcInv(int oldIdx, int oldValue) { int idx = mobileIdx.lowerBound(oldIdx); int value = mobileValue.lowerBound(oldValue); int res = forward[idx][value] + backward[idx][value]; for (int i = 0; i < idx; ++i) if (perm[mobileIdx.get(i)] > oldValue) { ++res; } for (int i = idx + 1; i < mobileIdx.size; ++i) if (oldValue > perm[mobileIdx.get(i)]) { ++res; } return res; } void swap(int lower, int upper) { IntArrayUtils.swap(perm, lower, upper); permIdx[perm[lower]] = lower; permIdx[perm[upper]] = upper; } } static class QuickWriter { private final PrintWriter writer; public QuickWriter(OutputStream outputStream) { this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public QuickWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; ++i) { if (i > 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.print('\n'); } public void close() { writer.close(); } } static class IntArrayList implements IntCollection { private static final int[] EMPTY = {}; public int[] values; public int size; public IntArrayList() { values = EMPTY; clear(); } public IntArrayList(int capacity) { values = new int[IntUtils.nextPow2(capacity)]; clear(); } public IntArrayList(Collection<Integer> collection) { this(collection.size()); addAll(collection); } public void clear() { size = 0; } public void add(int value) { ensureCapacity(size + 1); addInternal(value); } public void addAll(Collection<Integer> values) { ensureCapacity(size + values.size()); for (int value : values) { addInternal(value); } } public int get(int idx) { if (idx >= size) throw new ArrayIndexOutOfBoundsException(); return values[idx]; } public void sort() { IntArrayUtils.sort(values, 0, size); } public void unique() { size = IntArrayUtils.unique(values, 0, size); } public void sortAndUnique() { sort(); unique(); } public int lowerBound(int value) { return IntArrayUtils.lowerBound(values, 0, size, value); } public String toString() { return IntArrayUtils.toString(values, 0, size); } public void ensureCapacity(int capacity) { if (capacity <= values.length) return; int[] newValues = new int[IntUtils.nextPow2(capacity)]; for (int i = 0; i < size; ++i) { newValues[i] = values[i]; } values = newValues; } private void addInternal(int value) { values[size++] = value; } } static class IntArrayUtils { private static final Random RANDOM = new Random(1000000007); public static int unique(int[] values, int fromIdx, int toIdx) { if (fromIdx == toIdx) return 0; int res = 1; for (int i = fromIdx + 1; i < toIdx; ++i) { if (values[i - 1] != values[i]) { values[fromIdx + res++] = values[i]; } } return res; } public static void sort(int[] values, int fromIdx, int toIdx) { shuffle(values, fromIdx, toIdx); Arrays.sort(values, fromIdx, toIdx); } public static int lowerBound(int[] values, int fromIdx, int toIdx, int value) { int res = toIdx; for (int lower = fromIdx, upper = toIdx - 1; lower <= upper; ) { int medium = (lower + upper) >> 1; if (value <= values[medium]) { res = medium; upper = medium - 1; } else { lower = medium + 1; } } return res; } public static void swap(int[] values, int uIdx, int vIdx) { if (uIdx == vIdx) return; values[uIdx] ^= values[vIdx]; values[vIdx] ^= values[uIdx]; values[uIdx] ^= values[vIdx]; } public static void shuffle(int[] values, int fromIdx, int toIdx) { for (int i = toIdx - fromIdx - 1; i > 0; --i) { swap(values, i + fromIdx, RANDOM.nextInt(i + 1) + fromIdx); } } public static String toString(int[] values, int fromIdx, int toIdx) { StringBuilder sb = new StringBuilder("["); for (int i = fromIdx; i < toIdx; ++i) { if (i != fromIdx) sb.append(", "); sb.append(values[i]); } return sb.append("]").toString(); } } static interface IntCollection { } static class IntUtils { public static boolean isPow2(int n) { return n > 0 && (n & (n - 1)) == 0; } public static int nextPow2(int n) { if (n < 1) return 1; return isPow2(n) ? n : Integer.highestOneBit(n) << 1; } } static class QuickScanner { private static final int BUFFER_SIZE = 1024; private InputStream stream; private byte[] buffer; private int currentPosition; private int numberOfChars; public QuickScanner(InputStream stream) { this.stream = stream; this.buffer = new byte[BUFFER_SIZE]; this.currentPosition = 0; this.numberOfChars = 0; } public int nextInt() { int c = nextNonSpaceChar(); boolean positive = true; if (c == '-') { positive = false; c = nextChar(); } int res = 0; do { if (c < '0' || '9' < c) throw new RuntimeException(); res = res * 10 + c - '0'; c = nextChar(); } while (!isSpaceChar(c)); return positive ? res : -res; } public int nextNonSpaceChar() { int res = nextChar(); for (; isSpaceChar(res) || res < 0; res = nextChar()) ; return res; } public int nextChar() { if (numberOfChars == -1) { throw new RuntimeException(); } if (currentPosition >= numberOfChars) { currentPosition = 0; try { numberOfChars = stream.read(buffer); } catch (Exception e) { throw new RuntimeException(e); } if (numberOfChars <= 0) { return -1; } } return buffer[currentPosition++]; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\t' || isEndOfLineChar(c); } public boolean isEndOfLineChar(int c) { return c == '\n' || c == '\r' || c < 0; } } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
a9c32b9c82c580bd4b3c686d59f3e390
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 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.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jialin Ouyang (Jialin.Ouyang@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; QuickScanner in = new QuickScanner(inputStream); QuickWriter out = new QuickWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { int n; int m; int sqrtN; int[] perm; int[] blockIdx; IntAddBinaryIndexedTree2D biTree; long res; public void solve(int testNumber, QuickScanner in, QuickWriter out) { n = in.nextInt(); for (sqrtN = 1; sqrtN < n / sqrtN; ++sqrtN) { } perm = new int[n]; blockIdx = new int[n]; m = 0; for (int i = 0; i < n; i += sqrtN, ++m) { for (int j = i, k = 0; j < n && k < sqrtN; ++j, ++k) { perm[j] = j; blockIdx[j] = m; // biTree.update(m, i, 1); } } // blockSize = new int[m]; biTree = new IntAddBinaryIndexedTree2D(m, n); // for (int i = 0; i < m; ++i) { // blockSize[i] = Math.min(n - i * sqrtN, sqrtN); // } for (int i = 0; i < n; ++i) biTree.update(blockIdx[i], i, 1); res = 0; for (int q = in.nextInt(); q > 0; --q) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; out.println(calc(x, y)); } } long calc(int x, int y) { if (x > y) return calc(y, x); if (x == y) return res; res += perm[x] > perm[y] ? -1 : 1; res -= subCalc(x, y); //System.out.printf("subCalc(%d,%d):%d\n", x, y, subCalc(x, y)); biTree.update(blockIdx[x], perm[x], -1); biTree.update(blockIdx[y], perm[y], -1); IntArrayUtils.swap(perm, x, y); biTree.update(blockIdx[x], perm[x], 1); biTree.update(blockIdx[y], perm[y], 1); //System.out.printf("subCalc(%d,%d):%d\n", x, y, subCalc(x, y)); res += subCalc(x, y); return res; } int subCalc(int x, int y) { int idxX = blockIdx[x], idxY = blockIdx[y]; int valueX = perm[x], valueY = perm[y]; int res = 0; //System.out.printf("subCalc(%d,%d) idxX:%d idxY:%d\n", x, y, idxX, idxY); if (idxX + 1 < idxY) { res += biTree.calcRange(idxX + 1, 0, idxY, valueX); res += biTree.calcRange(idxX + 1, valueY + 1, idxY, n); } //System.out.printf("\t%d\n", res); if (idxX == idxY) { for (int i = x + 1; i < y; ++i) { if (valueX > perm[i]) ++res; if (perm[i] > valueY) ++res; } } else { for (int i = Math.min((idxX + 1) * sqrtN, n) - 1; i > x; --i) { if (valueX > perm[i]) ++res; if (perm[i] > valueY) ++res; } for (int i = sqrtN * idxY; i < y; ++i) { if (valueX > perm[i]) ++res; if (perm[i] > valueY) ++res; } } //System.out.printf("\t%d\n", res); return res; } } static abstract class AbstractIntBinaryIndexedTree2D { private int n; private int m; private int[][] values; public AbstractIntBinaryIndexedTree2D(int capacity1, int capacity2) { values = new int[capacity1][capacity2]; } public abstract int merge(int x, int y); public void init(int n, int m, int initValue) { this.n = n; this.m = m; for (int i = 0; i < n; ++i) { Arrays.fill(values[i], 0, m, initValue); } } public void update(int x, int y, int value) { for (; x < n; x |= x + 1) for (int i = y; i < m; i |= i + 1) { values[x][i] = merge(values[x][i], value); } } public int calc(int x, int y, int initValue) { int res = initValue; for (; x >= 0; x = (x & (x + 1)) - 1) for (int i = y; i >= 0; i = (i & (i + 1)) - 1) { res = merge(res, values[x][i]); } return res; } } static class QuickWriter { private final PrintWriter writer; public QuickWriter(OutputStream outputStream) { this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public QuickWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; ++i) { if (i > 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.print('\n'); } public void close() { writer.close(); } } static class IntAddBinaryIndexedTree2D extends AbstractIntBinaryIndexedTree2D { public IntAddBinaryIndexedTree2D(int capacity1, int capacity2) { super(capacity1, capacity2); init(capacity1, capacity2); } public int merge(int x, int y) { return x + y; } public void init(int n, int m, int initValue) { throw new UnsupportedOperationException(); } public int calc(int x, int y, int initValue) { throw new UnsupportedOperationException(); } public void init(int n, int m) { super.init(n, m, 0); } public int calc(int x, int y) { return super.calc(x, y, 0); } public int calcRange(int x1, int y1, int x2, int y2) { if (x1 >= x2 || y1 >= y2) return 0; int res = calc(x2 - 1, y2 - 1); if (x1 > 0) res -= calc(x1 - 1, y2 - 1); if (y1 > 0) res -= calc(x2 - 1, y1 - 1); if (x1 > 0 && y1 > 0) res += calc(x1 - 1, y1 - 1); return res; } } static class IntArrayUtils { public static void swap(int[] values, int uIdx, int vIdx) { if (uIdx == vIdx) return; values[uIdx] ^= values[vIdx]; values[vIdx] ^= values[uIdx]; values[uIdx] ^= values[vIdx]; } } static class QuickScanner { private static final int BUFFER_SIZE = 1024; private InputStream stream; private byte[] buffer; private int currentPosition; private int numberOfChars; public QuickScanner(InputStream stream) { this.stream = stream; this.buffer = new byte[BUFFER_SIZE]; this.currentPosition = 0; this.numberOfChars = 0; } public int nextInt() { int c = nextNonSpaceChar(); boolean positive = true; if (c == '-') { positive = false; c = nextChar(); } int res = 0; do { if (c < '0' || '9' < c) throw new RuntimeException(); res = res * 10 + c - '0'; c = nextChar(); } while (!isSpaceChar(c)); return positive ? res : -res; } public int nextNonSpaceChar() { int res = nextChar(); for (; isSpaceChar(res) || res < 0; res = nextChar()) ; return res; } public int nextChar() { if (numberOfChars == -1) { throw new RuntimeException(); } if (currentPosition >= numberOfChars) { currentPosition = 0; try { numberOfChars = stream.read(buffer); } catch (Exception e) { throw new RuntimeException(e); } if (numberOfChars <= 0) { return -1; } } return buffer[currentPosition++]; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\t' || isEndOfLineChar(c); } public boolean isEndOfLineChar(int c) { return c == '\n' || c == '\r' || c < 0; } } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
9afabc7b149939dfde183ba2d791888c
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
import java.util.*; import java.io.*; public class E { public static int sqrt, maxn, bit[][], arr[]; public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(); int q = in.nextInt(); sqrt = 1 + (int) Math.sqrt(n); maxn = 200000 + 5; bit = new int[sqrt + 5][maxn]; arr = new int[maxn]; long ans = 0; for (int i = 1; i <= n; i++) { arr[i] = i; } for (int i = 1; i <= n; i++) { int j = i / sqrt; if (i % sqrt != 0) { j++; } update(j, arr[i], 1); } for (int qq = 1; qq <= q; qq++) { int l1 = in.nextInt(), r1 = in.nextInt(); if (l1 > r1) { int t = l1; l1 = r1; r1 = t; } int ls1 = l1 / sqrt, rs1 = r1 / sqrt; if (l1 % sqrt != 0) { ls1++; } if (r1 % sqrt != 0) { rs1++; } int l = l1 + 1; int r = r1 - 1; int ls = l / sqrt; int rs = r / sqrt; if (l % sqrt != 0) { ls++; } if (r % sqrt != 0) { rs++; } ans -= getBigger(l, r, ls, rs, n, arr[r1]); ans -= getSmaller(l, r, ls, rs, n, arr[l1]); ans += getBigger(l, r, ls, rs, n, arr[l1]); ans += getSmaller(l, r, ls, rs, n, arr[r1]); if (arr[l1] > arr[r1]) { ans--; } else if (arr[r1] > arr[l1]) { ans++; } update(ls1, arr[l1], -1); update(rs1, arr[l1], 1); update(ls1, arr[r1], 1); update(rs1, arr[r1], -1); int temp = arr[l1]; arr[l1] = arr[r1]; arr[r1] = temp; out.println(ans); } out.close(); } static int getBigger(int l, int r, int ls, int rs, int n, int num) { int cnt = 0; if (rs - ls <= 1) { for (int i = l; i <= r; i++) { if (arr[i] > num) { cnt++; } } return cnt; } else { cnt += query(rs - 1, num + 1, n); cnt -= query(ls, num + 1, n); for (int i = l; i <= (ls) * sqrt; i++) { if (arr[i] > num) { cnt++; } } for (int i = (rs - 1) * sqrt + 1; i <= r; i++) { if (arr[i] > num) { cnt++; } } return cnt; } } static int getSmaller(int l, int r, int ls, int rs, int n, int num) { int cnt = 0; if (rs - ls <= 1) { for (int i = l; i <= r; i++) { if (arr[i] < num) { cnt++; } } return cnt; } else { cnt += query(rs - 1, 1, num - 1); cnt -= query(ls, 1, num - 1); for (int i = l; i <= (ls) * sqrt; i++) { if (arr[i] < num) { cnt++; } } for (int i = (rs - 1) * sqrt + 1; i <= r; i++) { if (arr[i] < num) { cnt++; } } return cnt; } } public static void update(int x, int y, int val) { int y1; while (x < bit.length) { y1 = y; while (y1 < bit[x].length) { bit[x][y1] += val; y1 += (y1 & -y1); } x += (x & -x); } } public static int getSum(int x, int y) { int sum = 0; while (x > 0) { int y1 = y; while (y1 > 0) { sum += bit[x][y1]; y1 -= y1 & -y1; } x -= x & -x; } return sum; } public static int query(int x, int l, int r) { int p = getSum(x, r); int q = getSum(x, l - 1); return p - q; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() throws Exception { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public String nextLine() throws Exception { String line = null; tokenizer = null; line = reader.readLine(); return line; } public int nextInt() throws Exception { return Integer.parseInt(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
84588a773338427dce4b64c8b3b30004
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
import java.io.*; import java.util.*; public class InversionNSqrtNNoVectors { private static final int BLOCK_SZ_Q = 256; private static final int BLOCK_SZ_N = 512; public static class ToProcess { public int x, y1, y2, sgn, id; public void set(int pX, int pY1, int pY2, int pSgn, int pId) { x = pX; y1 = pY1; y2 = pY2; sgn = pSgn; id = pId; } public ToProcess() { } } public static class ToProcessCompareAsc implements Comparator<ToProcess> { @Override public int compare(ToProcess o1, ToProcess o2) { return o1.x - o2.x; } } public static class ToProcessCompareDesc implements Comparator<ToProcess> { @Override public int compare(ToProcess o1, ToProcess o2) { return o2.x - o1.x; } } static int n, q; static int[] p; static ToProcess[] queryL, queryR; static int queryLCnt, queryRCnt; static SQRTDecomposition sum; static ToProcessCompareAsc ascCmp = new ToProcessCompareAsc(); static ToProcessCompareDesc descCmp = new ToProcessCompareDesc(); public static final void add(int q, int sgn, int id) { if (q-1 >= 0) { queryL[queryLCnt++].set(q-1, p[q]+1, n-1, sgn, id); } if (q+1 < n) { queryR[queryRCnt++].set(q+1, 0, p[q]-1, sgn, id); } } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); n = Integer.parseInt(tokenizer.nextToken()); q = Integer.parseInt(tokenizer.nextToken()); int[] qL = new int[q], qR = new int[q]; long[] ans = new long[q], preAns = new long[q]; p = new int[n]; for (int i = 0; i < n; i++) { p[i] = i; } for (int i = 0; i < q; i++) { tokenizer = new StringTokenizer(reader.readLine()); qL[i] = Integer.parseInt(tokenizer.nextToken()) - 1; qR[i] = Integer.parseInt(tokenizer.nextToken()) - 1; } long cnt = 0; boolean[] good = new boolean[n]; int[] goods = new int[n]; int goodsSize = 0; queryL = new ToProcess[4 * BLOCK_SZ_Q]; queryR = new ToProcess[4 * BLOCK_SZ_Q]; for (int j = 0; j < 4 * BLOCK_SZ_Q; j++) { queryL[j] = new ToProcess(); queryR[j] = new ToProcess(); } SQRTDecomposition sum = new SQRTDecomposition(n, BLOCK_SZ_N); for (int i = 0; i < q; i += BLOCK_SZ_Q) { int iEnd = Math.min(q, i + BLOCK_SZ_Q); Arrays.fill(good, false); for (int j = i; j < iEnd; j++) { good[qL[j]] = true; good[qR[j]] = true; } goodsSize = 0; for (int j = 0; j < n; j++) { if (good[j]) { goods[goodsSize++] = j; } } long goodCnt = 0; queryLCnt = 0; queryRCnt = 0; for (int j = i; j < iEnd; j++) { int a = qL[j], b = qR[j]; if (a == b) { ans[j] += goodCnt; continue; } for (int k = 0; k < goodsSize; k++) { int q = goods[k]; if (q == a || q == b) { continue; } if ((p[q] < p[a] && q > a) || (p[q] > p[a] && q < a)) { goodCnt--; } if ((p[q] < p[b] && q > b) || (p[q] > p[b] && q < b)) { goodCnt--; } if ((p[q] < p[b] && q > a) || (p[q] > p[b] && q < a)) { goodCnt++; } if ((p[q] < p[a] && q > b) || (p[q] > p[a] && q < b)) { goodCnt++; } } if ((a < b && p[a] > p[b]) || (a > b && p[a] < p[b])) { goodCnt--; } else { goodCnt++; } ans[j] += goodCnt; add(a, -1, j); add(b, -1, j); int tmp = p[a]; p[a] = p[b]; p[b] = tmp; add(a, +1, j); add(b, +1, j); } sum.clear(); Arrays.sort(queryL, 0, queryLCnt, ascCmp); int curL = 0; for (int j = 0; j < n; j++) { if (!good[j]) { sum.add(p[j], 1); } for (; curL < queryLCnt; curL++) { ToProcess cur = queryL[curL]; if (cur.x != j) { break; } int res = sum.sum(cur.y1, cur.y2); res *= cur.sgn; preAns[cur.id] += res; } } sum.clear(); Arrays.sort(queryR, 0, queryRCnt, descCmp); int curR = 0; for (int j = n-1; j >= 0; j--) { if (!good[j]) { sum.add(p[j], 1); } for (; curR < queryRCnt; curR++) { ToProcess cur = queryR[curR]; if (cur.x != j) { break; } int res = sum.sum(cur.y1, cur.y2); res *= cur.sgn; preAns[cur.id] += res; } } for (int j = i; j < iEnd; j++) { if (j != i) { preAns[j] += preAns[j-1]; } ans[j] += cnt + preAns[j]; } cnt = ans[iEnd - 1]; } for (int i = 0; i < q; i++) { writer.write(Long.toString(ans[i])); writer.newLine(); } reader.close(); writer.close(); } } class SQRTDecomposition { private int n; private int sz; private int[] val; private int[] blocks; public final void add(int v, int delta) { val[v] += delta; blocks[v / sz] += delta; } public final int sum(int l, int r) { if (l < 0) { l = 0; } if (r >= n) { r = n; } r++; int res = 0; int lBlock = (l + sz - 1) / sz, rBlock = r / sz; for (int i = lBlock; i < rBlock; i++) { res += blocks[i]; } int lBlockR = lBlock * sz, rBlockR = rBlock * sz; if (lBlockR >= rBlockR) { for (int i = l; i < r; i++) { res += val[i]; } } else { for (int i = l; i < lBlockR; i++) { res += val[i]; } for (int i = rBlockR; i < r; i++) { res += val[i]; } } return res; } public void clear() { Arrays.fill(val, 0); Arrays.fill(blocks, 0); } SQRTDecomposition(int pN, int pSz) { n = pN; sz = pSz; val = new int[n]; blocks = new int[(n + sz - 1) / sz]; } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
6009a539b74172106fd2df2ee3f54a2d
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
import java.io.*; import java.util.*; public class InversionNSqrtNNoVectors { private static final int BLOCK_SZ_Q = 256; private static final int BLOCK_SZ_N = 512; public static class ToProcess { public int x, y1, y2, sgn, id; public void set(int pX, int pY1, int pY2, int pSgn, int pId) { x = pX; y1 = pY1; y2 = pY2; sgn = pSgn; id = pId; } public ToProcess() { } } public static class ToProcessCompareAsc implements Comparator<ToProcess> { @Override public int compare(ToProcess o1, ToProcess o2) { return o1.x - o2.x; } } public static class ToProcessCompareDesc implements Comparator<ToProcess> { @Override public int compare(ToProcess o1, ToProcess o2) { return o2.x - o1.x; } } static int n, q; static int[] p; static ToProcess[] queryL, queryR; static int queryLCnt, queryRCnt; static SQRTDecomposition sum; static ToProcessCompareAsc ascCmp = new ToProcessCompareAsc(); static ToProcessCompareDesc descCmp = new ToProcessCompareDesc(); public static final void add(int q, int sgn, int id) { if (q-1 >= 0) { queryL[queryLCnt++].set(q-1, p[q]+1, n-1, sgn, id); } if (q+1 < n) { queryR[queryRCnt++].set(q+1, 0, p[q]-1, sgn, id); } } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); n = Integer.parseInt(tokenizer.nextToken()); q = Integer.parseInt(tokenizer.nextToken()); int[] qL = new int[q], qR = new int[q]; long[] ans = new long[q], preAns = new long[q]; p = new int[n]; for (int i = 0; i < n; i++) { p[i] = i; } for (int i = 0; i < q; i++) { tokenizer = new StringTokenizer(reader.readLine()); qL[i] = Integer.parseInt(tokenizer.nextToken()) - 1; qR[i] = Integer.parseInt(tokenizer.nextToken()) - 1; } long cnt = 0; boolean[] good = new boolean[n]; int[] goods = new int[n]; int goodsSize = 0; queryL = new ToProcess[4 * BLOCK_SZ_Q]; queryR = new ToProcess[4 * BLOCK_SZ_Q]; for (int j = 0; j < 4 * BLOCK_SZ_Q; j++) { queryL[j] = new ToProcess(); queryR[j] = new ToProcess(); } SQRTDecomposition sum = new SQRTDecomposition(n, BLOCK_SZ_N); for (int i = 0; i < q; i += BLOCK_SZ_Q) { int iEnd = Math.min(q, i + BLOCK_SZ_Q); Arrays.fill(good, false); for (int j = i; j < iEnd; j++) { good[qL[j]] = true; good[qR[j]] = true; } goodsSize = 0; for (int j = 0; j < n; j++) { if (good[j]) { goods[goodsSize++] = j; } } long goodCnt = 0; queryLCnt = 0; queryRCnt = 0; for (int j = i; j < iEnd; j++) { int a = qL[j], b = qR[j]; if (a == b) { ans[j] += goodCnt; continue; } for (int k = 0; k < goodsSize; k++) { int q = goods[k]; if (q == a || q == b) { continue; } if ((p[q] < p[a] && q > a) || (p[q] > p[a] && q < a)) { goodCnt--; } if ((p[q] < p[b] && q > b) || (p[q] > p[b] && q < b)) { goodCnt--; } if ((p[q] < p[b] && q > a) || (p[q] > p[b] && q < a)) { goodCnt++; } if ((p[q] < p[a] && q > b) || (p[q] > p[a] && q < b)) { goodCnt++; } } if ((a < b && p[a] > p[b]) || (a > b && p[a] < p[b])) { goodCnt--; } else { goodCnt++; } ans[j] += goodCnt; add(a, -1, j); add(b, -1, j); int tmp = p[a]; p[a] = p[b]; p[b] = tmp; add(a, +1, j); add(b, +1, j); } sum.clear(); Arrays.sort(queryL, 0, queryLCnt, ascCmp); int curL = 0; for (int j = 0; j < n; j++) { if (!good[j]) { sum.add(p[j], 1); } for (; curL < queryLCnt; curL++) { ToProcess cur = queryL[curL]; if (cur.x != j) { break; } int res = sum.sum(cur.y1, cur.y2); res *= cur.sgn; preAns[cur.id] += res; } } sum.clear(); Arrays.sort(queryR, 0, queryRCnt, descCmp); int curR = 0; for (int j = n-1; j >= 0; j--) { if (!good[j]) { sum.add(p[j], 1); } for (; curR < queryRCnt; curR++) { ToProcess cur = queryR[curR]; if (cur.x != j) { break; } int res = sum.sum(cur.y1, cur.y2); res *= cur.sgn; preAns[cur.id] += res; } } for (int j = i; j < iEnd; j++) { if (j != i) { preAns[j] += preAns[j-1]; } ans[j] += cnt + preAns[j]; } cnt = ans[iEnd - 1]; } for (int i = 0; i < q; i++) { writer.write(Long.toString(ans[i])); writer.newLine(); } reader.close(); writer.close(); } } class SQRTDecomposition { private int n; private int sz; private int[] val; private int[] blocks; public final void add(int v, int delta) { val[v] += delta; blocks[v / sz] += delta; } public final int sum(int l, int r) { if (l < 0) { l = 0; } if (r >= n) { r = n; } r++; int res = 0; int lBlock = (l + sz - 1) / sz, rBlock = r / sz; for (int i = lBlock; i < rBlock; i++) { res += blocks[i]; } int lBlockR = lBlock * sz, rBlockR = rBlock * sz; if (lBlockR >= rBlockR) { for (int i = l; i < r; i++) { res += val[i]; } } else { for (int i = l; i < lBlockR; i++) { res += val[i]; } for (int i = rBlockR; i < r; i++) { res += val[i]; } } return res; } public void clear() { Arrays.fill(val, 0); Arrays.fill(blocks, 0); } SQRTDecomposition(int pN, int pSz) { n = pN; sz = pSz; val = new int[n]; blocks = new int[(n + sz - 1) / sz]; } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
99e9e1079b4fd9284b614d10741f1bf7
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class AntonPermutation { int n, q, b, m; int[] a; int[][] bit; void solve() { n = in.nextInt(); q = in.nextInt(); b = (int) (Math.sqrt(n) + 0.5); m = (n + b - 1) / b; a = new int[n]; bit = new int[m][n]; for (int i = 0; i < n; i++) { a[i] = n - 1 - i; update(i, 1); } long ans = 0; while (q-- > 0) { int l = in.nextInt() - 1, r = in.nextInt() - 1; if (l != r) { if (l > r) { int tmp = l; l = r; r = tmp; } ans -= query(l) + query(r); update(l, -1); update(r, -1); int tmp = a[l]; a[l] = a[r]; a[r] = tmp; update(l, 1); update(r, 1); ans += query(l) + query(r); ans += a[l] < a[r] ? -1 : 1; } out.println(ans); } } void update(int i, int v) { update(i / b, a[i], v); } void update(int i, int j, int v) { for (int x = i; x < m; x = x | (x + 1)) { for (int y = j; y < n; y = y | (y + 1)) { bit[x][y] += v; } } } int query(int i) { int L = query(i / b - 1, a[i]); for (int j = i / b * b; j < i; j++) { if (a[j] < a[i]) L++; } int R = (n - i - 1) - (a[i] - L); return L + R; } int query(int i, int j) { int sum = 0; for (int x = i; x >= 0; x = (x & (x + 1)) - 1) { for (int y = j; y >= 0; y = (y & (y + 1)) - 1) { sum += bit[x][y]; } } return sum; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new AntonPermutation().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
f7e252bcede8296881af71295d5e036b
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; /** * * @author usquare */ public class E785 { static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; static int[][] bit; static void update(int ind,int i,int d){ for(;i<bit[ind].length;i+=(i&-i)) bit[ind][i]+=d; } static int query(int ind,int i){ int ans=0; for(;i>0;i-=(i&-i)) ans+=bit[ind][i]; return ans; } public static void main(String[] args) throws FileNotFoundException { in = new InputReader(System.in); out = new PrintWriter(System.out); int n=in.ni(); int q=in.ni(); int sqrt=(int) Math.sqrt(n); int[] arr=new int[n+1]; bit=new int[n/sqrt+1][n+1]; for(int i=1;i<=n;i++){ arr[i]=i; update(i/sqrt, i, 1); } long ans=0; while(q-->0){ int l=in.ni(); int r=in.ni(); if(l==r){ out.println(ans); continue; } if(l>r){ l=l^r; r=l^r; l=l^r; } int ls=l/sqrt; int rs=r/sqrt; for(int i=ls+1;i<rs;i++){ ans-=2*query(i, arr[l]); ans+=2*query(i, arr[r]); } int j=l+1; while(j<r && j/sqrt==ls){ if(arr[j]<arr[l]) ans--; else ans++; if(ls!=rs){ if(arr[j]<arr[r]) ans++; else ans--; } j++; } j=r-1; while(j>l && j/sqrt==rs){ if(arr[j]>arr[r]) ans--; else ans++; if(ls!=rs){ if(arr[j]>arr[l]) ans++; else ans--; } j--; } update(ls, arr[l], -1); update(rs, arr[r], -1); if(arr[l]>arr[r]) ans--; else ans++; arr[l]=arr[l]^arr[r]; arr[r]=arr[l]^arr[r]; arr[l]=arr[l]^arr[r]; update(ls, arr[l], 1); update(rs, arr[r], 1); out.println(ans); } out.close(); } static class Pair implements Comparable<Pair>{ int x; int y,i; Pair (int x,int y,int i){ this.x=x; this.y=y; this.i=i; } Pair (int x,int y){ this.x=x; this.y=y; } public int compareTo(Pair o) { return Long.compare(this.y,o.y); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y == y && p.i==i; } return false; } @Override public String toString() { return x+" "+y+" "+i; } } static class Merge { public static void sort(long inputArr[]) { int length = inputArr.length; doMergeSort(inputArr,0, length - 1); } private static void doMergeSort(long[] arr,int lowerIndex, int higherIndex) { if (lowerIndex < higherIndex) { int middle = lowerIndex + (higherIndex - lowerIndex) / 2; doMergeSort(arr,lowerIndex, middle); doMergeSort(arr,middle + 1, higherIndex); mergeParts(arr,lowerIndex, middle, higherIndex); } } private static void mergeParts(long[]array,int lowerIndex, int middle, int higherIndex) { long[] temp=new long[higherIndex-lowerIndex+1]; for (int i = lowerIndex; i <= higherIndex; i++) { temp[i-lowerIndex] = array[i]; } int i = lowerIndex; int j = middle + 1; int k = lowerIndex; while (i <= middle && j <= higherIndex) { if (temp[i-lowerIndex] < temp[j-lowerIndex]) { array[k] = temp[i-lowerIndex]; i++; } else { array[k] = temp[j-lowerIndex]; j++; } k++; } while (i <= middle) { array[k] = temp[i-lowerIndex]; k++; i++; } while(j<=higherIndex){ array[k]=temp[j-lowerIndex]; k++; j++; } } } static long add(long a,long b){ long x=(a+b); while(x>=mod) x-=mod; return x; } static long sub(long a,long b){ long x=(a-b); while(x<0) x+=mod; return x; } static long mul(long a,long b){ a%=mod; b%=mod; long x=(a*b); return x%mod; } static boolean isPal(String s){ for(int i=0, j=s.length()-1;i<=j;i++,j--){ if(s.charAt(i)!=s.charAt(j)) return false; } return true; } static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } static long gcd(long x,long y){ if(y==0) return x; else return gcd(y,x%y); } static int gcd(int x,int y){ if(y==0) return x; else return gcd(y,x%y); } static long gcdExtended(long a,long b,long[] x){ if(a==0){ x[0]=0; x[1]=1; return b; } long[] y=new long[2]; long gcd=gcdExtended(b%a, a, y); x[0]=y[1]-(b/a)*y[0]; x[1]=y[0]; return gcd; } static long mulmod(long a,long b,long m) { if (m <= 1000000009) return a * b % m; long res = 0; while (a > 0) { if ((a&1)!=0) { res += b; if (res >= m) res -= m; } a >>= 1; b <<= 1; if (b >= m) b -= m; } return res; } static int abs(int a,int b){ return (int)Math.abs(a-b); } public static long abs(long a,long b){ return (long)Math.abs(a-b); } static int max(int a,int b){ if(a>b) return a; else return b; } static int min(int a,int b){ if(a>b) return b; else return a; } static long max(long a,long b){ if(a>b) return a; else return b; } static long min(long a,long b){ if(a>b) return b; else return a; } static long pow(long n,long p,long m){ long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } static long pow(long n,long p){ long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nl(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
2688ce44c33c88a54e60ff5e692b368d
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
import java.io.*; import java.util.*; public class CF785E { // http://codeforces.com/contest/785/submission/25535933 (Narenji58) int[] aa, bb; int n, k; int search(int i, int j, int a) { int lower = i - 1, upper = j; while (upper - lower > 1) { int m = (lower + upper) / 2; if (bb[m] <= a) lower = m; else upper = m; } return lower; } int count(int i, int j, int lower, int upper) { int cnt = 0; for (; i < j && i % k > 0; i++) if (aa[i] > lower && aa[i] < upper) cnt++; for (; i / k < j / k; i += k) cnt += search(i, i + k, upper) - search(i, i + k, lower); for (; i < j; i++) if (aa[i] > lower && aa[i] < upper) cnt++; return cnt; } void update(int x, int a, int b) { int i = x / k * k, j = Math.min(i + k, n); int h = search(i, j, a); if (a < b) while (h + 1 < j && bb[h + 1] < b) { bb[h] = bb[h + 1]; h++; } else while (h - 1 >= i && bb[h - 1] > b) { bb[h] = bb[h - 1]; h--; } bb[h] = b; } public static void main(String[] args) throws IOException { new CF785E().solve(); } void solve() throws IOException { MyReader mr = new MyReader(); PrintWriter pw = new PrintWriter(System.out); n = mr.nextInt(); int q = mr.nextInt(); aa = new int[n]; bb = new int[n]; for (int i = 0; i < n; i++) aa[i] = bb[i] = i; k = (int) Math.sqrt(n * 3); long cnt = 0; while (q-- > 0) { int l = mr.nextInt() - 1; int r = mr.nextInt() - 1; if (l != r) { int i, j, tmp; if (l > r) { tmp = l; l = r; r = tmp; } if (aa[l] < aa[r]) cnt += count(l + 1, r, aa[l], aa[r]) * 2 + 1; else cnt -= count(l + 1, r, aa[r], aa[l]) * 2 + 1; if (l / k != r / k) { update(l, aa[l], aa[r]); update(r, aa[r], aa[l]); } tmp = aa[l]; aa[l] = aa[r]; aa[r] = tmp; } pw.println(cnt); } pw.close(); } static class MyReader { byte[] bb = new byte[1 << 15]; int k, l; byte read() throws IOException { if (k >= l) { k = 0; l = System.in.read(bb); } return bb[k++]; } private int skip() throws IOException { int b; while ((b = read()) <= 32) ; return b; } int nextInt() throws IOException { int n = 0; for (int b = skip(); b > 32; b = read()) n = n * 10 + b - '0'; return n; } } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
806c0ed375dd8eabcc1a1f66d672fd54
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
import java.io.*; public class CF785E { static int[] aa; static int[][] tt; static int n, k, m; static void update(int i, int j_, int a) { while (i < m) { int j = j_; while (j < n) { tt[i][j] += a; j |= j + 1; } i |= i + 1; } } static int query(int i, int j_) { int sum = 0; while (i >= 0) { int j = j_; while (j >= 0) { sum += tt[i][j]; j &= j + 1; j--; } i &= i + 1; i--; } return sum; } static void update(int i, int a) { update(i / k, aa[i], a); } static int query(int i) { int cnt = query(i / k - 1, aa[i]); for (int j = i / k * k; j < i; j++) if (aa[j] < aa[i]) cnt++; return cnt * 2 + aa[i] - i; // magic } public static void main(String[] args) throws IOException { MyReader mr = new MyReader(); PrintWriter pw = new PrintWriter(System.out); n = mr.nextInt(); int q = mr.nextInt(); k = (int) Math.sqrt(n); m = (n - 1) / k + 1; aa = new int[n]; tt = new int[m][n]; for (int i = 0; i < n; i++) { aa[i] = n - 1 - i; update(i, 1); } long cnt = 0; while (q-- > 0) { int l = mr.nextInt() - 1; int r = mr.nextInt() - 1; if (l != r) { int i, j, tmp; if (l > r) { tmp = l; l = r; r = tmp; } cnt -= query(l) + query(r); update(l, -1); update(r, -1); tmp = aa[l]; aa[l] = aa[r]; aa[r] = tmp; cnt += aa[l] < aa[r] ? -1 : 1; // cancel double count update(l, 1); update(r, 1); cnt += query(l) + query(r); } pw.println(cnt); } pw.close(); } static class MyReader { byte[] bb = new byte[1 << 15]; int k, l; byte read() throws IOException { if (k >= l) { k = 0; l = System.in.read(bb); } return bb[k++]; } private int skip() throws IOException { int b; while ((b = read()) <= 32) ; return b; } int nextInt() throws IOException { int n = 0; for (int b = skip(); b > 32; b = read()) n = n * 10 + b - '0'; return n; } } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
01bcfeec016ceef129fc4799236df508
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
import java.util.*; public class E{ final int MAXN = (int)2e5 + 10, SQ = 333; int[] a = new int[MAXN], b = new int[MAXN]; int n; int bs(int l, int r, int x){ int lo = 0, hi = r-l+1; while (hi-lo>1){ int mid = hi+lo>>1; if (b[l+mid - 1] < x) lo = mid; else hi = mid; } return lo; } int get(int l, int r, int x){ int ret = 0; for (; l%SQ>0 && l < r; l++) if (a[l] < x) ret++; for (; l/SQ != r/SQ; l += SQ) ret += bs(l, l+SQ, x); for (; l<r; l++) if (a[l] < x) ret++; return ret; } void solve(){ Scanner sc = new Scanner(System.in); n = sc.nextInt(); int q = sc.nextInt(); for (int i = 0; i < n; i++) a[i] = b[i] = i; long ans = 0; while (q-->0){ int u = sc.nextInt(), v = sc.nextInt(); u--; v--; if (u > v){ int temp = u; u = v; v = temp; } if (u != v){ int temp = get(u, v, a[v]); ans += temp; ans -= (v-u-temp); temp = get(u+1, v, a[u]); ans -= temp; ans += (v-u-1-temp); { temp = a[u]; a[u] = a[v]; a[v] = temp; } int l = u/SQ*SQ; for (int i = l; i < l+SQ && i < n; i++) b[i] = a[i]; Arrays.sort(b, l, Math.min(l+SQ, n)); l = v/SQ*SQ; for (int i = l; i < l+SQ && i < n; i++) b[i] = a[i]; Arrays.sort(b, l, Math.min(l+SQ, n)); } System.out.println(ans);//XXX } } public static void main(String[] argc){ E sol = new E(); sol.solve(); } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
dc029947a4d950ebfc0b0e5dfc18f93d
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
/* Used 2d-BIT and square-root decomsition. 1st devide the array into sqrt(n) blocks. now we have to sqrt(n) blocks. Each block has a BIT. to fasten the update operation in all the blocks, used 2d-BIT. */ import java.util.*; import java.io.*; public class CF785E_5{ public static int sqrt, maxn, bit[][], arr[]; public static void main(String[] args)throws Exception { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(), q = in.nextInt(); sqrt = 1 + (int)Math.sqrt(n); maxn = n+5; bit = new int[sqrt+5][maxn]; arr = new int[maxn]; long ans = 0; for(int i = 1; i <= n; i++){ arr[i] = i; } for(int i = 1; i <= n; i++){ int j = i / sqrt; if(i % sqrt != 0) j++; update(j, arr[i], 1); } for(int qq = 1; qq <= q; qq++){ int l1 = in.nextInt(), r1 = in.nextInt(); if(l1 > r1){ int t = l1; l1 = r1; r1 = t; } int ls1 = l1 / sqrt, rs1 = r1 / sqrt; if(l1 % sqrt != 0) ls1++; if(r1 % sqrt != 0) rs1++; int l = l1+1, r = r1-1; int ls = l / sqrt, rs = r / sqrt; if(l % sqrt != 0) ls++; if(r % sqrt != 0) rs++; ans -= getBigger(l, r, ls, rs, n, arr[r1]); ans -= getSmaller(l, r, ls, rs, n, arr[l1]); ans += getBigger(l, r, ls, rs, n, arr[l1]); ans += getSmaller(l, r, ls, rs, n, arr[r1]); if(arr[l1] > arr[r1]) ans--; else if(arr[r1] > arr[l1]) ans++; // for(int i = ls1; i < rs1; i++){ // update(i, arr[l1], -1); // } update(ls1, arr[l1], -1); update(rs1, arr[l1], 1); // // for(int i = ls1; i < rs1; i++){ // update(i, arr[r1], 1); // } update(ls1, arr[r1], 1); update(rs1, arr[r1], -1); int temp = arr[l1]; arr[l1] = arr[r1]; arr[r1] = temp; pw.println(ans); } pw.close(); } static int getBigger(int l, int r, int ls, int rs, int n, int num){ int cnt = 0; if(rs-ls <= 1){ for(int i = l; i <= r; i++){ if(arr[i] > num) cnt++; } return cnt; } else{ cnt += query(rs-1, num+1, n); cnt -= query(ls, num+1, n); for(int i = l; i <= (ls)*sqrt; i++){ if(arr[i] > num) cnt++; } for(int i = (rs-1)*sqrt+1; i <= r; i++){ if(arr[i] > num) cnt++; } return cnt; } } static int getSmaller(int l, int r, int ls, int rs, int n, int num){ int cnt = 0; if(rs-ls <= 1){ for(int i = l; i <= r; i++){ if(arr[i] < num) cnt++; } return cnt; } else{ cnt += query(rs-1, 1, num-1); cnt -= query(ls, 1, num-1); for(int i = l; i <= (ls)*sqrt; i++){ if(arr[i] < num) cnt++; } for(int i = (rs-1)*sqrt+1; i <= r; i++){ if(arr[i] < num) cnt++; } return cnt; } } public static void update(int x, int y, int val){ int y1; while (x < bit.length){ y1 = y; while (y1 < bit[x].length){ bit[x][y1] += val; y1 += (y1 & -y1); } x += (x & -x); } } public static int getSum(int x, int y){ int sum= 0; while( x > 0){ int y1 = y; while(y1 > 0){ sum += bit[x][y1]; y1 -= y1 & -y1; } x -= x & -x; } return sum; } public static int query(int x, int l, int r){ return getSum(x, r) -getSum(x, l-1); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next()throws Exception { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public String nextLine()throws Exception { String line = null; tokenizer = null; line = reader.readLine(); return line; } public int nextInt()throws Exception { return Integer.parseInt(next()); } public double nextDouble() throws Exception{ return Double.parseDouble(next()); } public long nextLong()throws Exception { return Long.parseLong(next()); } } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
7cdf5e9c0f76b488a39aaafec2fa026d
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
import java.util.*; import java.io.*; public class CF785E_5{ public static int sqrt, maxn, bit[][], arr[]; public static void main(String[] args)throws Exception { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(), q = in.nextInt(); sqrt = 1 + (int)Math.sqrt(n); maxn = 200000+5; bit = new int[sqrt+5][maxn]; arr = new int[maxn]; long ans = 0; for(int i = 1; i <= n; i++){ arr[i] = i; } for(int i = 1; i <= n; i++){ int j = i / sqrt; if(i % sqrt != 0) j++; // for(; j <= sqrt; j++){ // update(j, arr[i], 1); // } update(j, arr[i], 1); } for(int qq = 1; qq <= q; qq++){ int l1 = in.nextInt(), r1 = in.nextInt(); if(l1 > r1){ int t = l1; l1 = r1; r1 = t; } int ls1 = l1 / sqrt, rs1 = r1 / sqrt; if(l1 % sqrt != 0) ls1++; if(r1 % sqrt != 0) rs1++; int l = l1+1, r = r1-1; int ls = l / sqrt, rs = r / sqrt; if(l % sqrt != 0) ls++; if(r % sqrt != 0) rs++; ans -= getBigger(l, r, ls, rs, n, arr[r1]); //pw.println(ans+" "+arr[r1]+" "+getBigger(l, r, ls, rs, n, arr[r1])); ans -= getSmaller(l, r, ls, rs, n, arr[l1]); //pw.println(ans+" "+arr[l1]+" "+getSmaller(l, r, ls, rs, n, arr[l1])); ans += getBigger(l, r, ls, rs, n, arr[l1]); ans += getSmaller(l, r, ls, rs, n, arr[r1]); if(arr[l1] > arr[r1]) ans--; else if(arr[r1] > arr[l1]) ans++; // for(int i = ls1; i < rs1; i++){ // update(i, arr[l1], -1); // } update(ls1, arr[l1], -1); update(rs1, arr[l1], 1); // // for(int i = ls1; i < rs1; i++){ // update(i, arr[r1], 1); // } update(ls1, arr[r1], 1); update(rs1, arr[r1], -1); int temp = arr[l1]; arr[l1] = arr[r1]; arr[r1] = temp; pw.println(ans); //pw.println(Arrays.toString(arr)); } pw.close(); } static int getBigger(int l, int r, int ls, int rs, int n, int num){ int cnt = 0; if(rs-ls <= 1){ for(int i = l; i <= r; i++){ if(arr[i] > num) cnt++; } return cnt; } else{ cnt += query(rs-1, num+1, n); //if(num == 3) System.err.println(cnt+" "+query(rs-1, num+1, n)); cnt -= query(ls, num+1, n); //if(num == 3)System.err.println(cnt+" "+query(ls, num+1, n)); for(int i = l; i <= (ls)*sqrt; i++){ if(arr[i] > num) cnt++; } for(int i = (rs-1)*sqrt+1; i <= r; i++){ if(arr[i] > num) cnt++; } return cnt; } } static int getSmaller(int l, int r, int ls, int rs, int n, int num){ int cnt = 0; if(rs-ls <= 1){ for(int i = l; i <= r; i++){ if(arr[i] < num) cnt++; } return cnt; } else{ cnt += query(rs-1, 1, num-1); //if(num == 3) System.err.println(cnt+" "+query(rs-1, num+1, n)); cnt -= query(ls, 1, num-1); //if(num == 3)System.err.println(cnt+" "+query(ls, num+1, n)); for(int i = l; i <= (ls)*sqrt; i++){ if(arr[i] < num) cnt++; } for(int i = (rs-1)*sqrt+1; i <= r; i++){ if(arr[i] < num) cnt++; } return cnt; } } /* static void update(int x, int y, int val){ //update }*/ public static void update(int x, int y, int val){ int y1; while (x < bit.length){ y1 = y; while (y1 < bit[x].length){ bit[x][y1] += val; y1 += (y1 & -y1); } x += (x & -x); } } public static int getSum(int x, int y){ //return sum form 1,1 int sum= 0; while( x > 0){ int y1 = y; while(y1 > 0){ sum += bit[x][y1]; y1 -= y1 & -y1; } x -= x & -x; } return sum; } public static int query(int x, int l, int r){ int p = getSum(x, r); int q = getSum(x, l-1); return p - q; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next()throws Exception { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public String nextLine()throws Exception { String line = null; tokenizer = null; line = reader.readLine(); return line; } public int nextInt()throws Exception { return Integer.parseInt(next()); } public double nextDouble() throws Exception{ return Double.parseDouble(next()); } public long nextLong()throws Exception { return Long.parseLong(next()); } } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
5c12a9945da372a52047411b5a3eb28c
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
//package round404; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; public class E2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int Q = ni(); int[][] qs = new int[Q][]; for(int i = 0;i < Q;i++){ qs[i] = new int[]{ni()-1, ni()-1}; if(qs[i][0] > qs[i][1]){ int d = qs[i][0]; qs[i][0] = qs[i][1]; qs[i][1] = d; } } int[][] co = new int[n+2*Q][]; { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = i; int p = 0; for(int i = 0;i < n;i++){ co[p++] = new int[]{i, i}; } for(int i = 0;i < Q;i++){ int[] q = qs[i]; int d = a[q[0]]; a[q[0]] = a[q[1]]; a[q[1]] = d; co[p++] = new int[]{q[0], a[q[0]]}; co[p++] = new int[]{q[1], a[q[1]]}; } assert p == co.length; } StaticRangeTreeRSQ srt = new StaticRangeTreeRSQ(co, n+1); int[] a = new int[n]; for(int i = 0;i < n;i++){ a[i] = i; srt.add(i, i, 1); } long inv = 0; for(int i = 0;i < Q;i++){ int[] q = qs[i]; if(q[0] != q[1]){ if(a[q[0]] < a[q[1]]){ inv += srt.sum(q[0]+1, q[1], a[q[0]]+1, a[q[1]])*2 + 1; }else{ inv -= srt.sum(q[0]+1, q[1], a[q[1]]+1, a[q[0]])*2 + 1; } srt.add(q[0], a[q[0]], -1); srt.add(q[1], a[q[1]], -1); int d = a[q[0]]; a[q[0]] = a[q[1]]; a[q[1]] = d; srt.add(q[0], a[q[0]], 1); srt.add(q[1], a[q[1]], 1); } out.println(inv); } } public static class StaticRangeTreeRSQ { public int M, H, N; public int[][] fts; public int[][] maps; public int[] count; public int I = Integer.MAX_VALUE; /** * @param co DESTRUCTIVE * @param n limit of coordinate */ public StaticRangeTreeRSQ(int[][] co, int n) { N = n; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; Arrays.sort(co, new Comparator<int[]>() { // x asc public int compare(int[] a, int[] b) { if(a[0] != b[0])return a[0] - b[0]; return a[1] - b[1]; } }); int p = co.length; // int p = 0; // for(int i = 0;i < co.length;i++){ // if(i == 0 || !(co[i][0] == co[i-1][0] && co[i][1] == co[i-1][1])){ // co[p++] = co[i]; // } // } maps = new int[M][]; fts = new int[M][]; count = new int[M]; for(int i = 0;i < p;i++){ count[H+co[i][0]]++; } int off = 0; for(int i = 0;i < n;i++){ maps[H+i] = new int[count[H+i]]; for(int j = 0;j < count[H+i];j++,off++){ maps[H+i][j] = co[off][1]; } fts[H+i] = new int[count[H+i]+1]; } for(int i = H-1;i >= 1;i--){ if(maps[2*i+1] == null){ maps[i] = maps[2*i]; count[i] = count[2*i]; }else{ count[i] = count[2*i] + count[2*i+1]; maps[i] = new int[count[i]]; int l = 0; int j = 0, k = 0; while(j < count[2*i] && k < count[2*i+1]){ if(maps[2*i][j] < maps[2*i+1][k]){ maps[i][l++] = maps[2*i][j++]; }else if(maps[2*i][j] > maps[2*i+1][k]){ maps[i][l++] = maps[2*i+1][k++]; }else{ maps[i][l++] = maps[2*i][j++]; k++; } } while(j < count[2*i])maps[i][l++] = maps[2*i][j++]; while(k < count[2*i+1])maps[i][l++] = maps[2*i+1][k++]; if(l != count[i]){ // uniq count[i] = l; maps[i] = Arrays.copyOf(maps[i], l); } } fts[i] = new int[count[i]+1]; } } public void add(int x, int y, int v) { for(int pos = H+x;pos >= 1;pos>>>=1){ int ind = Arrays.binarySearch(maps[pos], y); if(ind >= 0){ addFenwick(fts[pos], ind, v); }else{ throw new RuntimeException(String.format("access to non-existing point : (%d,%d):%d", x, y, v)); } } } public long gsum; // [xl,xr)*[yl,yr) public long sum(int xl, int xr, int yl, int yr) { gsum = 0; sum(xl, xr, yl, yr, 0, H, 1); return gsum; } public void sum(int xl, int xr, int yl, int yr, int cl, int cr, int cur) { if(xl <= cl && cr <= xr){ int indl = Arrays.binarySearch(maps[cur], yl-1); int indr = Arrays.binarySearch(maps[cur], yr-1); if(indl < 0)indl = -indl - 2; if(indr < 0)indr = -indr - 2; gsum += sumFenwick(fts[cur], indr) - sumFenwick(fts[cur], indl); }else{ int mid = cl+cr>>>1; if(cl < xr && xl < mid)sum(xl, xr, yl, yr, cl, mid, 2*cur); if(mid < xr && xl < cr)sum(xl, xr, yl, yr, mid, cr, 2*cur+1); } } public static int sumFenwick(int[] ft, int i) { int sum = 0; for(i++;i > 0;i -= i&-i)sum += ft[i]; return sum; } public static void addFenwick(int[] ft, int i, int v) { if(v == 0 || i < 0)return; int n = ft.length; for(i++;i < n;i += i&-i)ft[i] += v; } } 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 E2().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
837912a44b9de2c4bf0fb99907fbc79b
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
//package round404; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; public class E { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int Q = ni(); int[][] qs = new int[Q][]; for(int i = 0;i < Q;i++){ qs[i] = new int[]{ni()-1, ni()-1}; if(qs[i][0] > qs[i][1]){ int d = qs[i][0]; qs[i][0] = qs[i][1]; qs[i][1] = d; } } int[][] co = new int[n+2*Q][]; { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = i; int p = 0; for(int i = 0;i < n;i++){ co[p++] = new int[]{i, i}; } for(int i = 0;i < Q;i++){ int[] q = qs[i]; int d = a[q[0]]; a[q[0]] = a[q[1]]; a[q[1]] = d; co[p++] = new int[]{q[0], a[q[0]]}; co[p++] = new int[]{q[1], a[q[1]]}; } assert p == co.length; } StaticRangeTreeRSQ srt = new StaticRangeTreeRSQ(co, n+1); int[] a = new int[n]; for(int i = 0;i < n;i++){ a[i] = i; srt.add(i, i, 1); } long inv = 0; for(int i = 0;i < Q;i++){ int[] q = qs[i]; if(q[0] != q[1]){ if(a[q[0]] < a[q[1]]){ inv += srt.sum(q[0]+1, q[1], a[q[0]]+1, a[q[1]])*2 + 1; }else{ inv -= srt.sum(q[0]+1, q[1], a[q[1]]+1, a[q[0]])*2 + 1; } srt.add(q[0], a[q[0]], -1); srt.add(q[1], a[q[1]], -1); int d = a[q[0]]; a[q[0]] = a[q[1]]; a[q[1]] = d; srt.add(q[0], a[q[0]], 1); srt.add(q[1], a[q[1]], 1); } out.println(inv); } } public static class StaticRangeTreeRSQ { public int M, H, N; public int[][] fts; public int[][] maps; public int[] count; public int I = Integer.MAX_VALUE; /** * @param co DESTRUCTIVE * @param n limit of coordinate */ public StaticRangeTreeRSQ(int[][] co, int n) { N = n; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; Arrays.sort(co, new Comparator<int[]>() { // x asc public int compare(int[] a, int[] b) { if(a[0] != b[0])return a[0] - b[0]; return a[1] - b[1]; } }); int p = 0; for(int i = 0;i < co.length;i++){ if(i == 0 || !(co[i][0] == co[i-1][0] && co[i][1] == co[i-1][1])){ co[p++] = co[i]; } } maps = new int[M][]; fts = new int[M][]; count = new int[M]; for(int i = 0;i < p;i++){ count[H+co[i][0]]++; } int off = 0; for(int i = 0;i < n;i++){ maps[H+i] = new int[count[H+i]]; for(int j = 0;j < count[H+i];j++,off++){ maps[H+i][j] = co[off][1]; } fts[H+i] = new int[count[H+i]+1]; } for(int i = H-1;i >= 1;i--){ if(maps[2*i+1] == null){ maps[i] = maps[2*i]; count[i] = count[2*i]; }else{ count[i] = count[2*i] + count[2*i+1]; maps[i] = new int[count[i]]; int l = 0; int j = 0, k = 0; while(j < count[2*i] && k < count[2*i+1]){ if(maps[2*i][j] < maps[2*i+1][k]){ maps[i][l++] = maps[2*i][j++]; }else if(maps[2*i][j] > maps[2*i+1][k]){ maps[i][l++] = maps[2*i+1][k++]; }else{ maps[i][l++] = maps[2*i][j++]; k++; } } while(j < count[2*i])maps[i][l++] = maps[2*i][j++]; while(k < count[2*i+1])maps[i][l++] = maps[2*i+1][k++]; if(l != count[i]){ // uniq count[i] = l; maps[i] = Arrays.copyOf(maps[i], l); } } fts[i] = new int[count[i]+1]; } } public void add(int x, int y, int v) { for(int pos = H+x;pos >= 1;pos>>>=1){ int ind = Arrays.binarySearch(maps[pos], y); if(ind >= 0){ addFenwick(fts[pos], ind, v); }else{ throw new RuntimeException(String.format("access to non-existing point : (%d,%d):%d", x, y, v)); } } } public long gsum; // [xl,xr)*[yl,yr) public long sum(int xl, int xr, int yl, int yr) { gsum = 0; sum(xl, xr, yl, yr, 0, H, 1); return gsum; } public void sum(int xl, int xr, int yl, int yr, int cl, int cr, int cur) { if(xl <= cl && cr <= xr){ int indl = Arrays.binarySearch(maps[cur], yl-1); int indr = Arrays.binarySearch(maps[cur], yr-1); if(indl < 0)indl = -indl - 2; if(indr < 0)indr = -indr - 2; gsum += sumFenwick(fts[cur], indr) - sumFenwick(fts[cur], indl); }else{ int mid = cl+cr>>>1; if(cl < xr && xl < mid)sum(xl, xr, yl, yr, cl, mid, 2*cur); if(mid < xr && xl < cr)sum(xl, xr, yl, yr, mid, cr, 2*cur+1); } } public static int sumFenwick(int[] ft, int i) { int sum = 0; for(i++;i > 0;i -= i&-i)sum += ft[i]; return sum; } public static void addFenwick(int[] ft, int i, int v) { if(v == 0 || i < 0)return; int n = ft.length; for(i++;i < n;i += i&-i)ft[i] += v; } } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new E().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
7f824d0e29d6de1dff8f7852abebebfb
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
//package round404; 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 E3 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int Q = ni(); int[][] qs = new int[Q][]; for(int i = 0;i < Q;i++){ qs[i] = new int[]{ni()-1, ni()-1}; if(qs[i][0] > qs[i][1]){ int d = qs[i][0]; qs[i][0] = qs[i][1]; qs[i][1] = d; } } int[][] co = new int[n+2*Q][]; { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = i; int p = 0; for(int i = 0;i < n;i++){ co[p++] = new int[]{i, i}; } for(int i = 0;i < Q;i++){ int[] q = qs[i]; int d = a[q[0]]; a[q[0]] = a[q[1]]; a[q[1]] = d; co[p++] = new int[]{q[0], a[q[0]]}; co[p++] = new int[]{q[1], a[q[1]]}; } assert p == co.length; } StaticRangeTreeRSQ srt = new StaticRangeTreeRSQ(co, n+1); int[] a = new int[n]; for(int i = 0;i < n;i++){ a[i] = i; srt.add(i, i, 1); } long inv = 0; for(int i = 0;i < Q;i++){ int[] q = qs[i]; if(q[0] != q[1]){ if(a[q[0]] < a[q[1]]){ inv += srt.sum(q[0]+1, q[1], a[q[0]]+1, a[q[1]])*2 + 1; }else{ inv -= srt.sum(q[0]+1, q[1], a[q[1]]+1, a[q[0]])*2 + 1; } srt.add(q[0], a[q[0]], -1); srt.add(q[1], a[q[1]], -1); int d = a[q[0]]; a[q[0]] = a[q[1]]; a[q[1]] = d; srt.add(q[0], a[q[0]], 1); srt.add(q[1], a[q[1]], 1); } out.println(inv); } } public static class StaticRangeTreeRSQ { public int M, H, N; public int[][] fts; public int[][] maps; public int[] count; public int I = Integer.MAX_VALUE; /** * @param co DESTRUCTIVE * @param n limit of coordinate */ public StaticRangeTreeRSQ(int[][] co, int n) { N = n; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; // Arrays.sort(co, new Comparator<int[]>() { // x asc // public int compare(int[] a, int[] b) { // if(a[0] != b[0])return a[0] - b[0]; // return a[1] - b[1]; // } // }); mergesort(co, 0, co.length); int p = co.length; // int p = 0; // for(int i = 0;i < co.length;i++){ // if(i == 0 || !(co[i][0] == co[i-1][0] && co[i][1] == co[i-1][1])){ // co[p++] = co[i]; // } // } maps = new int[M][]; fts = new int[M][]; count = new int[M]; for(int i = 0;i < p;i++){ count[H+co[i][0]]++; } int off = 0; for(int i = 0;i < n;i++){ maps[H+i] = new int[count[H+i]]; for(int j = 0;j < count[H+i];j++,off++){ maps[H+i][j] = co[off][1]; } fts[H+i] = new int[count[H+i]+1]; } for(int i = H-1;i >= 1;i--){ if(maps[2*i+1] == null){ maps[i] = maps[2*i]; count[i] = count[2*i]; }else{ count[i] = count[2*i] + count[2*i+1]; maps[i] = new int[count[i]]; int l = 0; int j = 0, k = 0; while(j < count[2*i] && k < count[2*i+1]){ if(maps[2*i][j] < maps[2*i+1][k]){ maps[i][l++] = maps[2*i][j++]; }else if(maps[2*i][j] > maps[2*i+1][k]){ maps[i][l++] = maps[2*i+1][k++]; }else{ maps[i][l++] = maps[2*i][j++]; k++; } } while(j < count[2*i])maps[i][l++] = maps[2*i][j++]; while(k < count[2*i+1])maps[i][l++] = maps[2*i+1][k++]; if(l != count[i]){ // uniq count[i] = l; maps[i] = Arrays.copyOf(maps[i], l); } } fts[i] = new int[count[i]+1]; } } public void add(int x, int y, int v) { for(int pos = H+x;pos >= 1;pos>>>=1){ int ind = Arrays.binarySearch(maps[pos], y); if(ind >= 0){ addFenwick(fts[pos], ind, v); }else{ throw new RuntimeException(String.format("access to non-existing point : (%d,%d):%d", x, y, v)); } } } public long gsum; // [xl,xr)*[yl,yr) public long sum(int xl, int xr, int yl, int yr) { gsum = 0; sum(xl, xr, yl, yr, 0, H, 1); return gsum; } public void sum(int xl, int xr, int yl, int yr, int cl, int cr, int cur) { if(xl <= cl && cr <= xr){ int indl = Arrays.binarySearch(maps[cur], yl-1); int indr = Arrays.binarySearch(maps[cur], yr-1); if(indl < 0)indl = -indl - 2; if(indr < 0)indr = -indr - 2; gsum += sumFenwick(fts[cur], indr) - sumFenwick(fts[cur], indl); }else{ int mid = cl+cr>>>1; if(cl < xr && xl < mid)sum(xl, xr, yl, yr, cl, mid, 2*cur); if(mid < xr && xl < cr)sum(xl, xr, yl, yr, mid, cr, 2*cur+1); } } public static int sumFenwick(int[] ft, int i) { int sum = 0; for(i++;i > 0;i -= i&-i)sum += ft[i]; return sum; } public static void addFenwick(int[] ft, int i, int v) { if(v == 0 || i < 0)return; int n = ft.length; for(i++;i < n;i += i&-i)ft[i] += v; } } static int[][] stemp = new int[300005][]; public static void mergesort(int[][] a, int s, int e) { if(e - s <= 1)return; int h = s+e>>1; mergesort(a, s, h); mergesort(a, h, e); int p = 0; int i= s, j = h; for(;i < h && j < e;)stemp[p++] = a[i][0] < a[j][0] || a[i][0] == a[j][0] && a[i][1] < a[j][1] ? a[i++] : a[j++]; while(i < h)stemp[p++] = a[i++]; while(j < e)stemp[p++] = a[j++]; System.arraycopy(stemp, 0, a, s, e-s); } 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 E3().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
f68188c04539a3964e1a8b5759fa5273
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
import java.io.*; import java.util.*; import java.math.*; public final class anton_and_perm { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); static int block=450; static int[] a,start,end,p; static int[][] bit; static int maxn=(int)(2e5+5); static long res=0; static int n,q; static void update(int idx1,int idx2,int val) { while(idx2<maxn) { bit[idx1][idx2]+=val;idx2+=idx2&-idx2; } } static int query(int idx1,int idx2) { int ret=0; while(idx2>0) { ret=ret+bit[idx1][idx2];idx2-=idx2&-idx2; } return ret; } static void update(int l,int r) { for(int i=p[l]+1;i<p[r];i++) { long val1=query(i,a[l]),val2=n-val1,val3=query(i,a[r]),val4=n-val3; res+=(-val1+val2+val3-val4); } for(int i=l+1;i<=Math.min(r-1,end[p[l]]);i++) { if(a[i]>a[l]) res++; if(a[i]<a[l]) res--; if(a[i]<a[r]) res++; if(a[i]>a[r]) res--; } if(p[r]!=p[l]) { for(int i=start[p[r]];i<r;i++) { if(a[i]>a[l]) res++; if(a[i]<a[l]) res--; if(a[i]<a[r]) res++; if(a[i]>a[r]) res--; } } res=res+(a[l]<a[r]?1:-1); update(p[l],a[l],-1);update(p[l],a[r],1);update(p[r],a[l],1);update(p[r],a[r],-1); int temp=a[l];a[l]=a[r];a[r]=temp; } public static void main(String args[]) throws Exception { n=sc.nextInt();q=sc.nextInt();a=new int[n]; for(int i=0;i<n;i++) { a[i]=i+1; } start=new int[block];end=new int[block];p=new int[n];int curr=0; for(int i=0;i<n;i+=block) { start[curr]=i;end[curr]=Math.min(n-1,i+block-1); for(int j=start[curr];j<=end[curr];j++) { p[j]=curr; } curr++; } bit=new int[block][maxn]; for(int i=0;i<n;i++) { update(p[i],a[i],1); } for(int i=0;i<q;i++) { int l=sc.nextInt()-1,r=sc.nextInt()-1; if(l!=r) { update(Math.min(l,r),Math.max(l,r)); } out.println(res); } out.close(); } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
a088358a6dcc50d2e98d09aaca2af997
train_002.jsonl
1489590300
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i, j) such that 1 ≀ i &lt; j ≀ n and ai &gt; aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1, 2, ..., n}, that is ai = i for all i such that 1 ≀ i ≀ n.
512 megabytes
/* * Author Ayub Subhaniya * Institute DA-IICT */ import java.io.*; import java.math.*; import java.util.*; public class JuneLong{ InputStream in; PrintWriter out; int MAX; int N; void solve() { int n=ni(); int m=ni(); int a[]=new int[n]; for (int i=0;i<n;i++) a[i]=i+1; MAX=n; N=500; //tr(N); FenwickTree ft[]=new FenwickTree[N]; for (int i=0;i<N;i++) ft[i]=new FenwickTree(); for (int j=0;j<N;j++) { for (int i=N*j;i<Math.min(n, N*(j+1));i++) { ft[j].update(a[i],1); } //tr(N*j+" "+(Math.min(n, N*(j+1))-1)); } long temp=0; for (int i=0;i<m;i++) { //tr(a); int a1=ni()-1; int a2=ni()-1; if (a1==a2) { out.println(temp); continue; } if (a1>a2) { int tmp=a1; a1=a2; a2=tmp; } //tr(a1+" "+a2); int bk1=a1/N; int bk2=a2/N; //tr(bk1+" "+bk2); if (bk1==bk2) { for (int j=a1+1;j<a2;j++) { if (a[j]>a[a1]) temp++; else temp--; if (a[j]>a[a2]) temp--; else temp++; } if (a[a1]>a[a2]) temp--; else temp++; out.println(temp); int tmp=a[a1]; a[a1]=a[a2]; a[a2]=tmp; continue; } for (int j=bk1+1;j<bk2;j++) { if (a[a1]>a[a2]) { temp-=(long)ft[j].query(a[a2]+1,a[a1]); temp-=(long)ft[j].query(a[a2],a[a1]-1); } else { temp+=(long)ft[j].query(a[a1]+1,a[a2]); temp+=(long)ft[j].query(a[a1],a[a2]-1); } //tr(temp); } for (int j=a1+1;j< N*(bk1+1);j++) { if (a[j]<a[a1]) temp--; else temp++; if (a[j]<a[a2]) temp++; else temp--; } //tr(temp); for (int j=N*bk2;j<a2;j++) { if (a[j]>a[a2]) temp--; else temp++; if (a[j]>a[a1]) temp++; else temp--; } //tr(temp); if (a[a1]>a[a2]) temp--; else temp++; out.println(temp); ft[bk1].update(a[a1], -1); ft[bk1].update(a[a2], 1); ft[bk2].update(a[a2], -1); ft[bk2].update(a[a1], 1); int tmp=a[a1]; a[a1]=a[a2]; a[a2]=tmp; } } class FenwickTree { int size; int bit[]; FenwickTree() { size = MAX; bit = new int[size + 1]; } void update(int x, int val) { for (; x <= size; x += x & (-x)) bit[x] += val; } int query(int x) { int sum = 0; for (; x > 0; x -= x & (-x)) sum += bit[x]; return sum; } int query(int l,int r) { return query(r)-query(l-1); } } class Merge { void sort(int inputArr[]) { int length = inputArr.length; doMergeSort(inputArr, 0, length - 1); } void doMergeSort(int[] arr, int lowerIndex, int higherIndex) { if (lowerIndex < higherIndex) { int middle = lowerIndex + (higherIndex - lowerIndex) / 2; doMergeSort(arr, lowerIndex, middle); doMergeSort(arr, middle + 1, higherIndex); mergeParts(arr, lowerIndex, middle, higherIndex); } } void mergeParts(int[] array, int lowerIndex, int middle, int higherIndex) { int[] temp = new int[higherIndex - lowerIndex + 1]; for (int i = lowerIndex; i <= higherIndex; i++) { temp[i - lowerIndex] = array[i]; } int i = lowerIndex; int j = middle + 1; int k = lowerIndex; while (i <= middle && j <= higherIndex) { if (temp[i - lowerIndex] < temp[j - lowerIndex]) { array[k] = temp[i - lowerIndex]; i++; } else { array[k] = temp[j - lowerIndex]; j++; } k++; } while (i <= middle) { array[k] = temp[i - lowerIndex]; k++; i++; } while (j <= higherIndex) { array[k] = temp[j - lowerIndex]; k++; j++; } } } void run() throws Exception { String INPUT = "C:/Users/ayubs/Desktop/input.txt"; in = oj ? System.in : new FileInputStream(INPUT); 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 JuneLong().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 = in.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean inSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && inSpaceChar(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 (!(inSpaceChar(b))) { // when nextLine, (inSpaceChar(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 && !(inSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"]
4 seconds
["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"]
NoteConsider the first sample.After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5).After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4).After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
Java 8
standard input
[ "data structures", "brute force" ]
ed9375dfd4749173472c0c18814c2855
The first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 50 000)Β β€” the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1 ≀ li, ri ≀ n)Β β€” the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.
2,200
Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.
standard output
PASSED
d6dbe9c1f06d6c99d69c8e0a3cbe049a
train_002.jsonl
1384156800
Let's assume that we are given an n × m table filled by integers. We'll mark a cell in the i-th row and j-th column as (i, j). Thus, (1, 1) is the upper left cell of the table and (n, m) is the lower right cell. We'll assume that a circle of radius r with the center in cell (i0, j0) is a set of such cells (i, j) that . We'll consider only the circles that do not go beyond the limits of the table, that is, for which r + 1 ≀ i0 ≀ n - r and r + 1 ≀ j0 ≀ m - r. A circle of radius 3 with the center at (4, 5). Find two such non-intersecting circles of the given radius r that the sum of numbers in the cells that belong to these circles is maximum. Two circles intersect if there is a cell that belongs to both circles. As there can be more than one way to choose a pair of circles with the maximum sum, we will also be interested in the number of such pairs. Calculate the number of unordered pairs of circles, for instance, a pair of circles of radius 2 with centers at (3, 4) and (7, 7) is the same pair as the pair of circles of radius 2 with centers at (7, 7) and (3, 4).
256 megabytes
//363E import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class TwoCircles { 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()); int r = Integer.parseInt(st.nextToken()); int[][] t = new int[n][m]; // Table int[][] v = new int[n-2*r][m-2*r]; // Sum per circle int[] w = new int[1+2*r]; // Semicircle width per row int[] d = new int[2*r+1]; // Minimum dy given the value of dx // Get semicircle row width getWidths(w,r); // Get minimum dy given dx getDists(d,w,r); // Get table for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); for (int j = 0; j < m; j++) { t[i][j] = Integer.parseInt(st.nextToken()); } } // Get sum for first circle for (int i = 0; i < 1+2*r; i++) { for (int j = r-w[i]; j <= r+w[i]; j++) { v[0][0] += t[i][j]; } } // Get sums for other circles from row for (int j = 1; j < m-2*r; j++) { v[0][j] = v[0][j-1]; for (int k = 0; k < w.length; k++) { v[0][j] -= t[k][r-w[k]+j-1]; v[0][j] += t[k][r+w[k]+j]; } } // Get sums for other rows for (int i = 1; i < n-2*r; i++) { for (int j = 0; j < m-2*r; j++) { v[i][j] = v[i-1][j]; for (int k = 0; k < 1+2*r; k++) { v[i][j] -= t[r+i-1-w[k]][j+k]; v[i][j] += t[r+i+w[k]][j+k]; } } } // Check pairs int max = Integer.MIN_VALUE; long cnt = 0L; for (int j1 = v[0].length-1; j1 >= 0; j1--) { int cmax = Integer.MIN_VALUE; // Maximum from current column (j1) int ccnt = 0; // Current cmax count for (int i1 = v.length-1; i1 >= 0; i1--) { for (int j2 = 0; j2 < v[0].length; j2++) { int i2; if (abs(j1-j2) < d.length) { i2 = i1+d[abs(j1-j2)]; if (i2 >= v.length) continue; } else if (j1 > j2) { i2 = i1+1; if (i2 >= v.length) continue; } else { i2 = i1; } if (v[i2][j2] > cmax) { ccnt = 1; cmax = v[i2][j2]; } else if (v[i2][j2] == cmax) { ccnt++; } } if (ccnt > 0 && v[i1][j1]+cmax > max) { cnt = ccnt; max = v[i1][j1]+cmax; } else if (v[i1][j1]+cmax == max) { cnt += ccnt; } } } System.out.printf("%d %d\n", max != Integer.MIN_VALUE ? max : 0, cnt); } private static int abs(int i) { return i < 0 ? -i : i; } private static void getDists(int[] d, int[] w, int r) { for (int i = 0; i < d.length; i++) { d[i] = 0; // Dos casos, i <= r e i > r for (int j = (i < r ? 0 : i-r); j <= i && j <= r; j++) { if (w[r+j]+w[r-i+j]+1 > d[i]) { d[i] = w[r+j]+w[r-i+j]+1; } } } } private static void getWidths(int[] w, int r) { int rr = r*r; for (int i = r; i < 2*r+1; i++) { w[i] = (int) Math.sqrt(rr - (i-r)*(i-r)); } for (int i = 0; i < r; i++) { w[i] = w[2*r-i]; } } }
Java
["2 2 0\n1 2\n2 4", "5 6 1\n4 2 1 3 2 6\n2 3 2 4 7 2\n5 2 2 1 1 3\n1 4 3 3 6 4\n5 1 4 2 3 2", "3 3 1\n1 2 3\n4 5 6\n7 8 9"]
4 seconds
["6 2", "34 3", "0 0"]
null
Java 8
standard input
[ "data structures", "implementation", "brute force" ]
a1ef0079119e18de424a81b05b68bb4c
The first line contains three integers n, m and r (2 ≀ n, m ≀ 500, r β‰₯ 0). Each of the following n lines contains m integers from 1 to 1000 each β€” the elements of the table. The rows of the table are listed from top to bottom at the elements in the rows are listed from left to right. It is guaranteed that there is at least one circle of radius r, not going beyond the table limits.
2,500
Print two integers β€” the maximum sum of numbers in the cells that are located into two non-intersecting circles and the number of pairs of non-intersecting circles with the maximum sum. If there isn't a single pair of non-intersecting circles, print 0 0.
standard output
PASSED
d1d855522be19e51af6ecbe94ef9bc07
train_002.jsonl
1572087900
The only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the $$$k$$$ TV shows. You know the schedule for the next $$$n$$$ days: a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show, the episode of which will be shown in $$$i$$$-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $$$d$$$ ($$$1 \le d \le n$$$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $$$d$$$ consecutive days in which all episodes belong to the purchased shows.
256 megabytes
import java.util.*; import java.io.*; public class Main { static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().charAt(0); } public float nextFloat() { return Float.parseFloat(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] intArray = new int[n]; for (int i = 0; i < n; i++) { intArray[i] = nextInt(); } return intArray; } } public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1, in, out); out.close(); } static class Task { public static int q, n, k, d; public static int[] N = new int[200005]; public static int[] check = new int[1000005]; public void solve(int testNumber, InputReader in, PrintWriter out) { int q = in.nextInt(); while (q-- > 0) { n = in.nextInt(); k = in.nextInt(); d = in.nextInt(); int count = 0; int mi = Integer.MAX_VALUE; for (int i = 0; i < d - 1; i++) { N[i] = in.nextInt() - 1; if (check[N[i]] == 0) { count++; } check[N[i]]++; } for (int i = d - 1; i < n; i++) { N[i] = in.nextInt() - 1; if (check[N[i]] == 0) { count++; } check[N[i]]++; if (count < mi) { mi = count; } if (check[N[i - d + 1]] == 1) { count--; } check[N[i - d + 1]]--; } out.println(mi); for (int i = n - d + 1; i < n; i++) { check[N[i]]--; } } } } }
Java
["4\n5 2 2\n1 2 1 2 1\n9 3 3\n3 3 3 2 2 2 1 1 1\n4 10 4\n10 8 6 4\n16 9 8\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3"]
2 seconds
["2\n1\n4\n5"]
NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show $$$1$$$ and on show $$$2$$$. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows $$$3,5,7,8,9$$$, and you will be able to watch shows for the last eight days.
Java 11
standard input
[ "two pointers", "implementation" ]
56da4ec7cd849c4330d188d8c9bd6094
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases in the input. Then $$$t$$$ test case descriptions follow. The first line of each test case contains three integers $$$n, k$$$ and $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show that is broadcasted on the $$$i$$$-th day. It is guaranteed that the sum of the values ​​of $$$n$$$ for all test cases in the input does not exceed $$$100$$$.
1,300
Print $$$t$$$ integers β€” the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $$$d$$$ consecutive days. Please note that it is permissible that you will be able to watch more than $$$d$$$ days in a row.
standard output
PASSED
18a63d9a1de09337f9f01afca9562748
train_002.jsonl
1572087900
The only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the $$$k$$$ TV shows. You know the schedule for the next $$$n$$$ days: a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show, the episode of which will be shown in $$$i$$$-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $$$d$$$ ($$$1 \le d \le n$$$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $$$d$$$ consecutive days in which all episodes belong to the purchased shows.
256 megabytes
import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class TVSubscriptionsB_Hard extends PrintWriter { //this trick improves performances TVSubscriptionsB_Hard() { super(System.out); } public static void main(String[] $) { TVSubscriptionsB_Hard o = new TVSubscriptionsB_Hard(); o.main(); o.flush(); } void main() { Scanner sc = new Scanner(System.in); int count = sc.nextInt(); //use this if just a single test //int count = 1; while (count-- > 0) { final int n = sc.nextInt(); final int k = sc.nextInt(); final int d = sc.nextInt(); final int[] shows = new int[n]; final HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < d; i++) { shows[i] = sc.nextInt(); map.put(shows[i], map.getOrDefault(shows[i], 0) + 1); } int min = map.size(); //the min is the number of different elements in the first d //i now starts from d for (int i = d; i < n; i++) { shows[i] = sc.nextInt(); final int exclude = shows[i - d]; if(shows[i]==exclude){ continue; } map.put(shows[i], map.getOrDefault(shows[i], 0) + 1); if(map.get(exclude)==1){ map.remove(exclude); }else { map.put(exclude, map.get(exclude) - 1); } min = Math.min(min, map.size()); } println(min); } sc.close(); } }
Java
["4\n5 2 2\n1 2 1 2 1\n9 3 3\n3 3 3 2 2 2 1 1 1\n4 10 4\n10 8 6 4\n16 9 8\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3"]
2 seconds
["2\n1\n4\n5"]
NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show $$$1$$$ and on show $$$2$$$. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows $$$3,5,7,8,9$$$, and you will be able to watch shows for the last eight days.
Java 11
standard input
[ "two pointers", "implementation" ]
56da4ec7cd849c4330d188d8c9bd6094
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases in the input. Then $$$t$$$ test case descriptions follow. The first line of each test case contains three integers $$$n, k$$$ and $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show that is broadcasted on the $$$i$$$-th day. It is guaranteed that the sum of the values ​​of $$$n$$$ for all test cases in the input does not exceed $$$100$$$.
1,300
Print $$$t$$$ integers β€” the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $$$d$$$ consecutive days. Please note that it is permissible that you will be able to watch more than $$$d$$$ days in a row.
standard output
PASSED
2d88521308e6fa9b42ecc00fb215b681
train_002.jsonl
1572087900
The only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the $$$k$$$ TV shows. You know the schedule for the next $$$n$$$ days: a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show, the episode of which will be shown in $$$i$$$-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $$$d$$$ ($$$1 \le d \le n$$$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $$$d$$$ consecutive days in which all episodes belong to the purchased shows.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Main{ public static void main(String []args){ Scanner in = new Scanner(System.in); int test; test = in.nextInt(); while(test-->0){ int n, k, d; n = in.nextInt(); k = in.nextInt(); d = in.nextInt(); int []arr = new int[n]; Set<Integer> ss = new HashSet<Integer>(); Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); for(int i=0;i<n;i++){ int input; input = in.nextInt(); arr[i] = input; if(i<d) { ss.add(input); if(mp.containsKey(input)) { int value = mp.get(input); mp.replace(input, value+1); } else{ mp.put(input, 1); } } } int vaue = ss.size(); //System.out.println(ss.size()); for(int i=d;i<n;i++) { //System.out.println(ss.size()); ss.remove(arr[i - d]); ss.add(arr[i]); //System.out.println(mp.get(arr[i-d])); if (mp.get(arr[i - d]) > 1) { ss.add(arr[i-d]); int val = mp.get(arr[i - d]); mp.replace(arr[i - d], val - 1); } else{ int val = mp.get(arr[i - d]); mp.replace(arr[i - d], val - 1); } if (mp.containsKey(arr[i])) { int val = mp.get(arr[i]); mp.replace(arr[i], val + 1); } else { mp.put(arr[i], 1); } //System.out.println((arr[i-d])+ " " +(arr[i]) + " " + ss.size()); vaue = Math.min(vaue, ss.size()); } System.out.println(vaue); } } }
Java
["4\n5 2 2\n1 2 1 2 1\n9 3 3\n3 3 3 2 2 2 1 1 1\n4 10 4\n10 8 6 4\n16 9 8\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3"]
2 seconds
["2\n1\n4\n5"]
NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show $$$1$$$ and on show $$$2$$$. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows $$$3,5,7,8,9$$$, and you will be able to watch shows for the last eight days.
Java 11
standard input
[ "two pointers", "implementation" ]
56da4ec7cd849c4330d188d8c9bd6094
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases in the input. Then $$$t$$$ test case descriptions follow. The first line of each test case contains three integers $$$n, k$$$ and $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show that is broadcasted on the $$$i$$$-th day. It is guaranteed that the sum of the values ​​of $$$n$$$ for all test cases in the input does not exceed $$$100$$$.
1,300
Print $$$t$$$ integers β€” the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $$$d$$$ consecutive days. Please note that it is permissible that you will be able to watch more than $$$d$$$ days in a row.
standard output
PASSED
00465690e25225d1ed0ee824777e37ce
train_002.jsonl
1572087900
The only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the $$$k$$$ TV shows. You know the schedule for the next $$$n$$$ days: a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show, the episode of which will be shown in $$$i$$$-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $$$d$$$ ($$$1 \le d \le n$$$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $$$d$$$ consecutive days in which all episodes belong to the purchased shows.
256 megabytes
// practice with kaiboy import java.io.*; import java.util.*; public class CF1247B2 extends PrintWriter { CF1247B2() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1247B2 o = new CF1247B2(); o.main(); o.flush(); } static final int A = 1000000; void main() { int t = sc.nextInt(); int[] kk = new int[A + 1]; while (t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int d = sc.nextInt(); int[] aa = new int[n]; int ans = d, cnt = 0; for (int i = 0; i < n; i++) { int a = sc.nextInt(); aa[i] = a; if (kk[a]++ == 0) cnt++; if (i >= d - 1) { ans = Math.min(ans, cnt); a = aa[i - d + 1]; if (--kk[a] == 0) cnt--; } } for (int i = 0; i < n; i++) { int a = aa[i]; kk[a] = 0; } println(ans); } } }
Java
["4\n5 2 2\n1 2 1 2 1\n9 3 3\n3 3 3 2 2 2 1 1 1\n4 10 4\n10 8 6 4\n16 9 8\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3"]
2 seconds
["2\n1\n4\n5"]
NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show $$$1$$$ and on show $$$2$$$. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows $$$3,5,7,8,9$$$, and you will be able to watch shows for the last eight days.
Java 11
standard input
[ "two pointers", "implementation" ]
56da4ec7cd849c4330d188d8c9bd6094
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases in the input. Then $$$t$$$ test case descriptions follow. The first line of each test case contains three integers $$$n, k$$$ and $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show that is broadcasted on the $$$i$$$-th day. It is guaranteed that the sum of the values ​​of $$$n$$$ for all test cases in the input does not exceed $$$100$$$.
1,300
Print $$$t$$$ integers β€” the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $$$d$$$ consecutive days. Please note that it is permissible that you will be able to watch more than $$$d$$$ days in a row.
standard output
PASSED
089bace00f63154b6cdf745bd4d56e06
train_002.jsonl
1572087900
The only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the $$$k$$$ TV shows. You know the schedule for the next $$$n$$$ days: a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show, the episode of which will be shown in $$$i$$$-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $$$d$$$ ($$$1 \le d \le n$$$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $$$d$$$ consecutive days in which all episodes belong to the purchased shows.
256 megabytes
import java.util.*; import java.math.*; public class cf { final static int N = (int) (2e5+10); static int t,n,k,d; static Map<Integer,Integer> mp=new HashMap<Integer,Integer>(); static int a[]=new int[N]; public static void main(String[] args) { Scanner scan=new Scanner(System.in); t=scan.nextInt();; while(--t>=0) { n=scan.nextInt();k=scan.nextInt();d=scan.nextInt(); for(int i=1;i<=n;i++) a[i]=scan.nextInt(); mp.clear(); for(int i=1;i<=d;i++) { if(mp.get(a[i])==null) mp.put(a[i], 1); else mp.put(a[i], mp.get(a[i])+1); } int mi=mp.size(); Iterator<Integer> it=mp.keySet().iterator(); for(int i=d+1;i<=n;i++) { if(mp.get(a[i])==null) mp.put(a[i], 1); else mp.put(a[i], mp.get(a[i])+1); int val=mp.get(a[i-d]); if(val==1) mp.remove(a[i-d]); else mp.put(a[i-d],val-1); mi=Math.min(mi,(int)mp.size()); } System.out.println(mi); } } }
Java
["4\n5 2 2\n1 2 1 2 1\n9 3 3\n3 3 3 2 2 2 1 1 1\n4 10 4\n10 8 6 4\n16 9 8\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3"]
2 seconds
["2\n1\n4\n5"]
NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show $$$1$$$ and on show $$$2$$$. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows $$$3,5,7,8,9$$$, and you will be able to watch shows for the last eight days.
Java 11
standard input
[ "two pointers", "implementation" ]
56da4ec7cd849c4330d188d8c9bd6094
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases in the input. Then $$$t$$$ test case descriptions follow. The first line of each test case contains three integers $$$n, k$$$ and $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show that is broadcasted on the $$$i$$$-th day. It is guaranteed that the sum of the values ​​of $$$n$$$ for all test cases in the input does not exceed $$$100$$$.
1,300
Print $$$t$$$ integers β€” the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $$$d$$$ consecutive days. Please note that it is permissible that you will be able to watch more than $$$d$$$ days in a row.
standard output
PASSED
c83b4880f88e40c99b70d348d58db9c3
train_002.jsonl
1572087900
The only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the $$$k$$$ TV shows. You know the schedule for the next $$$n$$$ days: a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show, the episode of which will be shown in $$$i$$$-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $$$d$$$ ($$$1 \le d \le n$$$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $$$d$$$ consecutive days in which all episodes belong to the purchased shows.
256 megabytes
import java.io.*; import java.util.*; public class B { public void solve() throws IOException { int t = nextInt(); while (t-- > 0) { int n = nextInt(), k = nextInt(), d = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } Map<Integer, Integer> p = new HashMap<>(); // int[] pod = new int[k + 1]; int number = 0; for (int i = 0; i < d; i++) { p.putIfAbsent(a[i], 0); if (p.get(a[i]) == 0) number++; p.put(a[i], p.get(a[i]) + 1); // if (pod[a[i]] == 0) number++; // pod[a[i]]++; } int min = number; for (int i = d; i < n; i++) { int c = a[i - d]; // if (pod[a[i]] == 0) number++; // pod[a[i]]++; // pod[c]--; // if (pod[c] == 0) number--; p.putIfAbsent(a[i], 0); if (p.get(a[i]) == 0) number++; p.put(a[i], p.get(a[i]) + 1); p.put(c, p.get(c) - 1); if (p.get(c) == 0) number--; min = Math.min(min, number); } out.println(min); } } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public int[] nextArr(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new B().run(); } }
Java
["4\n5 2 2\n1 2 1 2 1\n9 3 3\n3 3 3 2 2 2 1 1 1\n4 10 4\n10 8 6 4\n16 9 8\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3"]
2 seconds
["2\n1\n4\n5"]
NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show $$$1$$$ and on show $$$2$$$. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows $$$3,5,7,8,9$$$, and you will be able to watch shows for the last eight days.
Java 11
standard input
[ "two pointers", "implementation" ]
56da4ec7cd849c4330d188d8c9bd6094
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases in the input. Then $$$t$$$ test case descriptions follow. The first line of each test case contains three integers $$$n, k$$$ and $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show that is broadcasted on the $$$i$$$-th day. It is guaranteed that the sum of the values ​​of $$$n$$$ for all test cases in the input does not exceed $$$100$$$.
1,300
Print $$$t$$$ integers β€” the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $$$d$$$ consecutive days. Please note that it is permissible that you will be able to watch more than $$$d$$$ days in a row.
standard output
PASSED
488004bffc26849faa956ce76d3a1789
train_002.jsonl
1572087900
The only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the $$$k$$$ TV shows. You know the schedule for the next $$$n$$$ days: a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show, the episode of which will be shown in $$$i$$$-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $$$d$$$ ($$$1 \le d \le n$$$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $$$d$$$ consecutive days in which all episodes belong to the purchased shows.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws Throwable { sc = new Scanner(); pw = new PrintWriter(System.out); int mx = (int) 1e6 + 1; int[] cnt = new int[mx]; int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); sc.nextInt(); int d = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); int cntDistinct = 0; for (int i = 0; i < d; i++) { cnt[a[i]]++; if (cnt[a[i]] == 1) cntDistinct++; } int minDistinct = cntDistinct; for (int i = d; i < n; i++) { cnt[a[i]]++; if (cnt[a[i]] == 1) cntDistinct++; cnt[a[i - d]]--; if (cnt[a[i - d]] == 0) cntDistinct--; minDistinct = Math.min(minDistinct, cntDistinct); } for (int i = n - d; i < n; i++) cnt[a[i]]--; pw.println(minDistinct); } pw.close(); } static Scanner sc; static PrintWriter pw; static class Scanner { StringTokenizer st; BufferedReader br; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String s) throws Throwable { br = new BufferedReader(new FileReader(new File(s))); } String next() throws Throwable { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Throwable { return Integer.parseInt(next()); } long nextLong() throws Throwable { return Long.parseLong(next()); } double nextDouble() throws Throwable { return Double.parseDouble(next()); } } }
Java
["4\n5 2 2\n1 2 1 2 1\n9 3 3\n3 3 3 2 2 2 1 1 1\n4 10 4\n10 8 6 4\n16 9 8\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3"]
2 seconds
["2\n1\n4\n5"]
NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show $$$1$$$ and on show $$$2$$$. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows $$$3,5,7,8,9$$$, and you will be able to watch shows for the last eight days.
Java 11
standard input
[ "two pointers", "implementation" ]
56da4ec7cd849c4330d188d8c9bd6094
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases in the input. Then $$$t$$$ test case descriptions follow. The first line of each test case contains three integers $$$n, k$$$ and $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show that is broadcasted on the $$$i$$$-th day. It is guaranteed that the sum of the values ​​of $$$n$$$ for all test cases in the input does not exceed $$$100$$$.
1,300
Print $$$t$$$ integers β€” the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $$$d$$$ consecutive days. Please note that it is permissible that you will be able to watch more than $$$d$$$ days in a row.
standard output
PASSED
f6e45946989ef989027be8eabe13a584
train_002.jsonl
1572087900
The only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the $$$k$$$ TV shows. You know the schedule for the next $$$n$$$ days: a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show, the episode of which will be shown in $$$i$$$-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $$$d$$$ ($$$1 \le d \le n$$$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $$$d$$$ consecutive days in which all episodes belong to the purchased shows.
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(),k=sc.nextInt(),d=sc.nextInt(); int[]in=sc.takearr(n); HashMap<Integer, Integer>occ=new HashMap<Integer, Integer>(); int distinct=0; for(int i=0;i<d;i++) { if(occ.getOrDefault(in[i], 0)==0) { distinct++; } occ.put(in[i], occ.getOrDefault(in[i], 0)+1); } int ans=distinct; for(int i=d;i<n;i++) { occ.put(in[i-d], occ.getOrDefault(in[i-d], 0)-1); if(occ.getOrDefault(in[i-d], 0)==0) { distinct--; } if(occ.getOrDefault(in[i], 0)==0) { distinct++; } occ.put(in[i], occ.getOrDefault(in[i], 0)+1); ans=Math.min(ans, distinct); } pw.println(ans); } 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[] takearr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt()-1; return in; } public long[] takearrl(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public Integer[] takearrobj(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] takearrlobj(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); } } }
Java
["4\n5 2 2\n1 2 1 2 1\n9 3 3\n3 3 3 2 2 2 1 1 1\n4 10 4\n10 8 6 4\n16 9 8\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3"]
2 seconds
["2\n1\n4\n5"]
NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show $$$1$$$ and on show $$$2$$$. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows $$$3,5,7,8,9$$$, and you will be able to watch shows for the last eight days.
Java 11
standard input
[ "two pointers", "implementation" ]
56da4ec7cd849c4330d188d8c9bd6094
The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) β€” the number of test cases in the input. Then $$$t$$$ test case descriptions follow. The first line of each test case contains three integers $$$n, k$$$ and $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show that is broadcasted on the $$$i$$$-th day. It is guaranteed that the sum of the values ​​of $$$n$$$ for all test cases in the input does not exceed $$$100$$$.
1,300
Print $$$t$$$ integers β€” the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $$$d$$$ consecutive days. Please note that it is permissible that you will be able to watch more than $$$d$$$ days in a row.
standard output
PASSED
187720767162cb5eddc8bfa3fb9cb52f
train_002.jsonl
1588775700
Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal ($$$\forall$$$) and existential ($$$\exists$$$). You can read more about them here.The universal quantifier is used to make a claim that a statement holds for all real numbers. For example: $$$\forall x,x&lt;100$$$ is read as: for all real numbers $$$x$$$, $$$x$$$ is less than $$$100$$$. This statement is false. $$$\forall x,x&gt;x-1$$$ is read as: for all real numbers $$$x$$$, $$$x$$$ is greater than $$$x-1$$$. This statement is true. The existential quantifier is used to make a claim that there exists some real number for which the statement holds. For example: $$$\exists x,x&lt;100$$$ is read as: there exists a real number $$$x$$$ such that $$$x$$$ is less than $$$100$$$. This statement is true. $$$\exists x,x&gt;x-1$$$ is read as: there exists a real number $$$x$$$ such that $$$x$$$ is greater than $$$x-1$$$. This statement is true. Moreover, these quantifiers can be nested. For example: $$$\forall x,\exists y,x&lt;y$$$ is read as: for all real numbers $$$x$$$, there exists a real number $$$y$$$ such that $$$x$$$ is less than $$$y$$$. This statement is true since for every $$$x$$$, there exists $$$y=x+1$$$. $$$\exists y,\forall x,x&lt;y$$$ is read as: there exists a real number $$$y$$$ such that for all real numbers $$$x$$$, $$$x$$$ is less than $$$y$$$. This statement is false because it claims that there is a maximum real number: a number $$$y$$$ larger than every $$$x$$$. Note that the order of variables and quantifiers is important for the meaning and veracity of a statement.There are $$$n$$$ variables $$$x_1,x_2,\ldots,x_n$$$, and you are given some formula of the form $$$$$$ f(x_1,\dots,x_n):=(x_{j_1}&lt;x_{k_1})\land (x_{j_2}&lt;x_{k_2})\land \cdots\land (x_{j_m}&lt;x_{k_m}), $$$$$$where $$$\land$$$ denotes logical AND. That is, $$$f(x_1,\ldots, x_n)$$$ is true if every inequality $$$x_{j_i}&lt;x_{k_i}$$$ holds. Otherwise, if at least one inequality does not hold, then $$$f(x_1,\ldots,x_n)$$$ is false.Your task is to assign quantifiers $$$Q_1,\ldots,Q_n$$$ to either universal ($$$\forall$$$) or existential ($$$\exists$$$) so that the statement $$$$$$ Q_1 x_1, Q_2 x_2, \ldots, Q_n x_n, f(x_1,\ldots, x_n) $$$$$$is true, and the number of universal quantifiers is maximized, or determine that the statement is false for every possible assignment of quantifiers.Note that the order the variables appear in the statement is fixed. For example, if $$$f(x_1,x_2):=(x_1&lt;x_2)$$$ then you are not allowed to make $$$x_2$$$ appear first and use the statement $$$\forall x_2,\exists x_1, x_1&lt;x_2$$$. If you assign $$$Q_1=\exists$$$ and $$$Q_2=\forall$$$, it will only be interpreted as $$$\exists x_1,\forall x_2,x_1&lt;x_2$$$.
256 megabytes
/** * @author derrick20 */ import java.io.*; import java.util.*; public class QuantifierQuestion { public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); int M = sc.nextInt(); adjList = new ArrayList[N]; revAdjList = new ArrayList[N]; Arrays.setAll(adjList, i -> new ArrayList<>()); Arrays.setAll(revAdjList, i -> new ArrayList<>()); for (int i = 0; i < M; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; adjList[u].add(v); revAdjList[v].add(u); } vis = new int[N]; for (int i = 0; i < N; i++) { if (vis[i] == 0) { dfs(i); } } if (hasCycle) { out.println(-1); } else { boolean[] ans = new boolean[N]; boolean[] vis1 = new boolean[N]; boolean[] vis2 = new boolean[N]; for (int u = 0; u < N; u++) { if (!vis1[u] && !vis2[u]) { vis1[u] = true; vis2[u] = true; ans[u] = true; // can start here } // regardless, we need to update our information ArrayDeque<Integer> q = new ArrayDeque<>(); q.add(u); while (q.size() > 0) { int top = q.pollFirst(); for (int adj : adjList[top]) { if (!vis1[adj]) { vis1[adj] = true; q.add(adj); } } } q.clear(); q.add(u); while (q.size() > 0) { int top = q.pollFirst(); for (int adj : revAdjList[top]) { if (!vis2[adj]) { vis2[adj] = true; q.add(adj); } } } } int ct = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < N; i++) { if (ans[i]) { sb.append('A'); ct++; } else { sb.append('E'); } } out.println(ct); out.println(sb); } out.close(); } static ArrayList<Integer>[] adjList, revAdjList; static int[] vis; static boolean hasCycle; static void dfs(int node) { vis[node] = 1; for (int adj : adjList[node]) { if (vis[adj] == 0) { dfs(adj); } else if (vis[adj] == 1) { hasCycle = true; } } vis[node] = 2; } static class FastScanner { private int BS = 1<<16; private char NC = (char)0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt=1; boolean neg = false; if(c==NC)c=getChar(); for(;(c<'0' || c>'9'); c = getChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=getChar()) { res = (res<<3)+(res<<1)+c-'0'; cnt*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/cnt; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c>32) { res.append(c); c=getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c!='\n') { res.append(c); c=getChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=getChar(); if(c==NC)return false; else if(c>32)return true; } } } }
Java
["2 1\n1 2", "4 3\n1 2\n2 3\n3 1", "3 2\n1 3\n2 3"]
1 second
["1\nAE", "-1", "2\nAAE"]
NoteFor the first test, the statement $$$\forall x_1, \exists x_2, x_1&lt;x_2$$$ is true. Answers of "EA" and "AA" give false statements. The answer "EE" gives a true statement, but the number of universal quantifiers in this string is less than in our answer.For the second test, we can show that no assignment of quantifiers, for which the statement is true exists.For the third test, the statement $$$\forall x_1, \forall x_2, \exists x_3, (x_1&lt;x_3)\land (x_2&lt;x_3)$$$ is true: We can set $$$x_3=\max\{x_1,x_2\}+1$$$.
Java 11
standard input
[ "dp", "dfs and similar", "graphs" ]
94e58f3f7aa4d860b95d34c7c9f89058
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2\le n\le 2\cdot 10^5$$$; $$$1\le m\le 2\cdot 10^5$$$)Β β€” the number of variables and the number of inequalities in the formula, respectively. The next $$$m$$$ lines describe the formula. The $$$i$$$-th of these lines contains two integers $$$j_i$$$,$$$k_i$$$ ($$$1\le j_i,k_i\le n$$$, $$$j_i\ne k_i$$$).
2,600
If there is no assignment of quantifiers for which the statement is true, output a single integer $$$-1$$$. Otherwise, on the first line output an integer, the maximum possible number of universal quantifiers. On the next line, output a string of length $$$n$$$, where the $$$i$$$-th character is "A" if $$$Q_i$$$ should be a universal quantifier ($$$\forall$$$), or "E" if $$$Q_i$$$ should be an existential quantifier ($$$\exists$$$). All letters should be upper-case. If there are multiple solutions where the number of universal quantifiers is maximum, print any.
standard output
PASSED
12140b2d3a23892128c58cb6f212597f
train_002.jsonl
1588775700
Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal ($$$\forall$$$) and existential ($$$\exists$$$). You can read more about them here.The universal quantifier is used to make a claim that a statement holds for all real numbers. For example: $$$\forall x,x&lt;100$$$ is read as: for all real numbers $$$x$$$, $$$x$$$ is less than $$$100$$$. This statement is false. $$$\forall x,x&gt;x-1$$$ is read as: for all real numbers $$$x$$$, $$$x$$$ is greater than $$$x-1$$$. This statement is true. The existential quantifier is used to make a claim that there exists some real number for which the statement holds. For example: $$$\exists x,x&lt;100$$$ is read as: there exists a real number $$$x$$$ such that $$$x$$$ is less than $$$100$$$. This statement is true. $$$\exists x,x&gt;x-1$$$ is read as: there exists a real number $$$x$$$ such that $$$x$$$ is greater than $$$x-1$$$. This statement is true. Moreover, these quantifiers can be nested. For example: $$$\forall x,\exists y,x&lt;y$$$ is read as: for all real numbers $$$x$$$, there exists a real number $$$y$$$ such that $$$x$$$ is less than $$$y$$$. This statement is true since for every $$$x$$$, there exists $$$y=x+1$$$. $$$\exists y,\forall x,x&lt;y$$$ is read as: there exists a real number $$$y$$$ such that for all real numbers $$$x$$$, $$$x$$$ is less than $$$y$$$. This statement is false because it claims that there is a maximum real number: a number $$$y$$$ larger than every $$$x$$$. Note that the order of variables and quantifiers is important for the meaning and veracity of a statement.There are $$$n$$$ variables $$$x_1,x_2,\ldots,x_n$$$, and you are given some formula of the form $$$$$$ f(x_1,\dots,x_n):=(x_{j_1}&lt;x_{k_1})\land (x_{j_2}&lt;x_{k_2})\land \cdots\land (x_{j_m}&lt;x_{k_m}), $$$$$$where $$$\land$$$ denotes logical AND. That is, $$$f(x_1,\ldots, x_n)$$$ is true if every inequality $$$x_{j_i}&lt;x_{k_i}$$$ holds. Otherwise, if at least one inequality does not hold, then $$$f(x_1,\ldots,x_n)$$$ is false.Your task is to assign quantifiers $$$Q_1,\ldots,Q_n$$$ to either universal ($$$\forall$$$) or existential ($$$\exists$$$) so that the statement $$$$$$ Q_1 x_1, Q_2 x_2, \ldots, Q_n x_n, f(x_1,\ldots, x_n) $$$$$$is true, and the number of universal quantifiers is maximized, or determine that the statement is false for every possible assignment of quantifiers.Note that the order the variables appear in the statement is fixed. For example, if $$$f(x_1,x_2):=(x_1&lt;x_2)$$$ then you are not allowed to make $$$x_2$$$ appear first and use the statement $$$\forall x_2,\exists x_1, x_1&lt;x_2$$$. If you assign $$$Q_1=\exists$$$ and $$$Q_2=\forall$$$, it will only be interpreted as $$$\exists x_1,\forall x_2,x_1&lt;x_2$$$.
256 megabytes
// upsolve with kaiboy import java.io.*; import java.util.*; public class CF1345E extends PrintWriter { CF1345E() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1345E o = new CF1345E(); o.main(); o.flush(); } int[] oo, oj; int __ = 1; int link(int o, int j) { oo[__] = o; oj[__] = j; return __++; } int[] ae, af; boolean[] visited, instack; int[] qu; int cnt; int[] dp, dq; boolean dfs(int i) { if (visited[i]) return instack[i]; visited[i] = instack[i] = true; for (int o = ae[i]; o != 0; o = oo[o]) { int j = oj[o]; if (dfs(j)) return true; } instack[i] = false; qu[--cnt] = i; return false; } void init(int n, int m) { oo = new int[1 + m * 2]; oj = new int[1 + m * 2]; ae = new int[n]; af = new int[n]; visited = new boolean[n]; instack = new boolean[n]; qu = new int[n]; dp = new int[n]; dq = new int[n]; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); init(n, m); while (m-- > 0) { int i = sc.nextInt() - 1; int j = sc.nextInt() - 1; ae[i] = link(ae[i], j); af[j] = link(af[j], i); } cnt = n; for (int i = 0; i < n; i++) if (!visited[i] && dfs(i)) { println(-1); return; } for (int i = 0; i < n; i++) dp[i] = dq[i] = i; for (int h = 0; h < n; h++) { int i = qu[h]; for (int o = ae[i]; o != 0; o = oo[o]) { int j = oj[o]; dp[j] = Math.min(dp[j], dp[i]); } } for (int h = n - 1; h >= 0; h--) { int i = qu[h]; for (int o = af[i]; o != 0; o = oo[o]) { int j = oj[o]; dq[j] = Math.min(dq[j], dq[i]); } } char[] cc = new char[n]; int k = 0; for (int i = 0; i < n; i++) if (dp[i] < i || dq[i] < i) cc[i] = 'E'; else { cc[i] = 'A'; k++; } println(k); println(cc); } }
Java
["2 1\n1 2", "4 3\n1 2\n2 3\n3 1", "3 2\n1 3\n2 3"]
1 second
["1\nAE", "-1", "2\nAAE"]
NoteFor the first test, the statement $$$\forall x_1, \exists x_2, x_1&lt;x_2$$$ is true. Answers of "EA" and "AA" give false statements. The answer "EE" gives a true statement, but the number of universal quantifiers in this string is less than in our answer.For the second test, we can show that no assignment of quantifiers, for which the statement is true exists.For the third test, the statement $$$\forall x_1, \forall x_2, \exists x_3, (x_1&lt;x_3)\land (x_2&lt;x_3)$$$ is true: We can set $$$x_3=\max\{x_1,x_2\}+1$$$.
Java 11
standard input
[ "dp", "dfs and similar", "graphs" ]
94e58f3f7aa4d860b95d34c7c9f89058
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2\le n\le 2\cdot 10^5$$$; $$$1\le m\le 2\cdot 10^5$$$)Β β€” the number of variables and the number of inequalities in the formula, respectively. The next $$$m$$$ lines describe the formula. The $$$i$$$-th of these lines contains two integers $$$j_i$$$,$$$k_i$$$ ($$$1\le j_i,k_i\le n$$$, $$$j_i\ne k_i$$$).
2,600
If there is no assignment of quantifiers for which the statement is true, output a single integer $$$-1$$$. Otherwise, on the first line output an integer, the maximum possible number of universal quantifiers. On the next line, output a string of length $$$n$$$, where the $$$i$$$-th character is "A" if $$$Q_i$$$ should be a universal quantifier ($$$\forall$$$), or "E" if $$$Q_i$$$ should be an existential quantifier ($$$\exists$$$). All letters should be upper-case. If there are multiple solutions where the number of universal quantifiers is maximum, print any.
standard output
PASSED
537e5c561a331e4a34715b791bd35427
train_002.jsonl
1588775700
Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal ($$$\forall$$$) and existential ($$$\exists$$$). You can read more about them here.The universal quantifier is used to make a claim that a statement holds for all real numbers. For example: $$$\forall x,x&lt;100$$$ is read as: for all real numbers $$$x$$$, $$$x$$$ is less than $$$100$$$. This statement is false. $$$\forall x,x&gt;x-1$$$ is read as: for all real numbers $$$x$$$, $$$x$$$ is greater than $$$x-1$$$. This statement is true. The existential quantifier is used to make a claim that there exists some real number for which the statement holds. For example: $$$\exists x,x&lt;100$$$ is read as: there exists a real number $$$x$$$ such that $$$x$$$ is less than $$$100$$$. This statement is true. $$$\exists x,x&gt;x-1$$$ is read as: there exists a real number $$$x$$$ such that $$$x$$$ is greater than $$$x-1$$$. This statement is true. Moreover, these quantifiers can be nested. For example: $$$\forall x,\exists y,x&lt;y$$$ is read as: for all real numbers $$$x$$$, there exists a real number $$$y$$$ such that $$$x$$$ is less than $$$y$$$. This statement is true since for every $$$x$$$, there exists $$$y=x+1$$$. $$$\exists y,\forall x,x&lt;y$$$ is read as: there exists a real number $$$y$$$ such that for all real numbers $$$x$$$, $$$x$$$ is less than $$$y$$$. This statement is false because it claims that there is a maximum real number: a number $$$y$$$ larger than every $$$x$$$. Note that the order of variables and quantifiers is important for the meaning and veracity of a statement.There are $$$n$$$ variables $$$x_1,x_2,\ldots,x_n$$$, and you are given some formula of the form $$$$$$ f(x_1,\dots,x_n):=(x_{j_1}&lt;x_{k_1})\land (x_{j_2}&lt;x_{k_2})\land \cdots\land (x_{j_m}&lt;x_{k_m}), $$$$$$where $$$\land$$$ denotes logical AND. That is, $$$f(x_1,\ldots, x_n)$$$ is true if every inequality $$$x_{j_i}&lt;x_{k_i}$$$ holds. Otherwise, if at least one inequality does not hold, then $$$f(x_1,\ldots,x_n)$$$ is false.Your task is to assign quantifiers $$$Q_1,\ldots,Q_n$$$ to either universal ($$$\forall$$$) or existential ($$$\exists$$$) so that the statement $$$$$$ Q_1 x_1, Q_2 x_2, \ldots, Q_n x_n, f(x_1,\ldots, x_n) $$$$$$is true, and the number of universal quantifiers is maximized, or determine that the statement is false for every possible assignment of quantifiers.Note that the order the variables appear in the statement is fixed. For example, if $$$f(x_1,x_2):=(x_1&lt;x_2)$$$ then you are not allowed to make $$$x_2$$$ appear first and use the statement $$$\forall x_2,\exists x_1, x_1&lt;x_2$$$. If you assign $$$Q_1=\exists$$$ and $$$Q_2=\forall$$$, it will only be interpreted as $$$\exists x_1,\forall x_2,x_1&lt;x_2$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { private boolean hasCir(List<List<Integer>> g) { int n = g.size(); int[] d = new int[n]; for (List<Integer> child : g) { for (int v : child) { ++d[v]; } } Queue<Integer> q = new ArrayDeque<>(); for (int u = 0; u < n; u++) { if (d[u] == 0) { q.add(u); } } int r = n; while (!q.isEmpty()) { int u = q.poll(); --r; for (int v : g.get(u)) { --d[v]; if (d[v] == 0) { q.add(v); } } } return r != 0; } private void dfs(int u, char[] ans, List<List<Integer>> g) { for (int v : g.get(u)) { if (ans[v] == 0) { ans[v] = 'E'; dfs(v, ans, g); } } } private void solve() { int n = sc.nextInt(); int m = sc.nextInt(); List<List<Integer>> go = new ArrayList<>(); List<List<Integer>> gr = new ArrayList<>(); for (int u = 0; u < n; ++u) { go.add(new ArrayList<>()); gr.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; go.get(u).add(v); gr.get(v).add(u); } if (hasCir(go) || hasCir(gr)) { out.println(-1); return; } char[] ao = new char[n]; char[] ar = new char[n]; for (int u = 0; u < n; ++u) { if (ao[u] == 0) { ao[u] = 'A'; dfs(u, ao, go); } if (ar[u] == 0) { ar[u] = 'A'; dfs(u, ar, gr); } } char[] ans = new char[n]; int count = 0; for (int u = 0; u < n; u++) { ans[u] = ao[u] == 'A' && ar[u] == 'A' ? 'A' : 'E'; count += ans[u] == 'A' ? 1 : 0; } out.println(count); out.println(new String(ans)); } private static PrintWriter out; private static MyScanner sc; private static class MyScanner { BufferedReader br; StringTokenizer st; private 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()); } } public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new MyScanner(); new Main().solve(); out.close(); } }
Java
["2 1\n1 2", "4 3\n1 2\n2 3\n3 1", "3 2\n1 3\n2 3"]
1 second
["1\nAE", "-1", "2\nAAE"]
NoteFor the first test, the statement $$$\forall x_1, \exists x_2, x_1&lt;x_2$$$ is true. Answers of "EA" and "AA" give false statements. The answer "EE" gives a true statement, but the number of universal quantifiers in this string is less than in our answer.For the second test, we can show that no assignment of quantifiers, for which the statement is true exists.For the third test, the statement $$$\forall x_1, \forall x_2, \exists x_3, (x_1&lt;x_3)\land (x_2&lt;x_3)$$$ is true: We can set $$$x_3=\max\{x_1,x_2\}+1$$$.
Java 11
standard input
[ "dp", "dfs and similar", "graphs" ]
94e58f3f7aa4d860b95d34c7c9f89058
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2\le n\le 2\cdot 10^5$$$; $$$1\le m\le 2\cdot 10^5$$$)Β β€” the number of variables and the number of inequalities in the formula, respectively. The next $$$m$$$ lines describe the formula. The $$$i$$$-th of these lines contains two integers $$$j_i$$$,$$$k_i$$$ ($$$1\le j_i,k_i\le n$$$, $$$j_i\ne k_i$$$).
2,600
If there is no assignment of quantifiers for which the statement is true, output a single integer $$$-1$$$. Otherwise, on the first line output an integer, the maximum possible number of universal quantifiers. On the next line, output a string of length $$$n$$$, where the $$$i$$$-th character is "A" if $$$Q_i$$$ should be a universal quantifier ($$$\forall$$$), or "E" if $$$Q_i$$$ should be an existential quantifier ($$$\exists$$$). All letters should be upper-case. If there are multiple solutions where the number of universal quantifiers is maximum, print any.
standard output
PASSED
44b44cd22ab5dd3f00f5714f47c8dcab
train_002.jsonl
1492266900
One day Masha came home and noticed n mice in the corridor of her flat. Of course, she shouted loudly, so scared mice started to run to the holes in the corridor.The corridor can be represeted as a numeric axis with n mice and m holes on it. ith mouse is at the coordinate xi, and jth hole β€” at coordinate pj. jth hole has enough room for cj mice, so not more than cj mice can enter this hole.What is the minimum sum of distances that mice have to go through so that they all can hide in the holes? If ith mouse goes to the hole j, then its distance is |xi - pj|.Print the minimum sum of distances.
256 megabytes
import java.io.*; import java.lang.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; public class F { public static void main(String[] args) { int n = in.nextInt(); int m = in.nextInt(); long[] x = in.nextLongs(n, true); long[][] pc = new long[m + 1][2]; /* for (int n = 2; n <= 50; ++n) { */ /* int m = n; */ /* long[] x = rand.nextLongs(n, true, 1, n * m + 1); */ /* long[][] pc = new long[m + 1][2]; */ long totalCapacity = 0; for (int i = 1; i <= m; ++i) { pc[i][0] = in.nextLong(); /* pc[i][0] = rand.nextLong(1, m * n + 1); */ pc[i][1] = in.nextLong(); /* pc[i][1] = rand.nextLong(1, m * n + 1); */ totalCapacity += pc[i][1]; /* } */ /* long dpOnly = dpOnly(n, m, x, pc, totalCapacity); */ /* long dpMmq = dpMmq(n, m, x, pc, totalCapacity); */ /* if (dpOnly != dpMmq) { */ /* out.println(n + " " + m); */ /* out.println(x, false); */ /* out.println(pc); */ /* out.println("dpOnly: " + dpOnly + " dpMmq: " + dpMmq); */ /* throw new RuntimeException(); */ /* } */ } // out.println(dpOnly(n, m, x, pc, totalCapacity)); out.println(dpMmq(n, m, x, pc, totalCapacity)); } static long dpOnly(int n, int m, long[] x, long[][] pc, long totalCapacity) { Arrays.sort(x, 1, n + 1); Arrays.sort(pc, 1, m + 1, (long[] pc1, long[] pc2) -> Long.compare(pc1[0], pc2[0])); if (totalCapacity < n) { return -1; } long[][] M = new long[m + 1][n + 1]; M[1][1] = Math.abs(x[1] - pc[1][0]); for (int j = 2; j <= n; ++j) { M[1][j] = j <= pc[1][1] ? M[1][j - 1] + Math.abs(x[j] - pc[1][0]) : -1; } for (int i = 2; i <= m; ++i) { for (int j = 1; j <= n; ++j) { long mij = M[i - 1][j]; long dist = 0; for (int k = 0; k < j && k < pc[i][1]; ++k) { dist += Math.abs(x[j - k] - pc[i][0]); if (M[i - 1][j - k - 1] != -1) { mij = mij != -1 ? Math.min(mij, M[i - 1][j - k - 1] + dist) : M[i - 1][j - k - 1] + dist; } } M[i][j] = mij; } } // out.println(M); return M[m][n]; } static long dpMmq(int n, int m, long[] x, long[][] pc, long totalCapacity) { Arrays.sort(x, 1, n + 1); Arrays.sort(pc, 1, m + 1, (long[] pc1, long[] pc2) -> Long.compare(pc1[0], pc2[0])); if (totalCapacity < n) { return -1; } long[][] M = new long[m + 1][n + 1]; M[1][1] = Math.abs(x[1] - pc[1][0]); for (int j = 2; j <= n; ++j) { M[1][j] = j <= pc[1][1] ? M[1][j - 1] + Math.abs(x[j] - pc[1][0]) : -1; } MinMaxQueueLong mmql = new MinMaxQueueLong(n); for (int i = 2; i <= m; ++i) { long dist = 0; /* long dist = Math.abs(x[1] - pc[i][0]); */ /* M[i][1] = Math.min(M[i - 1][1], dist); */ /* mmql.enqueue(0); */ /* mmql.enqueue(M[i - 1][1] - dist); */ int j1 = 0; for (int j = 0; j <= n && M[i - 1][j] != -1; ++j, ++j1) { /* out.println(mmql); */ dist += Math.abs(x[j] - pc[i][0]); mmql.enqueue(M[i - 1][j] - dist); // out.println(mmql); M[i][j] = mmql.getMin() + dist; if (mmql.size() > pc[i][1]) { mmql.dequeue(); } } int j2 = j1; for (int j = 0; j1 + j <= n && j < pc[i][1]; ++j, ++j2) { if (mmql.size() > pc[i][1] - j) { mmql.dequeue(); } /* out.println(mmql); */ dist += Math.abs(x[j1 + j] - pc[i][0]); // out.println(mmql); M[i][j1 + j] = mmql.getMin() + dist; } for (int j = 0; j2 + j <= n; ++j) { M[i][j2 + j] = -1; } mmql.reset(); } /* out.println(M); */ return M[m][n]; } static MyScanner in = new MyScanner(); static MyPrintWriter out = new MyPrintWriter(); static RandScanner rand = new RandScanner(); static class MyPrintWriter { BufferedOutputStream bos; PrintWriter pw; MyPrintWriter() { this.bos = new BufferedOutputStream(System.out); this.pw = new PrintWriter(bos, true); } void flush() { pw.flush(); } void print(String t) { pw.print(t); } void println() { pw.println(""); } void println(String s) { pw.println(s); } void println(int t) { pw.println(t); } void println(long t) { pw.println(t); } void println(double t) { pw.println(t); } <T> void println(T t) { pw.println(t.toString()); } void println(int[] ts) { println(ts, true); } void println(long[] ts) { println(ts, true); } void println(double[] ts) { println(ts, true); } <T> void println(T[] ts) { println(ts, true); } <T> void println(Collection<T> ts) { println(ts, true); } <T, U> void println(Map<T, U> ts) { println(ts, true); } void println(int[] ts, boolean newline) { StringBuilder sb = new StringBuilder(); for (int t : ts) { sb.append(t); sb.append((newline ? "\n" : " ")); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } pw.println(sb.toString()); } void println(long[] ts, boolean newline) { StringBuilder sb = new StringBuilder(); for (long t : ts) { sb.append(t); sb.append((newline ? "\n" : " ")); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } pw.println(sb.toString()); } void println(double[] ts, boolean newline) { StringBuilder sb = new StringBuilder(); for (double t : ts) { sb.append(t); sb.append((newline ? "\n" : " ")); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } pw.println(sb.toString()); } <T> void println(T[] ts, boolean newline) { println(Arrays.asList(ts), newline); } <T> void println(Collection<T> ts, boolean newline) { StringBuilder sb = new StringBuilder(); for (T t : ts) { sb.append(t.toString()); sb.append((newline ? "\n" : " ")); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } pw.println(sb.toString()); } <T, U> void println(Map<T, U> ts, boolean newline) { StringBuilder sb = new StringBuilder(); for (Map.Entry<T, U> t : ts.entrySet()) { sb.append(t.getKey().toString()); sb.append(" -> "); sb.append(t.getValue().toString()); sb.append((newline ? "\n" : " ")); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } pw.println(sb.toString()); } void println(int[][] tss) { StringBuilder sb = new StringBuilder(); for (int[] ts : tss) { for (int t : ts) { sb.append(t).append(" "); } if (ts.length > 0) { sb.setCharAt(sb.length() - 1, '\n'); } else { sb.append('\n'); } } pw.print(sb.toString()); pw.flush(); } void println(long[][] tss) { StringBuilder sb = new StringBuilder(); for (long[] ts : tss) { for (long t : ts) { sb.append(t).append(" "); } if (ts.length > 0) { sb.setCharAt(sb.length() - 1, '\n'); } else { sb.append('\n'); } } pw.print(sb.toString()); pw.flush(); } void println(double[][] tss) { StringBuilder sb = new StringBuilder(); for (double[] ts : tss) { for (double t : ts) { sb.append(t).append(" "); } if (ts.length > 0) { sb.setCharAt(sb.length() - 1, '\n'); } else { sb.append('\n'); } } pw.print(sb.toString()); pw.flush(); } } static class MyScanner { InputStreamReader is; BufferedReader br; StringTokenizer st; MyScanner() { this.is = new InputStreamReader(System.in); this.br = new BufferedReader(is); } void findToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } } String next() { findToken(); return st.nextToken(); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int nextInt() { return Integer.parseInt(next()); } int[] nextInts(int n) { return nextInts(n, false); } int[] nextInts(int n, boolean oneBased) { if (oneBased) { return nextInts(n, 1, n + 1); } else { return nextInts(n, 0, n); } } int[] nextInts(int n, int iMin, int iMax) { int[] ints = new int[iMax]; for (int i = iMin; i < iMax; ++i) { ints[i] = nextInt(); } return ints; } long nextLong() { return Long.parseLong(next()); } long[] nextLongs(int n) { return nextLongs(n, false); } long[] nextLongs(int n, boolean oneBased) { if (oneBased) { return nextLongs(n, 1, n + 1); } else { return nextLongs(n, 0, n); } } long[] nextLongs(int n, int iMin, int iMax) { long[] longs = new long[iMax]; for (int i = iMin; i < iMax; ++i) { longs[i] = nextLong(); } return longs; } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubles(int n) { return nextDoubles(n, false); } double[] nextDoubles(int n, boolean oneBased) { if (oneBased) { return nextDoubles(n, 1, n + 1); } else { return nextDoubles(n, 0, n); } } double[] nextDoubles(int n, int iMin, int iMax) { double[] doubles = new double[iMax]; for (int i = iMin; i < iMax; ++i) { doubles[i] = nextDouble(); } return doubles; } } static class RandScanner { ThreadLocalRandom r; RandScanner() { this.r = ThreadLocalRandom.current(); } int nextInt() { return nextInt(0, Integer.MAX_VALUE); } int nextInt(int lowerBound, int upperBound) { return r.nextInt(lowerBound, upperBound); } int[] nextInts(int n) { return nextInts(n, 0, Integer.MAX_VALUE); } int[] nextInts(int n, int lowerBound, int upperBound) { return nextInts(n, false, lowerBound, upperBound); } int[] nextInts(int n, boolean oneBased) { return nextInts(n, oneBased, 0, Integer.MAX_VALUE); } int[] nextInts(int n, boolean oneBased, int lowerBound, int upperBound) { if (oneBased) { return nextInts(n, 1, n + 1, lowerBound, upperBound); } else { return nextInts(n, 0, n, lowerBound, upperBound); } } // int[] nextInts(int n, int iMin, int iMax) { // return nextInts(n, iMin, iMax, 0, Integer.MAX_VALUE); // } int[] nextInts(int n, int iMin, int iMax, int lowerBound, int upperBound) { int[] ints = new int[iMax]; for (int i = iMin; i < iMax; ++i) { ints[i] = nextInt(lowerBound, upperBound); } return ints; } long nextLong() { return nextLong(0L, Long.MAX_VALUE); } long nextLong(long lowerBound, long upperBound) { return r.nextLong(lowerBound, upperBound); } long[] nextLongs(int n) { return nextLongs(n, 0L, Long.MAX_VALUE); } long[] nextLongs(int n, long lowerBound, long upperBound) { return nextLongs(n, false, lowerBound, upperBound); } long[] nextLongs(int n, boolean oneBased) { return nextLongs(n, oneBased, 0L, Long.MAX_VALUE); } long[] nextLongs(int n, boolean oneBased, long lowerBound, long upperBound) { if (oneBased) { return nextLongs(n, 1, n + 1, lowerBound, upperBound); } else { return nextLongs(n, 0, n, lowerBound, upperBound); } } // long[] nextLongs(int n, int iMin, int iMax) { // return nextLongs(n, iMin, iMax, 0L, Long.MAX_VALUE); // } long[] nextLongs(int n, int iMin, int iMax, long lowerBound, long upperBound) { long[] longs = new long[iMax]; for (int i = iMin; i < iMax; ++i) { longs[i] = nextLong(lowerBound, upperBound); } return longs; } double nextDouble() { return nextDouble(0, 1); } double nextDouble(double lowerBound, double upperBound) { return r.nextDouble(lowerBound, upperBound); } double[] nextDoubles(int n) { return nextDoubles(n, 0, 1); } double[] nextDoubles(int n, double lowerBound, double upperBound) { return nextDoubles(n, false, lowerBound, upperBound); } double[] nextDoubles(int n, boolean oneBased) { return nextDoubles(n, oneBased, 0, 1); } double[] nextDoubles(int n, boolean oneBased, double lowerBound, double upperBound) { if (oneBased) { return nextDoubles(n, 1, n + 1, lowerBound, upperBound); } else { return nextDoubles(n, 0, n, lowerBound, upperBound); } } // double[] nextDoubles(int n, int iMin, int iMax) { // return nextDoubles(n, iMin, iMax); // } double[] nextDoubles(int n, int iMin, int iMax, double lowerBound, double upperBound) { double[] doubles = new double[iMax]; for (int i = iMin; i < iMax; ++i) { doubles[i] = nextDouble(lowerBound, upperBound); } return doubles; } } static class MinMaxStackLong { long[][] stack; int top; MinMaxStackLong(int capacity) { stack = new long[capacity][2]; top = -1; } long getMax() { return stack[top][2]; } long getMin() { return stack[top][1]; } boolean isEmpty() { return top == -1; } long pop() { /* if (stack.length >= 4 && top == stack.length / 4) { */ /* stack = Arrays.copyOf(stack, Math.max(1, stack.length / 2)); */ /* } */ return stack[top--][0]; } void push(long i) { if (top == stack.length - 1) { int oldStackLength = stack.length; int newStackLength = oldStackLength * 2; stack = Arrays.copyOf(stack, newStackLength); for (int j = oldStackLength; j < newStackLength; ++j) { stack[j] = new long[2]; } } top++; stack[top][0] = i; stack[top][1] = top == 0 ? i : Math.min(i, stack[top - 1][1]); /* stack[top][2] = top == 0 ? i : Math.max(i, stack[top - 1][2]); */ } void reset() { top = -1; } int size() { return top + 1; } public String toString() { StringBuilder sb = new StringBuilder(stack.length * 6); for (int j = 0; j < 3; ++j) { toString(sb, j, false); sb.append("\n"); } return sb.toString(); } void toString(StringBuilder sb, int j, boolean reversed) { if (reversed) { for (int i = 0; i < size(); ++i) { sb.append(stack[i][j] + " "); } } else { for (int i = 0; i < size(); ++i) { sb.append(stack[size() - i - 1][j] + " "); } } if (size() > 0) { sb.deleteCharAt(sb.length() - 1); } } } static class MinMaxQueueLong { MinMaxStackLong stackIn; MinMaxStackLong stackOut; MinMaxQueueLong(int queueCapacity) { stackIn = new MinMaxStackLong(queueCapacity); stackOut = new MinMaxStackLong(queueCapacity); } long dequeue() { if (!stackOut.isEmpty()) { return stackOut.pop(); } else { while (!stackIn.isEmpty()) { stackOut.push(stackIn.pop()); } return stackOut.pop(); } } long getMax() { return stackIn.isEmpty() ? stackOut.getMax() : stackOut.isEmpty() ? stackIn.getMax() : Math.max(stackIn.getMax(), stackOut.getMax()); } long getMin() { return stackIn.isEmpty() ? stackOut.getMin() : stackOut.isEmpty() ? stackIn.getMin() : Math.min(stackIn.getMin(), stackOut.getMin()); } boolean isEmpty() { return stackIn.isEmpty() && stackOut.isEmpty(); } void enqueue(long i) { stackIn.push(i); } void reset() { stackIn.reset(); stackOut.reset(); } int size() { return stackIn.size() + stackOut.size(); } public String toString() { StringBuilder sb = new StringBuilder(size() * 6); for (int j = 0; j < 3; ++j) { stackIn.toString(sb, j, true); if (stackIn.size() > 0) { sb.append(" "); } stackOut.toString(sb, j, false); sb.append("\n"); } return sb.toString(); } } }
Java
["4 5\n6 2 8 9\n3 6\n2 1\n3 6\n4 7\n4 7", "7 2\n10 20 30 40 50 45 35\n-1000000000 10\n1000000000 1"]
1.5 seconds
["11", "7000000130"]
null
Java 8
standard input
[ "dp", "sortings", "greedy", "data structures" ]
d9adb80515689c6939f8e010005f7208
The first line contains two integer numbers n, m (1 ≀ n, m ≀ 5000) β€” the number of mice and the number of holes, respectively. The second line contains n integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109), where xi is the coordinate of ith mouse. Next m lines contain pairs of integer numbers pj, cj ( - 109 ≀ pj ≀ 109, 1 ≀ cj ≀ 5000), where pj is the coordinate of jth hole, and cj is the maximum number of mice that can hide in the hole j.
2,600
Print one integer number β€” the minimum sum of distances. If there is no solution, print -1 instead.
standard output
PASSED
9135d93094375b267ad32ce6f616f4d6
train_002.jsonl
1492266900
One day Masha came home and noticed n mice in the corridor of her flat. Of course, she shouted loudly, so scared mice started to run to the holes in the corridor.The corridor can be represeted as a numeric axis with n mice and m holes on it. ith mouse is at the coordinate xi, and jth hole β€” at coordinate pj. jth hole has enough room for cj mice, so not more than cj mice can enter this hole.What is the minimum sum of distances that mice have to go through so that they all can hide in the holes? If ith mouse goes to the hole j, then its distance is |xi - pj|.Print the minimum sum of distances.
256 megabytes
//package educational.round19; 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 FY { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); int[] rats = na(n); int[][] holes = new int[m][]; for(int i = 0;i < m;i++){ holes[i] = na(2); } int bal = 0; for(int[] h : holes)bal += h[1]; bal -= n; if(bal < 0){ out.println(-1); return; } Arrays.sort(holes, (x, y) -> x[0]-y[0]); Arrays.sort(rats); long[] dp = new long[n+1]; Arrays.fill(dp, Long.MAX_VALUE / 3); dp[0] = 0; for(int i = 0;i < m;i++){ // ndp[j] = dp[k] + sum_{k<=l<j} d(rat[l], hole[i]) int[] stack = new int[n+1]; long[] vals = new long[n+1]; int head = 0, tail = 0; long offset = 0; for(int j = 0;j <= n;j++){ if(j > 0){ offset += Math.abs(rats[j-1] - holes[i][0]); } long v = dp[j] - offset; while(tail < head && vals[head-1] > v){ head--; } stack[head] = j; vals[head++] = v; while(tail < head && stack[tail] < j-holes[i][1])tail++; dp[j] = vals[tail] + offset; } } out.println(dp[n]); } 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 FY().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
["4 5\n6 2 8 9\n3 6\n2 1\n3 6\n4 7\n4 7", "7 2\n10 20 30 40 50 45 35\n-1000000000 10\n1000000000 1"]
1.5 seconds
["11", "7000000130"]
null
Java 8
standard input
[ "dp", "sortings", "greedy", "data structures" ]
d9adb80515689c6939f8e010005f7208
The first line contains two integer numbers n, m (1 ≀ n, m ≀ 5000) β€” the number of mice and the number of holes, respectively. The second line contains n integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109), where xi is the coordinate of ith mouse. Next m lines contain pairs of integer numbers pj, cj ( - 109 ≀ pj ≀ 109, 1 ≀ cj ≀ 5000), where pj is the coordinate of jth hole, and cj is the maximum number of mice that can hide in the hole j.
2,600
Print one integer number β€” the minimum sum of distances. If there is no solution, print -1 instead.
standard output
PASSED
d0acd0b2be5b2969184448192dc079eb
train_002.jsonl
1492266900
One day Masha came home and noticed n mice in the corridor of her flat. Of course, she shouted loudly, so scared mice started to run to the holes in the corridor.The corridor can be represeted as a numeric axis with n mice and m holes on it. ith mouse is at the coordinate xi, and jth hole β€” at coordinate pj. jth hole has enough room for cj mice, so not more than cj mice can enter this hole.What is the minimum sum of distances that mice have to go through so that they all can hide in the holes? If ith mouse goes to the hole j, then its distance is |xi - pj|.Print the minimum sum of distances.
256 megabytes
//package educational.round19; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; // 1621 public class FX { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); int[] rats = na(n); int[][] holes = new int[m][]; for(int i = 0;i < m;i++){ holes[i] = na(2); } Arrays.sort(holes, (x, y) -> x[0] - y[0]); { int o = 0; for(int i = 0;i < m;i++){ if(i == 0 || holes[i][0] != holes[i-1][0]){ holes[o++] = holes[i]; }else{ holes[o-1][1] += holes[i][1]; } } holes = Arrays.copyOf(holes, o); m = o; } int[] xs = new int[n+m]; int p = 0; int q = 0; int[] hxs = new int[m]; for(int i = 0;i < n;i++){ xs[p++] = rats[i]; } for(int i = 0;i < m;i++){ xs[p++] = holes[i][0]; hxs[q++] = holes[i][0]; } Arrays.sort(xs); xs = uniq(xs); Arrays.sort(hxs); long[] fs = new long[xs.length]; int[] cap = new int[m]; long ans = 0; for(int r : rats){ int rid = Arrays.binarySearch(xs, r); int hid = Arrays.binarySearch(hxs, r); long mincost = Long.MAX_VALUE; int arg = -1; int dir = 0; long cost = 0; for(int i = rid-1, j = hid >= 0 ? hid-1 : -hid-2;i >= 0 && j >= 0;i--){ cost += (fs[i] > 0 ? -1 : 1) * (xs[i+1] - xs[i]); if(hxs[j] == xs[i]){ if(cost < mincost && cap[j] < holes[j][1]){ mincost = cost; arg = j; dir = -1; } j--; } } cost = 0; for(int i = rid+1, j = hid >= 0 ? hid+1 : -hid-1;i < xs.length && j < m;i++){ cost += (fs[i-1] >= 0 ? 1 : -1) * (xs[i] - xs[i-1]); if(hxs[j] == xs[i]){ if(cost < mincost && cap[j] < holes[j][1]){ mincost = cost; arg = j; dir = 1; } j++; } } if(hid >= 0 && cap[hid] < holes[hid][1]){ if(0 < mincost){ mincost = 0; arg = hid; dir = 0; } } ans += mincost; if(arg == -1){ out.println(-1); return; } cap[arg]++; if(dir == -1){ for(int i = rid-1;i >= 0 && xs[i] >= hxs[arg];i--){ fs[i]--; } }else if(dir == 1){ for(int i = rid;i < xs.length && xs[i] < hxs[arg];i++){ fs[i]++; } } } out.println(ans); } public static int[] uniq(int[] a) { int n = a.length; int p = 0; for(int i = 0;i < n;i++) { if(i == 0 || a[i] != a[i-1])a[p++] = a[i]; } return Arrays.copyOf(a, p); } 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 FX().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
["4 5\n6 2 8 9\n3 6\n2 1\n3 6\n4 7\n4 7", "7 2\n10 20 30 40 50 45 35\n-1000000000 10\n1000000000 1"]
1.5 seconds
["11", "7000000130"]
null
Java 8
standard input
[ "dp", "sortings", "greedy", "data structures" ]
d9adb80515689c6939f8e010005f7208
The first line contains two integer numbers n, m (1 ≀ n, m ≀ 5000) β€” the number of mice and the number of holes, respectively. The second line contains n integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109), where xi is the coordinate of ith mouse. Next m lines contain pairs of integer numbers pj, cj ( - 109 ≀ pj ≀ 109, 1 ≀ cj ≀ 5000), where pj is the coordinate of jth hole, and cj is the maximum number of mice that can hide in the hole j.
2,600
Print one integer number β€” the minimum sum of distances. If there is no solution, print -1 instead.
standard output
PASSED
0e68286f35ef8c8a4ac247a7e6a47ab4
train_002.jsonl
1492266900
One day Masha came home and noticed n mice in the corridor of her flat. Of course, she shouted loudly, so scared mice started to run to the holes in the corridor.The corridor can be represeted as a numeric axis with n mice and m holes on it. ith mouse is at the coordinate xi, and jth hole β€” at coordinate pj. jth hole has enough room for cj mice, so not more than cj mice can enter this hole.What is the minimum sum of distances that mice have to go through so that they all can hide in the holes? If ith mouse goes to the hole j, then its distance is |xi - pj|.Print the minimum sum of distances.
256 megabytes
//package educational.round19; 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 FY { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); int[] rats = na(n); int[][] holes = new int[m][]; for(int i = 0;i < m;i++){ holes[i] = na(2); } int bal = 0; for(int[] h : holes)bal += h[1]; bal -= n; if(bal < 0){ out.println(-1); return; } Arrays.sort(holes, (x, y) -> x[0]-y[0]); Arrays.sort(rats); long[] dp = new long[n+1]; Arrays.fill(dp, Long.MAX_VALUE / 3); dp[0] = 0; for(int i = 0;i < m;i++){ // ndp[j] = dp[k] + sum_{k<=l<j} d(rat[l], hole[i]) int[] deque = new int[n+1]; long[] vals = new long[n+1]; int head = 0, tail = 0; long offset = 0; for(int j = 0;j <= n;j++){ long v = dp[j] - offset; while(tail < head && vals[head-1] > v){ head--; } deque[head] = j; vals[head++] = v; while(tail < head && deque[tail] < j-holes[i][1])tail++; dp[j] = vals[tail] + offset; if(j < n)offset += Math.abs(rats[j] - holes[i][0]); } } out.println(dp[n]); } 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 FY().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
["4 5\n6 2 8 9\n3 6\n2 1\n3 6\n4 7\n4 7", "7 2\n10 20 30 40 50 45 35\n-1000000000 10\n1000000000 1"]
1.5 seconds
["11", "7000000130"]
null
Java 8
standard input
[ "dp", "sortings", "greedy", "data structures" ]
d9adb80515689c6939f8e010005f7208
The first line contains two integer numbers n, m (1 ≀ n, m ≀ 5000) β€” the number of mice and the number of holes, respectively. The second line contains n integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109), where xi is the coordinate of ith mouse. Next m lines contain pairs of integer numbers pj, cj ( - 109 ≀ pj ≀ 109, 1 ≀ cj ≀ 5000), where pj is the coordinate of jth hole, and cj is the maximum number of mice that can hide in the hole j.
2,600
Print one integer number β€” the minimum sum of distances. If there is no solution, print -1 instead.
standard output
PASSED
399b0e8f074d8a352611f3dc50afc3d2
train_002.jsonl
1414170000
You play the game with your friend. The description of this game is listed below. Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals . You want to guess which string was chosen by your friend. In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: Β«What character stands on position pos in the string you have chosen?Β» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions. You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.
256 megabytes
//import java.awt.Dimension; import java.awt.Point; import java.io.*; import static java.lang.Character.*; import static java.lang.Math.*; import java.math.BigDecimal; import java.math.BigInteger; import static java.math.BigInteger.*; import java.util.*; import static java.util.Arrays.*; import java.util.logging.Level; import java.util.logging.Logger; //import java.math.BigInteger; //import static java.lang.Character.*; //import static java.lang.Math.*; //import static java.math.BigInteger.*; //import static java.util.Arrays.*; //import java.awt.Point; // interger !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //import java.awt.Polygon; //import java.awt.Rectangle; //import java.awt.geom.AffineTransform; //import java.awt.geom.Line2D; //import java.awt.geom.Point2D; //import javafx.scene.shape.Line; //import javafx.scene.transform.Rotate; //<editor-fold defaultstate="collapsed" desc="Main"> public class Main { // https://netbeans.org/kb/73/java/editor-codereference_ru.html#display private void run() { try { Locale.setDefault(Locale.US); } catch (Exception e) { } boolean oj = true; try { oj = System.getProperty("MYLOCAL") == null; } catch (Exception e) { } if (oj) { sc = new FastScanner(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } else { try { sc = new FastScanner(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); } catch (IOException e) { MLE(); } } Solver s = new Solver(); s.sc = sc; s.out = out; s.solve(); if (!oj) { err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3); err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20); } out.flush(); } private void show(int[] arr) { for (int v : arr) { err.print(" " + v); } err.println(); } public static void exit() { err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3); err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20); out.flush(); out.close(); System.exit(0); } public static void MLE() { int[][] arr = new int[1024 * 1024][]; for (int i = 0; i < arr.length; i++) { arr[i] = new int[1024 * 1024]; } } public static void main(String[] args) { new Main().run(); } static long timeBegin = System.currentTimeMillis(); static FastScanner sc; static PrintWriter out; static PrintStream err = System.err; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="FastScanner"> class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStreamReader reader) { br = new BufferedReader(reader); st = new StringTokenizer(""); } String next() { while (!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception ex) { return null; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return br.readLine(); } catch (IOException ex) { return null; } } } //</editor-fold> class Solver { void myAssert(boolean OK) { if (!OK) { Main.MLE(); } } FastScanner sc; PrintWriter out; static PrintStream err = System.err; int n, k; String[] arrStr; long[] bad; void solve() { n = sc.nextInt(); arrStr = new String[n]; for (int i = 0; i < n; i++) { arrStr[i] = sc.next(); } k = arrStr[0].length(); bad = new long[1<<k]; for (int i = 0 ; i < n; i++) { for (int j = i + 1; j < n; j++) { int diff = 0; for (int p = 0; p < k; p++) if( arrStr[i].charAt(p) == arrStr[j].charAt(p) ) diff |= 1<<p; bad[diff] |= (1L<<i) | (1L<<j); } } double[] f = new double[1<<k]; for( int t = (1<<k)-2; 0 <= t; --t ){ for (int i = 0; i < k; i++) { if( (t & (1<<i)) == 0 ){ f[t] += f[t | (1<<i)]; bad[t] |= bad[t | (1 << i)]; } } f[t] = f[t] / (k - Integer.bitCount(t)) + (double)Long.bitCount(bad[t])/ n; } out.printf( "%.15f\n", f[0] ); } }
Java
["2\naab\naac", "3\naaA\naBa\nCaa", "3\naca\nvac\nwqq"]
1 second
["2.000000000000000", "1.666666666666667", "1.000000000000000"]
NoteIn the first sample the strings only differ in the character in the third position. So only the following situations are possible: you guess the string in one question. The event's probability is ; you guess the string in two questions. The event's probability is Β· = (as in this case the first question should ask about the position that is other than the third one); you guess the string in three questions. The event's probability is Β· Β· = ; Thus, the expected value is equal to In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is .In the third sample whatever position we ask about in the first question, we immediately identify the string.
Java 7
standard input
[ "dp", "bitmasks", "probabilities" ]
a95d9aef6a64c30e46330dcc8e6d4a67
The first line contains a single integer n (1 ≀ n ≀ 50)Β β€” the number of strings your friend came up with. The next n lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.
2,600
Print the single number β€” the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
standard output
PASSED
0fa97a4bf99d4c7e6e26701217f53ca7
train_002.jsonl
1414170000
You play the game with your friend. The description of this game is listed below. Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals . You want to guess which string was chosen by your friend. In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: Β«What character stands on position pos in the string you have chosen?Β» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions. You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.
256 megabytes
//import java.awt.Dimension; import java.awt.Point; import java.io.*; import static java.lang.Character.*; import static java.lang.Math.*; import java.math.BigDecimal; import java.math.BigInteger; import static java.math.BigInteger.*; import java.util.*; import static java.util.Arrays.*; import java.util.logging.Level; import java.util.logging.Logger; //import java.math.BigInteger; //import static java.lang.Character.*; //import static java.lang.Math.*; //import static java.math.BigInteger.*; //import static java.util.Arrays.*; //import java.awt.Point; // interger !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //import java.awt.Polygon; //import java.awt.Rectangle; //import java.awt.geom.AffineTransform; //import java.awt.geom.Line2D; //import java.awt.geom.Point2D; //import javafx.scene.shape.Line; //import javafx.scene.transform.Rotate; //<editor-fold defaultstate="collapsed" desc="Main"> public class Main { // https://netbeans.org/kb/73/java/editor-codereference_ru.html#display private void run() { try { Locale.setDefault(Locale.US); } catch (Exception e) { } boolean oj = true; try { oj = System.getProperty("MYLOCAL") == null; } catch (Exception e) { } if (oj) { sc = new FastScanner(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } else { try { sc = new FastScanner(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); } catch (IOException e) { MLE(); } } Solver s = new Solver(); s.sc = sc; s.out = out; s.solve(); if (!oj) { err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3); err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20); } out.flush(); } private void show(int[] arr) { for (int v : arr) { err.print(" " + v); } err.println(); } public static void exit() { err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3); err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20); out.flush(); out.close(); System.exit(0); } public static void MLE() { int[][] arr = new int[1024 * 1024][]; for (int i = 0; i < arr.length; i++) { arr[i] = new int[1024 * 1024]; } } public static void main(String[] args) { new Main().run(); } static long timeBegin = System.currentTimeMillis(); static FastScanner sc; static PrintWriter out; static PrintStream err = System.err; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="FastScanner"> class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStreamReader reader) { br = new BufferedReader(reader); st = new StringTokenizer(""); } String next() { while (!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception ex) { return null; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return br.readLine(); } catch (IOException ex) { return null; } } } //</editor-fold> class Solver { void myAssert(boolean OK) { if (!OK) { Main.MLE(); } } FastScanner sc; PrintWriter out; static PrintStream err = System.err; int n, k; String[] arrStr; long[] bad; void solve() { n = sc.nextInt(); arrStr = new String[n]; for (int i = 0; i < n; i++) { arrStr[i] = sc.next(); } k = arrStr[0].length(); bad = new long[1<<k]; for (int i = 0 ; i < n; i++) { for (int j = i + 1; j < n; j++) { int diff = 0; for (int p = 0; p < k; p++) if( arrStr[i].charAt(p) == arrStr[j].charAt(p) ) diff |= 1<<p; bad[diff] |= (1L<<i) | (1L<<j); } } double[] f = new double[1<<k]; for( int t = (1<<k)-2; 0 <= t; --t ){ for (int i = 0; i < k; i++) { if( (t & (1<<i)) == 0 ){ f[t] += f[t | (1<<i)]; bad[t] |= bad[t | (1 << i)]; } } f[t] = f[t] / (k - Integer.bitCount(t)) + Long.bitCount(bad[t]) * 1.0 / n; } out.printf( "%.15f\n", f[0] ); } }
Java
["2\naab\naac", "3\naaA\naBa\nCaa", "3\naca\nvac\nwqq"]
1 second
["2.000000000000000", "1.666666666666667", "1.000000000000000"]
NoteIn the first sample the strings only differ in the character in the third position. So only the following situations are possible: you guess the string in one question. The event's probability is ; you guess the string in two questions. The event's probability is Β· = (as in this case the first question should ask about the position that is other than the third one); you guess the string in three questions. The event's probability is Β· Β· = ; Thus, the expected value is equal to In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is .In the third sample whatever position we ask about in the first question, we immediately identify the string.
Java 7
standard input
[ "dp", "bitmasks", "probabilities" ]
a95d9aef6a64c30e46330dcc8e6d4a67
The first line contains a single integer n (1 ≀ n ≀ 50)Β β€” the number of strings your friend came up with. The next n lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.
2,600
Print the single number β€” the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
standard output
PASSED
e2788c8c2fd1f1130dd549039413301c
train_002.jsonl
1414170000
You play the game with your friend. The description of this game is listed below. Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals . You want to guess which string was chosen by your friend. In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: Β«What character stands on position pos in the string you have chosen?Β» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions. You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] word = new String[n]; for (int i = 0; i < n; i++) { word[i] = sc.next(); } int k = word[0].length(); long[] bad = new long[1 << k]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int diff = 0; for (int p = 0; p < k; p++) { if (word[i].charAt(p) == word[j].charAt(p)) { diff |= 1 << p; } } bad[diff] |= (1L << i) + (1L << j); } } double[] f = new double[1 << k]; for (int t = (1 << k) - 2; t >= 0; t--) { for (int i = 0; i < k; i++) { if ((t & (1 << i)) == 0) { f[t] += f[t ^ (1 << i)]; bad[t] |= bad[t ^ (1 << i)]; } } f[t] = f[t] / (k - Integer.bitCount(t)) + Long.bitCount(bad[t]) * 1.0 / n; } System.out.println(f[0]); } }
Java
["2\naab\naac", "3\naaA\naBa\nCaa", "3\naca\nvac\nwqq"]
1 second
["2.000000000000000", "1.666666666666667", "1.000000000000000"]
NoteIn the first sample the strings only differ in the character in the third position. So only the following situations are possible: you guess the string in one question. The event's probability is ; you guess the string in two questions. The event's probability is Β· = (as in this case the first question should ask about the position that is other than the third one); you guess the string in three questions. The event's probability is Β· Β· = ; Thus, the expected value is equal to In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is .In the third sample whatever position we ask about in the first question, we immediately identify the string.
Java 7
standard input
[ "dp", "bitmasks", "probabilities" ]
a95d9aef6a64c30e46330dcc8e6d4a67
The first line contains a single integer n (1 ≀ n ≀ 50)Β β€” the number of strings your friend came up with. The next n lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.
2,600
Print the single number β€” the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
standard output
PASSED
ba3c058b2254a21d207d12d631e60479
train_002.jsonl
1414170000
You play the game with your friend. The description of this game is listed below. Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals . You want to guess which string was chosen by your friend. In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: Β«What character stands on position pos in the string you have chosen?Β» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions. You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] word = new String[n]; for (int i = 0; i < n; i++) { word[i] = sc.next(); } int k = word[0].length(); long[] bad = new long[1 << k]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int diff = 0; for (int p = 0; p < k; p++) { if (word[i].charAt(p) == word[j].charAt(p)) { diff |= 1 << p; } } bad[diff] |= (1L << i) + (1L << j); } } double[] f = new double[1 << k]; for (int t = (1 << k) - 1; t >= 0; t--) { for (int i = 0; i < k; i++) { if ((t & (1 << i)) > 0) { bad[t ^ (1 << i)] |= bad[t]; } } int cnt = 0; for (int i = 0; i < k; i++) { if ((t & (1 << i)) == 0) { f[t] += f[t ^ (1 << i)]; cnt++; } } if (cnt > 0) { f[t] /= cnt; } f[t] += Long.bitCount(bad[t]) * 1.0 / n; } System.out.println(f[0]); } }
Java
["2\naab\naac", "3\naaA\naBa\nCaa", "3\naca\nvac\nwqq"]
1 second
["2.000000000000000", "1.666666666666667", "1.000000000000000"]
NoteIn the first sample the strings only differ in the character in the third position. So only the following situations are possible: you guess the string in one question. The event's probability is ; you guess the string in two questions. The event's probability is Β· = (as in this case the first question should ask about the position that is other than the third one); you guess the string in three questions. The event's probability is Β· Β· = ; Thus, the expected value is equal to In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is .In the third sample whatever position we ask about in the first question, we immediately identify the string.
Java 7
standard input
[ "dp", "bitmasks", "probabilities" ]
a95d9aef6a64c30e46330dcc8e6d4a67
The first line contains a single integer n (1 ≀ n ≀ 50)Β β€” the number of strings your friend came up with. The next n lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.
2,600
Print the single number β€” the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
standard output
PASSED
7eb210190973aab664a1544590e55db6
train_002.jsonl
1414170000
You play the game with your friend. The description of this game is listed below. Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals . You want to guess which string was chosen by your friend. In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: Β«What character stands on position pos in the string you have chosen?Β» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions. You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] word = new String[n]; for (int i = 0; i < n; i++) { word[i] = sc.next(); } int k = word[0].length(); long[] bad = new long[1 << k]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int diff = 0; for (int p = 0; p < k; p++) { if (word[i].charAt(p) == word[j].charAt(p)) { diff |= 1 << p; } } bad[diff] |= (1L << i) + (1L << j); } } double[] f = new double[1 << k]; for (int t = (1 << k) - 1; t >= 0; t--) { int cnt = 0; for (int i = 0; i < k; i++) { if ((t & (1 << i)) == 0) { f[t] += f[t ^ (1 << i)]; cnt++; } else { bad[t ^ (1 << i)] |= bad[t]; } } if (cnt > 0) { f[t] /= cnt; } f[t] += Long.bitCount(bad[t]) * 1.0 / n; } System.out.println(f[0]); } }
Java
["2\naab\naac", "3\naaA\naBa\nCaa", "3\naca\nvac\nwqq"]
1 second
["2.000000000000000", "1.666666666666667", "1.000000000000000"]
NoteIn the first sample the strings only differ in the character in the third position. So only the following situations are possible: you guess the string in one question. The event's probability is ; you guess the string in two questions. The event's probability is Β· = (as in this case the first question should ask about the position that is other than the third one); you guess the string in three questions. The event's probability is Β· Β· = ; Thus, the expected value is equal to In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is .In the third sample whatever position we ask about in the first question, we immediately identify the string.
Java 7
standard input
[ "dp", "bitmasks", "probabilities" ]
a95d9aef6a64c30e46330dcc8e6d4a67
The first line contains a single integer n (1 ≀ n ≀ 50)Β β€” the number of strings your friend came up with. The next n lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.
2,600
Print the single number β€” the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
standard output
PASSED
f670649adddcfa3237941b77d3d198c6
train_002.jsonl
1414170000
You play the game with your friend. The description of this game is listed below. Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals . You want to guess which string was chosen by your friend. In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: Β«What character stands on position pos in the string you have chosen?Β» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions. You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] word = new String[n]; for (int i = 0; i < n; i++) { word[i] = sc.next(); } int k = word[0].length(); long[] bad = new long[1 << k]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int diff = 0; for (int p = 0; p < k; p++) { if (word[i].charAt(p) == word[j].charAt(p)) { diff |= 1 << p; } } bad[diff] |= (1L << i) + (1L << j); } } double[] f = new double[1 << k]; for (int t = (1 << k) - 2; t >= 0; t--) { double sum = 0.0; for (int i = 0; i < k; i++) { if ((t & (1 << i)) == 0) { sum += f[t ^ (1 << i)]; } else { bad[t ^ (1 << i)] |= bad[t]; } } f[t] = sum / (k - Integer.bitCount(t)) + Long.bitCount(bad[t]) * 1.0 / n; } System.out.println(f[0]); } }
Java
["2\naab\naac", "3\naaA\naBa\nCaa", "3\naca\nvac\nwqq"]
1 second
["2.000000000000000", "1.666666666666667", "1.000000000000000"]
NoteIn the first sample the strings only differ in the character in the third position. So only the following situations are possible: you guess the string in one question. The event's probability is ; you guess the string in two questions. The event's probability is Β· = (as in this case the first question should ask about the position that is other than the third one); you guess the string in three questions. The event's probability is Β· Β· = ; Thus, the expected value is equal to In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is .In the third sample whatever position we ask about in the first question, we immediately identify the string.
Java 7
standard input
[ "dp", "bitmasks", "probabilities" ]
a95d9aef6a64c30e46330dcc8e6d4a67
The first line contains a single integer n (1 ≀ n ≀ 50)Β β€” the number of strings your friend came up with. The next n lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.
2,600
Print the single number β€” the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
standard output
PASSED
73dcc3f5ed2f104b1c7c5aa9a2c1078c
train_002.jsonl
1414170000
You play the game with your friend. The description of this game is listed below. Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals . You want to guess which string was chosen by your friend. In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: Β«What character stands on position pos in the string you have chosen?Β» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions. You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); int[] inInput = new int[256]; input = new char[n][]; for (int i = 0; i < n; i++) { char[] c = in.nextToken().toCharArray(); c = Arrays.copyOf(c, c.length + 1); c[c.length - 1] = (char) i; input[i] = c; for (int j = 0; j < c.length - 1; j++) { inInput[c[j]] = 1; } } for (int i = 1; i < inInput.length; i++) { inInput[i] += inInput[i - 1]; } for (int i = 0; i < n; i++) { char[] c = input[i]; for (int j = 0; j < c.length - 1; j++) { c[j] = (char) (inInput[c[j]] - 1); } } MAX = inInput[inInput.length - 1]; cnt = new int[MAX]; bits = input[0].length - 1; inputPerLevel = new char[bits + 1][n][]; System.arraycopy(input, 0, inputPerLevel[0], 0, n); factorial = new double[bits + 1]; factorial[0] = 1; for (int i = 1; i <= bits; i++) { factorial[i] = factorial[i - 1] * i; } equivalenceClassPerLevel = new int[bits + 1][n]; whatWeAreCalculatingPerInput = new double[n]; goAll(0, 0); double worst = 0; for (double d : whatWeAreCalculatingPerInput) { worst += d; } double answer = worst / factorial[bits] / n + (n==1?0:1); out.println(answer); } static int bits; static int n; static char[][] input; static char[][][] inputPerLevel; static double[] whatWeAreCalculatingPerInput; static double[] factorial; static int[][] equivalenceClassPerLevel; static int MAX; static void goAll(int curBit, int mask) { if (curBit == bits) { return; } int k = Integer.bitCount(mask) + 1; double add = factorial[k] * factorial[bits - k]; for (int takeBit = curBit; takeBit < bits; takeBit++) { goodSort(inputPerLevel[curBit], equivalenceClassPerLevel[curBit], inputPerLevel[takeBit + 1], equivalenceClassPerLevel[takeBit + 1], takeBit, add); goAll(takeBit + 1, mask | (1 << takeBit)); } } static int[] cnt; private static void goodSort(char[][] in, int[] equivIn, char[][] out, int[] equivOut, int sortBy, double add) { Arrays.fill(cnt, 0); for (int i = 0; i < n; i++) { ++cnt[in[i][sortBy]]; } for (int i = 1; i < cnt.length; i++) { cnt[i] += cnt[i - 1]; } for (int i = n - 1; i >= 0; --i) { int what = in[i][sortBy]; out[--cnt[what]] = in[i]; } int lastEquiv = -1; int lastVal = -1; int equivId = -1; int last = -1; for (int i = 0; i < n; i++) { int who = out[i][bits]; int curEquiv = equivIn[who]; int curVal = out[i][sortBy]; if (curVal != lastVal || curEquiv != lastEquiv) { ++equivId; lastVal = curVal; lastEquiv = curEquiv; if (i - last > 1) { for (int j = last; j < i; j++) { int guy = out[j][bits]; whatWeAreCalculatingPerInput[guy] += add; } } last = i; } equivOut[who] = equivId; } if (n - last > 1) { for (int j = last; j < n; j++) { int guy = out[j][bits]; whatWeAreCalculatingPerInput[guy] += add; } } } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } }
Java
["2\naab\naac", "3\naaA\naBa\nCaa", "3\naca\nvac\nwqq"]
1 second
["2.000000000000000", "1.666666666666667", "1.000000000000000"]
NoteIn the first sample the strings only differ in the character in the third position. So only the following situations are possible: you guess the string in one question. The event's probability is ; you guess the string in two questions. The event's probability is Β· = (as in this case the first question should ask about the position that is other than the third one); you guess the string in three questions. The event's probability is Β· Β· = ; Thus, the expected value is equal to In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is .In the third sample whatever position we ask about in the first question, we immediately identify the string.
Java 7
standard input
[ "dp", "bitmasks", "probabilities" ]
a95d9aef6a64c30e46330dcc8e6d4a67
The first line contains a single integer n (1 ≀ n ≀ 50)Β β€” the number of strings your friend came up with. The next n lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.
2,600
Print the single number β€” the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
standard output
PASSED
34269ab6f33176a8331f0951fa5c392c
train_002.jsonl
1414170000
You play the game with your friend. The description of this game is listed below. Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals . You want to guess which string was chosen by your friend. In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: Β«What character stands on position pos in the string you have chosen?Β» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions. You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.
256 megabytes
//package round275; 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 C3 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); char[][] s = new char[n][]; for(int i = 0;i < n;i++){ s[i] = ns().toCharArray(); } int m = s[0].length; int[] sames = new int[1<<m]; long[] dp = new long[1<<m]; for(int i = 0;i < n;i++){ for(int j = 0;j < n;j++){ if(j == i)continue; int same = 0; for(int k = 0;k < m;k++){ if(s[i][k] == s[j][k])same |= 1<<k; } dp[same] |= 1L<<i; } } for(int j = 0;j < m;j++){ for(int k = 0;k < 1<<m;k++){ dp[k] |= dp[k|1<<j]; } } for(int k = 0;k < 1<<m;k++){ sames[k] = Long.bitCount(dp[k]); } // k!(n-1-k)!/n! double[] ps = new double[m]; double[] f = new double[60]; f[0] = 1; for(int i = 1;i < 60;i++)f[i] = f[i-1] * i; for(int k = 0;k < m;k++){ ps[k] = f[k] * f[m-1-k] / f[m]; } // tr(sames); double e = 0; for(int i = 0;i < 1<<m;i++){ int k = Integer.bitCount(i); for(int j = 0;j < m;j++){ if(i<<~j<0){ e += k * ps[k-1] * (sames[i^1<<j]-sames[i]); } } } out.printf("%.12f\n", e/n); } int ord(char c) { if(c >= 'a' && c <= 'z')return c - 'a'; return c - 'A' + 26; } 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 C3().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\naab\naac", "3\naaA\naBa\nCaa", "3\naca\nvac\nwqq"]
1 second
["2.000000000000000", "1.666666666666667", "1.000000000000000"]
NoteIn the first sample the strings only differ in the character in the third position. So only the following situations are possible: you guess the string in one question. The event's probability is ; you guess the string in two questions. The event's probability is Β· = (as in this case the first question should ask about the position that is other than the third one); you guess the string in three questions. The event's probability is Β· Β· = ; Thus, the expected value is equal to In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is .In the third sample whatever position we ask about in the first question, we immediately identify the string.
Java 7
standard input
[ "dp", "bitmasks", "probabilities" ]
a95d9aef6a64c30e46330dcc8e6d4a67
The first line contains a single integer n (1 ≀ n ≀ 50)Β β€” the number of strings your friend came up with. The next n lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.
2,600
Print the single number β€” the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.
standard output
PASSED
dc928252b4020a07f201e39ea2883c99
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.InputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.math.BigInteger; public class Main{ static PrintWriter out; static InputReader ir; static void solve(){ int n=ir.nextInt(); int[] p=ir.nextIntArray(n); for(int i=0;i<n;i++) p[i]--; int[][] sw=new int[n][n]; for(int i=0;i<n;i++){ String s=ir.next(); for(int j=0;j<n;j++){ sw[i][j]=s.charAt(j)-'0'; } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ for(int k=0;k<n;k++){ sw[j][k]|=sw[j][i]&sw[i][k]; } } } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(sw[i][j]==1&&p[i]>p[j]) swap(p,i,j); } } for(int i=0;i<n;i++) p[i]++; for(int i=0;i<n;i++){ out.print(p[i]+(i==n-1?"\n":" ")); } } public static void swap(int[] a,int p,int q){ int temp=a[p]; a[p]=a[q]; a[q]=temp; } public static void main(String[] args) throws Exception{ ir=new InputReader(System.in); out=new PrintWriter(System.out); solve(); out.flush(); } static class InputReader { private InputStream in; private byte[] buffer=new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) {this.in=in; this.curbuf=this.lenbuf=0;} public boolean hasNextByte() { if(curbuf>=lenbuf){ curbuf= 0; try{ lenbuf=in.read(buffer); }catch(IOException e) { throw new InputMismatchException(); } if(lenbuf<=0) return false; } return true; } private int readByte(){if(hasNextByte()) return buffer[curbuf++]; else return -1;} private boolean isSpaceChar(int c){return !(c>=33&&c<=126);} private void skip(){while(hasNextByte()&&isSpaceChar(buffer[curbuf])) curbuf++;} public boolean hasNext(){skip(); return hasNextByte();} public String next(){ if(!hasNext()) throw new NoSuchElementException(); StringBuilder sb=new StringBuilder(); int b=readByte(); while(!isSpaceChar(b)){ sb.appendCodePoint(b); b=readByte(); } return sb.toString(); } public int nextInt() { if(!hasNext()) throw new NoSuchElementException(); int c=readByte(); while (isSpaceChar(c)) c=readByte(); boolean minus=false; if (c=='-') { minus=true; c=readByte(); } int res=0; do{ if(c<'0'||c>'9') throw new InputMismatchException(); res=res*10+c-'0'; c=readByte(); }while(!isSpaceChar(c)); return (minus)?-res:res; } public long nextLong() { if(!hasNext()) throw new NoSuchElementException(); int c=readByte(); while (isSpaceChar(c)) c=readByte(); boolean minus=false; if (c=='-') { minus=true; c=readByte(); } long res = 0; do{ if(c<'0'||c>'9') throw new InputMismatchException(); res=res*10+c-'0'; c=readByte(); }while(!isSpaceChar(c)); return (minus)?-res:res; } public double nextDouble(){return Double.parseDouble(next());} public BigInteger nextBigInteger(){return new BigInteger(next());} public int[] nextIntArray(int n){ int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] nextLongArray(int n){ long[] a=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public char[][] nextCharMap(int n,int m){ char[][] map=new char[n][m]; for(int i=0;i<n;i++) map[i]=next().toCharArray(); return map; } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
f873da3b48c7f1d3df1f1c8a82d1fbfc
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.InputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.math.BigInteger; public class Main{ static PrintWriter out; static InputReader ir; static void solve(){ int n=ir.nextInt(); int[] p=ir.nextIntArray(n); int[][] sw=new int[n][n]; for(int i=0;i<n;i++){ String s=ir.next(); for(int j=0;j<n;j++){ sw[i][j]=s.charAt(j)-'0'; } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ for(int k=0;k<n;k++){ sw[j][k]|=sw[j][i]&sw[i][k]; } } } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(sw[i][j]==1&&p[i]>p[j]) swap(p,i,j); } } for(int i=0;i<n;i++){ out.print(p[i]+(i==n-1?"\n":" ")); } } public static void swap(int[] a,int p,int q){ int temp=a[p]; a[p]=a[q]; a[q]=temp; } public static void main(String[] args) throws Exception{ ir=new InputReader(System.in); out=new PrintWriter(System.out); solve(); out.flush(); } static class InputReader { private InputStream in; private byte[] buffer=new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) {this.in=in; this.curbuf=this.lenbuf=0;} public boolean hasNextByte() { if(curbuf>=lenbuf){ curbuf= 0; try{ lenbuf=in.read(buffer); }catch(IOException e) { throw new InputMismatchException(); } if(lenbuf<=0) return false; } return true; } private int readByte(){if(hasNextByte()) return buffer[curbuf++]; else return -1;} private boolean isSpaceChar(int c){return !(c>=33&&c<=126);} private void skip(){while(hasNextByte()&&isSpaceChar(buffer[curbuf])) curbuf++;} public boolean hasNext(){skip(); return hasNextByte();} public String next(){ if(!hasNext()) throw new NoSuchElementException(); StringBuilder sb=new StringBuilder(); int b=readByte(); while(!isSpaceChar(b)){ sb.appendCodePoint(b); b=readByte(); } return sb.toString(); } public int nextInt() { if(!hasNext()) throw new NoSuchElementException(); int c=readByte(); while (isSpaceChar(c)) c=readByte(); boolean minus=false; if (c=='-') { minus=true; c=readByte(); } int res=0; do{ if(c<'0'||c>'9') throw new InputMismatchException(); res=res*10+c-'0'; c=readByte(); }while(!isSpaceChar(c)); return (minus)?-res:res; } public long nextLong() { if(!hasNext()) throw new NoSuchElementException(); int c=readByte(); while (isSpaceChar(c)) c=readByte(); boolean minus=false; if (c=='-') { minus=true; c=readByte(); } long res = 0; do{ if(c<'0'||c>'9') throw new InputMismatchException(); res=res*10+c-'0'; c=readByte(); }while(!isSpaceChar(c)); return (minus)?-res:res; } public double nextDouble(){return Double.parseDouble(next());} public BigInteger nextBigInteger(){return new BigInteger(next());} public int[] nextIntArray(int n){ int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] nextLongArray(int n){ long[] a=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public char[][] nextCharMap(int n,int m){ char[][] map=new char[n][m]; for(int i=0;i<n;i++) map[i]=next().toCharArray(); return map; } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
17f7548dcd71a5c23fbfad17e052e9aa
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.*; import java.util.*; public class B { static Set<Integer> g[]; static int[] vis; static ArrayList<Integer> list; static TreeSet<Integer> set; public static void main(String[] args)throws IOException { FastReader f=new FastReader(); StringBuffer sb = new StringBuffer(); int n=f.nextInt(); g=new HashSet[n+1]; for(int i=0;i<=n;i++) g[i]=new HashSet<>(); vis=new int[n+1]; int a[]=new int[n+1]; for(int i=1;i<=n;i++) a[i]=f.nextInt(); for(int i=1;i<=n;i++) { String s=f.next(); for(int j=1;j<=n;j++) { char x=s.charAt(j-1); if(x=='1') { g[i].add(j); g[j].add(i); } } } for(int i=1;i<=n;i++) { if(vis[i]==0) { list=new ArrayList<>(); set=new TreeSet<>(); dfs(i,a); //List --idx all component of cc //treeset --> val of all comp Collections.sort(list); for(int idx : list) { a[idx]=set.first(); set.pollFirst(); } } } for(int i=1;i<=n;i++) System.out.print(a[i]+" "); } static void dfs(int n,int a[]) { vis[n] = 1; list.add(n); set.add(a[n]); for (int child : g[n]) { if (vis[child]==0) dfs(child,a); } } } 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
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
f6fdbad90136004213dc2bad7fcc3f1d
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static PrintWriter out; private static FastReader in; private static boolean[] used; private static ArrayList<Integer> component; private static class FastReader { public BufferedReader reader; public StringTokenizer tokenizer; public FastReader(InputStream inputStream) { reader = new BufferedReader( new InputStreamReader(inputStream), 1 << 16); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException ex) { throw new RuntimeException(ex); } } return tokenizer.nextToken(); } public String nextLine() { try { return reader.readLine(); } catch (IOException ex) { throw new RuntimeException(ex); } } public int nextInt() { return Integer.parseInt(next()); } } public static void main(String[] args) throws FileNotFoundException { in = new FastReader(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); int[] P = new int[n]; for (int i = 0; i < n; ++i) { P[i] = in.nextInt(); } boolean[][] A = new boolean[n][n]; for (int i = 0; i < n; ++i) { char[] next = in.next().toCharArray(); for (int j = 0; j < n; ++j) { A[i][j] = next[j] == '1'; } } used = new boolean[n]; Arrays.fill(used, false); for (int i = 0; i < n; ++i) { if (!used[i]) { bfs(A, i); Collections.sort(component); int size = component.size(); for (int j = 0; j < size; ++j) { for (int k = j + 1; k < size; ++k) { int indexJ = component.get(j); int indexK = component.get(k); if (P[indexJ] > P[indexK]) { int t = P[indexJ]; P[indexJ] = P[indexK]; P[indexK] = t; } } } } } for (int i : P) { out.print(i + " "); } out.println(); out.flush(); } private static void bfs(boolean[][] G, int v) { Queue<Integer> Q = new ArrayDeque<>(); Q.add(v); used[v] = true; component = new ArrayList<>(); while (!Q.isEmpty()) { int from = Q.remove(); component.add(from); for (int i = 0; i < G.length; ++i) { if (G[from][i] && !used[i]) { Q.add(i); used[i] = true; } } } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
8630958cdeb5bc525e75caba04039a25
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Vector; public class B { private int[] id; private int count; public B(int N) { count = N; id = new int[N]; for (int i = 0; i < N; i++) id[i] = i; } public int count() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); } public int find(int p) { return id[p]; } public void union(int p, int q) { int pID = find(p); int qID = find(q); if (pID == qID) return; for (int i = 0; i < id.length; i++) { if (id[i] == pID) id[i] = qID; } count--; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); B uf = new B(n); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { String s = sc.next(); for (int j = 0; j < n; j++) { if (s.charAt(j) == '1') { uf.union(i, j); } } } Map<Integer, String> map = new HashMap<Integer, String>(); for (int i = 0; i < n; i++) { if (!map.containsKey(uf.find(i))) { map.put(uf.find(i), String.valueOf(i)); } else { String temp = map.get(uf.find(i)); temp += String.valueOf(i); map.replace(uf.find(i), temp); } } Map<Integer, Vector<Integer>> map1 = new HashMap<Integer, Vector<Integer>>(); for (int i = 0; i < n; i++) { if (!map1.containsKey(uf.find(i))) { Vector<Integer> vtemp = new Vector<Integer>(); vtemp.add(i); map1.put(uf.find(i), vtemp); } else { Vector<Integer> vtemp = map1.get(uf.find(i)); vtemp.add(i); } } Object[] value = map.values().toArray(); Object[] value1 = map1.values().toArray(); int[] result = new int[n]; // for (int i = 0; i < value.length; i++) { // System.out.println(value1[i]); // } for (int i = 0; i < value1.length; i++) { Vector vele = (Vector) value1[i]; String s = value[i].toString(); int temp[] = new int[vele.size()]; String pos = ""; for (int j = 0; j < vele.size(); j++) { pos = "" + vele.elementAt(j); temp[j] = a[Integer.parseInt(pos)]; } Arrays.sort(temp); for (int j = 0; j < temp.length; j++) { int tempvalue = temp[j]; result[Integer.parseUnsignedInt("" + vele.elementAt(j))] = tempvalue; } } for (int i = 0; i < n; i++) { System.out.print(result[i] + " "); } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
9c8e7e64d6e8256c807299500ffc8b8f
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] p = new int[n]; for (int i = 0; i < p.length; i++) { p[i] = sc.nextInt(); } char[][] A = new char[n][n]; for (int i = 0; i < n; i++) { String line = sc.next(); for (int j = 0; j < n; j++) { A[i][j] = line.charAt(j); } } System.out.println(solve(p, A)); sc.close(); } static String solve(int[] p, char[][] A) { boolean[] visited = new boolean[p.length]; for (int i = 0; i < visited.length; i++) { if (!visited[i]) { List<Integer> indices = new ArrayList<>(); search(indices, A, visited, i); sort(p, indices); } } return Arrays.stream(p).mapToObj(String::valueOf).collect(Collectors.joining(" ")); } static void search(List<Integer> indices, char[][] A, boolean[] visited, int node) { visited[node] = true; indices.add(node); for (int i = 0; i < visited.length; i++) { if (!visited[i] && A[node][i] == '1') { search(indices, A, visited, i); } } } static void sort(int[] p, List<Integer> indices) { int[] sortedIndices = indices.stream().sorted().mapToInt(x -> x).toArray(); int[] values = indices.stream().mapToInt(i -> p[i]).sorted().toArray(); for (int i = 0; i < sortedIndices.length; i++) { p[sortedIndices[i]] = values[i]; } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
b01f5543547fe0aa8d18e1961a29c3ac
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
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.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { int[] a; boolean[] taken; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); a = new int[n]; taken = new boolean[n]; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); } Vertex[] vs = new Vertex[n]; for (int i = 0; i < n; ++i) { vs[i] = new Vertex(); vs[i].index = i; } for (int i = 0; i < n; ++i) { String s = in.next(); for (int j = 0; j < s.length(); ++j) { if (s.charAt(j) == '1') { vs[i].adj.add(vs[j]); vs[j].adj.add(vs[i]); } } } for (int i = 0; i < n; ++i) { int minIdx = vs[i].findMinReplacement(); swap(a, minIdx, i); taken[i] = true; reset(vs); } for (int i = 0; i < n; ++i) { if (i > 0) out.print(" "); out.print(a[i]); } out.println(); } private void swap(int[] a, int minIdx, int i) { int temp = a[i]; a[i] = a[minIdx]; a[minIdx] = temp; } private void reset(Vertex[] vs) { for (int i = 0; i < vs.length; ++i) { vs[i].mark = false; } } class Vertex { int index; boolean mark = false; List<Vertex> adj = new ArrayList<>(); public int findMinReplacement() { this.mark = true; int res = index; int minValue = a[index]; if (taken[index]) { res = -1; minValue = Integer.MAX_VALUE; } for (Vertex v : adj) { if (v.mark) continue; int vIndex = v.findMinReplacement(); if (vIndex == -1) continue; if (minValue > a[vIndex]) { res = vIndex; minValue = a[vIndex]; } } return res; } } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
fa98504b3721299504b0aeed567a181c
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class NewYearPermutation { public static void main(String[] args) { FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = scan.nextInt(); boolean[][] can = new boolean[n][n]; for(int i = 0; i < n; i++){ char[] in = scan.next().toCharArray(); for(int j = 0; j < n; j++) if(in[j] == '1' || i == j) can[i][j] = true; } for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) for(int k = 0; k < n; k++) can[j][k] = (can[j][i] && can[i][k]) || can[j][k]; boolean[] u = new boolean[n]; for(int i = 0; i < n; i++){ int min = -1; for(int j = 0; j < n; j++){ if(!u[j] && can[i][j]){ if(min == -1 || a[min] > a[j]){ min = j; } } } u[min] = true; out.print(a[min]+" "); } out.close(); } static 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 String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; try {line = br.readLine();} catch (Exception e) {e.printStackTrace();} return line; } public int[] nextArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
d09954b77593a4d3397f7af1780e9d07
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void solution(BufferedReader reader, PrintWriter out) throws IOException { In in = new In(reader); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); UnionFind uf = new UnionFind(n); for (int i = 0; i < n; i++) { String s = in.next(); for (int j = 0; j < n; j++) if (s.charAt(j) == '1') uf.union(i, j); } boolean[] done = new boolean[n]; for (int i = 0; i < n; i++) if (!done[i]) { ArrayList<Integer> list = new ArrayList<Integer>(); for (int j = i; j < n; j++) if (uf.find(i) == uf.find(j)) { done[j] = true; list.add(a[j]); } Collections.sort(list); for (int j = i, k = 0; j < n; j++) if (uf.find(i) == uf.find(j)) a[j] = list.get(k++); } out.print(a[0]); for (int i = 1; i < n; i++) out.printf(" %d", a[i]); out.println(); } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out))); solution(reader, out); out.close(); } protected static class In { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public In(BufferedReader reader) { this.reader = reader; } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } } class UnionFind { private int[] id; public UnionFind(int n) { id = new int[n]; for (int i = 0; i < n; i++) id[i] = i; } public int find(int i) { return id[i] == i ? i : (id[i] = find(id[i])); } public void union(int p, int q) { int i = find(p); int j = find(q); if (i == j) return; id[j] = i; } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
91d0897be49ad70daf2db3160919bc71
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.StringTokenizer; public class Main { static class FastScanner { BufferedReader reader; StringTokenizer tokenizer; public FastScanner(InputStream stream) { this.reader = new BufferedReader(new InputStreamReader(stream)); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public int[] nextIntegerArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = nextLong(); } return a; } public int nextInt(int radix) throws IOException { return Integer.parseInt(next(), radix); } public long nextLong() throws IOException { return Long.parseLong(next()); } public long nextLong(int radix) throws IOException { return Long.parseLong(next(), radix); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } public BigInteger nextBigInteger(int radix) throws IOException { return new BigInteger(next(), radix); } public String next() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); return this.next(); } return tokenizer.nextToken(); } public void close() throws IOException { this.reader.close(); } } //SOLUTION // FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException{ new Main().solve(); }//void main void solve() throws IOException{ int n=in.nextInt(); int[] a = new int[n]; a=in.nextIntegerArray(n); int[][] rel = new int[n][n]; String s=null; for(int i = 0; i < n; i++) { s=in.next(); for(int j = 0; j < n; j++) if(s.charAt(j)=='1')rel[i][j]=1; else rel[i][j]=0; } for(int i = 0; i < n; i++) rel[i][i]=1; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ for(int k =0; k < n; k++){ if(rel[k][i]==1 && rel[i][j]==1) rel[j][k]=1; } } } int[] b = new int[n]; int min=0; for(int i = 0; i < n; i++ ){ min=i; for(int j = i; j < n; j++){ if(rel[i][j]==1 && a[min]>a[j]) min=j; } b[i]=a[min]; a[min]=a[i]; } for(int i = 0; i < n; i++) out.print(b[i]+" "); in.close(); out.flush(); out.close(); } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
8c55dff4f7b2c9db49d816e77bcc5ea8
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class GB14B { static int[] a; static char[][] mat; static int n; public static void main (String[] args) throws java.lang.Exception { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); n = in.nextInt(); a = in.nextIntArray(n); mat = new char[n][]; for (int i = 0; i < n; i++) mat[i] = in.next().toCharArray(); DJSet ds = new DJSet(n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) if (mat[i][j] == '1') ds.union(i, j); } for (int i = 0; i < n; i++) { int minind = i; for (int j = i + 1; j < n; j++) if (a[j] < a[minind] && ds.equiv(i, j)) minind = j; if (minind != i) { int temp = a[i]; a[i] = a[minind]; a[minind] = temp; } } for (int x : a) w.print(x + " "); w.close(); } public static class DJSet { public int[] upper; public DJSet(int n) { upper = new int[n]; Arrays.fill(upper, -1); } public int root(int x) { return upper[x] < 0 ? x : (upper[x] = root(upper[x])); } public boolean equiv(int x, int y) { return root(x) == root(y); } public boolean union(int x, int y) { x = root(x); y = root(y); if (x != y) { if (upper[y] < upper[x]) { int d = x; x = y; y = d; } upper[x] += upper[y]; upper[y] = x; } return x == y; } public int countCompo() { int ct = 0; for (int u : upper) if (u < 0) ct++; return ct; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } 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 void skip(int x) { while (x-- > 0) read(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextString() { return next(); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public boolean hasNext() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value != -1; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
df2f6f924d0d1b762e09276b9a981d62
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; import java.util.StringTokenizer; public class p022 { static boolean[][] G; static int[] a,b; static int n; public static void main(String args[]) throws Exception { StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next()); StringBuilder sb = new StringBuilder(); n = Integer.parseInt(stok.nextToken()); a = new int[n+1]; for (int i = 1; i <= n; i++) { a[i] = Integer.parseInt(stok.nextToken()); } G = new boolean[n+1][n+1]; for(int i=1;i<=n;i++) { char[] s = stok.nextToken().toCharArray(); for(int j=0;j<n;j++) if(s[j]=='1') G[i][j+1]=true; } b = new int[n+1]; int cnt=0; for(int i=1;i<=n;i++) if(b[i]==0) dfs(i,++cnt); ArrayList<Integer>[] als = new ArrayList[cnt+1]; for(int i=1;i<=cnt;i++) als[i] = new ArrayList<Integer>(); for(int i=1;i<=n;i++) als[b[i]].add(a[i]); for(int i=1;i<=cnt;i++) Collections.sort(als[i]); int[] mp = new int[cnt+1]; for(int i=1;i<=n;sb.append(a[i]+" "),i++) a[i] =als[b[i]].get(mp[b[i]]++); System.out.println(sb); } private static void dfs(int id, int v) { if(b[id]!=0) return; b[id]=v; for(int i=1;i<=n;i++) if(G[id][i]) dfs(i,v); } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
940533e30448461f7eaed7bb7f7c9b2d
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
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.TreeSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author bhavy seth */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public static void dfs(int initial, int u, TreeSet list[], boolean vis[], char[][] ch) { if (!vis[u]) { vis[u] = true; for (int i = 0; i < ch[u].length; i++) { if (ch[u][i] == '1') { //vis[u][i]=true; list[i].add(initial); dfs(initial, i, list, vis, ch); } } } } public void solve(int testNumber, InputReader sc, PrintWriter out) { int n = sc.nextInt(); Integer a[] = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } TreeSet<Integer> list[] = new TreeSet[n]; for (int i = 0; i < n; i++) { list[i] = new TreeSet<>(); } String s[] = new String[n]; char[][] ch = new char[n][n]; for (int i = 0; i < n; i++) { s[i] = sc.nextLine(); for (int j = 0; j < n; j++) { ch[i][j] = s[i].charAt(j); } } for (int i = 0; i < n; i++) { boolean vis[] = new boolean[n]; dfs(a[i], i, list, vis, ch); } HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < n; i++) { /* for(int j=0;j<list[i].size();j++){ if(!set.contains(list[i].get(j))){ a[i]=list[i].get(j); set.add(list[i].get(j)); break; } }*/ while (true) { if (list[i].size() == 0) break; else { int x = list[i].pollFirst(); if (!set.contains(x)) { a[i] = x; set.add(x); break; } } } } for (int i = 0; i < n; i++) { out.print(a[i] + " "); } } } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
fd5bf059e72c78cb7e5bcded2613c620
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { InputReader in = new InputReader(System.in); StringBuilder sb = new StringBuilder(); int n = in.nextInt(); int[] p = new int[n]; for(int i = 0; i < n; i++) p[i] = in.nextInt() - 1; int[][] A = new int[n][n]; for(int i = 0; i < n; i++) { String line = in.next(); for(int j = 0; j < n; j++) A[i][j] = line.charAt(j) - '0'; } boolean[] done = new boolean[n]; for(int i = 0; i < n; i++) if(!done[i]) { done[i] = true; ArrayList<Integer> indices = new ArrayList<Integer>(); indices.add(i); for(int j = 0; j < indices.size(); j++) { int cur = indices.get(j); for(int k = 0; k < n; k++) if(A[cur][k] == 1 && !done[k]) { indices.add(k); done[k] = true; } } int[] a = new int[indices.size()]; for(int j = 0; j < a.length; j++) a[j] = p[indices.get(j)]; Arrays.sort(a); Collections.sort(indices); for(int j = 0; j < a.length; j++) p[indices.get(j)] = a[j]; } for(int i = 0; i < n - 1; i++) sb.append(p[i] + 1 + " "); sb.append(p[n-1] + 1); System.out.println(sb); } static class InputReader { StringTokenizer st; BufferedReader br; public InputReader(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
baf43bb27e7a982dd3578e8f0ecd50c6
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.InputMismatchException; import java.util.StringTokenizer; public class permutations{ public static void main(String[] args){ Task task = new Task(); FastOutput out = new FastOutput(); task.solve(new FastInput(), out); out.close(); } } class Task{ int [] v; String[] m; int [] c; int [] c2; boolean [] vis; int csize; public void dfs(int i){ if(vis[i]) return; vis[i] = true; c[csize] = v[i]; c2[csize++] = i; for(int j = 0; j < m[i].length(); j++) if(m[i].charAt(j) == '1') dfs(j); } public void solve(FastInput in, FastOutput out){ int n = in.readInt(); v = new int[n]; in.readIntArray(v); m = new String[n]; for(int i = 0; i < n; i++) m[i] = in.read(); vis = new boolean[n]; Arrays.fill(vis, false); c = new int[n]; c2 = new int[n]; Integer[] ans = new Integer[n]; for(int i = 0; i < n; i++){ if(!vis[i]){ csize = 0; dfs(i); Arrays.sort(c, 0, csize); Arrays.sort(c2, 0, csize); for(int k = 0; k < csize; k++) ans[c2[k]] = c[k]; } } out.printLine(ans); } } class FastInput{ private BufferedReader reader; private StringTokenizer tokenizer; public FastInput(){ reader = new BufferedReader(new InputStreamReader(System.in), 1<<16); tokenizer = null; } public String read(){ while(tokenizer == null || !tokenizer.hasMoreTokens()){ try{ tokenizer = new StringTokenizer(reader.readLine()); }catch(Exception ex){ throw new InputMismatchException(); } } return tokenizer.nextToken(); } public int readInt(){ return Integer.parseInt(read()); } public long readLong(){ return Long.parseLong(read()); } public double readDouble(){ return Double.parseDouble(read()); } public char readChar(){ return read().charAt(0); } public void readIntArray(int[]... array){ for(int i = 0; i < array.length; i++) for(int j = 0; j < array[0].length; j++) array[i][j] = readInt(); } } class FastOutput { private PrintWriter writer; public FastOutput(){ writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } public void print(Object...args){ for(int i = 0; i < args.length; i++){ if(i > 0) writer.print(' '); writer.print(args[i]); } } public void printLine(Object[]...args){ for(int i = 0; i < args.length; i++){ print(args[i]); writer.println(); } } public void close(){ writer.close(); } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
d570372522d51d1f80d0d47fede474cc
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String ar[]) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); String s1[]=br.readLine().split(" "); int a[]=new int[n]; int b[][]=new int[n][n]; HashSet<Integer> hs[]=new HashSet[n+1]; TreeSet<Integer> ts[]=new TreeSet[n+1]; int c[]=new int[n+1]; HashSet<Integer> h=new HashSet<Integer>(); for(int i=1;i<=n;i++) { hs[i]=new HashSet<Integer>(); ts[i]=new TreeSet<Integer>(); } for(int i=0;i<n;i++) a[i]=Integer.parseInt(s1[i]); for(int i=0;i<n;i++) { String s2=br.readLine(); for(int j=0;j<n;j++) { b[i][j]=s2.charAt(j)-48; if(b[i][j]==1) { hs[a[i]].add(a[j]); hs[a[j]].add(a[i]); } } } int t=1; for(int i=1;i<=n;i++) { if(h.contains(i)) continue; ts[t].add(i); c[i]=t; Queue<Integer> q=new LinkedList<Integer>(); q.add(i); h.add(i); while(!q.isEmpty()) { int u=q.poll(); Iterator it=hs[u].iterator(); while(it.hasNext()) { int v=(int)it.next(); if(!h.contains(v)) { h.add(v); q.add(v); c[v]=t; ts[t].add(v); } } } t++; } // System.out.println(Arrays.toString(c)); // for(int i=1;i<t;i++) // System.out.println(ts[i]); StringBuffer sb=new StringBuffer(); for(int i=0;i<n;i++) { int u=a[i]; int p=c[u]; a[i]=ts[p].pollFirst(); //System.out.println(a[i]); //ts[u].remove(a[i]); sb.append(a[i]).append(" "); } System.out.println(sb); } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
15b6cbbc0f8c0afaef9d1ebee33b723c
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
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.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class Solution{ /////////////////////////////////////////////////////////////////////////// static class FastScanner{ BufferedReader s; StringTokenizer st; public FastScanner(InputStream InputStream){ st = new StringTokenizer(""); s = new BufferedReader(new InputStreamReader(InputStream)); } public FastScanner(File f) throws FileNotFoundException{ st = new StringTokenizer(""); s = new BufferedReader (new FileReader(f)); } public int nextInt() throws IOException{ if(st.hasMoreTokens()) return Integer.parseInt(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextInt(); } } public double nextDouble() throws IOException{ if(st.hasMoreTokens()) return Double.parseDouble(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextDouble(); } } public long nextLong() throws IOException{ if(st.hasMoreTokens()) return Long.parseLong(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextLong(); } } public String nextString() throws IOException{ if(st.hasMoreTokens()) return st.nextToken(); else{ st = new StringTokenizer(s.readLine()); return nextString(); } } public String readLine() throws IOException{ return s.readLine(); } public void close() throws IOException{ s.close(); } } //////////////////////////////////////////////////////////////////// // Number Theory long pow(long a,long b,long mod){ long x = 1; long y = a; while(b > 0){ if(b % 2 == 1){ x = (x*y); x %= mod; } y = (y*y); y %= mod; b /= 2; } return x; } int divisor(long x,long[] a){ long limit = x; int numberOfDivisors = 0; for (int i=1; i < limit; ++i) { if (x % i == 0) { limit = x / i; if (limit != i) { numberOfDivisors++; } numberOfDivisors++; } } return numberOfDivisors; } void findSubsets(int array[]){ long numOfSubsets = 1 << array.length; for(int i = 0; i < numOfSubsets; i++){ int pos = array.length - 1; int bitmask = i; while(bitmask > 0){ if((bitmask & 1) == 1) ww.print(array[pos]+" "); bitmask >>= 1; pos--; } ww.println(); } } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b,a%b); } public static int lcm(int a,int b, int c){ return lcm(lcm(a,b),c); } public static int lcm(int a, int b){ return (int) (a*b/gcd(a,b)); } public static long invl(long a, long mod) { long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } return p < 0 ? p + mod : p; } //////////////////////////////////////////////////////////////////// // private static FastScanner s = new FastScanner(new File("input.txt")); // private static PrintWriter ww = new PrintWriter(new FileWriter("output.txt")); static InputStream inputStream = System.in; static FastScanner s = new FastScanner(inputStream); static OutputStream outputStream = System.out; static PrintWriter ww = new PrintWriter(new OutputStreamWriter(outputStream)); // private static Scanner s = new Scanner(System.in); @SuppressWarnings("unused") private static int[][] states = { {-1,0} , {1,0} , {0,-1} , {0,1} }; //////////////////////////////////////////////////////////////////// public static void main(String[] args) throws IOException{ new Solution().solve(); s.close(); ww.close(); } //////////////////////////////////////////////////////////////////// char[][] vis; boolean[] lt; boolean[][] mark; int cnt = 0; void dfs(int x){ lt[x] = true; for(int i=0;i<vis.length;i++){ if(vis[x][i] == '1' && !lt[i]){ mark[cnt][i] = true; dfs(i); } } } void solve() throws IOException{ int n = s.nextInt(); int[] a = new int[n]; lt = new boolean[n]; mark = new boolean[n][n]; for(int i=0;i<n;i++) a[i] = s.nextInt(); vis = new char[n][n]; for(int i=0;i<n;i++){ String x = s.nextString(); for(int j=0;j<n;j++) vis[i][j] = x.charAt(j); } for(int i=0;i<n;i++){ Arrays.fill(lt, false); cnt = i; dfs(i); mark[i][i] = true; } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(a[j] < a[i] && mark[i][j]){ int sw = a[i]; a[i] = a[j]; a[j] = sw; } } } for(int i=0;i<n;i++) ww.print(a[i]+" "); } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
ee6501d7598d3092a05282d147812110
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.util.*; import java.util.Scanner; public class Position { static int[] color; static ArrayList<ArrayList> Link; // Link[colorindex] gives the vertices in that colored region static int N; static int[] arr; static int[][] A; static ArrayList<Integer> dfs(int i, int col){ //Coloring starting from the index i, color j color[i]=col; ArrayList<Integer> ans= new ArrayList<Integer>(); for(int j=1; j<=N; j++){ if( A[i][j] == 1 && color[j] == -1){ ans.addAll(dfs(j, col)); } } ans.add(i); Link.set(col, ans); return ans; } public static void main(String[] args) { // Link[colorindex] gives the vertices in that colored region Scanner scan=new Scanner(System.in); int n=Integer.parseInt(scan.nextLine()); Link= new ArrayList<ArrayList>(); N=n; color= new int[n+1]; arr= new int[n+1]; Arrays.fill(color, -1); String[] ss= new String[n]; ss =scan.nextLine().split(" "); for(int i=0; i<n;i++){ arr[i+1]= Integer.parseInt(ss[i]); } A= new int[n+1][n+1]; for(int i=1; i<=n; i++){ String[] s= scan.nextLine().split(""); for(int j=1;j<=n; j++){ A[i][j]= Integer.parseInt(s[j-1]); } } int j=0; for(int i=1; i<=n; i++){ if( color[i] == -1){ Link.add(new ArrayList<>()); dfs(i,j); j++; } } for(int i=1; i<=n-1; i++){ int swappingindex=i; ArrayList<Integer> ar= Link.get(color[i]); for(int k=0; k<ar.size(); k++){ if( i<= ar.get(k) && arr[swappingindex]>arr[ar.get(k)]){ swappingindex= ar.get(k); } } int a= arr[i]; arr[i]= arr[swappingindex]; arr[swappingindex]=a; } for(int l=1; l<=n; l++){ System.out.print(arr[l] + " "); } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
e90f9c76032ddc827cde965b047ee81f
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B { static int[] arr; static boolean[][] pos; static int N; public static void sort() { for (int j = 0; j < N; ++j) { for (int k = 0; k < N; ++k) { if (j != k && pos[j][k] && arr[j] < arr[k]) { swap(j, k); } } } } private static void swap(int a, int b) { int tmp = arr[a]; arr[a] = arr[b]; arr[b] = tmp; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); N = Integer.parseInt(st.nextToken()); arr = new int[N]; pos = new boolean[N][N]; st = new StringTokenizer(in.readLine()); for (int i = 0; i < N; i++) { arr[i] = Integer.parseInt(st.nextToken()); } for (int i = 0; i < N; i++) { String line = in.readLine(); for (int j = 0; j < N; j++) { pos[i][j] = line.charAt(j) == '1'; } } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < N; k++) { if (pos[j][i] && pos[i][k]) pos[j][k] = true; } } } sort(); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
a3dd615a94134cacf71072ed3d19d34d
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Bye_2014 { public static void main(String[] args) throws IOException{ PrintWriter pw = new PrintWriter(System.out, true); BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String[] line; int n = Integer.parseInt(input.readLine()); line = input.readLine().split(" "); int[] N = new int[n]; int[] index = new int[n]; for(int i=0;i<n;i++){ N[i] = Integer.parseInt(line[i])-1; index[N[i]] = i; } boolean[][] graph = new boolean[n][n]; String s; for(int i=0;i<n;i++){ s = input.readLine(); for(int j=0;j<n;j++){ if(s.charAt(j) == '0'){ graph[i][j] = false; }else{ graph[i][j] = true; } } graph[i][i] = true; } for(int k=0;k<n;k++){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ graph[i][j] = graph[i][j] || ((graph[i][k] && graph[k][j])); //graph[j][i] = graph[i][j]; } } } int tmp; boolean[] check = new boolean[n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(graph[i][index[j]] && !check[j]){ check[j] = true; tmp = N[i]; N[i] = N[index[j]]; N[index[j]] = tmp; int xx = index[j]; index[j] = i; index[tmp] = xx; break; } } } for(int i=0;i<n-1;i++){ pw.print((N[i]+1)+" "); } pw.println((N[n-1]+1)); pw.close(); input.close(); } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
341341f292f6f30e6dc04c237f37dcb7
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Codechef { static PrintWriter out=new PrintWriter(System.out);static FastScanner in = new FastScanner(System.in);static class FastScanner {BufferedReader br;StringTokenizer stok;FastScanner(InputStream is) {br = new BufferedReader(new InputStreamReader(is));} String next() throws IOException {while (stok == null || !stok.hasMoreTokens()) {String s = br.readLine();if (s == null) {return null;} stok = new StringTokenizer(s);}return stok.nextToken();} int ni() throws IOException {return Integer.parseInt(next());}long nl() throws IOException {return Long.parseLong(next());}double nd() throws IOException {return Double.parseDouble(next());}char nc() throws IOException {return (char) (br.read());}String ns() throws IOException {return br.readLine();} int[] nia(int n) throws IOException{int a[] = new int[n];for (int i = 0; i < n; i++)a[i] = ni();return a;}long[] nla(int n) throws IOException {long a[] = new long[n];for (int i = 0; i < n; i++)a[i] = nl();return a;} double[] nda(int n)throws IOException {double a[] = new double[n];for (int i = 0; i < n; i++)a[i] = nd();return a;}int [][] imat(int n,int m) throws IOException{int mat[][]=new int[n][m];for(int i=0;i<n;i++){for(int j=0;j<m;j++)mat[i][j]=ni();}return mat;} } static long mod=Long.MAX_VALUE; static ArrayList<Integer> arr[]; static ArrayList<Integer> temp; static boolean visited[]; public static void main (String[] args) throws java.lang.Exception { int i,j; HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); /* if(hm.containsKey(z)) hm.put(z,hm.get(z)+1); else hm.put(z,1); */ HashSet<Integer> set=new HashSet<Integer>(); PriorityQueue<Integer> pq=new PriorityQueue<Integer>(); int n=in.ni(); int a[]=new int[n+1]; for(i=1;i<=n;i++) a[i]=in.ni(); arr=new ArrayList[n+1]; for(i=0;i<=n;i++) arr[i]=new ArrayList<Integer>(); visited=new boolean[n+1]; for(i=1;i<=n;i++) { String s=in.next(); for(j=0;j<n;j++) if(s.charAt(j)=='1') { arr[i].add(j+1); arr[j+1].add(i); } } int ans[]=new int[n+1]; for(i=1;i<=n;i++) { if(!visited[i]) { temp=new ArrayList<Integer>(); dfs(i); Collections.sort(temp); //out.println(temp); for(int c:temp) pq.add(a[c]); for(int c:temp) ans[c]=pq.poll(); } } for(i=1;i<=n;i++) out.print(ans[i]+" "); out.close(); } static void dfs(int a) { if(visited[a]) return ; visited[a]=true; temp.add(a); for(int c:arr[a]) dfs(c); } static class pair implements Comparable<pair>{ int x, y; public pair(int x, int y){this.x = x; this.y = y;} @Override public int compareTo(pair arg0) { if(x<arg0.x) return -1; else if(x==arg0.x) { if(y<arg0.y) return -1; else if(y>arg0.y) return 1; else return 0; } else return 1; } } static long gcd(long a,long b) { if(b==0) return a; return gcd(b,a%b); } static long exponent(long a,long n) { long ans=1; while(n!=0) { if(n%2==1) ans=(ans*a)%mod; a=(a*a)%mod; n=n>>1; } return ans; } static int binarySearch(int a[], int item, int low, int high) { if (high <= low) return (item > a[low])? (low + 1): low; int mid = (low + high)/2; if(item == a[mid]) return mid+1; if(item > a[mid]) return binarySearch(a, item, mid+1, high); return binarySearch(a, item, low, mid-1); } static void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else{ arr[k] = R[j]; j++; } k++; } while (i < n1){ arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } static void Sort(int arr[], int l, int r) {if (l < r) { int m = (l+r)/2; Sort(arr, l, m); Sort(arr , m+1, r); merge(arr, l, m, r); } } static void sort(int a[]) {Sort(a,0,a.length-1);} }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
d37a92d442bc790a9240b82bfcabf592
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.util.Scanner; public class Main { static int n; static int[] arr; static int[][] a; static boolean[] visited; static int value, pos, aim; public static void main(String[] args) { Scanner cin = new Scanner(System.in); n = cin.nextInt(); arr = new int[n]; a = new int[n][n]; for (int i = 0; i < n; i++) { arr[i] = cin.nextInt(); } cin.nextLine(); for (int i = 0; i < n; i++) { char[] s = cin.nextLine().toCharArray(); for (int j = 0; j < n; j++) { a[i][j] = s[j] - '0'; } } for (int i = 0; i < n; i++) { visited = new boolean[n]; value = arr[i]; pos = i; aim = i; dfs(i); swap(i, pos); } show(); cin.close(); } protected static void show() { for (int i=0;i<n;i++) { System.out.print(arr[i] + " "); } System.out.println(); } private static void swap(int x, int y) { int temp = arr[x]; arr[x] = arr[y]; arr[y] = temp; } private static void dfs(int now) { visited[now] = true; for (int i = 0; i < n; i++) { if (a[now][i] == 1) { if (arr[i] < value && aim < i) { value = arr[i]; pos = i; } if (!visited[i]) { dfs(i); } } } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
a7016f4c325501f25a27de616e3145eb
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.*; public class A_GENERAL { // for fast output printing : use printwriter or stringbuilder // remember to close pw using pw.close() static StringBuilder sb = new StringBuilder(); static long seive_size = (long) 1e6; static String alpha = "abcdefghijklmnopqrstuvwxyz"; static ArrayList<Integer> primes = new ArrayList<>(); static boolean[] set = new boolean[(int) seive_size+1]; static int n, m, k; static ArrayList<Integer>[] adj; static boolean[] visited; static ArrayDeque<Integer> q = new ArrayDeque<>(); static final long MOD = 998244353; static int[] dx = new int[] {1, 0, -1, 0, 1, 1, -1, -1}; static int[] dy = new int[] {0, 1, 0, -1, 1, -1, 1, -1}; static long[][] arr; static int[] rank; static int[] parent; static int[] p; static char[][] A; static ArrayList<Integer> res; static ArrayList<Integer> indices; public static void main(String[] args) { PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); MyScanner sc = new MyScanner(); n = sc.nextInt(); p = new int[n+1]; init(n); parent = new int[n+1]; for(int i = 1; i <= n; i++) { p[i] = sc.nextInt(); parent[p[i]] = i; } A = new char[n+1][n+1]; for(int i = 1; i <=n; i++) { String s= sc.next(); for(int j = 1; j <=n; j++) { A[i][j] = s.charAt(j-1); } } for(int i = 1; i <= n; i++) { if(!visited[i]) { res = new ArrayList<>(); indices = new ArrayList<>(); dfs(i); // for(int x : res) { // System.out.println("x = " + x + ", parent[x] = " + parent[x]); // indices.add(parent[x]); // } Collections.sort(res); Collections.sort(indices); int tt = 0; for(int x : indices) { // System.out.println("x = " + x + ", res.get(tt++) = " + res.get(tt)); p[x] = res.get(tt++); } } } for(int i = 1; i <= n; i++) { out.print(p[i] + " "); } out.close(); } public static void dfs(int u) { visited[u] = true; res.add(p[u]); indices.add(u); for(int v = 1; v < A[u].length; v++) { if(!visited[v] && A[u][v] == '1') { dfs(v); } } } public static class Triplet implements Comparable<Triplet> { int x; int y; int z; Triplet(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public int compareTo(Triplet o) { return Integer.compare(this.x, o.x); } } public static class Pair implements Comparable<Pair>{ long f; long s; Pair(long f, long s) { this.f = f; this.s = s; } public int compareTo(Pair o) { return Long.compare(this.f, o.f); } } public static void init(int n) { adj = new ArrayList[n+1]; visited = new boolean[n+1]; parent = new int[n+1]; rank = new int[n+1]; for(int i = 0; i <= n; i++) { adj[i] = new ArrayList(); parent[i] = i; rank[i] = 0; } } // print string "s" multiple times // prefer to use this function for multiple printing public static String mp(String s, int times) { return String.valueOf(new char[times]).replace("\0", s); } // take log with base 2 public static long log2(long k) { return 63-Long.numberOfLeadingZeros(k); } // using lambda function for sorting public static void lambdaSort() { Arrays.sort(arr, (a, b) -> Double.compare(a[0], b[0])); } // (n choose k) = (n/k) * ((n-1) choose (k-1)) public static long choose(long n, long k) { return (k == 0) ? 1 : (n*choose(n-1, k-1))/k; } // just for keeping gcd function for other personal purposes public static long gcd(long a, long b) { return (a == 0) ? b : gcd(b%a, a); } public static long max(long... as) { long max = Long.MIN_VALUE; for (long a : as) max = Math.max(a, max); return max; } public static long min(int... as) { long min = Long.MAX_VALUE; for (long a : as) min = Math.min(a, min); return min; } public static long modpow(long x, long n, long mod) { if(n == 0) return 1%mod; long u = modpow(x, n/2, mod); u = (u*u)%mod; if(n%2 == 1) u = (u*x)%mod; return u; } // ======================= binary search (lower and upper bound) ======================= public static int lowerBound(long[] a, int x) { int lo = 0; int hi = a.length-1; int ans = -1; while(lo <= hi) { int mid = (lo+hi)/2; if(x < a[mid]) { hi = mid-1; } else if(x > a[mid]) { lo = mid+1; } else if(lo != hi) { hi = mid-1; // for first occurrence ans = mid; } else { return mid; } } return ans; } public static int upperBound(long[] a, long x) { int lo = 0; int hi = a.length-1; int ans = -1; while(lo <= hi) { int mid = (lo+hi)/2; if(x < a[mid]) { hi = mid-1; } else if(x > a[mid]) { lo = mid+1; } else if(lo != hi) { lo = mid+1; // for last occurrence ans = mid; } else { return mid; } } return ans; } // ================================================================ // ================== SEIVE OF ERATOSTHENES ======================= // Complexity : O(N * log(log(N))) ( almost O(N) ) public static void generatePrimes() { // set.add(0); // set.add(1); Arrays.fill(set, true); set[0] = false; set[1] = false; for(int i = 2; i <= seive_size; i++) { if(set[i]) { for(long j = (long) i*i; j <= seive_size; j+=i) set[(int)j] = false; primes.add(i); } } } public static boolean isPrime(long N) { if(N <= seive_size) return set[(int)N]; for (int i = 0; i < (int)primes.size(); i++) if (N % primes.get(i) == 0) return false; return true; } // =========================================================== // ================ Permutation of String ==================== public static void permute(String str) { permute(str, 0, str.length()-1); } public static void permute(String str, int l, int r) { if (l == r) System.out.println(str); else { for (int i = l; i <= r; i++) { str = swap(str,l,i); permute(str, l+1, r); str = swap(str,l,i); } } } public static String swap(String a, int i, int j) { char temp; char[] charArray = a.toCharArray(); temp = charArray[i] ; charArray[i] = charArray[j]; charArray[j] = temp; return String.valueOf(charArray); } // Union-find // static int[] parent, rank; // public static void makeSet(int n) { // // parent = new int[n+1]; // rank = new int[n+1]; // for(int i = 1; i <= n; i++) { // parent[i] = i; // rank[i] = 0; // } // } public static int find(int u) { if(parent[u] == u) return u; int v = find(parent[u]); parent[u] = v; return v; } public static boolean connected(int u, int v) { return find(u) == find(v); } public static void Union(int u, int v) { int x = find(u); //root of u int y = find(v); //root of v if(x == y) return; if(rank[x] == rank[y]) { parent[y] = x; rank[x]++; } else if(rank[x] > rank[y]) { parent[y] = x; } else { parent[x] = y; } } // public static int dijkstra(int x, int y) { // int[] dist = new int[n+1]; // Arrays.fill(dist, Integer.MAX_VALUE); // PriorityQueue<Node> q = new PriorityQueue<>(); // q.add(new Node(x, 0)); // dist[x] = 0; // while(!q.isEmpty()) { // Node node = q.poll(); // int u = node.key; // if(u == y) { // break; // } // for(int v : res[u]) { // if(dist[v] > dist[u]+count[u]) { // dist[v] = dist[u] + count[u]; // q.add(new Node(v, dist[v])); // } // } // } // if(dist[y] == Integer.MAX_VALUE) { // return -1; // } // return dist[y]; // } 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;} 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; } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
88e59ed20b35be3920910e6d31b59acf
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; /** * * @author Tu Van Ninh */ public class ACMTraining { Scanner sc; int n; int[] p,v; String[] perm; ArrayList<Integer>[] edge; ArrayList<Integer>[] dsu; /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here ACMTraining object = new ACMTraining(); object.readData(); object.createGraph(); object.createDSU(); object.Solve(); } private void readData(){ sc = new Scanner(System.in); n = sc.nextInt(); p = new int[n+1]; perm = new String[n+1]; for (int i=0; i<n; i++) p[i] = sc.nextInt(); for (int i=0; i<n; i++) perm[i] = sc.next(); sc.close(); } private void createGraph(){ edge = new ArrayList[n+1]; for (int i=1; i<n+1; i++){ edge[i] = new ArrayList<>(); for(int j=0; j<perm[i-1].length(); j++){ if (perm[i-1].charAt(j) == '1'){ edge[i].add(j+1); } } } } private void createDSU(){ v = new int[n+1]; for (int i=0; i<n+1; i++) v[i] = i; for (int i=1; i<n+1; i++){ for (int j=0; j<edge[i].size(); j++){ int u = findParent(edge[i].get(j)); int w = findParent(i); if (w > u) w = getItself(u, u = w); v[u] = w; } } dsu = new ArrayList[n+1]; for (int i=0; i<n+1; i++) dsu[i] = new ArrayList<>(); for (int i=1; i<n+1; i++){ int u = findParent(v[i]); dsu[u].add(i); } for (int i=1; i<n+1; i++){ Collections.sort(dsu[i]); } } private int findParent(int u){ if (v[u] == u) return u; return v[u] = findParent(v[u]); } private int getItself(int a, int b){ return a; } private void Solve(){ ArrayList<Integer> tmpList = new ArrayList<>(); for (int i=1; i<n+1; i++){ if (dsu[i].size() > 0){ tmpList.clear(); for (Integer it : dsu[i]){ tmpList.add(p[it-1]); } Collections.sort(tmpList); for (int j=0; j<dsu[i].size(); j++){ p[dsu[i].get(j)-1] = tmpList.get(j); } } } for (int i=0; i<n; i++) System.out.printf("%d ", p[i]); } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
3fe56b7671cc44f8c33409ae1beb83ce
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
//package denxx; import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] p = new int[n]; for (int i = 0; i < n; ++i) { p[i] = in.nextInt(); } String[] a = new String[n]; for (int i = 0; i < n; ++i) { a[i] = in.next(); } int[] res = new int[n]; boolean[] v = new boolean[n]; for (int i = 0; i < n; ++i) { if (!v[i]) { ArrayList<Integer> pos = new ArrayList<Integer>(); ArrayList<Integer> num = new ArrayList<Integer>(); Stack<Integer> q = new Stack<Integer>(); v[i] = true; q.push(i); while (!q.isEmpty()) { int t = q.pop(); pos.add(t); num.add(p[t]); v[t] = true; for (int j = 0; j < n; ++j) { if (a[t].charAt(j) == '1' && !v[j]) { v[j] = true; q.push(j); } } } Collections.sort(num); Collections.sort(pos); for (int j = 0; j < pos.size(); ++j) { res[pos.get(j)] = num.get(j); } } } for (int i = 0; i < n; ++i) { if (i > 0) System.out.print(" "); System.out.print(res[i]); } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
eea6a364c2ba29c7c048c38c6663174d
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.util.*; import java.io.*; public class Codeforces { InputStream is; PrintWriter out; String INPUT = ""; //----------------------------------------------------------------------------------------------------// void solve() { int n=ni(); Dsu uf=new Dsu(n); int a[]=new int[n]; for (int i = 0; i < n; i++) { a[i]=ni()-1; } for (int i = 0; i < n; i++) { char s[]=ns(n); for (int j = 0; j < n; j++) { if(s[j]=='1'){ uf.union(j, i); } } } int c=uf.count(); int roots[]=new int[n]; int idx=0; for (Integer r : uf.roots) { roots[r]=idx; idx++; } List<List<Integer>> al = new ArrayList<>(); for (int i = 0; i < c; i++) { List<Integer> l = new ArrayList<Integer>(); al.add(i,l); } for (int i = 0; i < n; i++) { int rt=uf.root(i); if(uf.size[rt]>1) al.get(roots[rt]).add(i); } for (List<Integer> l : al) { Collections.sort(l); int x[]=new int[l.size()]; idx=0; for (Integer i : l) { x[idx]=a[i]; idx++; } Arrays.sort(x); for (int i = 0; i < idx; i++) { a[l.get(i)]=x[i]; } } for (int i = 0; i < n; i++) { out.print(a[i]+1+" "); } } //----------------------------------------------------------------------------------------------------// boolean isPrime(int n) { if (n <= 1) { return false; } for (int i = 2; i <= (int) Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } Vector<Integer> sieveOfEratosthenes(int n) { boolean[] prime = new boolean[n + 1]; for (int i = 0; i < n; i++) { prime[i] = true; } for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int j = p * p; j <= n; j += p) { prime[j] = false; } } } Vector<Integer> v = new Vector<>(); for (int i = 2; i <= n; i++) { if (prime[i]) { v.add(i); } } return v; } void swap(int a[], int l, int r) { int temp = a[l]; a[l] = a[r]; a[r] = temp; } long nCr(int n, int k) { long C[] = new long[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { for (int j = Math.min(i, k); j > 0; j--) { C[j] = C[j] + C[j - 1]; } } return C[k]; } int gcd(int s, int l) { if (s == 0) { return l; } return gcd(l % s, s); } int power(long x, long y, int m) { //log(y) if (y == 0) { return 1; } long p = power(x, y / 2, m) % m; p = (p * p) % m; return (int) ((y % 2 == 0) ? p : (x * p) % m); } int modInverse(int a, int m) // O(Log m) whem m is prime (fermat's little theorem) { if (gcd(a, m) != 1) { return -1; } else { return power(a, m - 2, m); } } public HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<Integer, Integer>> list = new LinkedList<>(hm.entrySet()); //->change o1,o2 for reverseorder Collections.sort(list, (Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) -> (o1.getValue()).compareTo(o2.getValue())); // put data from sorted list to hashmap HashMap<Integer, Integer> temp = new LinkedHashMap<>(); list.forEach((aa) -> { temp.put(aa.getKey(), aa.getValue()); }); return temp; } void run() throws Exception { is = System.in;//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 Codeforces().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)); } } class Pair { /*SORTING PAIRS BY COMPARING Y OF PAIR. Pair[] p=new Pair[n]; p[i]=new Pair(i,ni()); Arrays.sort(p,( p1, p2) -> {return p1.y-p2.y;}); */ int x; int y; Pair(int u, int v) { x = u; y = v; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Pair)) { return false; } Pair key = (Pair) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } } class Dsu { int par[]; int size[]; int cnt; Set<Integer> roots = new HashSet<>(); //boolean belongs[]; Dsu(int n) { cnt = n;//cnt=0; par = new int[n]; size = new int[n]; //belongs=new boolean[n]; for (int i = 0; i < n; i++) { par[i] = i; size[i] = 1; //belongs[i]=false; } } int root(int i) { if (i == par[i]) { return i; } return par[i] = root(par[i]); } boolean find(int p, int q) { return root(p) == root(q); } void union(int p, int q) { int a = root(p); int b = root(q); roots.add(a); roots.add(b); if (a != b) { cnt--; } /*if(!belongs[p]&&!belongs[q])cnt++; else if(belongs[p]&&belongs[q]){ if(a!=b)cnt--; } belongs[p]=belongs[q]=true;*/ if (a == b) { return; } if (size[a] < size[b]) { int temp = a; a = b; b = temp; } par[b] = a; size[a] += size[b]; roots.add(a); if (roots.contains(b)) { roots.remove(b); } } Set<Integer> getRoots() { return roots; } int count() { return cnt; } } } //isPrime(int) //Vector<Integer> sieveOfEratosthenes(int n){PRIME NO <=n} //swap(arr,i,j) //HashMap sortByValue(map); //long comb=nCr(5,2); //int gcd(s,l); //Pair p=new Pair(x,y); // Dsu dsu=new Dsu(n);
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
e8969313b29ee2dd5364df362f4b5827
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.util.*; import java.io.*; public class Graph { ArrayList<Integer> adj[]; static int V; Graph(int v) { V=v; adj=new ArrayList[v]; for(int i=0;i<v;i++) adj[i] = new ArrayList<>(); } void addEdge(int u,int v) { adj[u].add(v); adj[v].add(u); } void DFS(int a[]){ for(int i=0;i<V;i++) { boolean visited[]=new boolean[V]; int t=DFSUtil(i,visited,a,i); int temp=a[t]; a[t]=a[i]; a[i]=temp; } boolean visited[]=new boolean[V]; // ArrayList<Integer> arr=new ArrayList<>(); // int t=DFSUtil(2,visited,a,2,arr); //for(int i=0;i<arr.size();i++) // System.out.print(arr.get(i)+" "); //System.out.println(t); for(int i=0;i<V;i++) System.out.print(a[i]+" "); System.out.println(); } int DFSUtil(int s,boolean visited[],int a[],int p){ visited[s]=true; int minI=s; if(s<p) minI=p; for(int i=0;i<adj[s].size();i++){ if(!visited[adj[s].get(i)]){ int t=DFSUtil(adj[s].get(i),visited,a,p); if(a[t]<a[minI]&&t>p) minI=t; } } return minI; } public static void main (String[] args)throws java.lang.Exception { // Reader sc=new Reader(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=1; // t=sc.nextInt(); // int t=Integer.parseInt(br.readLine()); while(--t>=0){ int n=Integer.parseInt(br.readLine()); Graph g=new Graph(n); StringTokenizer st=new StringTokenizer(br.readLine()); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=Integer.parseInt(st.nextToken()); for(int i=0;i<n;i++) { String s=br.readLine(); for(int j=0;j<s.length();j++) if(s.charAt(j)=='1') g.addEdge(i,j); } g.DFS(a); } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
119df9b844d43ede6d019216700a2372
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.util.PriorityQueue; import java.util.AbstractQueue; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Ribhav */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BNewYearPermutation solver = new BNewYearPermutation(); solver.solve(1, in, out); out.close(); } static class BNewYearPermutation { public void solve(int testNumber, FastReader in, PrintWriter out) { int quant = in.nextInt(); int[] arr = in.nextIntArray(quant); int[][] con = new int[quant][quant]; for (int x = 0; x < quant; x++) { String s = in.readLine(); for (int y = 0; y < quant; y++) { con[x][y] = s.charAt(y) - '0'; } } int counter = 1; int[] visited = new int[quant]; for (int x = 0; x < visited.length; x++) { if (visited[x] == 0) { DFS(x, visited, con, counter); counter++; } } int[] res = new int[quant]; for (int x = 1; x <= quant; x++) { PriorityQueue<Integer> set = new PriorityQueue<Integer>(); for (int y = 0; y < quant; y++) { if (visited[y] == x) { set.add(arr[y]); } } for (int y = 0; y < quant; y++) { if (visited[y] == x) { res[y] = set.remove(); } } } for (int x = 0; x < quant - 1; x++) { System.out.print(res[x] + " "); } System.out.println(res[quant - 1]); } private static void DFS(int loc, int[] visited, int[][] con, int count) { visited[loc] = count; for (int x = 0; x < con.length; x++) { if (con[loc][x] == 1 && visited[x] == 0) { DFS(x, visited, con, count); } } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(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 boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
4f015be5a8ba2d3fd4d1720bcc0ce99e
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.util.Scanner; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class Java { static Scanner sc = new Scanner(System.in); static int n = sc.nextInt(); static int[] fix = new int[n]; static ArrayList<ArrayList<Integer>> V = new ArrayList<ArrayList<Integer>>(); public static void main(String[] args) { int[] arr = new int[n]; char[][] matrix = new char[n][n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); for (int i = 0; i < n; i++) { String s = sc.next(); for (int j = 0; j < n; j++) matrix[i][j] = s.charAt(j); } for (int i = 0; i < n; i++) { V.add(new ArrayList<Integer>()); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == '1') { V.get(i).add(j); } } } ArrayList<ArrayList<Integer>> components = new ArrayList<ArrayList<Integer>>(); for (int i = 0; i <= n; i++) components.add(new ArrayList<Integer>()); int num = 1; for (int i = 0; i < n; i++) { if (fix[i] > 0) { components.get(fix[i]).add(arr[i]); continue; } dfs(i, num); components.get(fix[i]).add(arr[i]); num++; } int[] fixed = new int[n]; for (int i = 0; i < components.size(); i++) Collections.sort(components.get(i)); int[] count = new int[components.size()]; for (int i = 0; i < components.size() - 1; i++) { System.out.print(components.get(fix[i]).get(count[fix[i]]) + " "); count[fix[i]]++; } } public static void dfs(int vertex, int num) { fix[vertex] = num; for (int i = 0; i < V.get(vertex).size(); i++) { if (fix[V.get(vertex).get(i)] == 0) dfs(V.get(vertex).get(i), num); } return; } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
5e291bad21d10b487ecfef1b8ee07793
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.*; import java.util.*; public class NeyYearPerm{ static int[] id; public static void main(String[]args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] a=new int[n+1]; id=new int[n+1]; for(int i=0;i<n;i++){ a[i]=Integer.parseInt(st.nextToken()); id[i]=i; } char[][] matrix=new char[n][n]; for(int i=0;i<n;i++){ matrix[i]=br.readLine().toCharArray(); } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(matrix[i][j]=='1')union(i,j); } } for(int i=0;i<n;i++){ //int mini=i; for(int j=i+1;j<n;j++){ if(a[i]>a[j] && find_root(i)==find_root(j)){ int tmp=a[i]; a[i]=a[j];a[j]=tmp; } } } bw.write(a[0]+""); for(int i=1;i<n;i++){ bw.write(" "+a[i]); } bw.close(); } private static void union(int i,int j){ int root1=find_root(i),root2=find_root(j); id[root1]=id[root2]; } private static int find_root(int i){ while(id[i]!=i){ id[i]=id[id[i]]; i=id[i]; } return i; } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
493b0bc54e56917804ef35552bbffbe9
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; public class Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static boolean eof = false; static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws IOException { tokenizer = null; // reader = new BufferedReader(new FileReader("grave.in")); // writer = new PrintWriter(new FileWriter("grave.out")); reader = new BufferedReader(new InputStreamReader(System.in, "ISO-8859-1")); writer = new PrintWriter(System.out); banana(); reader.close(); writer.close(); } static List<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>(); static List<Integer> inds = new ArrayList<Integer>(); static List<Integer> vals = new ArrayList<Integer>(); static boolean used[]; static int a[]; static void dfs(int v) { used[v] = true; inds.add(v); vals.add(a[v]); for (int i = 0; i < g.get(v).size(); ++i) { int to = g.get(v).get(i); if (!used[to]) dfs(to); } } static void banana() throws IOException { int n = nextInt(); a = new int[n]; used = new boolean[n + 1]; for (int i = 0; i < n; ++i) a[i] = nextInt(); int b[][] = new int[n][n]; for (int i = 0; i < n; ++i) { String s = nextToken(); for (int j = 0; j < n; ++j) { b[i][j] = s.charAt(j); } } for (int i = 0; i <= n; ++i) g.add(new ArrayList<Integer>()); for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) { if (b[i][j] == '1') { g.get(i).add(j); g.get(j).add(i); } } for (int i = 0; i < n; ++i) { inds = new ArrayList<Integer>(); vals = new ArrayList<Integer>(); if (!used[i]) dfs(i); Collections.sort(vals); Collections.sort(inds); for (int j = 0; j < vals.size(); ++j) a[inds.get(j)] = vals.get(j); } for (int i = 0; i < n; ++i) System.out.print(a[i] + " "); } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
4fbf07d078fb0392b63f26ed1984640f
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Map; import java.util.Map.Entry; import java.util.Collections; 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); BNewYearPermutation solver = new BNewYearPermutation(); solver.solve(1, in, out); out.close(); } static class BNewYearPermutation { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[][] arr = new int[n + 1][n + 1]; int[] p = new int[n + 1]; for (int i = 1; i <= n; i++) p[i] = in.nextInt(); BNewYearPermutation.DisjointSet ds = new BNewYearPermutation.DisjointSet(n); for (int i = 1; i <= n; i++) { String str = in.nextLine(); for (int j = 1; j <= n; j++) { arr[i][j] = str.charAt(j - 1) - 48; if (arr[i][j] == 1) ds.union(i, j); } } HashMap<Integer, ArrayList<Integer>> parents = new HashMap<>(); for (int i = 1; i <= n; i++) { int par = ds.root(i); if (!parents.containsKey(par)) parents.put(par, new ArrayList<>()); parents.get(par).add(i); } int[] ans = new int[n + 1]; for (Map.Entry<Integer, ArrayList<Integer>> entry : parents.entrySet()) { ArrayList<Integer> indices = entry.getValue(); ArrayList<Integer> num = new ArrayList<>(); for (int x : indices) num.add(p[x]); Collections.sort(indices); Collections.sort(num); for (int i = 0; i < indices.size(); i++) ans[indices.get(i)] = num.get(i); } for (int i = 1; i <= n; i++) out.printf("%d ", ans[i]); } static class DisjointSet { private int[] parent; private int[] setSize; private int numOfSets; private DisjointSet(int n) { parent = new int[n + 1]; setSize = new int[n + 1]; for (int i = 1; i <= n; i++) { parent[i] = i; setSize[i] = 1; } numOfSets = n; } private int root(int x) { if (x == parent[x]) return x; return parent[x] = root(parent[x]); } private boolean union(int n1, int n2) { return _union(root(n1), root(n2)); } private boolean _union(int n1, int n2) { if (n1 == n2) return false; if (setSize[n1] > setSize[n2]) { parent[n2] = parent[n1]; setSize[n1] += setSize[n2]; } else { parent[n1] = parent[n2]; setSize[n2] += setSize[n1]; } numOfSets--; return true; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public InputReader(FileInputStream file) { this.stream = file; } 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 = (res << 3) + (res << 1) + c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } 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(); } 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
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
17c903deab905cba0577ec7b5eeecdd9
train_002.jsonl
1419951600
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≀ k ≀ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak &lt; bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≀ i, j ≀ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.
256 megabytes
import java.util.Scanner; public class NewYearPermutation{ /* public static double[] merge( double[] a, double[] b ){ int index1; int index2; int index3; double[] res; res = new double[ a.length + b.length ]; index1 = 0; index2 = 0; index3 = 0; while( index1 < a.length || index2 < b.length ){ if( index1 < a.length && index2 < b.length ){ if( a[index1] <= b[index2] ){ res[index3] = a[index1]; index1++; index3++; } else if( a[index1] > b[index2] ) { res[index3] = b[ index2 ]; index2++; index3++; } } else if( index1 == a.length ){ res[ index3 ] = b[ index2 ]; index2++; index3++; } else{ res[ index3 ] = a[ index1 ]; index1++; index3++; } } return res; } public static double[] divide( double[][] a ){ double[] b; double[][] c; int size; if( a.length == 1 ){ b = a[0]; return b; } else{ if( a.length%2 == 0 ){ c = new double[a.length/2][a[0].length*2]; for( int index = 0; index < a.length / 2; index++ ){ c[index] = merge( a[2*index], a[2*index + 1] ); } } else{ c = new double[(a.length/2) + 1][a[0].length*2]; for( int index = 0; index < a.length / 2; index++ ){ c[index] = merge( a[2*index], a[2*index + 1] ); } c[(a.length/2)] = a[a.length - 1]; } } return divide( c ); } public static double[] sort( double[] input ){ double[][] a; a= new double[input.length][1]; for( int index =0; index < input.length; index++ ){ a[index][0] = input[index]; } return divide( a ); } */ public static void main ( String args[] ){ int size; String temp; int[] perm; int[] perf; char[][] matr; int count = 1; Scanner scan = new Scanner( System.in ); size = scan.nextInt(); perm = new int[ size ]; perf = new int[ size ]; matr = new char[ size ][ size ]; temp = ""; for( int index = 0; index < size; index++ ){ perm[ index ] = scan.nextInt(); } for( int index = 0; index < size; index++ ){ perf[ index ] = 0; } temp = scan.nextLine(); for( int index = 0; index < size; index++ ){ temp = scan.nextLine(); for( int index2 = size - 1; index2 >= 0; index2-- ){ matr[index][index2] = temp.charAt( index2 ); } } while( count != 0){ count = 0; for( int index = 0; index < size; index++ ){ for( int index2 = 0; index2 < size; index2++ ){ for( int index3 = 0; index3 < size; index3++ ){ if( matr[index][index2] == '1' && matr[index2][index3] == '1' && matr[index][index3] != '1' ){ matr[index][index3] = '1'; matr[index3][index] = '1'; count++; } } } } } /* for( int index = 0; index < size; index++ ){ for( int index2 = 0; index2 < size; index2++ ){ System.out.print( matr[index][index2]); } System.out.println(); }*/ count = 1; while( count != 0 ){ count = 0; for( int index = 0; index < size; index++ ){ for( int index2 = size - 1; index2 >= index; index2-- ){ if( perm[index2] < perm[ index ] ){ if( matr[index][index2] == '1' ){ perf[ index ] = perm[ index ]; perm[ index ] = perm[ index2 ]; perm[ index2 ] = perf[ index ]; count++; } } } } } for( int index = 0; index < size - 1; index++ ){ System.out.print( perm[ index ] + " " ); } System.out.print( perm[ size - 1] ); } }
Java
["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"]
2 seconds
["1 2 4 3 6 7 5", "1 2 3 4 5"]
NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4). A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.
Java 8
standard input
[ "greedy", "graphs", "math", "dsu", "sortings", "dfs and similar" ]
a67ea891cd6084ceeaace8894cf18e60
The first line contains an integer n (1 ≀ n ≀ 300) β€” the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn β€” the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≀ i &lt; j ≀ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≀ i ≀ n, Ai, i = 0 holds.
1,600
In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.
standard output
PASSED
8754bcfb7fb78e7f7aff7ff0a6e86ee4
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Main { public static void main(String[] args) throws IOException { BufferedReader cin=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n=Integer.parseInt(cin.readLine()),m=0,arre[]=new int [n+1]; String aux[]=cin.readLine().split(" "); arre[0]=1; for(int i=1;i<=n;i++) arre[i]=Integer.parseInt(aux[i-1])+arre[i-1]; m=Integer.parseInt(cin.readLine()); String aux1[]=cin.readLine().split(" "); for(int i=0;i<m;i++) out.write(buscar(Integer.parseInt(aux1[i]),0,n,arre)+"\n"); out.flush(); } private static int buscar(int key, int l, int r, int[] arre) { int m=(int)((l+r)/2); if(arre[m]==key || (arre[m]<key && arre[m+1]>key)) return m+1; else if(arre[m]<key) return buscar(key,m+1,r,arre); else return buscar(key,l,m,arre); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
6fc79ca6ed1c76894f25450099abb186
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; public class B_Worms { static int [] list = new int[1000010]; public static void main(String[] args) { // TODO Auto-generated method stub Scanner x = new Scanner(System.in); int k = x.nextInt(),temp; for (int i = 0,t = 0; i < k; i++) { temp = x.nextInt(); while(temp>0) { temp--; list[t] = i +1 ; t++; } } k = x.nextInt(); for (int j = 0; j < k; j++) { temp = x.nextInt(); System.out.println(list[temp-1]); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
661ee7f7b82ba6a5cd949abd889650ca
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; public class Main { private static Scanner sc; private static int[] data; public static void main(String[] args) { sc = new Scanner(System.in); int n = sc.nextInt(); data = new int[n]; int init = 0; for (int i = 0; i < n; i++) { init += sc.nextInt(); data[i] = init; } int m = sc.nextInt(); int q; for (int i = 0; i < m; i++) { q = sc.nextInt(); System.out.println(binarySearch(0, n, q, n)+1); } } private static int binarySearch(int start, int end, int n, int tam){ int mid = (start+end)/2; if(mid == 0 || mid == tam-1) return mid; if(data[mid] >= n && data[mid-1] < n) return mid; if(data[mid] > n) return binarySearch(start, mid, n, tam); return binarySearch(mid, end, n, tam); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
24ea1b1507829dd41ec975dfcd538b8a
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Scanner; public class Main { static int[] pt = new int[100005]; static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); static int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } static String next() throws IOException { in.nextToken(); return in.sval; } public static void main(String[] args) throws IOException { while (in.nextToken() != StreamTokenizer.TT_EOF) { int n = (int) in.nval; int temp = 0; for (int i = 1; i <= n; i++) { int x = nextInt(); pt[i] = temp + 1; temp = x + temp; } int m = nextInt(); int max = 0; for (int a = 0; a < m; a++) { int x = nextInt(); int beg = 1; int end = n; if (x >= pt[end]) { System.out.println(end); } else { while (true) { if (end - beg == 1) { System.out.println(beg); break; } if (pt[(beg + end) / 2] > x) { end = (beg + end) / 2; } else if (pt[(beg + end) / 2] < x) { beg = (beg + end) / 2; } else { System.out.println((beg + end) / 2); break; } } } } } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
2f40c6239ffb98a2427afee1e28980da
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.*; import java.util.*; public class problem474B{ public static void main(String[]args)throws IOException{ BufferedReader x = new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(x.readLine()); int[]piles=new int[n]; StringTokenizer st=new StringTokenizer(x.readLine()); int totalsum=0; for (int i=0; i<n; i++){ piles[i]=Integer.parseInt(st.nextToken()); totalsum+=piles[i]; } int pilecounter=0; int totalcounter=piles[0]; int[]value=new int[totalsum+1]; for (int i=1; i<=totalsum; i++){ value[i]=pilecounter+1; totalcounter--; if (totalcounter==0 && i!=totalsum){ pilecounter++; totalcounter=piles[pilecounter]; } } int m=Integer.parseInt(x.readLine()); st=new StringTokenizer(x.readLine()); for (int i=0; i<m; i++){ System.out.println(value[Integer.parseInt(st.nextToken())]); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
eeb9a668e664336090076ec15752ef4d
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new PrintWriter(System.out)); int n = Integer.parseInt(br.readLine()); String[] ln1 = br.readLine().split(" "); int m = Integer.parseInt(br.readLine()); String[] ln2 = br.readLine().split(" "); int[] a = new int[n]; int[] b = new int[n]; int[] c = new int[m]; for(int i=0;i<m;i++){ c[i] = Integer.parseInt(ln2[i]); } for(int i=0;i<n;i++){ a[i] = Integer.parseInt(ln1[i]); } b[0] = 1; for(int i=1;i<n;i++){ b[i] = b[i-1]+a[i-1]; } // for(int i=0;i<n;i++){ // System.err.println(b[i]); // } // System.exit(0); for(int i=0;i<m;i++){ int index = bsearch(c[i],0,n-1,a,b); bw.append((index+1)+"\n"); } bw.close(); } private static int bsearch(int pin, int lo, int hi, int[] a, int[] b) { int d = -1; while(lo<hi){ int mid = lo+(hi-lo)/2; int x = b[mid]; int y = x+a[mid]-1; //System.out.println(lo+" "+hi+" "+mid+" "+x+" "+pin); if(pin<x) hi=mid-1; else if(pin>y) lo=mid+1; else return mid; } return lo; } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
c5c9db9358274b2a0e1ead9720f2eb08
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class CF474B { final static int N=100005; static int a[]=new int[N]; public static void main(String args[]) { InputReader in=new InputReader(System.in); PrintWriter out=new PrintWriter(System.out); int n=in.nextInt(); for(int i=0;i<n;i++) { a[i]=in.nextInt(); } for(int i=1;i<n;i++) { a[i]+=a[i-1]; } int m=in.nextInt(); for(int i=0;i<m;i++) { int q=in.nextInt(); int res=Arrays.binarySearch(a,0,n-1,q); if(res<0) res=-res; else res++; out.println(res); } out.close(); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader=new BufferedReader(new InputStreamReader(stream)); tokenizer=null; } public String next() { while(tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); }catch(IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
027bcbf9e22ffe1c5b2e627ef337d00d
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; public class Warms { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int WarmsGroup[] = new int[n]; for (int i = 0; i < n ; i++) { WarmsGroup[i] = sc.nextInt(); } for (int i = 1; i < n; i++) { WarmsGroup[i] = WarmsGroup[i] + WarmsGroup[i-1]; } int m = sc.nextInt(); int FreshWarms[] = new int[m]; for (int i = 0; i < m ; i++) { FreshWarms[i] = sc.nextInt(); } for (int i = 0; i < m; i++) { System.out.println(rank(FreshWarms[i], WarmsGroup)); } } public static int rank(int val, int[] arr) { return rank(val, arr, 0, arr.length - 1); } private static int rank(int val, int[] arr, int lo, int hi) { if (lo > hi) return lo+1; int mid = lo + (hi - lo) / 2; if (val < arr[mid]) { return rank(val, arr, lo, mid - 1); } else if (val > arr[mid]) { return rank(val, arr, mid + 1, hi); } else { return mid+1; } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
d62c77c1cd59dd7af5183c6801d0333f
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
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)); Scanner sc = new Scanner(System.in); int i,j,n,t,m; n = sc.nextInt(); int[] a = new int[n]; int[] sum = new int[n+1]; for(i=0;i<n;i++) { a[i] = sc.nextInt(); if (i==0) { sum[i] = a[i]; } else { sum[i] = sum[i-1] + a[i]; } } m = sc.nextInt(); int[] q = new int[m]; for (i=0;i<m;i++) { q[i] = sc.nextInt(); } for (i=0;i<m;i++) { System.out.println((binarySearch(sum,q[i],n)+1)); } } public static int binarySearch(int[] sum, int num, int n) { int low,high,mid; low = 0; high = n-1; while (low <= high) { mid = (low+high)/2; if (sum[mid] > num) { high = mid-1; } else if (sum[mid] < num) { low = mid + 1; } else { return mid; } } return high+1; } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
3cca424045da0cd9068386c06e134149
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.*; //PrintWriter import java.math.*; //BigInteger, BigDecimal import java.util.*; //StringTokenizer, ArrayList public class R271_Div2_B { FastReader in; PrintWriter out; public static void main(String[] args) { new R271_Div2_B().run(); } void run() { in = new FastReader(System.in); out = new PrintWriter(System.out); solve(); out.close(); } void solve() { int n = in.nextInt(); int[] a = new int[n+1]; for (int i = 1; i <= n; i++) a[i] = a[i-1] + in.nextInt(); int m = in.nextInt(); for (int i = 0; i < m; i++) { int goal = in.nextInt(); // int lo = 1, hi = n, mid; // // while (lo < hi) // { // mid = lo + (hi - lo) / 2; // if (a[mid] < goal) // lo = mid + 1; // else // hi = mid; // } // out.println(lo); int ind = Arrays.binarySearch(a, goal); if (ind < 0) ind = -ind - 1; out.println(ind); } //Alternate solution: // int n = in.nextInt(); // int[] p = new int[1_000_001]; // int ind = 0; // for (int i = 1; i <= n; i++) // { // int a = in.nextInt(); // for (int j = 0; j < a; j++) // p[++ind] = i; // } // int m = in.nextInt(); // for (int i = 0; i < m; i++) // { // int q = in.nextInt(); // out.println(p[q]); // } } //----------------------------------------------------- void runWithFiles() { in = new FastReader(new File("input.txt")); try { out = new PrintWriter(new File("output.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } solve(); out.close(); } class FastReader { BufferedReader br; StringTokenizer tokenizer; public FastReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public FastReader(File f) { try { br = new BufferedReader(new FileReader(f)); tokenizer = null; } catch (FileNotFoundException e) { e.printStackTrace(); } } private String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } BigInteger nextBigInteger() { return new BigInteger(next()); } BigDecimal nextBigDecimal() { return new BigDecimal(next()); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
644ae115c63eaf250266099fc24bef3a
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.*; //PrintWriter import java.math.*; //BigInteger, BigDecimal import java.util.*; //StringTokenizer, ArrayList public class R271_Div2_B { FastReader in; PrintWriter out; public static void main(String[] args) { new R271_Div2_B().run(); } void run() { in = new FastReader(System.in); out = new PrintWriter(System.out); solve(); out.close(); } void solve() { int n = in.nextInt(); int[] a = new int[n]; a[0] = in.nextInt(); for (int i = 1; i < n; i++) a[i] = a[i-1] + in.nextInt(); int m = in.nextInt(); int q; for (int i = 0; i < m; i++) { q = in.nextInt(); int left = 0, right = n, mid = 0; while (left < right) { mid = left + (right - left) /2; if (a[mid] < q) left = mid + 1; else right = mid; } if (a[left] < q) out.println(left+2); else out.println(left+1); } } //----------------------------------------------------- void runWithFiles() { in = new FastReader(new File("input.txt")); try { out = new PrintWriter(new File("output.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } solve(); out.close(); } class FastReader { BufferedReader br; StringTokenizer tokenizer; public FastReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public FastReader(File f) { try { br = new BufferedReader(new FileReader(f)); tokenizer = null; } catch (FileNotFoundException e) { e.printStackTrace(); } } private String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } BigInteger nextBigInteger() { return new BigInteger(next()); } BigDecimal nextBigDecimal() { return new BigDecimal(next()); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
641bb4adf29b60a665504e2deacf62ed
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.*; //PrintWriter import java.math.*; //BigInteger, BigDecimal import java.util.*; //StringTokenizer, ArrayList public class R271_Div2_B { FastReader in; PrintWriter out; public static void main(String[] args) { new R271_Div2_B().run(); } void run() { in = new FastReader(System.in); out = new PrintWriter(System.out); solve(); out.close(); } void solve() { int n = in.nextInt(); int[] a = new int[n+1]; for (int i = 1; i <= n; i++) a[i] = a[i-1] + in.nextInt(); int m = in.nextInt(); for (int i = 0; i < m; i++) { int goal = in.nextInt(); int lo = 1, hi = n, mid; while (lo < hi) { mid = lo + (hi - lo) / 2; if (a[mid] < goal) lo = mid + 1; else hi = mid; } out.println(lo); } } //----------------------------------------------------- void runWithFiles() { in = new FastReader(new File("input.txt")); try { out = new PrintWriter(new File("output.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } solve(); out.close(); } class FastReader { BufferedReader br; StringTokenizer tokenizer; public FastReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public FastReader(File f) { try { br = new BufferedReader(new FileReader(f)); tokenizer = null; } catch (FileNotFoundException e) { e.printStackTrace(); } } private String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } BigInteger nextBigInteger() { return new BigInteger(next()); } BigDecimal nextBigDecimal() { return new BigDecimal(next()); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
30b88e9eddae970db6c1435caf0827cf
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.io.*; //PrintWriter import java.math.*; //BigInteger, BigDecimal import java.util.*; //StringTokenizer, ArrayList public class R271_Div2_B { FastReader in; PrintWriter out; public static void main(String[] args) { new R271_Div2_B().run(); } void run() { in = new FastReader(System.in); out = new PrintWriter(System.out); solve(); out.close(); } void solve() { // int n = in.nextInt(); // // int[] a = new int[n+1]; // for (int i = 1; i <= n; i++) // a[i] = a[i-1] + in.nextInt(); // // int m = in.nextInt(); // for (int i = 0; i < m; i++) // { // int goal = in.nextInt(); // int lo = 1, hi = n, mid; // // while (lo < hi) // { // mid = lo + (hi - lo) / 2; // if (a[mid] < goal) // lo = mid + 1; // else // hi = mid; // } // out.println(lo); // } //Alternate solution: int n = in.nextInt(); int[] p = new int[1_000_001]; int ind = 0; for (int i = 1; i <= n; i++) { int a = in.nextInt(); for (int j = 0; j < a; j++) p[++ind] = i; } int m = in.nextInt(); for (int i = 0; i < m; i++) { int q = in.nextInt(); out.println(p[q]); } } //----------------------------------------------------- void runWithFiles() { in = new FastReader(new File("input.txt")); try { out = new PrintWriter(new File("output.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } solve(); out.close(); } class FastReader { BufferedReader br; StringTokenizer tokenizer; public FastReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public FastReader(File f) { try { br = new BufferedReader(new FileReader(f)); tokenizer = null; } catch (FileNotFoundException e) { e.printStackTrace(); } } private String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } BigInteger nextBigInteger() { return new BigInteger(next()); } BigDecimal nextBigDecimal() { return new BigDecimal(next()); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
21d81e73e3da91e292dfad54ab022008
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.Scanner; import java.util.Arrays; public class main { public static void main(String args[]) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++) { arr[i] = input.nextInt(); } int freq[] = new int[1000001]; int k = 1; int q = 0; for(int i=0;i<n;i++) { for(int j=0;j<arr[i];j++) { freq[k++] = q+1; } q++; } int m = input.nextInt(); for(int i=0;i<m;i++) { System.out.println(freq[input.nextInt()]); } } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
4164df4d47cee7f7646d70b66f735bf9
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int n= sc.nextInt(); int a; int temp=0; int result[] = new int[1000001]; for(int i=0;i<n;i++){ a=sc.nextInt(); for(int j=0;j<a;j++) result[temp++]=i+1; } int m=sc.nextInt(); //for(int i=0;i<26;i++){ // System.out.println("i"+i+":"+result[i]); //} for(int i=0;i<m;i++) System.out.println(result[sc.nextInt()-1]); } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output
PASSED
049585d55e886b1df07a98c72e5dbd9b
train_002.jsonl
1412609400
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
256 megabytes
import java.util.*; public class Worms { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int p = scanner.nextInt(); int[] piles = new int[p]; int[] nums = new int[p+1]; for(int i = 0; i < p; ++i) { piles[i] = scanner.nextInt(); nums[i+1] = nums[i]+piles[i]; } int juicy = scanner.nextInt(); for(int i = 0; i < juicy; ++i) { int worm = scanner.nextInt(); System.out.println(findPile(worm,nums)); } } public static int findPile(int worm, int[] nums) { int low = 1; int high = nums.length; boolean found = false; int mid = low+(high-low)/2; while(low <= high && !found) { mid = low + (high-low)/2; if(worm > nums[mid]) { low = mid; } else if(worm <= nums[mid] && worm > nums[mid-1]) { found = true; } else { high = mid; } } return mid; } }
Java
["5\n2 7 3 4 9\n3\n1 25 11"]
1 second
["1\n5\n3"]
NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile.
Java 7
standard input
[ "binary search", "implementation" ]
10f4fc5cc2fcec02ebfb7f34d83debac
The first line contains a single integer n (1 ≀ n ≀ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 103, a1 + a2 + ... + an ≀ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≀ qi ≀ a1 + a2 + ... + an), the labels of the juicy worms.
1,200
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
standard output