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
sequencelengths
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
237b85c3987e0bddb9aef233b1695a5b
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; //import java.math.*; public class Task{ // ..............code begins here.............. static long mod=(long)1e9+7,inf=(long)1e17; static void solve() throws IOException { int n=int_v(read()); int[] a=int_arr(); List<Integer> l0=new ArrayList<>(); List<Integer> l1=new ArrayList<>(); int f0=0,f1=0; for(int i=0;i<n;i++){ if(a[i]==0){l0.add(i);f0++;} else l1.add(i); } f1=n-f0; int[][] dp=new int[f1+1][f0+1]; for(int i=0;i<=f1;i++)Arrays.fill(dp[i],30000000); Arrays.fill(dp[0],0); for(int i=1;i<=f1;i++){ for(int j=1;j<=f0;j++){ int x=l1.get(i-1),y=l0.get(j-1); if(j>=i)dp[i][j]=Math.min(Math.abs(x-y)+dp[i-1][j-1],dp[i][j-1]); } } if(dp[f1][f0]==30000000)dp[f1][f0]=0; out.write(dp[f1][f0]+"\n"); } // public static void main(String[] args) throws IOException{ assign(); int t=1;//int_v(read()),cn=1; while(t--!=0){ //out.write("Case #"+cn+": "); solve(); //cn++; } out.flush(); } // taking inputs static BufferedReader s1; static BufferedWriter out; static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;} static int int_v (String s1){return Integer.parseInt(s1);} static long long_v(String s1){return Long.parseLong(s1);} static void sort(int[] a){List<Integer> l=new ArrayList<>();for(int x:a){l.add(x);}Collections.sort(l);for(int i=0;i<a.length;i++){a[i]=l.get(i);}} static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;} static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;} static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));} //static String setpreciosion(double d,int k){BigDecimal d1 = new BigDecimal(Double.toString(d));return d1.setScale(k,RoundingMode.HALF_UP).toString();}//UP DOWN HALF_UP static int add(int a,int b){int z=a+b;if(z>=mod)z-=mod;return z;} static long gcd(long a,long b){if(b==0){return a;}return gcd(b,a%b);} static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res%m;} static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;} static long ModInv(long a,long m){return Modpow(a,m-2,m);} //static long nck(int n,int r,long m){if(r>n){return 0l;}return Modmul(f[n],ModInv(Modmul(f[n-r],f[r],m),m),m);} //static long[] f; }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
3dd3178b4cb18046108dac01e78ddfd4
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; //import java.math.*; public class Task{ // ..............code begins here.............. static long mod=(long)1e9+7,inf=(long)1e17; static void solve() throws IOException { int n=int_v(read()); int[] a=int_arr(); TreeSet<Integer> s0=new TreeSet<>(); Set<Integer> s1=new HashSet<>(); List<Integer> l0=new ArrayList<>(); List<Integer> l1=new ArrayList<>(); int f0=0,f1=0; for(int i=0;i<n;i++){ if(a[i]==0){l0.add(i);f0++;} else l1.add(i); } f1=n-f0; int[][] dp=new int[f1+1][f0+1]; for(int i=0;i<=f1;i++)Arrays.fill(dp[i],30000000); Arrays.fill(dp[0],0); for(int i=1;i<=f1;i++){ for(int j=1;j<=f0;j++){ int x=l1.get(i-1),y=l0.get(j-1); if(j<i) continue; if(i==j){ dp[i][j]=Math.abs(x-y)+dp[i-1][j-1]; } else{ dp[i][j]=Math.min(Math.abs(x-y)+dp[i-1][j-1],dp[i][j-1]); } } } if(dp[f1][f0]==30000000)dp[f1][f0]=0; out.write(dp[f1][f0]+"\n"); } // public static void main(String[] args) throws IOException{ assign(); int t=1;//int_v(read()),cn=1; while(t--!=0){ //out.write("Case #"+cn+": "); solve(); //cn++; } out.flush(); } // taking inputs static BufferedReader s1; static BufferedWriter out; static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;} static int int_v (String s1){return Integer.parseInt(s1);} static long long_v(String s1){return Long.parseLong(s1);} static void sort(int[] a){List<Integer> l=new ArrayList<>();for(int x:a){l.add(x);}Collections.sort(l);for(int i=0;i<a.length;i++){a[i]=l.get(i);}} static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;} static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;} static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));} //static String setpreciosion(double d,int k){BigDecimal d1 = new BigDecimal(Double.toString(d));return d1.setScale(k,RoundingMode.HALF_UP).toString();}//UP DOWN HALF_UP static int add(int a,int b){int z=a+b;if(z>=mod)z-=mod;return z;} static long gcd(long a,long b){if(b==0){return a;}return gcd(b,a%b);} static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res%m;} static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;} static long ModInv(long a,long m){return Modpow(a,m-2,m);} //static long nck(int n,int r,long m){if(r>n){return 0l;}return Modmul(f[n],ModInv(Modmul(f[n-r],f[r],m),m),m);} //static long[] f; }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
31d57b31d0ef9207457fe78b0610b3b7
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.TreeSet; 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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); DArmchairs solver = new DArmchairs(); solver.solve(1, in, out); out.close(); } static class DArmchairs { int n; int[] arr; int[][] memo; TreeSet<Integer>[] sets; public void readInput(Scanner sc) { n = sc.nextInt(); arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); } public void solve(int testNumber, Scanner sc, PrintWriter pw) { int tc = 1; while (tc-- > 0) { readInput(sc); sets = new TreeSet[2]; for (int i = 0; i < 2; i++) sets[i] = new TreeSet<>(); for (int i = 0; i < n; i++) sets[arr[i]].add(i); memo = new int[n][n]; for (int[] x : memo) Arrays.fill(x, -1); if (sets[1].isEmpty()) { pw.println(0); } else { pw.println(dp(sets[0].first(), sets[1].first())); } } } private int dp(Integer i, Integer j) { if (j == null) return 0; if (j == null || i == null) return (int) 1e9; if (memo[i][j] != -1) return memo[i][j]; int leave = dp(sets[0].higher(i), j); return memo[i][j] = Math.min(Math.abs(j - i) + dp(sets[0].higher(i), sets[1].higher(j)), leave); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
2ea3a79c19a5a3b588b135195a78ee85
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.util.ResourceBundle.Control; import java.util.spi.TimeZoneNameProvider; import javax.management.openmbean.KeyAlreadyExistsException; // import java.lang.invoke.ConstantBootstraps; // import java.math.BigInteger; // import java.beans.IndexedPropertyChangeEvent; import java.io.*; @SuppressWarnings("unchecked") public class Main implements Runnable { static FastReader in; static PrintWriter out; static int bit(long n) { return (n == 0) ? 0 : (1 + bit(n & (n - 1))); } static void p(Object o) { out.print(o); } static void pn(Object o) { out.println(o); } static void pni(Object o) { out.println(o); out.flush(); } static String n() throws Exception { return in.next(); } static String nln() throws Exception { return in.nextLine(); } static int ni() throws Exception { return Integer.parseInt(in.next()); } static long nl() throws Exception { return Long.parseLong(in.next()); } static double nd() throws Exception { return Double.parseDouble(in.next()); } static class FastReader { static BufferedReader br; static StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception { br = new BufferedReader(new FileReader(s)); } String next() throws Exception { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception { String str = ""; try { str = br.readLine(); } catch (IOException e) { throw new Exception(e.toString()); } return str; } } static long power(long a, long b) { if (a == 0L) return 0L; if (b == 0) return 1; long val = power(a, b / 2); val = val * val; if ((b % 2) != 0) val = val * a; return val; } static long power(long a, long b, long mod) { if (a == 0L) return 0L; if (b == 0) return 1; long val = power(a, b / 2L, mod) % mod; val = (val * val) % mod; if ((b % 2) != 0) val = (val * a) % mod; return val; } static ArrayList<Long> prime_factors(long n) { ArrayList<Long> ans = new ArrayList<Long>(); while (n % 2 == 0) { ans.add(2L); n /= 2L; } for (long i = 3; i * i <= n; i++) { while (n % i == 0) { ans.add(i); n /= i; } } if (n > 2) { ans.add(n); } return ans; } static void sort(ArrayList<Long> a) { Collections.sort(a); } static void reverse_sort(ArrayList<Long> a) { Collections.sort(a, Collections.reverseOrder()); } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(List<Long> a, int i, int j) { long temp = a.get(i); a.set(j, a.get(i)); a.set(j, temp); } static void sieve(boolean[] prime) { int n = prime.length - 1; Arrays.fill(prime, true); for (int i = 2; i * i <= n; i++) { if (prime[i]) { for (int j = 2 * i; j <= n; j += i) { prime[j] = false; } } } } static long gcd(long a, long b) { // pn(a+" "+b); if (a < b) { long temp = a; a = b; b = temp; } if (b == 0) return a; return gcd(b, a % b); } static HashMap<Long, Long> map_prime_factors(long n) { HashMap<Long, Long> map = new HashMap<>(); while (n % 2 == 0) { map.put(2L, map.getOrDefault(2L, 0L) + 1L); n /= 2L; } for (long i = 3; i * i <= n; i++) { while (n % i == 0) { map.put(i, map.getOrDefault(i, 0L) + 1L); n /= i; } } if (n > 2) { map.put(n, map.getOrDefault(n, 0L) + 1L); } return map; } static List<Long> divisor(long n) { List<Long> ans = new ArrayList<>(); ans.add(1L); long count = 0; for (long i = 2L; i * i <= n; i++) { if (n % i == 0) { if (i == n / i) ans.add(i); else { ans.add(i); ans.add(n / i); } } } return ans; } static void sum_of_divisors(int n) { int[] dp = new int[n + 1]; for (int i = 1; i <= n; i++) { dp[i] += i; for (int j = i + i; j <= n; j += i) { dp[j] += i; } } } static void prime_factorization_using_sieve(int n) { int[] dp = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE); for (int i = 2; i <= n; i++) { dp[i] = Math.min(dp[i], i);// dp[i] stores smallest prime number which divides number i for (int j = 2 * i; j <= n; j++) {// can calculate prime factorization in O(logn) time by dividing // val/=dp[val]; till 1 is obtained dp[j] = Math.min(dp[j], i); } } } /* * ----------------------------------------------------Sorting------------------ * ------------------------------------------------ */ public static void sort(long[] arr, int l, int r) { if (l >= r) return; int mid = (l + r) / 2; sort(arr, l, mid); sort(arr, mid + 1, r); merge(arr, l, mid, r); } public static void sort(int[] arr, int l, int r) { if (l >= r) return; int mid = (l + r) / 2; sort(arr, l, mid); sort(arr, mid + 1, r); merge(arr, l, mid, r); } static void merge(int[] arr, int l, int mid, int r) { int[] left = new int[mid - l + 1]; int[] right = new int[r - mid]; for (int i = l; i <= mid; i++) { left[i - l] = arr[i]; } for (int i = mid + 1; i <= r; i++) { right[i - (mid + 1)] = arr[i]; } int left_start = 0; int right_start = 0; int left_length = mid - l + 1; int right_length = r - mid; int temp = l; while (left_start < left_length && right_start < right_length) { if (left[left_start] < right[right_start]) { arr[temp] = left[left_start++]; } else { arr[temp] = right[right_start++]; } temp++; } while (left_start < left_length) { arr[temp++] = left[left_start++]; } while (right_start < right_length) { arr[temp++] = right[right_start++]; } } static void merge(long[] arr, int l, int mid, int r) { long[] left = new long[mid - l + 1]; long[] right = new long[r - mid]; for (int i = l; i <= mid; i++) { left[i - l] = arr[i]; } for (int i = mid + 1; i <= r; i++) { right[i - (mid + 1)] = arr[i]; } int left_start = 0; int right_start = 0; int left_length = mid - l + 1; int right_length = r - mid; int temp = l; while (left_start < left_length && right_start < right_length) { if (left[left_start] < right[right_start]) { arr[temp] = left[left_start++]; } else { arr[temp] = right[right_start++]; } temp++; } while (left_start < left_length) { arr[temp++] = left[left_start++]; } while (right_start < right_length) { arr[temp++] = right[right_start++]; } } // static int[] smallest_prime_factor; // static int count = 1; // static int[] p = new int[100002]; // static long[] flat_tree = new long[300002]; // static int[] in_time = new int[1000002]; // static int[] out_time = new int[1000002]; // static long[] subtree_gcd = new long[100002]; // static int w = 0; // static boolean poss = true; /* * (a^b^c)%mod * Using fermats Little theorem * x^(mod-1)=1(mod) * so b^c can be written as b^c=x*(mod-1)+y * then (a^(x*(mod-1)+y))%mod=(a^(x*(mod-1))*a^(y))mod * the term (a^(x*(mod-1)))%mod=a^(mod-1)*a^(mod-1) * */ // ---------------------------------------------------Segment_Tree----------------------------------------------------------------// // static class comparator implements Comparator<node> { // public int compare(node a, node b) { // return a.a - b.a > 0 ? 1 : -1; // } // } static class Segment_Tree { private long[] segment_tree; public Segment_Tree(int n) { this.segment_tree = new long[4 * n + 1]; } void build(int index, int left, int right, int[] a) { if (left == right) { segment_tree[index] = a[left]; return; } int mid = (left + right) / 2; build(2 * index + 1, left, mid, a); build(2 * index + 2, mid + 1, right, a); segment_tree[index] = segment_tree[2 * index + 1] + segment_tree[2 * index + 2]; } long query(int index, int left, int right, int l, int r) { if (left > right) return 0; if (left >= l && r >= right) { return segment_tree[index]; } if (l > right || left > r) return 0; int mid = (left + right) / 2; return query(2 * index + 1, left, mid, l, r) + query(2 * index + 2, mid + 1, right, l, r); } void update(int index, int left, int right, int node, int val) { if (left == right) { segment_tree[index] = val; return; } int mid = (left + right) / 2; if (node <= mid) update(2 * index + 1, left, mid, node, val); else update(2 * index + 2, mid + 1, right, node, val); segment_tree[index] = segment_tree[2 * index + 1] + segment_tree[2 * index + 2]; } } static class min_Segment_Tree { private long[] segment_tree; public min_Segment_Tree(int n) { this.segment_tree = new long[4 * n + 1]; // Arrays.fill(segment_tree, Integer.MAX_VALUE); } void build(int index, int left, int right, long[] a) { if (left == right) { segment_tree[index] = a[left]; return; } int mid = (left + right) / 2; build(2 * index + 1, left, mid, a); build(2 * index + 2, mid + 1, right, a); // segment_tree[index] = Math.min(segment_tree[2 * index + 1], segment_tree[2 * // index + 2]); segment_tree[index] = gcd(segment_tree[2 * index + 1], segment_tree[2 * index + 2]); } long query(int index, int left, int right, int l, int r) { if (left > right) // return Integer.MAX_VALUE; return 0L; if (left >= l && r >= right) { return segment_tree[index]; } if (l > right || left > r) // return Integer.MAX_VALUE; return 0L; int mid = (left + right) / 2; // return Math.min(query(2 * index + 1, left, mid, l, r), query(2 * index + 2, // mid + 1, right, l, r)); return gcd(query(2 * index + 1, left, mid, l, r), query(2 * index + 2, mid + 1, right, l, r)); } void update(int index, int left, int right, int node, int val) { if (left == right) { segment_tree[index] = val; return; } int mid = (left + right) / 2; if (node <= mid) update(2 * index + 1, left, mid, node, val); else update(2 * index + 2, mid + 1, right, node, val); segment_tree[index] = Math.min(segment_tree[2 * index + 1], segment_tree[2 * index + 2]); } } static class max_Segment_Tree { public long[] segment_tree; public max_Segment_Tree(int n) { this.segment_tree = new long[4 * n + 1]; } void build(int index, int left, int right, long[] a) { // pn(index+" "+left+" "+right); if (left == right) { segment_tree[index] = a[left]; return; } int mid = (left + right) / 2; build(2 * index + 1, left, mid, a); build(2 * index + 2, mid + 1, right, a); segment_tree[index] = Math.max(segment_tree[2 * index + 1], segment_tree[2 * index + 2]); } long query(int index, int left, int right, int l, int r) { if (left >= l && r >= right) { return segment_tree[index]; } if (l > right || left > r) return Long.MIN_VALUE; int mid = (left + right) / 2; long ans1 = query(2 * index + 1, left, mid, l, r); long ans2 = query(2 * index + 2, mid + 1, right, l, r); long max = Math.max(ans1, ans2); // pn(index+" "+left+" "+right+" "+max+" "+l+" "+r+" "+ans1+" "+ans2); return max; } void update(int index, int left, int right, int node, int val) { if (left == right) { segment_tree[index] += val; return; } int mid = (left + right) / 2; if (node <= mid) update(2 * index + 1, left, mid, node, val); else update(2 * index + 2, mid + 1, right, node, val); segment_tree[index] = Math.max(segment_tree[2 * index + 1], segment_tree[2 * index + 2]); } } // // ------------------------------------------------------ DSU // // --------------------------------------------------------------------// static class dsu { private int[] parent; private int[] rank; private int[] size; public dsu(int n) { this.parent = new int[n + 1]; this.rank = new int[n + 1]; this.size = new int[n + 1]; for (int i = 0; i <= n; i++) { parent[i] = i; rank[i] = 1; size[i] = 1; } } int findParent(int a) { if (parent[a] == a) return a; else return parent[a] = findParent(parent[a]); } void join(int a, int b) { int parent_a = findParent(a); int parent_b = findParent(b); if (parent_a == parent_b) return; if (rank[parent_a] > rank[parent_b]) { parent[parent_b] = parent_a; size[parent_a] += size[parent_b]; } else if (rank[parent_a] < rank[parent_b]) { parent[parent_a] = parent_b; size[parent_b] += size[parent_a]; } else { parent[parent_a] = parent_b; size[parent_b] += size[parent_a]; rank[parent_b]++; } } } // ------------------------------------------------Comparable---------------------------------------------------------------------// public static class rectangle { int x1, x3, y1, y3;// lower left and upper rigth coordinates int x2, y2, x4, y4;// remaining coordinates /* * (x4,y4) (x3,y3) * ____________ * | | * |____________| * * (x1,y1) (x2,y2) */ public rectangle(int x1, int y1, int x3, int y3) { this.x1 = x1; this.y1 = y1; this.x3 = x3; this.y3 = y3; this.x2 = x3; this.y2 = y1; this.x4 = x1; this.y4 = y3; } public long area() { if (x3 < x1 || y3 < y1) return 0; return (long) Math.abs(x1 - x3) * (long) Math.abs(y1 - y3); } } static long intersection(rectangle a, rectangle b) { if (a.x3 < a.x1 || a.y3 < a.y1 || b.x3 < b.x1 || b.y3 < b.y1) return 0; long l1 = ((long) Math.min(a.x3, b.x3) - (long) Math.max(a.x1, b.x1)); long l2 = ((long) Math.min(a.y3, b.y3) - (long) Math.max(a.y1, b.y1)); if (l1 < 0 || l2 < 0) return 0; long area = ((long) Math.min(a.x3, b.x3) - (long) Math.max(a.x1, b.x1)) * ((long) Math.min(a.y3, b.y3) - (long) Math.max(a.y1, b.y1)); if (area < 0) return 0; return area; } // --------------------------------------------------------------Multiset---------------------------------------------------------------// public static class multiset { public TreeMap<Integer, Integer> map; public int size = 0; public multiset() { map = new TreeMap<>(); } public multiset(int[] a) { map = new TreeMap<>(); size = a.length; for (int i = 0; i < a.length; i++) { map.put(a[i], map.getOrDefault(a[i], 0) + 1); } } void add(int a) { size++; map.put(a, map.getOrDefault(a, 0) + 1); } void remove(int a) { size--; int val = map.get(a); map.put(a, val - 1); if (val == 1) map.remove(a); } void removeAll(int a) { if (map.containsKey(a)) { size -= map.get(a); map.remove(a); } } int ceiling(int a) { if (map.ceilingKey(a) != null) { int find = map.ceilingKey(a); return find; } else return Integer.MIN_VALUE; } int floor(int a) { if (map.floorKey(a) != null) { int find = map.floorKey(a); return find; } else return Integer.MAX_VALUE; } int lower(int a) { if (map.lowerKey(a) != null) { int find = map.lowerKey(a); return find; } else return Integer.MAX_VALUE; } int higher(int a) { if (map.higherKey(a) != null) { int find = map.higherKey(a); return find; } else return Integer.MIN_VALUE; } int first() { return map.firstKey(); } int last() { return map.lastKey(); } boolean contains(int a) { if (map.containsKey(a)) return true; return false; } int size() { return size; } void clear() { map.clear(); } int poll() { if (map.size() == 0) { return Integer.MAX_VALUE; } size--; int first = map.firstKey(); if (map.get(first) == 1) { map.pollFirstEntry(); } else map.put(first, map.get(first) - 1); return first; } int polllast() { if (map.size() == 0) { return Integer.MAX_VALUE; } size--; int last = map.lastKey(); if (map.get(last) == 1) { map.pollLastEntry(); } else map.put(last, map.get(last) - 1); return last; } } static class pair implements Comparable<pair> { int a; int b; int dir; public pair(int a, int b, int dir) { this.a = a; this.b = b; this.dir = dir; } public int compareTo(pair p) { // if (this.b == Integer.MIN_VALUE || p.b == Integer.MIN_VALUE) // return (int) (this.index - p.index); return (int) (this.a - p.a); } } static class pair2 implements Comparable<pair2> { long a; int index; public pair2(long a, int index) { this.a = a; this.index = index; } public int compareTo(pair2 p) { return (int) (this.a - p.a); } } static class node implements Comparable<node> { int l; int r; public node(int l, int r) { this.l = l; this.r = r; } public int compareTo(node a) { if (this.l == a.l) { return this.r - a.r; } return (int) (this.l - a.l); } } static long ans = 0; static int leaf = 0; static boolean poss = true; static long mod = 1000000007L; static int[] dx = { -1, 0, 0, 1, -1, -1, 1, 1 }; static int[] dy = { 0, -1, 1, 0, -1, 1, -1, 1 }; static Set<Integer> path_nodes; static int[] parent; static boolean[] visited; static int[] map_x; static int[] map_y; static int[][] map_x_visited; static int[][] map_y_visited; int count = 0; public static void main(String[] args) throws Exception { // new Thread(null, new Main(), "1", 1 << 26).start(); long start = System.nanoTime(); in = new FastReader(); out = new PrintWriter(System.out, false); int tc = 1; while (tc-- > 0) { int n = ni(); int[] a=new int[n]; boolean[] placed=new boolean[n]; TreeSet<Integer> zero=new TreeSet<>(); TreeSet<Integer> one=new TreeSet<>(); for(int i=0;i<n;i++){ a[i]=ni(); if(a[i]==1)one.add(i); else zero.add(i); } int[] y=new int[zero.size()+1]; int[] x=new int[n-zero.size()+1]; int i=1; n=zero.size(); int m=one.size(); if(m==0){ pn(0); continue; } while(!zero.isEmpty()){ y[i++]=zero.pollFirst(); } i=1; while(!one.isEmpty()){ x[i++]=one.pollFirst(); } long[][] dp=new long[n+2][m+2]; for(i=0;i<=n;i++){ for(int j=0;j<=m;j++){ dp[i][j]=Integer.MAX_VALUE; } dp[i][0]=0; } dp[0][0]=0; for(i=1;i<=n;i++){ for(int j=1;j<=m;j++){ dp[i][j]=Math.min(dp[i][j],dp[i-1][j]); dp[i][j]=Math.min(dp[i][j],((long)Math.abs(y[i]-x[j]))+dp[i-1][j-1]); // pn(i+" "+j+" "+dp[i][j]); } } pn(dp[n][m]); } long end = System.nanoTime(); // pn((end-start)*1.0/1000000000); out.flush(); out.close(); } static boolean intersect(node chord_a, node chord_b) { if (chord_a.l > chord_b.l) { node temp = chord_a; chord_a = chord_b; chord_b = temp; } if (chord_a.r > chord_b.l && chord_a.r < chord_b.r) return true; return false; } static void dfs(int i, int p, List<Set<Integer>> arr, int[] ans, int depth) { parent[i] = p; ans[i] = depth; for (int nei : arr.get(i)) { if (visited[nei] || nei == p) continue; dfs(nei, i, arr, ans, depth + 1); } } public void run() { try { } catch (Exception e) { pn("Excetiom"); } } static boolean dfs(int i, int p, int x, int y, Set<Integer> k_nodes, boolean[] visited, List<TreeSet<Integer>> arr, int[] dp) { visited[i] = true; boolean found = false; if (k_nodes.contains(i)) { found = true; } List<Integer> remove = new ArrayList<>(); for (int nei : arr.get(i)) { if (visited[nei] || nei == p) continue; boolean yes = dfs(nei, i, x, y, k_nodes, visited, arr, dp); if (!yes) remove.add(nei); // pn(i+" "+nei+" "+yes); found = found || yes; } for (int nei : remove) { arr.get(i).remove(nei); } return found; } static boolean inside(int i, int j, int n, int m) { if (i >= 0 && j >= 0 && i < n && j < m) return true; return false; } static long ncm(long[] fact, long[] fact_inv, int n, int m) { if (n < m) return 0L; long a = fact[n]; long b = fact_inv[n - m]; long c = fact_inv[m]; a = (a * b) % mod; return (a * c) % mod; } static int binary_search(int[] a, int val) { int l = 0; int r = a.length - 1; int ans = 0; while (l <= r) { int mid = l + (r - l) / 2; if (a[mid] <= val) { ans = mid; l = mid + 1; } else r = mid - 1; } return ans; } static int[] longest_common_prefix(String s) { int m = s.length(); int[] lcs = new int[m]; int len = 0; int i = 1; lcs[0] = 0; while (i < m) { if (s.charAt(i) == s.charAt(len)) { lcs[i++] = ++len; } else { if (len == 0) { lcs[i] = 0; i++; } else len = lcs[len - 1]; } } return lcs; } static void swap(char[] a, char[] b, int i, int j) { char temp = a[i]; a[i] = b[j]; b[j] = temp; } static void factorial(long[] fact, long[] fact_inv, int n, long mod) { fact[0] = 1; for (int i = 1; i < n; i++) { fact[i] = (i * fact[i - 1]) % mod; } for (int i = 0; i < n; i++) { fact_inv[i] = power(fact[i], mod - 2, mod);// (1/x)%m can be calculated by fermat's little theoram which is // (x**(m-2))%m when m is prime } // (a^(b^c))%m is equal to, let res=(b^c)%(m-1) then (a^res)%m // https://www.geeksforgeeks.org/find-power-power-mod-prime/?ref=rp } static void find(int i, int n, int[] row, int[] col, int[] d1, int[] d2) { if (i >= n) { ans++; return; } for (int j = 0; j < n; j++) { if (col[j] == 0 && d1[i - j + n - 1] == 0 && d2[i + j] == 0) { col[j] = 1; d1[i - j + n - 1] = 1; d2[i + j] = 1; find(i + 1, n, row, col, d1, d2); col[j] = 0; d1[i - j + n - 1] = 0; d2[i + j] = 0; } } } static int answer(int l, int r, int[][] dp) { if (l > r) return 0; if (l == r) { dp[l][r] = 1; return 1; } if (dp[l][r] != -1) return dp[l][r]; int val = Integer.MIN_VALUE; int mid = l + (r - l) / 2; val = 1 + Math.max(answer(l, mid - 1, dp), answer(mid + 1, r, dp)); return dp[l][r] = val; } static void print(int[] a) { for (int i = 0; i < a.length; i++) p(a[i] + " "); pn(""); } static long count(long n) { long count = 0; while (n != 0) { count += n % 10; n /= 10; } return count; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static int LcsOfPrefix(String a, String b) { int i = 0; int j = 0; int count = 0; while (i < a.length() && j < b.length()) { if (a.charAt(i) == b.charAt(j)) { j++; count++; } i++; } return a.length() + b.length() - 2 * count; } static void reverse(int[] a, int n) { for (int i = 0; i < n / 2; i++) { int temp = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = temp; } } static char get_char(int a) { return (char) (a + 'a'); } static int find1(int[] a, int val) { int ans = -1; int l = 0; int r = a.length - 1; while (l <= r) { int mid = l + (r - l) / 2; if (a[mid] <= val) { l = mid + 1; ans = mid; } else r = mid - 1; } return ans; } static int find2(int[] a, int val) { int l = 0; int r = a.length - 1; int ans = -1; while (l <= r) { int mid = l + (r - l) / 2; if (a[mid] <= val) { ans = mid; l = mid + 1; } else r = mid - 1; } return ans; } // static void dfs(List<List<Integer>> arr, int node, int parent, long[] val) { // p[node] = parent; // in_time[node] = count; // flat_tree[count] = val[node]; // subtree_gcd[node] = val[node]; // count++; // for (int adj : arr.get(node)) { // if (adj == parent) // continue; // dfs(arr, adj, node, val); // subtree_gcd[node] = gcd(subtree_gcd[adj], subtree_gcd[node]); // } // out_time[node] = count; // flat_tree[count] = val[node]; // count++; // } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
e1bd4f05eba1805f77770014543387a0
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(); int[] nums0 = new int[n + 10]; int[] nums1 = new int[n + 10]; int n0 = 0; int n1 = 0; for (int i = 1; i <= n; i++) { int v = in.nextInt(); if (v == 0) { nums0[++n0] = i; } else { nums1[++n1] = i; } } if (n1 == 0) { out.println(0); out.flush(); return; } // System.out.println(Arrays.toString(nums0)); // System.out.println(Arrays.toString(nums1)); int[][] dp = new int[n1 + 10][n0 + 10]; for (int i = 1; i <= n1; i++) { dp[i][0] = 99999999; } for (int i = 1; i <= n1; i++) { // dp[i - 1][0] = 0; for (int j = 1; j <= n0; j++) { dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j - 1] + Math.abs(nums0[j] - nums1[i])); } } // for (int i = 1; i <= n1; i++) { // dp[0][i - 1] = 0; // for (int j = 1; j <= n0; j++) { // out.print(dp[i][j] + " "); // } // out.println(); // } out.println(dp[n1][n0]); out.flush(); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
b4a00ed4a7367917e82659f94e9b255f
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
// package codeforces; import java.util.*; public class ArmChairs { static int[]arr; static ArrayList<Integer>a; static ArrayList<Integer>b; static int dp[][]; public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); arr=new int[n]; for(int i=0;i<n;i++) { arr[i]=scn.nextInt(); } dp=new int[n+1][n+1]; a =new ArrayList<>(); b =new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i]==0) { a.add(i); }else{ b.add(i); } } System.out.println(solve(0,0)); } public static int solve(int i,int j) { if(i==b.size()) { return 0; } if(j==a.size()) { return 100000000; } if(dp[i][j]!=0) { return dp[i][j]; } int x=Math.abs(a.get(j)-b.get(i))+solve(i+1,j+1); int y=solve(i,j+1); return dp[i][j]=Math.min(x, y); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
26684d1dee8eeb4f8e237167c06bf985
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.PriorityQueue; import java.util.Scanner; public class Armchairs { static List<Integer> zpos ; static List<Integer> opos ; static long[][] dp ; public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); zpos = new ArrayList<Integer>(); opos = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int x = sc.nextInt(); if (x == 1) opos.add(i); else zpos.add(i); } dp = new long[5001][5001]; for (int i = 0; i < 5001; i++) Arrays.fill(dp[i], -1); System.out.println(dp(0, 0, opos.size(), zpos.size(), opos.size())); } private static long dp(int i, int j, int m, int n, int cnt) { // TODO Auto-generated method stub if (cnt == 0) return 0; if (i >= m || j >= n) return Integer.MAX_VALUE; if (dp[i][j] != -1) return dp[i][j]; long dns = dp(i, j + 1, m, n, cnt); long s = Math.abs(zpos.get(j) - opos.get(i)) + dp(i + 1, j + 1, m, n, cnt - 1); return dp[i][j] = Math.min(dns, s); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
61ca3378323cf03c3d1c062a7652f08f
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.PriorityQueue; import java.util.Scanner; public class Armchairs { static List<Integer> zpos ; static List<Integer> opos ; static long[][] dp ; public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); zpos = new ArrayList<Integer>(); opos = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int x = sc.nextInt(); if (x == 1) opos.add(i); else zpos.add(i); } dp = new long[5001][5001]; for (int i = 0; i < 5001; i++) Arrays.fill(dp[i], -1); System.out.println(dp(0, 0, opos.size(), zpos.size(), opos.size())); } private static long dp(int i, int j, int m, int n, int cnt) { // TODO Auto-generated method stub if (cnt == 0) return 0; if (dp[i][j] != -1) return dp[i][j]; if (i >= m || j >= n) return Integer.MAX_VALUE; long dns = dp(i, j + 1, m, n, cnt); long s = Math.abs(zpos.get(j) - opos.get(i)) + dp(i + 1, j + 1, m, n, cnt - 1); return dp[i][j] = Math.min(dns, s); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
98f2025ebe18957290f4083847e74be6
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.PriorityQueue; import java.util.Scanner; public class Armchairs { static List<Integer> zpos ; static List<Integer> opos ; public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); zpos = new ArrayList<Integer>(); opos = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { int x = sc.nextInt(); if (x == 1) opos.add(i); else zpos.add(i); } long[][] dp = new long[5001][5001]; for (int i = 0; i < 5001; i++) Arrays.fill(dp[i], -1); System.out.println(dp(0, 0, opos.size(), zpos.size(), opos.size(), dp)); } private static long dp(int i, int j, int m, int n, int cnt, long[][] dp) { // TODO Auto-generated method stub if (cnt == 0) return 0; if (dp[i][j] != -1) return dp[i][j]; if (i >= m || j >= n) return Integer.MAX_VALUE; long dns = dp(i, j + 1, m, n, cnt, dp); long s = Math.abs(zpos.get(j) - opos.get(i)) + dp(i + 1, j + 1, m, n, cnt - 1, dp); return dp[i][j] = Math.min(dns, s); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
6fe594f56f5d2c0dc33f81990d33624c
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static int i, j, k, n, m, t, y, x, sum = 0; static long mod = 1000000007; static FastScanner fs = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); static String str; static long ans; static List<Integer> zeros = new ArrayList<>(); static List<Integer> ones = new ArrayList<>(); static int oneCount = 0; static int[][] dp = new int[5005][5005]; public static void main(String[] args) { t = 1; while (t-- > 0) { n = fs.nextInt(); for(int i = 0;i<n;i++){ x = fs.nextInt(); if(x==1){ ones.add(i); oneCount++; } else zeros.add(i); } for(int i=0;i<n;i++){ for(int j = 0; j<n;j++){ dp[i][j]=-1; } } out.println(minCost(0,0)); } out.close(); } static int minCost(int zIndex, int oIndex){ if(oIndex == ones.size()) return 0; if(zIndex == zeros.size()) return 1000000007; if(dp[zIndex][oIndex]==-1) dp[zIndex][oIndex]= Math.min(Math.abs(zeros.get(zIndex) - ones.get(oIndex))+minCost(zIndex+1, oIndex+1) , minCost(zIndex+1, oIndex)); return dp[zIndex][oIndex]; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static void ruffleSort(int[] a) { //ruffle int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n), temp = a[i]; a[i] = a[oi]; a[oi] = temp; } //then sort Arrays.sort(a); } static void ruffleSort(long[] a) { //ruffle int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n); long temp = a[i]; a[i] = a[oi]; a[oi] = temp; } //then sort Arrays.sort(a); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } static class Pair implements Comparable<Pair> { long first, second; public Pair(long first, long second) { this.first = first; this.second = second; } @Override public int compareTo(Pair o) { return Long.compare(first, o.first); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
a0f02aaae1d0213a3a0277faeea10ffe
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
//https://github.com/EgorKulikov/yaal/tree/master/lib/main/net/egork import java.util.*; import java.io.*; public class A{ static PrintWriter out; static InputReader in; public static void main(String args[]){ out = new PrintWriter(System.out); in = new InputReader(); new A(); out.flush(); out.close(); } A(){ solve(); } final int maxn = 5001, maxv = maxn * maxn + 100; void solve(){ // int t = in.nextInt(); int t = 1; while(t-- > 0){ int n = in.nextInt(); int a[][] = new int[n + 1][2], cnt[] = new int[2]; for(int i = 1; i <= n; i++){ int x = in.nextInt(); cnt[x]++; a[cnt[x]][x] = i; } int dp[][] = new int[cnt[1] + 1][cnt[0] + 1]; for(int i = 0; i <= cnt[1]; i++){ for(int j = 0; j <= cnt[0]; j++){ dp[i][j] = maxv; } } dp[0][0] = 0; for(int i = 0; i <= cnt[1]; i++){ for(int j = i; j <= cnt[0]; j++){ if(j == i && j == 0)continue; dp[i][j] = Math.min(dp[i][j - 1], i > 0 ? dp[i - 1][j - 1] + Math.abs(a[i][1] - a[j][0]) : maxv); } } out.print(dp[cnt[1]][cnt[0]]); } } public static class InputReader{ BufferedReader br; StringTokenizer st; InputReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){} } return st.nextToken(); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
89142fe7d5880942ffee10e8e7ce457d
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public class P1525D { static int n; static int x; static int y; static ArrayList<Integer> xs = new ArrayList<>(); static ArrayList<Integer> ys = new ArrayList<>(); static int[][] dp; public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); n = in.nextInt(); x = 0; // people y = 0; // empty chairs xs = new ArrayList<>(); ys = new ArrayList<>(); for (int i = 0; i < n; i++) { if (in.nextInt() == 1) { x++; xs.add(i); } else { y++; ys.add(i); } } in.close(); int result = 0; if (x != 0) { dp = new int[x + 1][y + 1]; dp[1][1] = Math.abs(xs.get(0) - ys.get(0)); rec(x, y); result = dp[x][y]; } x++; y++; System.out.println(result); } // a static void rec(int i, int j) { if (i > j) { dp[i][j] = Integer.MAX_VALUE; return; } if (i == 0) { dp[i][j] = 0; return; } if (dp[i - 1][j - 1] == 0) rec(i - 1, j - 1); if (dp[i][j - 1] == 0) rec(i, j - 1); int usesChair = dp[i - 1][j - 1] + Math.abs(xs.get(i - 1) - ys.get(j - 1)); dp[i][j] = Math.min(dp[i][j - 1], usesChair); } } /* * ANALYSIS * * * */
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
9863df8808192141f8952b68b90ba38b
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=1; while(T-->0) { int n=input.nextInt(); int a[]=new int[n]; ArrayList<Integer> list=new ArrayList<>(); ArrayList<Integer> space=new ArrayList<>(); for(int i=0;i<n;i++) { a[i]=input.nextInt(); if(a[i]==1) { list.add(i); } else { space.add(i); } } int pre[]=new int[space.size()]; for(int i=0;i<list.size();i++) { if(i==0) { int min=Integer.MAX_VALUE; for(int j=0;j<space.size();j++) { pre[j]=Math.abs(list.get(i)-space.get(j)); min=Math.min(min,pre[j]); pre[j]=min; } } else { int arr[]=new int[space.size()]; for(int j=0;j<i;j++) { arr[j]=Integer.MAX_VALUE; } int min=Integer.MAX_VALUE; for(int j=i;j<space.size();j++) { int v=Math.abs(list.get(i)-space.get(j)); v+=pre[j-1]; arr[j]=v; min=Math.min(min,v); arr[j]=min; } for(int j=0;j<space.size();j++) { pre[j]=arr[j]; } } } out.println(pre[space.size()-1]); } out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
63c2152c508399393809de9fe8493458
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { static long dp[][]; public static void main(String[] args) throws java.lang.Exception { FastReader in = new FastReader(System.in); StringBuilder sb = new StringBuilder(); int t = 1; //t = in.nextInt(); while (t > 0) { --t; int n = in.nextInt(); int arr[] = new int[n]; List<Integer> ones = new ArrayList<Integer>(); List<Integer> zero = new ArrayList<>(); for(int i = 0;i<n;i++) { int a = in.nextInt(); if(a == 1) ones.add(i); else zero.add(i); } if(ones.size() == 0) { sb.append(0+"\n"); continue; } dp = new long[ones.size()][zero.size()]; for(int i = 0;i<ones.size();i++) Arrays.fill(dp[i], -1); sb.append(findans(ones, zero, ones.size()-1, zero.size()-1)); } System.out.print(sb); } static long findans(List<Integer> ones,List<Integer> zero,int x,int y) { if(x < 0) return 0; if(y<0) return Integer.MAX_VALUE; if(dp[x][y]!=-1) return dp[x][y]; return dp[x][y] = Math.min(findans(ones, zero, x, y-1),findans(ones, zero, x-1, y-1) + (long)Math.abs(ones.get(x)-zero.get(y))); } static long gcd(long a, long b) { if (a == 0) return b; else return gcd(b % a, a); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } } class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } String nextLine() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c != 10 && c != 13; c = scan()) { sb.append((char) c); } return sb.toString(); } char nextChar() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; return (char) c; } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
5d1589b4e246d333099e635538ec7f81
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class D { public static void main(String[] args) { new D().solve(System.in, System.out); } public void solve(InputStream in, OutputStream out) { InputReader inputReader = new InputReader(in); PrintWriter writer = new PrintWriter(new BufferedOutputStream(out)); int n = inputReader.nextInt(); boolean[] occupied = new boolean[n]; for (int i = 0; i < n; i++) { occupied[i] = inputReader.nextInt() == 1; } writer.println(solve(n, occupied)); writer.close(); } public int solve(int n, boolean[] occupiedArray) { List<Integer> occ = new ArrayList<>(); List<Integer> free = new ArrayList<>(); for (int i = 0; i < n; i++) { if (occupiedArray[i]) { occ.add(i); } else { free.add(i); } } int occSize = occ.size(); if (occSize == 0) { return 0; } int freeSize = free.size(); long[][] d = new long[occSize][freeSize]; for (int j = 0; j < freeSize; j++) { d[0][j] = Integer.MAX_VALUE; for (int k = 0; k <= j; k++) { d[0][j] = Math.min(d[0][j], Math.abs(occ.get(0) - free.get(k))); } } for (int i = 1; i < occSize; i++) { for (int j = 0; j < freeSize; j++) { fillIJ(occ, free, d, i, j); } } return (int) d[occSize - 1][freeSize - 1]; } private void fillIJ(List<Integer> occ, List<Integer> free, long[][] d, int i, int j) { int left = i; int right = j; while (left < right) { int mid = (left + right) / 2; long countForMid = countFor(occ, free, d, i, mid); long countForMid1 = countFor(occ, free, d, i, mid + 1); if (countForMid1 > countForMid) { right = mid; } else { left = mid + 1; } } d[i][j] = countFor(occ, free, d, i, left); } private long countFor(List<Integer> occ, List<Integer> free, long[][] d, int i, int k) { return Math.abs(occ.get(i) - free.get(k)) + d[i - 1][k - 1]; } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
a52047f4ddfc31a6c04ad08808b5ea24
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class D { public static void main(String[] args) { new D().solve(System.in, System.out); } public void solve(InputStream in, OutputStream out) { InputReader inputReader = new InputReader(in); PrintWriter writer = new PrintWriter(new BufferedOutputStream(out)); int n = inputReader.nextInt(); boolean[] occupied = new boolean[n]; for (int i = 0; i < n; i++) { occupied[i] = inputReader.nextInt() == 1; } writer.println(solveV3(n, occupied)); writer.close(); } public int solve(int n, boolean[] occupied) { Tmp tmp = new Tmp(); tmp.n = n; tmp.occupied = occupied; tmp.used = new boolean[n]; tmp.current = 0; tmp.dfs(0); return tmp.best; } private static class Tmp { private int n; private boolean[] occupied; private boolean[] used; private int current; private int best = Integer.MAX_VALUE; private void dfs(int x) { if (x >= n) { if (current < best) { best = current; } return; } if (!occupied[x]) { dfs(x + 1); return; } for (int i = 0; i < n; i++) { if (!occupied[i] && !used[i]) { used[i] = true; current += Math.abs(x - i); dfs(x + 1); used[i] = false; current -= Math.abs(x - i); } } } } public int solveV2(int n, boolean[] occupiedArray) { List<Integer> occ = new ArrayList<>(); List<Integer> free = new ArrayList<>(); for (int i = 0; i < n; i++) { if (occupiedArray[i]) { occ.add(i); } else { free.add(i); } } int occSize = occ.size(); if (occSize == 0) { return 0; } int freeSize = free.size(); int[][] d = new int[occSize][freeSize]; for (int j = 0; j < freeSize; j++) { d[0][j] = Integer.MAX_VALUE; for (int k = 0; k <= j; k++) { d[0][j] = Math.min(d[0][j], Math.abs(occ.get(0) - free.get(k))); } } for (int i = 1; i < occSize; i++) { for (int j = 0; j < freeSize; j++) { d[i][j] = Integer.MAX_VALUE; for (int k = 1; k <= j; k++) { if (d[i - 1][k - 1] != Integer.MAX_VALUE) { d[i][j] = Math.min(d[i][j], Math.abs(occ.get(i) - free.get(k)) + d[i - 1][k - 1]); } } } } return d[occSize - 1][freeSize - 1]; } public int solveV3(int n, boolean[] occupiedArray) { List<Integer> occ = new ArrayList<>(); List<Integer> free = new ArrayList<>(); for (int i = 0; i < n; i++) { if (occupiedArray[i]) { occ.add(i); } else { free.add(i); } } int occSize = occ.size(); if (occSize == 0) { return 0; } int freeSize = free.size(); long[][] d = new long[occSize][freeSize]; for (int j = 0; j < freeSize; j++) { d[0][j] = Integer.MAX_VALUE; for (int k = 0; k <= j; k++) { d[0][j] = Math.min(d[0][j], Math.abs(occ.get(0) - free.get(k))); } } for (int i = 1; i < occSize; i++) { for (int j = 0; j < freeSize; j++) { fillIJ(occ, free, d, i, j); } } return (int) d[occSize - 1][freeSize - 1]; } private void fillIJ(List<Integer> occ, List<Integer> free, long[][] d, int i, int j) { d[i][j] = Integer.MAX_VALUE; // for (int k = i; k <= j; k++) { // d[i][j] = Math.min(d[i][j], Math.abs(occ.get(i) - free.get(k)) + d[i - 1][k - 1]); // } int left = i; int right = j; while (left < right) { int mid = (left + right) / 2; long countForMid = countFor(occ, free, d, i, mid); long countForMid1 = countFor(occ, free, d, i, mid + 1); if (countForMid1 > countForMid) { right = mid; } else { left = mid + 1; } } d[i][j] = countFor(occ, free, d, i, left); } private long countFor(List<Integer> occ, List<Integer> free, long[][] d, int i, int k) { return Math.abs(occ.get(i) - free.get(k)) + d[i - 1][k - 1]; } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
3917553f153a932fac8f570025ec3e61
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
/* * akshaygupta26 */ import java.io.*; import java.util.*; public class D { static ArrayList<Integer> taken,vacant; static long dp[][]; public static void main(String[] args) { FastReader sc=new FastReader(); StringBuffer ans=new StringBuffer(); int test=1; while(test-->0) { int n=sc.nextInt(); taken=new ArrayList<>();; vacant=new ArrayList<>(); dp=new long[n+1][n+1]; for(int i=0;i<=n;i++) { Arrays.fill(dp[i], -1); } for(int i=0;i<n;i++) { if(sc.nextInt() == 1) taken.add(i); else vacant.add(i); } long res =solve(0,0,taken.size(),vacant.size()); ans.append(res+"\n"); } System.out.print(ans); } static long solve(int t1,int v1,int nt1,int nv1) { //All taken given a seat if(t1 == nt1) return 0; //Vacant seats finishes if(v1 == nv1) return Integer.MAX_VALUE; //Not enough seat if(nt1-t1 > nv1-v1) return Integer.MAX_VALUE; /* * Two options: * 1) Use the current vacant seat * 2) Skip the current vacant seat */ if(dp[t1][v1] != -1) return dp[t1][v1]; long op1 = solve(t1+1,v1+1,nt1,nv1) + Math.abs(vacant.get(v1)-taken.get(t1)); long op2 = solve(t1,v1+1,nt1,nv1); return dp[t1][v1]=Math.min(op1, op2); } static long _gcd(long a,long b) { if(b == 0) return a; return _gcd(b,a%b); } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
1612dcd6155d32f0621afa9f12027c05
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
/*========================================================================== * AUTHOR: RonWonWon * CREATED: 18.05.2021 02:33:46 /*==========================================================================*/ import java.io.*; import java.util.*; public class D { public static void main(String[] args) { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int a[] = in.readArray(n); ArrayList<Integer> pos = new ArrayList<>(); for(int i=0;i<n;i++) if(a[i]==1) pos.add(i+1); int dp[][] = new int[n+1][pos.size()+1]; for(int i=0;i<=n;i++) Arrays.fill(dp[i],oo); for(int i=0;i<=n;i++) dp[i][0] = 0; for(int i=1;i<=n;i++){ for(int j=1;j<=pos.size();j++){ dp[i][j] = dp[i-1][j]; if(a[i-1]==0){ dp[i][j] = Math.min(dp[i][j],dp[i-1][j-1]+Math.abs(pos.get(j-1)-i)); } } } out.println(dp[n][pos.size()]); out.flush(); } static int oo = 1_000_000_000; static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while(!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch(IOException e) {} return st.nextToken(); } String nextLine(){ try{ return br.readLine(); } catch(IOException e) { } return ""; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } } static final Random random = new Random(); static void ruffleSort(int[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n), temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
4f072f674d05b549932c98c27dcae1de
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; public final class Solution { static PrintWriter out = new PrintWriter(System.out); static FastReader in = new FastReader(); static long mod = (long) 1e9 + 7; static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(1, 0), new Pair(0, -1), new Pair(0, 1)}; //Input // 0 0 1 0 1 0 1 0 1 1 0 0 public static void main(String[] args) { int tt = 1; out: while (tt-- > 0) { int n = i(); int[] arr = input(n); List<Integer> pos = new ArrayList<>(); List<Integer> ept = new ArrayList<>(); for (int i = 0; i < n; i++) { if (arr[i] == 1) { pos.add(i); } else { ept.add(i); } } int p = pos.size(); int e = ept.size(); if (p == 0) { out.println(0); continue; } int[][] dp = new int[p][e]; for (int i = 0; i < e; i++) { dp[0][i] = Math.abs(ept.get(i) - pos.get(0)); if (i > 0) { dp[0][i] = Math.min(dp[0][i], dp[0][i - 1]); } } for (int i = 1; i < p; i++) { for (int j = i; j < e; j++) { if (j == i) { dp[i][j] = dp[i - 1][j - 1] + Math.abs(ept.get(i) - pos.get(j)); } else { dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j - 1] + Math.abs(ept.get(j) - pos.get(i))); } } } out.println(dp[p - 1][e - 1]); } out.flush(); } static boolean isPS(double number) { double sqrt = Math.sqrt(number); return ((sqrt - Math.floor(sqrt)) == 0); } static int sd(long i) { int d = 0; while (i > 0) { d += i % 10; i = i / 10; } return d; } static int[] leastPrime; static void sieveLinear(int N) { int[] primes = new int[N]; int idx = 0; leastPrime = new int[N + 1]; for (int i = 2; i <= N; i++) { if (leastPrime[i] == 0) { primes[idx++] = i; leastPrime[i] = i; } int curLP = leastPrime[i]; for (int j = 0; j < idx; j++) { int p = primes[j]; if (p > curLP || (long) p * i > N) { break; } else { leastPrime[p * i] = p; } } } } static int lower(long A[], long x) { int l = -1, r = A.length; while (r - l > 1) { int m = (l + r) / 2; if (A[m] >= x) { r = m; } else { l = m; } } return r; } static int upper(long A[], long x) { int l = -1, r = A.length; while (r - l > 1) { int m = (l + r) / 2; if (A[m] <= x) { l = m; } else { r = m; } } return l; } static void swap(int A[], int a, int b) { int t = A[a]; A[a] = A[b]; A[b] = t; } static int lowerBound(int A[], int low, int high, int x) { if (low > high) { if (x >= A[high]) { return A[high]; } } int mid = (low + high) / 2; if (A[mid] == x) { return A[mid]; } if (mid > 0 && A[mid - 1] <= x && x < A[mid]) { return A[mid - 1]; } if (x < A[mid]) { return lowerBound(A, low, mid - 1, x); } return lowerBound(A, mid + 1, high, x); } static long pow(long a, long b) { long pow = 1; long x = a; while (b != 0) { if ((b & 1) != 0) { pow = (pow * x) % mod; } x = (x * x) % mod; b /= 2; } return pow; } static boolean isPrime(long N) { if (N <= 1) { return false; } if (N <= 3) { return true; } if (N % 2 == 0 || N % 3 == 0) { return false; } for (int i = 5; i * i <= N; i = i + 6) { if (N % i == 0 || N % (i + 2) == 0) { return false; } } return true; } static void print(char A[]) { for (char c : A) { out.print(c); } out.println(); } static void print(boolean A[]) { for (boolean c : A) { out.print(c + " "); } out.println(); } static void print(int A[]) { for (int c : A) { out.print(c + " "); } out.println(); } static void print(long A[]) { for (long i : A) { out.print(i + " "); } out.println(); } static void print(List<Integer> A) { for (int a : A) { out.print(a + " "); } } static void printYes() { out.println("YES"); } static void printNo() { out.println("NO"); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static String s() { return in.nextLine(); } static int[] input(int N) { int A[] = new int[N]; for (int i = 0; i < N; i++) { A[i] = in.nextInt(); } return A; } static long[] inputLong(int N) { long A[] = new long[N]; for (int i = 0; i < A.length; i++) { A[i] = in.nextLong(); } return A; } static int GCD(int a, int b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static long GCD(long a, long b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } } class BIT { int n; int[] tree; public BIT(int n) { this.n = n; this.tree = new int[n + 1]; } public static int lowbit(int x) { return x & (-x); } public void update(int x) { while (x <= n) { ++tree[x]; x += lowbit(x); } } public int query(int x) { int ans = 0; while (x > 0) { ans += tree[x]; x -= lowbit(x); } return ans; } public int query(int x, int y) { return query(y) - query(x - 1); } } class SegmentTree { long[] t; public SegmentTree(int n) { t = new long[n + n]; Arrays.fill(t, Long.MIN_VALUE); } public long get(int i) { return t[i + t.length / 2]; } public void add(int i, long value) { i += t.length / 2; t[i] = value; for (; i > 1; i >>= 1) { t[i >> 1] = Math.max(t[i], t[i ^ 1]); } } // max[a, b] public long max(int a, int b) { long res = Long.MIN_VALUE; for (a += t.length / 2, b += t.length / 2; a <= b; a = (a + 1) >> 1, b = (b - 1) >> 1) { if ((a & 1) != 0) { res = Math.max(res, t[a]); } if ((b & 1) == 0) { res = Math.max(res, t[b]); } } return res; } } class Pair { int i, j; Pair(int i, int j) { this.i = i; this.j = j; } } 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\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
153e8f61844cba111f0dda78126bd433
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Try2{ public static void main(String[] args) throws IOException { FastScanner fs = new FastScanner(); // int t =fs.nextInt(); int t=1; while (t-- > 0) { int n = fs.nextInt(); int a[] = new int[n]; int countOne = 0; ArrayList<Integer> aa = new ArrayList<Integer>(); for(int i =0;i<n;i++) { a[i] =fs.nextInt(); if(a[i]==1) { countOne++; aa.add(i); } } int dp[][] = new int[n+1][countOne+1]; for(int i =0 ;i<=n;i++) { for(int j =0 ;j<=countOne;j++) { dp[i][j] = Integer.MAX_VALUE; } } dp[0][0] =0; for(int i =0 ;i<n;i++) { for(int j =0 ;j<countOne+1;j++) { if(dp[i][j]==Integer.MAX_VALUE) continue; dp[i+1][j] = Math.min(dp[i][j], dp[i+1][j]); if(j<countOne && a[i]==0) { dp[i+1][j+1]=Math.min(dp[i][j]+Math.abs(aa.get(j)-i),dp[i+1][j+1]); } } } System.out.println(dp[n][countOne]); } } static final Random random = new Random(); static void ruffleSort(int[] a) { int n = a.length;// shuffle, then sort for (int i = 0; i < n; i++) { int oi = random.nextInt(n), temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
9bed219d45dd2f462b27ee9297938959
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.List; import java.util.StringJoiner; public class Solution { private static List<Long> chairs; private static List<Long> folks; private static Long[] data; private static Long[][] cache; public static void main(String[] args) { Print print = new Print(); Scan scan = new Scan(); int n = scan.scanInt(); data = scan.scan1dLongArray(); chairs = new ArrayList<>(); folks = new ArrayList<>(); cache = new Long[n][n]; for (int i = 0; i < n; i++) { if (data[i] == 0) { chairs.add((long) i); } else { folks.add((long) i); } } print.printLine(Long.toString(solve(folks, chairs, 0, 0))); print.close(); } private static long solve(List<Long> folks, List<Long> chairs, int i, int j) { if (i == folks.size()) { return 0; } if (j == chairs.size()) { return Integer.MAX_VALUE; } if (cache[i][j] != null) { return cache[i][j]; } return cache[i][j] = Math .min(Math.abs(folks.get(i) - chairs.get(j)) + solve(folks, chairs, i + 1, j + 1), solve(folks, chairs, i, j + 1)); } static class Scan { private byte[] buf = new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in = System.in; } public int scan() { if (total < 0) { throw new InputMismatchException(); } if (index >= total) { index = 0; try { total = in.read(buf); } catch (IOException ignored) { } if (total <= 0) { return -1; } } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) { n = scan(); } int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } else { throw new InputMismatchException(); } } return neg * integer; } public double scanDouble() { double doub = 0; int n = scan(); while (isWhiteSpace(n)) { n = scan(); } int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n) && n != '.') { if (n >= '0' && n <= '9') { doub *= 10; doub += n - '0'; n = scan(); } else { throw new InputMismatchException(); } } if (n == '.') { n = scan(); double temp = 1; while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { temp /= 10; doub += (n - '0') * temp; n = scan(); } else { throw new InputMismatchException(); } } } return doub * neg; } public Integer[] scan1dIntArray() { String[] s = this.scanString().split(" "); Integer[] arr = new Integer[s.length]; for (int i = 0; i < s.length; i++) { arr[i] = Integer.parseInt(s[i]); } return arr; } public Integer[][] scan2dIntArray(int n, int m) { Integer[][] arr = new Integer[n][m]; for (int i = 0; i < n; i++) { String[] s = this.scanString().split(" "); for (int j = 0; j < m; j++) { arr[i][j] = Integer.parseInt(s[j]); } } return arr; } public String[] scan1dStringArray() { return this.scanString().split(" "); } public String[][] scan2dStringArray(int n, int m) { String[][] arr = new String[n][m]; for (int i = 0; i < n; i++) { String[] s = this.scanString().split(" "); for (int j = 0; j < m; j++) { arr[i][j] = s[j]; } } return arr; } public char[] scan1dCharArray() { return this.scanString().toCharArray(); } public char[][] scan2dCharArray(int n, int m) { char[][] arr = new char[n][m]; for (int i = 0; i < n; i++) { char[] s = this.scanString().toCharArray(); for (int j = 0; j < m; j++) { arr[i][j] = s[j]; } } return arr; } public Long[] scan1dLongArray() { String[] s = this.scanString().split(" "); Long[] arr = new Long[s.length]; for (int i = 0; i < s.length; i++) { arr[i] = Long.parseLong(s[i]); } return arr; } public Long[][] scan2dLongArray(int n, int m) { Long[][] arr = new Long[n][m]; for (int i = 0; i < n; i++) { String[] s = this.scanString().split(" "); for (int j = 0; j < m; j++) { arr[i][j] = Long.parseLong(s[j]); } } return arr; } public String scanString() { StringBuilder sb = new StringBuilder(); int n = scan(); while (isWhiteSpace(n)) { n = scan(); } while (!isWhiteSpace(n)) { sb.append((char) n); n = scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if (n == '\n' || n == '\r' || n == '\t' || n == -1) { return true; } return false; } } static class Print { private final BufferedWriter bw; public Print() { bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(String str) { try { bw.append(str); } catch (IOException ignored) { } } public void printLine(Integer[] arr) { StringJoiner sj = new StringJoiner(" "); for (Integer x : arr) { sj.add(Integer.toString(x)); } printLine(sj.toString()); } public void printLine(Integer[][] arr) { for (Integer[] x : arr) { StringJoiner sj = new StringJoiner(" "); for (Integer y : x) { sj.add(Integer.toString(y)); } printLine(sj.toString()); } } public void printLine(String[] arr) { StringJoiner sj = new StringJoiner(" "); for (String x : arr) { sj.add(x); } printLine(sj.toString()); } public void printLine(String[][] arr) { for (String[] x : arr) { StringJoiner sj = new StringJoiner(" "); for (String y : x) { sj.add(y); } printLine(sj.toString()); } } public void printLine(char[] arr) { StringJoiner sj = new StringJoiner(" "); for (char x : arr) { sj.add(Character.toString(x)); } printLine(sj.toString()); } public void printLine(char[][] arr) { for (char[] x : arr) { StringJoiner sj = new StringJoiner(" "); for (char y : x) { sj.add(Character.toString(y)); } printLine(sj.toString()); } } public void printLine(Long[] arr) { StringJoiner sj = new StringJoiner(" "); for (Long x : arr) { sj.add(Long.toString(x)); } printLine(sj.toString()); } public void printLine(Long[][] arr) { for (Long[] x : arr) { StringJoiner sj = new StringJoiner(" "); for (Long y : x) { sj.add(Long.toString(y)); } printLine(sj.toString()); } } public void printLine(String str) { print(str); try { bw.append("\n"); } catch (IOException ignored) { } } public void close() { try { bw.close(); } catch (IOException ignored) { } } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
c861e47a0408906776c572164198fddc
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public class D1525 { static int[] arr; static int[][] dp; public static int dp(int idx, int av) { if (idx == arr.length) { if (av == 0) { return 0; } return (int) 1e9; } if (dp[idx][av + arr.length] != -1) { return dp[idx][av + arr.length]; } if (arr[idx] == 0) { return dp[idx][av + arr.length] = Math.min(dp(idx + 1, av) + Math.abs(av), dp(idx + 1, av + 1) + Math.abs(av + 1)); } else { return dp[idx][av + arr.length] = Math.abs(av - 1) + dp(idx + 1, av - 1); } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); arr = sc.nextIntArr(n); dp = new int[n][2 * n + 5]; for (int[] x : dp) Arrays.fill(x, -1); pw.println(dp(0, 0)); pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
4b98dce3c12130287769f06c55644438
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; public class C { static ArrayList<Integer>one; static ArrayList<Integer>zero; static int dp[][]=new int[5001][5001]; public static void main(String[] args) { Scanner sc=new Scanner(System.in); one =new ArrayList<>(); zero=new ArrayList<>(); int n =sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(a[i]==0) zero.add(i); else one.add(i); } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { dp[i][j]=-1; } } System.out.println(calc(0,0)); } static int calc(int i,int j) { if(dp[i][j]!=-1)return dp[i][j]; if(i==one.size())return 0; if(j==zero.size())return (int)(1e9); return dp[i][j]=Math.min(calc(i+1, j+1) +Math.abs(one.get(i)-zero.get(j)),calc(i,j+1)); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
5df4a52e0d98ebf9a0b55cbb1691ceeb
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main{ static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextArray(long n) { long[] a = new long[(int) n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } static class FastWriter extends PrintWriter { FastWriter(){ super(System.out); } void println(int[] array) { for(int i=0; i<array.length; i++) { print(array[i]+" "); } println(); } void println(long [] array) { for(int i=0; i<array.length; i++) { print(array[i]+" "); } println(); } } static ArrayList<Integer> ones,zeros; static int[][] dp; public static void main(String[] args){ FastScanner in = new FastScanner(); FastWriter out = new FastWriter(); //int t=in.nextInt(); int t=1; while (t-->0){ int n=in.nextInt(); int[] ar=in.nextArray(n); ones=new ArrayList<>();zeros=new ArrayList<>(); for (int i = 0; i < n; i++) { if(ar[i]==1){ ones.add(i); }else { zeros.add(i); } } int on= ones.size(); int ze=zeros.size(); dp=new int[on][ze]; for (int i = 0; i < on; i++) { Arrays.fill(dp[i],-1); } out.println(solve(on-1,ze-1)); } out.close(); } static int solve(int x,int y){ if(x==-1){ return 0; } if(x>y){ return Integer.MAX_VALUE; } if(dp[x][y] != -1){ return dp[x][y]; } return dp[x][y] = Math.min( Math.abs(ones.get(x)-zeros.get(y)) + solve(x-1,y-1) , solve(x,y-1) ); } static int reduceFraction(int x, int y) { int d= gcd(x, y); return x/d+y/d; } static boolean subset(int[] ar,int n,int sum){ if(sum==0){ return true; } if(n<0||sum<0){ return false; } return subset(ar,n-1,sum)||subset(ar,n-1,sum-ar[n]); } static boolean isPrime(int n){ if(n<=1) return false; for(int i = 2;i<=Math.sqrt(n);i++){ if (n % i == 0) return false; } return true; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static boolean isPowerOfTwo(int n) { if(n==0||n==1) return false; return ((int)(Math.ceil((Math.log(n) / Math.log(2)))) == (int)(Math.floor(((Math.log(n) / Math.log(2)))))); } static boolean isPerfectSquare(int x){ if (x >= 0) { int sr = (int)Math.sqrt(x); return ((sr * sr) == x); } return false; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
2b4c93e825d8d5df4b53eff666e2b9c4
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; public class C { //lexographically best moves... public static int dx[] = { 1, 0, 0, -1 }; public static int dy[] = { 0, -1, 1, 0 }; public static ArrayList<Integer> occ=new ArrayList<>(); public static ArrayList<Integer> unocc=new ArrayList<>(); public static long dp[][]=new long[5001][5001]; public static long func(int occ_idx,int unocc_idx,int n,int m) { if(occ_idx>=n) { return 0; } else if(unocc_idx>=m) { return Integer.MAX_VALUE; } else if(dp[occ_idx][unocc_idx]!=-1) { return dp[occ_idx][unocc_idx]; } else { dp[occ_idx][unocc_idx]=Math.min(Math.abs(occ.get(occ_idx)-unocc.get(unocc_idx))+func(occ_idx+1, unocc_idx+1, n, m), func(occ_idx, unocc_idx+1, n, m)); return dp[occ_idx][unocc_idx]; } } public static void main(String[] args) throws FileNotFoundException { FastScanner fs = new FastScanner(); FastOutput fo = new FastOutput(System.out); long initial_time = System.currentTimeMillis(); //int testcases = fs.nextInt(); //for (int tt = 0; tt < testcases; tt++) { //main code for(int i=0;i<5001;i++) { for(int j=0;j<5001;j++) { dp[i][j]=-1; } } int n=fs.nextInt(); char[] arr=new char[n]; for(int i=0;i<n;i++) { String s=fs.next(); arr[i]=s.charAt(0); } for(int i=0;i<n;i++) { if(arr[i]=='1') { occ.add(i); } else { unocc.add(i); } } fo.println(func(0,0,occ.size(),unocc.size())); //} fo.time(initial_time); fo.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() throws FileNotFoundException { if (System.getProperty("ONLINE_JUDGE") == null) { //Read from the File... File file = new File("src\\input"); br = new BufferedReader(new FileReader(file)); } else { //Read from the System... br = new BufferedReader(new InputStreamReader(System.in)); } st = new StringTokenizer(""); } String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } static class FastOutput extends PrintWriter { public FastOutput(PrintStream out) { super(out); } void time(long init) { if (System.getProperty("ONLINE_JUDGE") == null) { this.println(System.currentTimeMillis() - init + "ms"); } } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
42ef2a1803fce76c26005e16fcf7f3a6
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; public class Armchairs { public static PrintWriter out; static int mod=998244353; public static void main(String[] args)throws IOException { JS sc=new JS(); out = new PrintWriter(System.out); int t=1;//sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int a[]=new int[n]; int cnt=0; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(a[i]==0) { cnt++; } } int m=n-cnt; int seats[]=new int[cnt]; int ppl[]=new int[m]; int idx=0; int idx1=0; for(int i=0;i<n;i++) { if(a[i]==0) { seats[idx++]=i; }else { ppl[idx1++]=i; } } //dp state: current person picked seat picked; int dp[][]=new int[m+1][cnt+1]; for(int i=1;i<=m;i++) { Arrays.fill(dp[i], Integer.MAX_VALUE); } for(int i=0;i<m;i++) {//loop through person for(int j=0;j<cnt;j++) { if(i<cnt&&dp[i][j]!=Integer.MAX_VALUE) { dp[i+1][j+1]=Math.min(dp[i+1][j+1], dp[i][j]+Math.abs(ppl[i]-seats[j])); } dp[i][j+1]=Math.min(dp[i][j+1], dp[i][j]); } } int ans=Integer.MAX_VALUE; for(int i=0;i<=cnt;i++) { ans=Math.min(ans, dp[m][i]); } out.println(ans); } out.close(); } static class JS { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public JS() { in = new BufferedInputStream(System.in, BS); } public JS(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar(){ 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 long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
a05ba822fa8813efaf4145da27cd5b55
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public class Armchairs{ public static void main(String[] args) { FastReader fr = new FastReader(); PrintWriter out = new PrintWriter(System.out); Scanner sc= new Scanner (System.in); //Code From Here---- int t =fr.nextInt(); ArrayList <Integer> chairs= new ArrayList<>(); ArrayList <Integer> free= new ArrayList<>(); for (int i = 0; i < t; i++) { int state =fr.nextInt(); if(state==1) { chairs.add(i); } else{ free.add(i); } } int [][] dp=new int [t][t]; for (int[] is : dp) { Arrays.fill(is, -1); } int ans=solve(chairs,free,0,0,chairs.size(),dp); out.println(ans); out.flush(); sc.close(); } //This RadixSort() is for long method private static int solve(ArrayList<Integer> chairs, ArrayList<Integer> free, int i, int j, int size,int [][] dp) { if (dp[i][j]!=-1) { return dp[i][j]; } if (size==0) { return 0; } if (j==free.size()) { return 10000000; } int a=solve(chairs, free, i, j+1, size,dp); int b=Math.abs(chairs.get(i)-free.get(j))+solve(chairs, free, i+1, j+1, size-1,dp); dp[i][j]=Math.min(a, b); return dp[i][j]; } public static long[] radixSort(long[] f){ return radixSort(f, f.length); } public static long[] radixSort(long[] f, int n) { long[] to = new long[n]; { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>16&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>16&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>32&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>32&0xffff)]++] = f[i]; long[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>48&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>48&0xffff)]++] = f[i]; long[] d = f; f = to; to = d; } return f; } public static int[] radixSort2(int[] a) { int n = a.length; int[] c0 = new int[0x101]; int[] c1 = new int[0x101]; int[] c2 = new int[0x101]; int[] c3 = new int[0x101]; for(int v : a) { c0[(v&0xff)+1]++; c1[(v>>>8&0xff)+1]++; c2[(v>>>16&0xff)+1]++; c3[(v>>>24^0x80)+1]++; } for(int i = 0;i < 0xff;i++) { c0[i+1] += c0[i]; c1[i+1] += c1[i]; c2[i+1] += c2[i]; c3[i+1] += c3[i]; } int[] t = new int[n]; for(int v : a)t[c0[v&0xff]++] = v; for(int v : t)a[c1[v>>>8&0xff]++] = v; for(int v : a)t[c2[v>>>16&0xff]++] = v; for(int v : t)a[c3[v>>>24^0x80]++] = v; return a; } static int lowerBound(long a[], long x) { // x is the target value or key int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] >= x) r = m; else l = m; } return r; } static int upperBound(long a[], long x) {// x is the key or target value int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1L; if (a[m] <= x) l = m; else r = m; } return l + 1; } static int upperBound(long[] arr, int start, int end, long k) { int N = end; while (start < end) { int mid = start + (end - start) / 2; if (k >= arr[mid]) { start = mid + 1; } else { end = mid; } } if (start < N && arr[start] <= k) { start++; } return start; } static long lowerBound(long[] arr, int start, int end, long k) { int N = end; while (start < end) { int mid = start + (end - start) / 2; if (k <= arr[mid]) { end = mid; } else { start = mid + 1; } } if (start < N && arr[start] < k) { start++; } return start; } // For Fast Input ---- static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
1a690bcb99bc65ec19f22d3ff13af901
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class NewSolution { private static final int MAX = Integer.MAX_VALUE; public static void main(String[] args) { Reader myReader = new Reader(); int n = myReader.nextInt(); ArrayList<Integer> zero = new ArrayList<>(); ArrayList<Integer> one = new ArrayList<>(); int[] given = new int[n]; for (int i=0; i<n; i++) { int curr = myReader.nextInt(); given[i] = curr; if (curr==0) zero.add(i); else one.add(i); } int filled = one.size(); int[] dp = new int[filled+1]; Arrays.fill(dp, MAX); dp[0] = 0; for (int i=0; i<n; i++) { if (given[i]==1) continue; for (int j=filled-1; j>=0; j--) { if (dp[j]==MAX) continue; dp[j+1] = Math.min(dp[j+1], dp[j] + Math.abs(i - one.get(j))); } } System.out.println(dp[filled]); } static class Reader { BufferedReader reader; StringTokenizer st; Reader() { reader = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { try { if (st==null || !st.hasMoreTokens()) st = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
4f04112f98abffe6664668e4150ed982
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.util.Collections; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.*; public class Main1 { static ArrayList<Integer> list1 = new ArrayList<>() ; static ArrayList<Integer> list2 = new ArrayList<>() ; static int n , m ; static long dp[][] ; static long solver(int i , int j ){ // i = empty chairs if (j == m)return 0 ; int tt1 = n-i ; int tt2 = m-j ; if (n-i < m-j)return Long.MAX_VALUE/2 ; if ( dp[i][j] != -1 )return dp[i][j] ; long a = solver(i+1 , j) ; long b = abs( list1.get(i) - list2.get(j)) + solver(i+1 , j+1) ; return dp[i][j] = min(a , b) ; } public static void main(String[] args) throws IOException { // try { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = in.nextInt() ; int a[] = in.readArray(N) ; for (int i = 0; i <N ; i++) { if (a[i] == 1)list2.add(i) ; else list1.add(i) ; } n = list1.size() ; m = list2.size() ; dp = new long[n][m] ; for(int i=0 ; i<n ; i++) for(int j=0 ; j<m ; j++) dp[i][j] = -1 ; System.out.println(solver(0 , 0 )); out.flush(); out.close(); // } // catch (Exception e){ // return; // } } static long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } static ArrayList<Integer> list = new ArrayList<>(); static boolean A[] = new boolean[2 * 90000001]; static void seive(int n) { int maxn = n; //int maxn = 1000000 ; A[0] = A[1] = true; for (int i = 2; i * i <= maxn; i++) { if (!A[i]) { for (int j = i * i; j <= maxn; j += i) A[j] = true; } } for (int i = 2; i <= maxn; i++) if (!A[i]) list.add(i); } static int findLCA(int a, int b, int par[][], int depth[]) { if (depth[a] > depth[b]) { a = a ^ b; b = a ^ b; a = a ^ b; } int diff = depth[b] - depth[a]; for (int i = 19; i >= 0; i--) { if ((diff & (1 << i)) > 0) { b = par[b][i]; } } if (a == b) return a; for (int i = 19; i >= 0; i--) { if (par[b][i] != par[a][i]) { b = par[b][i]; a = par[a][i]; } } return par[a][0]; } static int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } static void formArrayForBinaryLifting(int n, int par[][]) { for (int j = 1; j < 20; j++) { for (int i = 0; i < n; i++) { if (par[i][j - 1] == -1) continue; par[i][j] = par[par[i][j - 1]][j - 1]; } } } static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 32 << 10; private final Writer os; private StringBuilder cache = new StringBuilder(THRESHOLD * 2); public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } private void afterWrite() { if (cache.length() < THRESHOLD) { return; } flush(); } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); afterWrite(); return this; } public FastOutput append(long c) { cache.append(c); afterWrite(); return this; } public FastOutput append(String c) { cache.append(c); afterWrite(); return this; } public FastOutput println() { return append(System.lineSeparator()); } public FastOutput flush() { try { // boolean success = false; // if (stringBuilderValueField != null) { // try { // char[] value = (char[]) stringBuilderValueField.get(cache); // os.write(value, 0, cache.length()); // success = true; // } catch (Exception e) { // } // } // if (!success) { os.append(cache); // } os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
303797f9c8799cb406bf3131dca6f29f
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; public class Armchairs { public static int findMinTime(List<Integer> zeros, List<Integer> ones) { if (ones.size() == 0) return 0; int oneSize = ones.size(); int zeroSize = zeros.size(); int [][] time = new int [oneSize + 1][zeroSize + 1]; for (int i=1; i<=oneSize; i++) { time[i][i] = time[i - 1][i - 1] + Math.abs(ones.get(i - 1) - zeros.get(i - 1)); for (int j=i+1; j<=zeroSize; j++) { time[i][j] = Math.min(time[i][j - 1], time[i - 1][j - 1] + Math.abs(ones.get(i - 1) - zeros.get(j - 1))); } } return time[oneSize][zeroSize]; } public static void main (String [] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); List<Integer> zeros = new ArrayList<>(); List<Integer> ones = new ArrayList<>(); for (int i=0; i<n; i++) { int number= sc.nextInt(); if (number == 1) ones.add(i); else zeros.add(i); } System.out.println(findMinTime(zeros, ones)); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
ccf65738913c742a4950efcf32fa644e
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; public class ProblemD { public static void main(String[] args) throws IOException { final int INF = 20000000; InputStream in = System.in; InputReader scan = new InputReader(in); int n = scan.nextInt(); int occ = 0; List<Integer> occPos = new ArrayList<>(); HashSet<Integer> occPosSet = new HashSet<>(); for(int i=1;i<=n;i++) { int num = scan.nextInt(); if(num==1) { occ++; occPos.add(i); occPosSet.add(i); } } int[][] dp = new int[n+1][occ+1]; for(int i=0;i<=n;i++) { for(int j=0;j<=occ;j++) { dp[i][j] = 20000000; } } for(int i=1;i<=n;i++) { int k=1; for(int pos: occPos) { if(occPosSet.contains(i)) { dp[i][k] = dp[i-1][k]; } else { dp[i][k] = Math.min(dp[i-1][k], dp[i-1][k-1]+Math.abs(pos-i)); if(k==1) dp[i][k]=Math.min(dp[i][k],Math.abs(pos-i)); } k++; } } if(dp[n][occ]==INF) { System.out.println(0); } else { System.out.println(dp[n][occ]); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException ioe) { ioe.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
8d7c1385a45d8a451a4d7ddd781ef141
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); InputReader in = new InputReader(inputStream); // for(int i=4;i<=4;i++) { // InputStream uinputStream = new FileInputStream("timeline.in"); //String f = i+".in"; //InputStream uinputStream = new FileInputStream(f); // InputReader in = new InputReader(uinputStream); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("timeline.out"))); // } Task t = new Task(); t.solve(in, out); out.close(); } static class Task{ public void solve(InputReader in, PrintWriter out) throws IOException { // String a[] = {"####F","#C...","M...."}; // String b[] = {"M.C...F"}; // String c[] = {"M.C...F"}; // String d[] = {"C...#","...#F","....#","M...."}; // String e[] = {".M...","..#..","#..#.","C#.#.","...#F"}; // String f[] = {"#..C...","M....#.","######.","######.","######.","######F"}; // //Dumper.print(canMouseWin(a,1,2)); // //Dumper.print(canMouseWin(b,1,4)); // //Dumper.print(canMouseWin(c,1,3)); // //Dumper.print(canMouseWin(d,2,5)); // //Dumper.print(canMouseWin(e,3,1)); // Dumper.print(canMouseWin(f,1,5)); int n = in.nextInt(); int arr[] = in.readIntArray(n); int p = 0; int q = 0; for(int i:arr) { if(i==0) q++; else p++; } if(p==0) { out.println(0); return; } int a[] = new int[p]; int b[] = new int[q]; p=0;q=0; for(int i=0;i<n;i++) { if(arr[i]==0) b[q++] = i; else a[p++] = i; } int dp[][] = new int[p][q]; for(int i=0;i<p;i++) { for(int j=0;j<q;j++) { dp[i][j] = 999999999; if(i==0) { dp[i][j] = Math.abs(a[i]-b[j]); if(j>0) dp[i][j] = Math.min(dp[i][j], dp[i][j-1]); } } } for(int i=1;i<p;i++) { for(int j=i;j<q;j++) { dp[i][j] = Math.min(dp[i][j], dp[i-1][j-1]+Math.abs(a[i]-b[j])); dp[i][j] = Math.min(dp[i][j], dp[i][j-1]); } } out.println(dp[p-1][q-1]); } public boolean canMouseWin(String[] grid, int catJump, int mouseJump) { int n = grid.length; int m = grid[0].length(); int cx = 0; int cy = 0; int mx = 0; int my = 0; int fx = 0; int fy = 0; char arr[][] = new char[n][m]; for(int i=0;i<n;i++) { arr[i] = grid[i].toCharArray(); for(int j=0;j<m;j++) { if(arr[i][j]=='M') { mx = i; my = j; } if(arr[i][j]=='C') { cx = i; cy = j; } if(arr[i][j]=='F') { fx = i; fy = j; } } } boolean can_jump[][][][] = new boolean[n][m][n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { for(int p=0;p<n;p++) { for(int q=0;q<m;q++) { if(i!=p&&j!=q) continue; if(i==p) { boolean flag = true; for(int k=Math.min(j, q);k<=Math.max(j, q);k++) { if(arr[i][k]=='#') { flag = false; break; } } can_jump[i][j][p][q] = flag; }else { boolean flag = true; for(int k=Math.min(i, p);k<=Math.max(i, p);k++) { if(arr[k][j]=='#') { flag = false; break; } } can_jump[i][j][p][q] = flag; } } } } } int dir[][] = {{-1,0},{1,0},{0,-1},{0,1}}; boolean dp[][][][] = new boolean[n][m][n][m]; dp[cx][cy][mx][my] = true; dfs(0,can_jump,dp,arr,cx,cy,mx,my,fx,fy,catJump,mouseJump,dir); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(dp[i][j][fx][fy]) return true; } } return false; } void dfs(int turn, boolean can[][][][], boolean dp[][][][], char arr[][], int cx, int cy, int mx, int my, int fx, int fy, int cj, int mj, int dir[][]) { if(turn==0) { for(int i=0;i<4;i++) { for(int j=0;j<=mj;j++) { int nxt_mx = mx+dir[i][0]*j; int nxt_my = my+dir[i][1]*j; if(nxt_mx<0||nxt_my<0||nxt_mx>=arr.length||nxt_my>=arr[0].length) continue; if(arr[nxt_mx][nxt_my]=='#'||(nxt_mx==cx&&nxt_my==cy)||dp[cx][cy][nxt_mx][nxt_my]||!can[mx][my][nxt_mx][nxt_my]) continue; dp[cx][cy][nxt_mx][nxt_my] = true; dfs(1-turn,can,dp,arr,cx,cy,nxt_mx,nxt_my,fx,fy,cj,mj,dir); } } }else { if(cx==mx&&Math.abs(cy-my)<=cj) return; if(cy==my&&Math.abs(cx-mx)<=cj) return; for(int i=0;i<4;i++) { for(int j=0;j<=mj;j++) { int nxt_cx = cx+dir[i][0]*j; int nxt_cy = cy+dir[i][1]*j; if(nxt_cx<0||nxt_cy<0||nxt_cx>=arr.length||nxt_cy>=arr[0].length) continue; if(arr[nxt_cx][nxt_cy]=='#'||dp[nxt_cx][nxt_cy][mx][my]||!can[cx][cy][nxt_cx][nxt_cy]) continue; dp[nxt_cx][nxt_cy][mx][my] = true; dfs(1-turn,can,dp,arr,nxt_cx,nxt_cy,mx,my,fx,fy,cj,mj,dir); } } } } class status { int cx,cy,mx,my; public status(int a, int b, int c, int d) { cx = a; cy = b; mx = c; my = d; } } public Set<Integer> get_factor(int number) { int n = number; Set<Integer> primeFactors = new HashSet<Integer>(); for (int i = 2; i <= n/i; i++) { while (n % i == 0) { primeFactors.add(i); n /= i; } } if(n>1) primeFactors.add(n); return primeFactors; } private static int combx(int n, int k) { int comb[][] = new int[n+1][n+1]; for(int i = 0; i <=n; i ++){ comb[i][0] = comb[i][i] = 1; for(int j = 1; j < i; j++){ comb[i][j] = comb[i-1][j] + comb[i-1][j-1]; comb[i][j] %= 1000000007; } } return comb[n][k]; } class trie_node{ boolean end; int val; int lvl; trie_node zero; trie_node one; public trie_node() { zero = null; one = null; end = false; val = -1; lvl = -1; } } class trie{ trie_node root = new trie_node(); public void build(int x, int sz) { trie_node cur = root; for(int i=sz;i>=0;i--) { int v = (x&(1<<i))==0?0:1; if(v==0&&cur.zero==null) { cur.zero = new trie_node(); } if(v==1&&cur.one==null) { cur.one = new trie_node(); } cur.lvl = i; if(i==0) { cur.end = true; cur.val = x; }else { if(v==0) cur = cur.zero; else cur = cur.one; cur.val = v; cur.lvl = i; } } } int search(int num, int limit, trie_node r, int lvl) { if(r==null) return -1; if(r.end) return r.val; int f = -1; int num_val = (num&1<<lvl)==0?0:1; int limit_val = (limit&1<<lvl)==0?0:1; if(limit_val==1) { if(num_val==0) { int t = search(num,limit,r.one,lvl-1); if(t>f) return t; t = search(num,limit,r.zero,lvl-1); if(t>f) return t; }else { int t = search(num,limit,r.zero,lvl-1); if(t>f) return t; t = search(num,limit,r.one,lvl-1); if(t>f) return t; } }else { int t = search(num,limit,r.zero,lvl-1); if(t>f) return t; } return f; } } public int[] maximizeXor(int[] nums, int[][] queries) { int m = queries.length; int ret[] = new int[m]; trie t = new trie(); int sz = 5; for(int i:nums) t.build(i,sz); int p = 0; for(int x[]:queries) { if(p==1) { Dumper.print("here"); } ret[p++] = t.search(x[0], x[1], t.root, sz); } return ret; } class edge implements Comparable<edge>{ int id,f,t; int len;int short_len; public edge(int a, int b, int c, int d, int e) { f=a;t=b;len=c;id=d;short_len = e; } @Override public int compareTo(edge t) { if(this.len-t.len>0) return 1; else if(this.len-t.len<0) return -1; return 0; } } static class lca_naive{ int n; ArrayList<edge>[] g; int lvl[]; int pare[]; int dist[]; public lca_naive(int t, ArrayList<edge>[] x) { n=t; g=x; lvl = new int[n]; pare = new int[n]; dist = new int[n]; } void pre_process() { dfs(0,-1,g,lvl,pare,dist); } void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[]) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; pare[nxt_edge.t] = cur; dfs(nxt_edge.t,cur,g,lvl,pare,dist); } } } public int work(int p, int q) { int a = p; int b = q; while(lvl[p]<lvl[q]) q = pare[q]; while(lvl[p]>lvl[q]) p = pare[p]; while(p!=q){p = pare[p]; q = pare[q];} int c = p; return dist[a]+dist[b]-dist[c]*2; } } static class lca_binary_lifting{ int n; ArrayList<edge>[] g; int lvl[]; int pare[]; int dist[]; int table[][]; public lca_binary_lifting(int a, ArrayList<edge>[] t) { n = a; g = t; lvl = new int[n]; pare = new int[n]; dist = new int[n]; table = new int[20][n]; } void pre_process() { dfs(0,-1,g,lvl,pare,dist); for(int i=0;i<20;i++) { for(int j=0;j<n;j++) { if(i==0) table[0][j] = pare[j]; else table[i][j] = table[i-1][table[i-1][j]]; } } } void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[]) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; pare[nxt_edge.t] = cur; dfs(nxt_edge.t,cur,g,lvl,pare,dist); } } } public int work(int p, int q) { int a = p; int b = q; if(lvl[p]>lvl[q]) { int tmp = p; p=q; q=tmp; } for(int i=19;i>=0;i--) { if(lvl[table[i][q]]>=lvl[p]) q=table[i][q]; } if(p==q) return p;// return dist[a]+dist[b]-dist[p]*2; for(int i=19;i>=0;i--) { if(table[i][p]!=table[i][q]) { p = table[i][p]; q = table[i][q]; } } return table[0][p]; //return dist[a]+dist[b]-dist[table[0][p]]*2; } } static class lca_sqrt_root{ int n; ArrayList<edge>[] g; int lvl[]; int pare[]; int dist[]; int jump[]; int sz; public lca_sqrt_root(int a, ArrayList<edge>[] b) { n=a; g=b; lvl = new int[n]; pare = new int[n]; dist = new int[n]; jump = new int[n]; sz = (int) Math.sqrt(n); } void pre_process() { dfs(0,-1,g,lvl,pare,dist,jump); } void dfs(int cur, int pre, ArrayList<edge>[] g, int lvl[], int pare[], int dist[], int[] jump) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; pare[nxt_edge.t] = cur; if(lvl[nxt_edge.t]%sz==0) { jump[nxt_edge.t] = cur; }else { jump[nxt_edge.t] = jump[cur]; } dfs(nxt_edge.t,cur,g,lvl,pare,dist,jump); } } } int work(int p, int q) { int a = p; int b = q; if(lvl[p]>lvl[q]) { int tmp = p; p=q; q=tmp; } while(jump[p]!=jump[q]) { if(lvl[p]>lvl[q]) p = jump[p]; else q = jump[q]; } while(p!=q) { if(lvl[p]>lvl[q]) p = pare[p]; else q = pare[q]; } return dist[a]+dist[b]-dist[p]*2; } } // class edge implements Comparable<edge>{ // int f,t,len; // public edge(int a, int b, int c) { // f=a;t=b;len=c; // } // @Override // public int compareTo(edge t) { // return t.len-this.len; // } // } class pair implements Comparable<pair>{ int idx,lvl; public pair(int a, int b) { idx = a; lvl = b; } @Override public int compareTo(pair t) { return t.lvl-this.lvl; } } static class lca_RMQ{ int n; ArrayList<edge>[] g; int lvl[]; int dist[]; int tour[]; int tour_rank[]; int first_occ[]; int c; sgt s; public lca_RMQ(int a, ArrayList<edge>[] b) { n=a; g=b; c=0; lvl = new int[n]; dist = new int[n]; tour = new int[2*n]; tour_rank = new int[2*n]; first_occ = new int[n]; Arrays.fill(first_occ, -1); } void pre_process() { tour[c++] = 0; dfs(0,-1); for(int i=0;i<2*n;i++) { tour_rank[i] = lvl[tour[i]]; if(first_occ[tour[i]]==-1) first_occ[tour[i]] = i; } s = new sgt(0,2*n,tour_rank); } void dfs(int cur, int pre) { for(edge nxt_edge:g[cur]) { if(nxt_edge.t!=pre) { lvl[nxt_edge.t] = lvl[cur]+1; dist[nxt_edge.t] = dist[cur]+nxt_edge.len; tour[c++] = nxt_edge.t; dfs(nxt_edge.t,cur); tour[c++] = cur; } } } int work(int p,int q) { int a = Math.max(first_occ[p], first_occ[q]); int b = Math.min(first_occ[p], first_occ[q]); int idx = s.query_min_idx(b, a+1); //Dumper.print(a+" "+b+" "+idx); int c = tour[idx]; return dist[p]+dist[q]-dist[c]*2; } } static class sgt{ sgt lt; sgt rt; int l,r; int sum, max, min, lazy; int min_idx; public sgt(int L, int R, int arr[]) { l=L;r=R; if(l==r-1) { sum = max = min = arr[l]; lazy = 0; min_idx = l; return; } lt = new sgt(l, l+r>>1, arr); rt = new sgt(l+r>>1, r, arr); pop_up(); } void pop_up() { this.sum = lt.sum + rt.sum; this.max = Math.max(lt.max, rt.max); this.min = Math.min(lt.min, rt.min); if(lt.min<rt.min) this.min_idx = lt.min_idx; else if(lt.min>rt.min) this.min_idx = rt.min_idx; else this.min = Math.min(lt.min_idx, rt.min_idx); } void push_down() { if(this.lazy!=0) { lt.sum+=lazy; rt.sum+=lazy; lt.max+=lazy; lt.min+=lazy; rt.max+=lazy; rt.min+=lazy; lt.lazy+=this.lazy; rt.lazy+=this.lazy; this.lazy = 0; } } void change(int L, int R, int v) { if(R<=l||r<=L) return; if(L<=l&&r<=R) { this.max+=v; this.min+=v; this.sum+=v*(r-l); this.lazy+=v; return; } push_down(); lt.change(L, R, v); rt.change(L, R, v); pop_up(); } int query_max(int L, int R) { if(L<=l&&r<=R) return this.max; if(r<=L||R<=l) return Integer.MIN_VALUE; push_down(); return Math.max(lt.query_max(L, R), rt.query_max(L, R)); } int query_min(int L, int R) { if(L<=l&&r<=R) return this.min; if(r<=L||R<=l) return Integer.MAX_VALUE; push_down(); return Math.min(lt.query_min(L, R), rt.query_min(L, R)); } int query_sum(int L, int R) { if(L<=l&&r<=R) return this.sum; if(r<=L||R<=l) return 0; push_down(); return lt.query_sum(L, R) + rt.query_sum(L, R); } int query_min_idx(int L, int R) { if(L<=l&&r<=R) return this.min_idx; if(r<=L||R<=l) return Integer.MAX_VALUE; int a = lt.query_min_idx(L, R); int b = rt.query_min_idx(L, R); int aa = lt.query_min(L, R); int bb = rt.query_min(L, R); if(aa<bb) return a; else if(aa>bb) return b; return Math.min(a,b); } } List<List<Integer>> convert(int arr[][]){ int n = arr.length; List<List<Integer>> ret = new ArrayList<>(); for(int i=0;i<n;i++) { ArrayList<Integer> tmp = new ArrayList<Integer>(); for(int j=0;j<arr[i].length;j++) tmp.add(arr[i][j]); ret.add(tmp); } return ret; } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public int GCD(int a, int b) { if (b==0) return a; return GCD(b,a%b); } public long GCD(long a, long b) { if (b==0) return a; return GCD(b,a%b); } } static class ArrayUtils { static final long seed = System.nanoTime(); static final Random rand = new Random(seed); public static void sort(int[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(int[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); int t = a[i]; a[i] = a[j]; a[j] = t; } } public static void sort(long[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(long[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); long t = a[i]; a[i] = a[j]; a[j] = t; } } } static class BIT{ int arr[]; int n; public BIT(int a) { n=a; arr = new int[n]; } int sum(int p) { int s=0; while(p>0) { s+=arr[p]; p-=p&(-p); } return s; } void add(int p, int v) { while(p<n) { arr[p]+=v; p+=p&(-p); } } } static class DSU{ int[] arr; int[] sz; public DSU(int n) { arr = new int[n]; sz = new int[n]; for(int i=0;i<n;i++) arr[i] = i; Arrays.fill(sz, 1); } public int find(int a) { if(arr[a]!=a) arr[a] = find(arr[a]); return arr[a]; } public void union(int a, int b) { int x = find(a); int y = find(b); if(x==y) return; arr[y] = x; sz[x] += sz[y]; } public int size(int x) { return sz[find(x)]; } } static class MinHeap<Key> implements Iterable<Key> { private int maxN; private int n; private int[] pq; private int[] qp; private Key[] keys; private Comparator<Key> comparator; public MinHeap(int capacity){ if (capacity < 0) throw new IllegalArgumentException(); this.maxN = capacity; n=0; pq = new int[maxN+1]; qp = new int[maxN+1]; keys = (Key[]) new Object[capacity+1]; Arrays.fill(qp, -1); } public MinHeap(int capacity, Comparator<Key> c){ if (capacity < 0) throw new IllegalArgumentException(); this.maxN = capacity; n=0; pq = new int[maxN+1]; qp = new int[maxN+1]; keys = (Key[]) new Object[capacity+1]; Arrays.fill(qp, -1); comparator = c; } public boolean isEmpty() { return n==0; } public int size() { return n; } public boolean contains(int i) { if (i < 0 || i >= maxN) throw new IllegalArgumentException(); return qp[i] != -1; } public int peekIdx() { if (n == 0) throw new NoSuchElementException("Priority queue underflow"); return pq[1]; } public Key peek(){ if(isEmpty()) throw new NoSuchElementException("Priority queue underflow"); return keys[pq[1]]; } public int poll(){ if(isEmpty()) throw new NoSuchElementException("Priority queue underflow"); int min = pq[1]; exch(1,n--); down(1); assert min==pq[n+1]; qp[min] = -1; keys[min] = null; pq[n+1] = -1; return min; } public void update(int i, Key key) { if (i < 0 || i >= maxN) throw new IllegalArgumentException(); if (!contains(i)) { this.add(i, key); }else { keys[i] = key; up(qp[i]); down(qp[i]); } } private void add(int i, Key x){ if (i < 0 || i >= maxN) throw new IllegalArgumentException(); if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue"); n++; qp[i] = n; pq[n] = i; keys[i] = x; up(n); } private void up(int k){ while(k>1&&less(k,k/2)){ exch(k,k/2); k/=2; } } private void down(int k){ while(2*k<=n){ int j=2*k; if(j<n&&less(j+1,j)) j++; if(less(k,j)) break; exch(k,j); k=j; } } public boolean less(int i, int j){ if (comparator == null) { return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0; } else { return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0; } } public void exch(int i, int j){ int swap = pq[i]; pq[i] = pq[j]; pq[j] = swap; qp[pq[i]] = i; qp[pq[j]] = j; } @Override public Iterator<Key> iterator() { // TODO Auto-generated method stub return null; } } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int zcurChar; private int znumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (znumChars == -1) throw new InputMismatchException(); if (zcurChar >= znumChars) { zcurChar = 0; try { znumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (znumChars <= 0) return -1; } return buf[zcurChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] readIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } static class Dumper { static void print_int_arr(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_char_arr(char[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_double_arr(double[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("---------------------"); } static void print_2d_arr(int[][] arr, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); System.out.println("---------------------"); } static void print_2d_arr(boolean[][] arr, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); System.out.println("---------------------"); } static void print(Object o) { System.out.println(o.toString()); } static void getc() { System.out.println("here"); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
10c221c99b89fd715ce857335603716d
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Solution { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(""); String next() { if (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } public static void main(String[] args) { new Solution().solve(); } long res = Long.MAX_VALUE; List<Integer> l = new ArrayList<>(), r = new ArrayList<>(); long dp[][]; long ok(int i, int j) { if (dp[i][j] != -1) return dp[i][j]; if (i >= l.size()) { return 0; } if (j >= r.size()) return Integer.MAX_VALUE; long op1 = ok(i + 1, j + 1) + Math.abs(l.get(i) - r.get(j)); long op2 = ok(i, j + 1); return dp[i][j] = Math.min(op1, op2); } void solve() { int t = 1; // t = nextInt(); for (int tt = 0; tt < t; tt++) { int n = nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); if (arr[i] == 0) r.add(i + 1); else l.add(i + 1); } dp = new long[n][n]; for (int i = 0; i < n; i++) Arrays.fill(dp[i], -1); out.println(ok(0, 0)); } out.close(); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
094a504e744a2940cc0f68479d524934
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; public class Armchairs { static int n; static int[] arr; static int[] pos; static int[][] dp; public static void main(String[] args) { Scanner scan = new Scanner(System.in); n = scan.nextInt(); arr = new int[n]; pos = new int[n]; Arrays.fill(pos, -1); int curr = 0; for(int i = 0; i < n; i++) { arr[i] = scan.nextInt(); if(arr[i] == 1) pos[curr++] = i; } dp = new int[n][n]; for(int i = 0; i < n; i++) Arrays.fill(dp[i], -1); System.out.println(go(0,0)); // for(int i = 0; i < n; i++) { // System.out.println(Arrays.toString(dp[i])); // } } static int go(int i, int numMatched) { if(i == n && pos[numMatched] == -1) return 0; else if(i == n) return Integer.MAX_VALUE/3; if(dp[i][numMatched] != -1) return dp[i][numMatched]; int res = Integer.MAX_VALUE/3; if(arr[i] == 0) { // match if(pos[numMatched] != -1) { int cost = Math.abs(i-pos[numMatched]); res = min(res, cost+go(i+1, numMatched+1)); } // skip res = min(res, go(i+1, numMatched)); } else { res = go(i+1, numMatched); } return dp[i][numMatched] = res; } static int min(int a, int b) { return a < b ? a : b; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
b436a162238cea484c7dcb72e3635526
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = in.nextInt(); } System.out.println(getMinimumTime(a, n)); } public static int getMinimumTime(int[] a, int n) { int[][] minTime = new int[n][n]; int[] posOfPerson = new int[n]; int totalOccupied = 0; for(int i=0; i<n; i++) { if(a[i] == 1) { posOfPerson[totalOccupied] = i; } totalOccupied += a[i]; } for(int i=0; i<n; i++) { Arrays.fill(minTime[i], 1, n, Integer.MAX_VALUE); } if(a[0] == 0) { minTime[0][1] = Math.abs(0-posOfPerson[0]); } int unoccupiedPlaces = 1-a[0]; for(int i=1; i<n; i++) { if(a[i] == 0) { unoccupiedPlaces++; } for(int j=1; j<=Math.min(totalOccupied, unoccupiedPlaces); j++) { if(a[i] == 1) { minTime[i][j] = minTime[i-1][j]; } else if(j == unoccupiedPlaces) { minTime[i][j] = minTime[i-1][j-1] + Math.abs(i-posOfPerson[j-1]); } else { minTime[i][j] = Math.min(minTime[i-1][j], minTime[i-1][j-1] + Math.abs(i-posOfPerson[j-1])); } } } return minTime[n-1][totalOccupied]; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
406859f989127c46aba4fefa9b81ae0b
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; import java.util.Arrays; public class codeforces { static int[]av; static int[]oc; static int[][]memo; static int n; public static void main(String[] args) throws Exception { // int t=sc.nextInt(); // while(t-->0) { n=sc.nextInt(); int[]a=new int[n]; int avs=0; for (int i = 0; i < a.length; i++) { a[i]=sc.nextInt(); if(a[i]==0)avs++; } av=new int[avs]; oc=new int[n-avs]; for (int i = 0,c=0,j=0; i < a.length; i++) { if(a[i]==1) { oc[c++]=i; }else { av[j++]=i; } } memo=new int[oc.length][av.length]; for(int[]e:memo)Arrays.fill(e, -1); pw.println(dp(0,0)); // } pw.close(); } public static int dp(int i,int j) { if(j==av.length) { return i!=oc.length?(int)1e9:0; } if(i==oc.length) { return 0; } if(memo[i][j]!=-1) { return memo[i][j]; } int take=dp(i+1,j+1)+Math.abs(av[j]-oc[i]); int leave=dp(i,j+1); return memo[i][j]=Math.min(take, leave); } public static boolean isSorted(int[]a) { for (int i = 0; i < a.length-1; i++) { if(a[i]>a[i+1])return false; } return true; } public static boolean isPrime(int n) { // Check if number is less than // equal to 1 if (n <= 1) return false; // Check if number is 2 else if (n == 2) return true; // Check if n is a multiple of 2 else if (n % 2 == 0) return false; // If not, then just check the odds for (int i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } public static long power(long x,long k) { long res=1; long mod=((int)1e9)+7; for (int i = 0; i < k; i++) { res*=x; res=res%mod; } return res; } public static int whichPower(int x) { int res=0; for (int j = 0; j < 31; j++) { if((1<<j&x)!=0) { res=j; break; } } return res; } public static long evaln(String x,int n) { long res=0; for (int i = 0; i < x.length(); i++) { res+=Long.parseLong(x.charAt(x.length()-1-i)+"")*Math.pow(n, i); } return res; } static void merge(int[] arr,int b,int m,int e) { int len1=m-b+1,len2=e-m; int[] l=new int[len1]; int[] r=new int[len2]; for(int i=0;i<len1;i++)l[i]=arr[b+i]; for(int i=0;i<len2;i++)r[i]=arr[m+1+i]; int i=0,j=0,k=b; while(i<len1 && j<len2) { if(l[i]<r[j])arr[k++]=l[i++]; else arr[k++]=r[j++]; } while(i<len1)arr[k++]=l[i++]; while(j<len2)arr[k++]=r[j++]; return; } static void mergesort(int[] arr,int b,int e) { if(b<e) { int m=b+(e-b)/2; mergesort(arr,b,m); mergesort(arr,m+1,e); merge(arr,b,m,e); } return; } static long mergen(int[] arr,int b,int m,int e) { int len1=m-b+1,len2=e-m; int[] l=new int[len1]; int[] r=new int[len2]; for(int i=0;i<len1;i++)l[i]=arr[b+i]; for(int i=0;i<len2;i++)r[i]=arr[m+1+i]; int i=0,j=0,k=b; long c=0; while(i<len1 && j<len2) { if(l[i]<r[j])arr[k++]=l[i++]; else { arr[k++]=r[j++]; c=c+(long)(len1-i); } } while(i<len1)arr[k++]=l[i++]; while(j<len2)arr[k++]=r[j++]; return c; } static long mergesortn(int[] arr,int b,int e) { long c=0; if(b<e) { int m=b+(e-b)/2; c=c+(long)mergesortn(arr,b,m); c=c+(long)mergesortn(arr,m+1,e); c=c+(long)mergen(arr,b,m,e); } return c; } public static long fac(int n) { if(n==0)return 1; return n*fac(n-1); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static long summ(long x) { long sum=0; while(x!=0) { sum+=x%10; x=x/10; } return sum; } public static void sort2darray(Integer[][]a){ Arrays.sort(a,Comparator.<Integer[]>comparingInt(x -> x[0]).thenComparingInt(x -> x[1])); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextArrint(int size) throws IOException { int[] a=new int[size]; for (int i = 0; i < a.length; i++) { a[i]=sc.nextInt(); } return a; } public long[] nextArrlong(int size) throws IOException { long[] a=new long[size]; for (int i = 0; i < a.length; i++) { a[i]=sc.nextLong(); } return a; } public int[][] next2dArrint(int rows,int columns) throws IOException{ int[][]a=new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { a[i][j]=sc.nextInt(); } } return a; } public long[][] next2dArrlong(int rows,int columns) throws IOException{ long[][]a=new long[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { a[i][j]=sc.nextLong(); } } return a; } } static Scanner sc=new Scanner(System.in); static PrintWriter pw=new PrintWriter(System.out); }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
f2657104901500e89b9e1f1c045e51a8
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; import java.lang.Math; public class Main { static PrintWriter pw; static Scanner sc; static StringBuilder ans; static long mod = 1000000000+7; static void pn(final Object arg) { pw.print(arg); pw.flush(); } /*-------------- for input in an value ---------------------*/ static int ni() { return sc.nextInt(); } static long nl() { return sc.nextLong(); } static double nd() { return sc.nextDouble(); } static String ns() { return sc.next(); } static void ap(int arg) { ans.append(arg); } static void ap(long arg) { ans.append(arg); } static void ap(String arg) { ans.append(arg); } static void ap(StringBuilder arg) { ans.append(arg); } /*-------------- for input in an array ---------------------*/ static void inputIntegerArray(int arr[]){ for(int i=0; i<arr.length; i++)arr[i] = ni(); } static void inputLongArray(long arr[]){ for(int i=0; i<arr.length; i++)arr[i] = nl(); } static void inputStringArray(String arr[]){ for(int i=0; i<arr.length; i++)arr[i] = ns(); } static void inputDoubleArray(double arr[]){ for(int i=0; i<arr.length; i++)arr[i] = nd(); } /*-------------- File vs Input ---------------------*/ static void runFile() throws Exception { sc = new Scanner(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); } static void runIo() throws Exception { pw =new PrintWriter(System.out); sc = new Scanner(System.in); } static void swap(int a, int b) { int t = a; a = b; b = t; } static boolean isPowerOfTwo (long x) { return x!=0 && ((x&(x-1)) == 0);} static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static int countDigit(long n){return (int)Math.floor(Math.log10(n) + 1);} static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean sv[] = new boolean[1000002]; static void seive() { //true -> not prime // false->prime sv[0] = sv[1] = true; sv[2] = false; for(int i = 0; i< sv.length; i++) { if( !sv[i] && (long)i*(long)i < sv.length ) { for ( int j = i*i; j<sv.length ; j += i ) { sv[j] = true; } } } } static long binpow( long a, long b) { long res = 1; while (b > 0) { if ( (b & 1) > 0){ res = (res * a)%mod; } a = (a * a)%mod; b >>= 1; } return res; } static long factorial(long n) { long res = 1, i; for (i = 2; i <= n; i++){ res = ((res%mod) * (i%mod))%mod; } return res; } static class Pair { int idx; int v; Pair(int idx, int v){ this.idx = idx; this.v = v; } } public static void main(String[] args) throws Exception { // runFile(); runIo(); int t; t = 1; // t = sc.nextInt(); ans = new StringBuilder(); while( t-- > 0 ) { solve(); } pn(ans+""); } static int N ; static int M ; static ArrayList<Integer> f; static ArrayList<Integer> e; static long dp[][]; static long find(int i, int j ) { if( i == N ) return 0; if( j == M ) return Integer.MAX_VALUE; if (dp[i][j] != -1 ) return dp[i][j]; return dp[i][j] = Math.min( find(i, j+1), Math.abs(f.get(i)-e.get(j)) + find(i+1, j+1) ); } public static void solve() { int n = ni(); f = new ArrayList(); e = new ArrayList(); for(int i = 0; i<n; i++) { int v = ni(); if( v == 0 ) { e.add(i); } else f.add(i); } N = f.size(); M = e.size(); dp = new long[N][M]; for(int i = 0; i<N; i++) Arrays.fill(dp[i], -1); ap(find(0, 0)+"\n"); } } // 0 1 2 3 4 5 6 7 // 1 1 0 0 0 1 0 0 // 1s -> { 0, 1, 5 } // 0s -> { 2, 3, 6, 7 }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
b24fd033f4ae2d2fbf721737bda4213b
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.Scanner; import java.util.ArrayList; public class D_Armchairs{ public static long solve(ArrayList<Integer> zeroes,ArrayList<Integer> ones,int i, int j,long matrix[][],int count){ if(matrix[i][j]!=0){ return matrix[i][j]; } if(count==0){ return 0; } if(i==zeroes.size() || j==ones.size()){ long a= Integer.MAX_VALUE; return a; } long ans1= Math.abs(zeroes.get(i)-ones.get(j))+solve(zeroes,ones,i+1,j+1,matrix,count-1); long ans2= solve(zeroes,ones,i+1,j,matrix,count); long finalans=Math.min(ans1,ans2); matrix[i][j]=finalans; return finalans; } public static void main(String[] args) { Scanner s= new Scanner(System.in); int n=s.nextInt(); ArrayList<Integer> zeroes = new ArrayList<Integer>(); ArrayList<Integer> ones = new ArrayList<Integer>(); int array[]= new int[n]; for(int i=0;i<n;i++){ array[i]=s.nextInt(); if(array[i]==0){ zeroes.add(i); } else{ ones.add(i); } } long matrix[][]= new long[5002][5002]; if(ones.size()==0){ System.out.println(0); return; } int count=ones.size(); long ans= solve(zeroes,ones,0,0,matrix,count); System.out.println(ans); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
2e6d5e0e9ec3bfe6820fbd690a0a839c
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
/* In_The_Name_Of_Allah_The_Merciful */ import java.util.*; import java.io.*; public class Main { PrintWriter out; FastReader sc; long[] m1= {(long)(1e9+7),998244353}; long mod=m1[0]; long maxlong=Long.MAX_VALUE; long minlong=Long.MIN_VALUE; StringBuilder sb; ArrayList<Integer> a,b; long[][] dp; long find(int x,int y) { if(x==a.size())return 0; else if(y==b.size())return Integer.MAX_VALUE; if(dp[x][y]!=-1)return dp[x][y]; return dp[x][y]=min(find(x+1,y+1)+abs(a.get(x)-b.get(y)),find(x,y+1)); } /****************************************************************************************** *****************************************************************************************/ public void sol(){ int n=ni(); a=new ArrayList<>();b=new ArrayList<>(); dp=new long[5001][5001]; int[] ar=new int[n]; for(int i=0;i<n;i++) { ar[i]=ni(); }for(int i=0;i<n;i++) { if(ar[i]==1)a.add(i); else b.add(i); }for(int i=0;i<5001;i++)Arrays.fill(dp[i],-1); pl(find(0,0)); } public static void main(String[] args) { Main g=new Main(); g.out=new PrintWriter(System.out); g.sc=new FastReader(); int t=1; // t=g.ni(); while(t-->0) g.sol(); g.out.flush(); } /**************************************************************************************** *****************************************************************************************/ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public int ni(){ return sc.nextInt(); }public long nl(){ return sc.nextLong(); }public double nd(){ return sc.nextDouble(); }public char[] rl(){ return sc.nextLine().toCharArray(); }public String rl1(){ return sc.nextLine(); } public void pl(Object s){ out.println(s); }public void ex(){ out.println(); } public void pr(Object s){ out.print(s); }public String next(){ return sc.next(); }public long abs(long x){ return Math.abs(x); } public int abs(int x){ return Math.abs(x); } public double abs(double x){ return Math.abs(x); }public long min(long x,long y){ return (long)Math.min(x,y); } public int min(int x,int y){ return (int)Math.min(x,y); } public double min(double x,double y){ return Math.min(x,y); }public long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); }public long lcm(long a, long b) { return (a / gcd(a, b)) * b; } void sort1(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) { l.add(i); } Collections.sort(l,Collections.reverseOrder()); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } } void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) { l.add(i); } Collections.sort(l); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } }void sort(char[] a) { ArrayList<Character> l = new ArrayList<>(); for (char i : a) { l.add(i); } Collections.sort(l); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } }void sort1(char[] a) { ArrayList<Character> l = new ArrayList<>(); for (char i : a) { l.add(i); } Collections.sort(l,Collections.reverseOrder()); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } } void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) { l.add(i); } Collections.sort(l); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } }void sort1(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) { l.add(i); } Collections.sort(l,Collections.reverseOrder()); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } } void sort(double[] a) { ArrayList<Double> l = new ArrayList<>(); for (double i : a) { l.add(i); } Collections.sort(l); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } }long pow(long a,long b){ if(b==0){ return 1; }long p=pow(a,b/2); if(b%2==0) return (p*p)%mod; else return (((p*p)%mod)*a)%mod; } int swap(int a,int b){ return a; }long swap(long a,long b){ return a; }double swap(double a,double b){ return a; } boolean isPowerOfTwo (int x) { return x!=0 && ((x&(x-1)) == 0); }boolean isPowerOfTwo (long x) { return x!=0 && ((x&(x-1)) == 0); }public long max(long x,long y){ return (long)Math.max(x,y); } public int max(int x,int y){ return (int)Math.max(x,y); } public double max(double x,double y){ return Math.max(x,y); }long sqrt(long x){ return (long)Math.sqrt(x); }int sqrt(int x){ return (int)Math.sqrt(x); }void input(int[] ar,int n){ for(int i=0;i<n;i++)ar[i]=ni(); }void input(long[] ar,int n){ for(int i=0;i<n;i++)ar[i]=nl(); }void fill(int[] ar,int k){ Arrays.fill(ar,k); }void yes(){ pl("YES"); }void no(){ pl("NO"); } long c2(long n) { return (n*(n-1))/2; } long[] sieve(int n) { long[] k=new long[n+1]; boolean[] pr=new boolean[n+1]; for(int i=1;i<=n;i++){ k[i]=i; pr[i]=true; }for(int i=2;i<=n;i++){ if(pr[i]){ for(int j=i+i;j<=n;j+=i){ pr[j]=false; if(k[j]==j){ k[j]=i; } } } }return k; } int strSmall(int[] arr, int target) { int start = 0, end = arr.length-1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr[mid] >= target) { end = mid - 1; } else { ans = mid; start = mid + 1; } } return ans; } int strSmall(ArrayList<Integer> arr, int target) { int start = 0, end = arr.size()-1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr.get(mid) > target) { start = mid + 1; ans=start; } else { end = mid - 1; } } return ans; }long mMultiplication(long a,long b) { long res = 0; a %= mod; while (b > 0) { if ((b & 1) > 0) { res = (res + a) % mod; } a = (2 * a) % mod; b >>= 1; } return res; }long nCr(int n, int r ,int p) { if (n<r) return 0; if (r == 0) return 1; long[] fac = new long[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i %p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; }long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; }long modInverse(long n, long p) { return power(n, p - 2, p); } int[][] floydWarshall(int graph[][],int INF,int V) { int dist[][] = new int[V][V]; int i, j, k; for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; for (k = 0; k < V; k++) { for (i = 0; i < V; i++) { for (j = 0; j < V; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } }return dist; } class Pair<U, V> { public final U first; // the first field of a pair public final V second; // the second field of a pair // Constructs a new pair with specified values private Pair(U first, V second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pair<?, ?> pair = (Pair<?, ?>) o; if (!first.equals(pair.first)) { return false; } return second.equals(pair.second); } @Override public int hashCode() { return 31 * first.hashCode() + second.hashCode(); } @Override public String toString() { return "(" + first + ", " + second + ")"; } public <U, V> Pair <U, V> of(U a, V b) { return new Pair<>(a, b); } } class minque { Deque<Long> q; minque(){ q=new ArrayDeque<Long>(); }public void add(long p){ while(!q.isEmpty()&&q.peekLast()>p)q.pollLast(); q.addLast(p); }public void remove(long p) { if(!q.isEmpty()&&q.getFirst()==p)q.removeFirst(); }public long min() { return q.getFirst(); } } int find(subset[] subsets, int i) { if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent); return subsets[i].parent; }void Union(subset[] subsets, int x, int y) { int xroot = find(subsets, x); int yroot = find(subsets, y); if (subsets[xroot].rank < subsets[yroot].rank) { subsets[xroot].parent = yroot; } else if (subsets[yroot].rank < subsets[xroot].rank) { subsets[yroot].parent = xroot; } else { subsets[xroot].parent = yroot; subsets[yroot].rank++; } }class subset { int parent; int rank; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
b2a2812b41cd343c284f36d9de836c92
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.lang.*; import java.util.*; import java.io.*; public class Main { static void deal(int[] arr,int n) { int m1 = 0; int m2 = 0; for(int i=0;i<n;i++) { if(arr[i]==1) { m1 ++; } else { m2 ++; } } if(m1 ==0) { System.out.println(0); return; } int[] arr1 = new int[m1]; int[] arr2 = new int[m2]; int index1 = 0; int index2 = 0; for(int i=0;i<n;i++) { if(arr[i] == 1) { arr1[index1] = i; index1++; } else { arr2[index2] = i; index2++; } } int[][] dp = new int[m2][m1]; dp[0][0] = Math.abs(arr1[0]-arr2[0]); for(int i=0;i<m1;i++) { if(i>0) dp[i][i] = dp[i-1][i-1] + Math.abs(arr1[i]-arr2[i]); for(int j=i+1;j<m2;j++) { if(i>0) { dp[j][i] = Math.min(dp[j-1][i],dp[j-1][i-1]+Math.abs(arr2[j]-arr1[i])); } else { dp[j][i] = Math.min(dp[j-1][i],Math.abs(arr2[j]-arr1[i])); } } } System.out.println(dp[m2-1][m1-1]); } public static void main(String[] args) { MyScanner scanner = new MyScanner(); int n = scanner.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) { arr[i] = scanner.nextInt(); } deal(arr,n); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
60d236de97cb1f3d0b0b49064eaebc54
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); StringBuffer out=new StringBuffer(); int t=1; while(t--!=0) { int n=in.nextInt(); ArrayList<Integer> list[]=new ArrayList[2]; for(int i=0; i<2; i++) list[i]=new ArrayList<>(); for (int i=0; i<n; i++) { list[in.nextInt()].add(i); } int x=list[0].size(), y=list[1].size(); out.append(solve(x-1, y-1, list, new Integer[x][y])); } System.out.println(out); } private static int solve(int i, int j, ArrayList<Integer> list[], Integer dp[][]) { if(i<j) return Integer.MAX_VALUE; if(j<0) return 0; if(dp[i][j]!=null) return dp[i][j]; return dp[i][j]=Math.min(Math.abs(list[0].get(i)-list[1].get(j))+solve(i-1, j-1, list, dp), solve(i-1, j, list, dp)); } private static int GCD(int a, int b) { if(a==0) return b; return GCD(b%a, a); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
dfcfc664d181c27a9b7effef8d112cd1
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
// package testing; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class A { static public class Pair{ int a,b; public Pair(int a,int b) { this.a = a; this.b = b; } } static class cmp implements Comparator<Pair>{ public int compare(Pair p,Pair q) { if(p.a<q.a) { return -1; } return 1; } } static int n; static int dp[][] = new int[5005][5005]; static int arr[] = new int[5005]; static int solve(int i,int j) { if(i>=n) { return 0; } if(dp[i][j]!=-1) { return dp[i][j]; } int ans = Integer.MAX_VALUE-1000000; if(arr[i]==0) { ans = Math.min(ans,solve(i+1,j)); } else { if(j<n&&arr[j]==0) { ans = Math.min(ans,Math.abs(i-j)+solve(i+1,j+1)); } if(j<n) { ans = Math.min(ans, solve(i,j+1)); } } return dp[i][j] = ans; } public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int test = 1; outer: for(int tt=1;tt<=test;tt++) { n=fs.nextInt(); for(int i=0;i<=5000;i++) { for(int j=0;j<=5000;j++) { dp[i][j] = -1; } } for(int i=0;i<n;i++) { arr[i]=fs.nextInt(); } out.println(solve(0,0)); } out.close(); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
5abb97eed2245f12e90dcf29160319ef
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.lang.*; public class Practice { public static long mod = (long) Math.pow(10, 9) + 7; public static long tt = 0; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int c = 1; // int t = Integer.parseInt(br.readLine()); // while (t-- > 0) { int n = Integer.parseInt(br.readLine()); int[] arr = new int[n]; String str = (br.readLine()); String[] s1 = str.split(" "); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(s1[i]); } ArrayList<Integer> a = new ArrayList<>(); ArrayList<Integer> b = new ArrayList<>(); for (int i = 0; i < n; i++) { if (arr[i] == 1) { b.add(i); } else { a.add(i); } }//System.out.println(a+" "+b); int[][] dp = new int[n + 1][n + 1]; for (int i = 0; i <= n; i++) { Arrays.fill(dp[i], -2); } int aa = getAns(dp, a, b, 0, 0); // for(int i=0;i<n;i++) { // for(int j=0;j<n;j++) { // System.out.print(dp[i][j]+" "); // }System.out.println(); // } pw.println(aa); // } pw.close(); } private static int getAns(int[][] dp, ArrayList<Integer> a, ArrayList<Integer> b, int i, int j) { // TODO Auto-generated method stub if(i==a.size()&&j==b.size()) { //System.out.println("*****"); return 0; }if(j==b.size()) { return 0; }if(i==a.size()) { return -1; } if(dp[i][j]!=-2) { return dp[i][j]; } int ans=Math.abs(b.get(j)-a.get(i)); int aa=getAns(dp,a,b,i+1,j+1); if(aa<0) { ans=-1; }else { ans+=aa; } //System.out.println(ans); int ans2=getAns(dp,a,b,i+1,j); //System.out.println(ans2+"lll"); if(ans==-1) { dp[i][j]=ans2; return ans2; }if(ans2==-1) { dp[i][j]=ans; return ans; } dp[i][j]=Math.min(ans2, ans); return Math.min(ans2, ans); } } //private static long getGCD(long l, long m) { // // TODO Auto-generated method stub // // long t1 = Math.min(l, m); // long t2 = Math.max(l, m); // while (true) { // long temp = t2 % t1; // if (temp == 0) { // return t1; // } // t2 = t1; // t1 = temp; // } //}
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
e7ed7e50892bffc3bb8fdc73de3f148d
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; public class D { public static void main(String[] args) { Scanner sc=new Scanner(System.in); ArrayList<Integer> o=new ArrayList<Integer>(), e=new ArrayList<Integer>(); int n = sc.nextInt(),dp[][]=new int[n+1][n+1]; for(int i=1;i<=n;i++){ int x=sc.nextInt(); if(x==1)o.add(i); else e.add(i); } for(int i=1;i<=o.size();i++){ dp[i][i]=dp[i-1][i-1]+Math.abs(o.get(i-1)-e.get(i-1)); for(int j=i+1;j<=e.size();j++) dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(o.get(i-1)-e.get(j-1))); } System.out.println(dp[o.size()][e.size()]); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
604a51b8acf6c6bec39b600300be3166
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
/* bts songs to dance to: I need U Run ON Filter I'm fine */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class x1525D { static long INF = Long.MAX_VALUE/2; public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int[] arr = readArr(N, infile, st); ArrayList<Integer> zeros = new ArrayList<Integer>(); ArrayList<Integer> ones = new ArrayList<Integer>(); for(int i=0; i < N; i++) { if(arr[i] == 0) zeros.add(i); else ones.add(i); } if(ones.size() == 0) { System.out.println(0); return; } N = ones.size(); int M = zeros.size(); long[][] dp = new long[N][M]; for(int i=0; i < N; i++) Arrays.fill(dp[i], INF); //last move for(int b=0; b < M; b++) { dp[N-1][b] = abs(ones.get(N-1)-zeros.get(b)); } for(int a=N-2; a >= 0; a--) { for(int b=M-2; b >= 0; b--) dp[a+1][b] = min(dp[a+1][b], dp[a+1][b+1]); for(int b=0; b < M; b++) { //if(b > 0) // dp[a][b] = min(dp[a][b], dp[a][b-1]); //take this element if(b+1 < M) dp[a][b] = min(dp[a][b], dp[a+1][b+1]+abs(ones.get(a)-zeros.get(b))); } } long res = dp[0][0]; for(int b=1; b < M; b++) res = min(res, dp[0][b]); System.out.println(res); } public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception { int[] arr = new int[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); return arr; } public static void print(ArrayList<Integer> arr) { //for debugging only for(int x: arr) out.print(x+" "); out.println(); } } /* dp is likely overlapping ranges, are they ever optimal? draw directed graph (two layers) */
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
da8d18b06ccbbf988e20b38f84ee3962
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
/* bts songs to dance to: I need U Run ON Filter I'm fine */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class x1525D { static int INF = Integer.MAX_VALUE/2; public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int[] arr = readArr(N, infile, st); ArrayList<Integer> zeros = new ArrayList<Integer>(); ArrayList<Integer> ones = new ArrayList<Integer>(); for(int i=0; i < N; i++) { if(arr[i] == 0) zeros.add(i); else ones.add(i); } if(ones.size() == 0) { System.out.println(0); return; } N = ones.size(); int M = zeros.size(); int[][] dp = new int[N][M]; for(int i=0; i < N; i++) Arrays.fill(dp[i], INF); //last move for(int b=0; b < M; b++) { dp[N-1][b] = abs(ones.get(N-1)-zeros.get(b)); if(debug) System.out.println((N-1)+" "+b+": "+dp[N-1][b]); } for(int a=N-2; a >= 0; a--) { for(int b=M-2; b >= 0; b--) dp[a+1][b] = min(dp[a+1][b], dp[a+1][b+1]); for(int b=0; b < M; b++) { //if(b > 0) // dp[a][b] = min(dp[a][b], dp[a][b-1]); //take this element if(b+1 < M) dp[a][b] = min(dp[a][b], dp[a+1][b+1]+abs(ones.get(a)-zeros.get(b))); } } int res = dp[0][0]; for(int b=1; b < M; b++) res = min(res, dp[0][b]); System.out.println(res); if(debug){ print(zeros); print(ones); } } static boolean debug = false; public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception { int[] arr = new int[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); return arr; } public static void print(ArrayList<Integer> arr) { //for debugging only for(int x: arr) out.print(x+" "); out.println(); } } /* dp is likely overlapping ranges, are they ever optimal? draw directed graph (two layers) */
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
e29292e7a0b23a5114b4c37640d3498c
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class tr1 { static PrintWriter out; static StringBuilder sb; static long mod = (long) 998244353; static int[][] memo, mat; static int n, m; static ArrayList<Integer>[] ad; static HashMap<Integer, Integer>[] going; static long inf = Long.MAX_VALUE; static char[][] g; static boolean[] vis; static int[] a; static int ans; static long[][] st; static HashMap<Integer, Integer> hmC, hmG; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); n = sc.nextInt(); int[] a = sc.nextArrInt(n); int z = 0; for (int i = 0; i < n; i++) if (a[i] == 0) z++; // System.out.println(Arrays.toString(a)+" "+z); if (z == n) { System.out.println(0); return; } mat = new int[n - z][z]; memo = new int[n - z][z]; for (int[] L : memo) Arrays.fill(L, -1); int idx = 0; int idxz = 0; for (int i = 0; i < n; i++) { if (a[i] == 1) { idxz = 0; for (int j = 0; j < n; j++) { if (a[j] == 0) { mat[idx][idxz++] = Math.abs(i - j); // System.out.println(Math.abs(i-j)); } } idx++; } } // System.out.println(Arrays.deepToString(mat)); System.out.println(dp(0, 0)); out.flush(); } static int dp(int i, int j) { if (i == memo.length) return 0; if(j==memo[i].length) return (int)1e8; if (memo[i][j] != -1) return memo[i][j]; int ans = mat[i][j] + dp(i + 1, j+1); if (j != memo[i].length - 1) ans = Math.min(ans, dp(i, j + 1)); return memo[i][j] = ans; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextArrIntSorted(int n) throws IOException { int[] a = new int[n]; Integer[] a1 = new Integer[n]; for (int i = 0; i < n; i++) a1[i] = nextInt(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].intValue(); return a; } public long[] nextArrLongSorted(int n) throws IOException { long[] a = new long[n]; Long[] a1 = new Long[n]; for (int i = 0; i < n; i++) a1[i] = nextLong(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].longValue(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
cf1c8f900820412b82ad060d373e0d84
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.math.BigInteger; //import javafx.util.*; public final class B { static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); static ArrayList<ArrayList<Integer>> g; static long mod=(long)(1e9+7); static int D1[],D2[],par[]; static boolean set[]; static int value[]; static long INF=Long.MAX_VALUE; static int dp[][]; static int N,M; static int A[][],B[][]; static int s=1; public static void main(String args[])throws IOException { int N=i(); int A[]=input(N); ArrayList<Integer> one=new ArrayList<Integer>(); ArrayList<Integer> zero=new ArrayList<Integer>(); for(int i=1; i<=N; i++) { if(A[i-1]==1)one.add(i); else zero.add(i); } int sum[][]=new int[N+5][N+5]; for(int i=1; i<=one.size(); i++) { for(int j=1; j<=zero.size(); j++) { sum[i][j]=Math.abs(one.get(i-1)-zero.get(j-1)); } //print(sum[i]); } dp=new int[N+5][N+5]; //for(int d[]:dp)Arrays.fill(d, Integer.MAX_VALUE); Arrays.fill(dp[0], 0); for(int i=1; i<=one.size(); i++) { for(int j=i; j<=zero.size(); j++) { if(i==j) { dp[i][j]=dp[i-1][j-1]+sum[i][j]; } else { dp[i][j]=Math.min(dp[i][j-1], dp[i-1][j-1]+sum[i][j]); } } } System.out.println(dp[one.size()][zero.size()]); // f(0,0,one,zero,0); //for(int d[]:dp)print(d); } static int f(int i,int j,ArrayList<Integer> one,ArrayList<Integer> zero, int s) { if(i==one.size())return s; if(j==zero.size())return Integer.MAX_VALUE; int a=one.get(i),b=zero.get(j); if(dp[a][b]==-1) { int min=Integer.MAX_VALUE; for(int t=j; t<zero.size(); t++) { min=Math.min(min, f(i+1,t+1,one,zero,s+Math.abs(b-a))); } dp[a][b]=min; } a=one.get(i);b=zero.get(j); return dp[a][b]; } static boolean isSorted(int A[]) { int N=A.length; for(int i=0; i<N-1; i++) { if(A[i]>A[i+1])return false; } return true; } static int f1(int x,ArrayList<Integer> A) { int l=-1,r=A.size(); while(r-l>1) { int m=(l+r)/2; int a=A.get(m); if(a<x)l=m; else r=m; } return l; } static int ask(int t,int i,int j,int x) { System.out.println("? "+t+" "+i+" "+j+" "+x); return i(); } static int ask(int a) { System.out.println("? 1 "+a); return i(); } static int f(int st,int end,int d) { if(st>end)return 0; int a=0,b=0,c=0; if(d>1)a=f(st+d-1,end,d-1); b=f(st+d,end,d); c=f(st+d+1,end,d+1); return value[st]+max(a,b,c); } static int max(int a,int b,int c) { return Math.max(a, Math.max(c, b)); } static int value(char X[],char Y[]) { int c=0; for(int i=0; i<7; i++) { if(Y[i]=='1' && X[i]=='0')return -1; if(X[i]=='1' && Y[i]=='0')c++; } return c; } static boolean isValid(int i,int j) { if(i<0 || i>=N)return false; if(j<0 || j>=M)return false; return true; } static long fact(long N) { long num=1L; while(N>=1) { num=((num%mod)*(N%mod))%mod; N--; } return num; } static boolean reverse(long A[],int l,int r) { while(l<r) { long t=A[l]; A[l]=A[r]; A[r]=t; l++; r--; } if(isSorted(A))return true; else return false; } static boolean isSorted(long A[]) { for(int i=1; i<A.length; i++)if(A[i]<A[i-1])return false; return true; } static boolean isPalindrome(char X[],int l,int r) { while(l<r) { if(X[l]!=X[r])return false; l++; r--; } return true; } static long min(long a,long b,long c) { return Math.min(a, Math.min(c, b)); } static void print(int a) { System.out.println("! "+a); } static int ask(int a,int b) { System.out.println("? "+a+" "+b); return i(); } static int find(int a) { if(par[a]<0)return a; return par[a]=find(par[a]); } static void union(int a,int b) { a=find(a); b=find(b); if(a!=b) { par[a]+=par[b]; //transfers the size par[b]=a; //changes the parent } } static void swap(char A[],int a,int b) { char ch=A[a]; A[a]=A[b]; A[b]=ch; } static void sort(long[] a) //check for long { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void setGraph(int N) { g=new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=N; i++) { g.add(new ArrayList<Integer>()); } } static long pow(long a,long b) { long mod=1000000007; long pow=1; long x=a; while(b!=0) { if((b&1)!=0)pow=(pow*x)%mod; x=(x*x)%mod; b/=2; } return pow; } static long toggleBits(long x)//one's complement || Toggle bits { int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1; return ((1<<n)-1)^x; } static int countBits(long a) { return (int)(Math.log(a)/Math.log(2)+1); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static boolean isPrime(long N) { if (N<=1) return false; if (N<=3) return true; if (N%2 == 0 || N%3 == 0) return false; for (int i=5; i*i<=N; i=i+6) if (N%i == 0 || N%(i+2) == 0) return false; return true; } static long GCD(long a,long b) { if(b==0) { return a; } else return GCD(b,a%b ); } //Debugging Functions Starts static void print(char A[]) { for(char c:A)System.out.print(c+" "); System.out.println(); } static void print(boolean A[]) { for(boolean c:A)System.out.print(c+" "); System.out.println(); } static void print(int A[]) { for(int a:A)System.out.print(a+" "); System.out.println(); } static void print(long A[]) { for(long i:A)System.out.print(i+ " "); System.out.println(); } static void print(ArrayList<Integer> A) { for(int a:A)System.out.print(a+" "); System.out.println(); } //Debugging Functions END //---------------------- //IO FUNCTIONS STARTS static HashMap<Integer,Integer> Hash(int A[]) { HashMap<Integer,Integer> mp=new HashMap<>(); for(int a:A) { int f=mp.getOrDefault(a,0)+1; mp.put(a, f); } return mp; } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static int[] input(int N){ int A[]=new int[N]; for(int i=0; i<N; i++) { A[i]=in.nextInt(); } return A; } static long[] inputLong(int N) { long A[]=new long[N]; for(int i=0; i<A.length; i++)A[i]=in.nextLong(); return A; } //IO FUNCTIONS END } class node implements Comparable<node> { int l,r,index; node(int l,int r,int index) { this.l=l; this.r=r; this.index=index; } public int compareTo(node X) { return X.r-this.r; } } class node1 implements Comparable<node1> { int l,r,index; node1(int l,int r,int index) { this.l=l; this.r=r; this.index=index; } public int compareTo(node1 X) { if(this.l==X.l) return X.r-this.r; return this.l-X.l; } } //Code For FastReader //Code For FastReader //Code For FastReader //Code For FastReader 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()); } //gey double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
709c75fa4607df0824e6fa713029d9f6
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "khokharnikunj8", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); DArmchairs solver = new DArmchairs(); solver.solve(1, in, out); out.close(); } } static class DArmchairs { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int[] ar = new int[n]; for (int i = 0; i < n; i++) ar[i] = in.readInt(); List<Integer> ls1 = new ArrayList<>(); List<Integer> ls0 = new ArrayList<>(); for (int i = 0; i < n; i++) if (ar[i] == 1) { ls1.add(i); } else { ls0.add(i); } int one = ls1.size(); int zero = ls0.size(); if (one == 0) { out.println(0); return; } int[][] dp = new int[one + 1][zero + 1]; for (int i = 0; i <= one; i++) Arrays.fill(dp[i], Integer.MAX_VALUE / 2); Arrays.fill(dp[0], 0); for (int i = 1; i <= one; i++) { for (int j = 1; j <= zero; j++) { dp[i][j] = Math.min(dp[i][j], dp[i][j - 1]); dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + Math.abs(ls1.get(i - 1) - ls0.get(j - 1))); } } out.println(dp[one][zero]); } } static class FastInput { private final InputStream is; private final byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private final Writer os; private final StringBuilder cache = new StringBuilder(5 << 20); public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(int c) { cache.append(c); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
63751ce2d1ea67aa45f4ef938faa4c79
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
/* || श्री राम समर्थ || || जय जय रघुवीर समर्थ || */ import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.util.*; import static java.util.Arrays.sort; public class CodeforcesTemp { static Reader scan = new Reader(); static FastPrinter out = new FastPrinter(); public static void main(String[] args) throws IOException { // int tt = scan.nextInt(); int tt = 1; for (int tc = 1; tc <= tt; tc++) { int n = scan.nextInt(); List<Integer> one=new ArrayList<>(); List<Integer> zero=new ArrayList<>(); for (int i = 0; i < n; i++) { int v= scan.nextInt(); if(v==1)one.add(i); else zero.add(i); } int[][] dp=new int[one.size()+1][zero.size()+1]; for (int i = 0; i <=one.size(); i++) { if(i==0){ Arrays.fill(dp[i],0); }else Arrays.fill(dp[i],Integer.MAX_VALUE); } for (int i = 1; i <= one.size(); i++) { for (int j = 1; j<= zero.size(); j++) { if(i>j){ continue; } int op=one.get(i-1); int zp=zero.get(j-1); dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(zp-op)); } } out.println(dp[one.size()][zero.size()]); out.flush(); } out.close(); } static class Reader { private final InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public Reader(InputStream in) { this.in = in; } public Reader() { this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("not number")); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("not number")); } } } } throw new ArithmeticException( String.format(" overflows long.")); } n = n * 10 + digit; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(long length) { long[] array = new long[(int) length]; for (int i = 0; i < length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = this.nextInt(); return array; } public int[][] nextIntArrayMulti(int length, int width) { int[][] arrays = new int[width][length]; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) arrays[j][i] = this.nextInt(); } return arrays; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width) { long[][] mat = new long[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width) { int[][] mat = new int[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width) { double[][] mat = new double[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width) { char[][] mat = new char[height][width]; for (int h = 0; h < height; h++) { String s = this.next(); for (int w = 0; w < width; w++) { mat[h][w] = s.charAt(w); } } return mat; } } static class FastPrinter extends PrintWriter { public FastPrinter(PrintStream stream) { super(stream); } public FastPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n - 1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length; for (int i = 0; i < n - 1; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n - 1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } public void printMatrix(int[][] arr) { for (int i = 0; i < arr.length; i++) { this.printArray(arr[i]); } } public void printCharMatrix(char[][] arr, int n, int m) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { this.print(arr[i][j] + " "); } this.println(); } } } static Random __r = new Random(); static int randInt(int min, int max) { return __r.nextInt(max - min + 1) + min; } static void reverse(int[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(long[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(double[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(char[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(char[] arr, int i, int j) { while (i < j) { char temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; i++; j--; } } static void reverse(int[] arr, int i, int j) { while (i < j) { int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; i++; j--; } } static void reverse(long[] arr, int i, int j) { while (i < j) { long temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; i++; j--; } } static void shuffle(int[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(long[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } private static int getlowest(int l) { if (l >= 1000000000) return 1000000000; if (l >= 100000000) return 100000000; if (l >= 10000000) return 10000000; if (l >= 1000000) return 1000000; if (l >= 100000) return 100000; if (l >= 10000) return 10000; if (l >= 1000) return 1000; if (l >= 100) return 100; if (l >= 10) return 10; return 1; } static void shuffle(double[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void rsort(int[] a) { shuffle(a); sort(a); } static void rsort(long[] a) { shuffle(a); sort(a); } static void rsort(double[] a) { shuffle(a); sort(a); } static int[] copy(int[] a) { int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static long[] copy(long[] a) { long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static double[] copy(double[] a) { double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static char[] copy(char[] a) { char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
2c96449106a2938bf9bc925cdad685e2
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public class Solution { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static int sum(int idx , int bit[]) { int sum = 0; while(idx > 0) { sum += bit[idx]; idx -= idx&(-idx); } return sum; } static void update(int n , int idx , int val , int bit[]) { while(idx <= n) { bit[idx] += val; idx += idx&(-idx); } } static long mod = 1000000007; static long pow(long a , long b) { if(b == 0) return 1; long ans = pow(a,b/2); if(b%2 == 0) return ans*ans%mod; return ans*ans%mod*a%mod; } static long f(long v) { if(v <= 0) return 0; return (v*(v+1)/2); } public static void main(String []args) throws IOException { Reader sc = new Reader(); int n = sc.nextInt(); int arr[] = new int[n+1]; int cnt = 0; for(int i = 1 ; i <= n ; i++) { arr[i] = sc.nextInt(); if(arr[i] == 1) cnt++; } long dp[][] = new long[cnt+1][n+1]; for(int i = 1 ; i <= cnt ; i++) { for(int j = 0 ; j <= n ; j++) { dp[i][j] = Integer.MAX_VALUE; } } int pos[] = new int[cnt+1]; cnt = 0; for(int i = 1 ; i <= n ; i++) { if(arr[i] == 1) { cnt++; pos[cnt] = i; } } for(int i = 1 ; i <= cnt ; i++) { for(int j = 1 ; j <= n ; j++) { if(arr[j] == 0) dp[i][j] = Math.min(dp[i][j],Math.abs(pos[i]-j)+dp[i-1][j-1]); dp[i][j] = Math.min(dp[i][j],dp[i][j-1]); } } long ans = Integer.MAX_VALUE; for(int i = 1 ; i <= n ; i++) { ans = Math.min(ans,dp[cnt][i]); } System.out.println(ans); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
6623b8fb573df19789d48579c02e637e
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.util.concurrent.TimeUnit; import java.io.*; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; public class D_Armchairs{ public static void solve(){ } static Printer p=new Printer(); public static void main(String args[])throws IOException, ParseException{ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++){ a[i]=sc.nextInt(); } ArrayList<Integer> ones=new ArrayList<>(); for(int i=0;i<n;i++){ if(a[i]==1) ones.add(i); } int no1=ones.size(); int dp[][]=new int[n+1][no1+1]; for(int i=0;i<=n;i++) { for(int j=0;j<=no1;j++)dp[i][j]=(int)1e9;} dp[0][0]=0; for(int i=0;i<n;i++){ for(int j=0;j<=no1;j++){ if(dp[i][j]==(int)1e9)continue; dp[i+1][j]=Math.min(dp[i][j],dp[i+1][j]); if(j<no1&& a[i]==0){ dp[i+1][j+1]=Math.min(dp[i+1][j+1],dp[i][j]+Math.max(i-ones.get(j),ones.get(j)-i)); } } } // for(int i=0;i<=n;i++){ // for(int j=0;j<=no1;j++){ // System.out.print(dp[i][j]+" "); // } // System.out.println(); // } System.out.println(dp[n][no1]); } public static <K,V> Map<K,V> getLimitedSizedCache(int size){ /*Returns an unlimited sized map*/ if(size==0){ return (LinkedHashMap<K, V>) Collections.synchronizedMap(new LinkedHashMap<K, V>()); } /*Returns the map with the limited size*/ Map<K, V> linkedHashMap = Collections.synchronizedMap(new LinkedHashMap<K, V>() { protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > size; } }); return linkedHashMap; } } class BinarySearch<T extends Comparable<T>> { T ele[]; int n; public BinarySearch(T ele[],int n){ this.ele=(T[]) ele; Arrays.sort(this.ele); this.n=n; } public int lower_bound(T x){ //Return next smallest element greater than ewqual to the current element int left=0; int right=n-1; while(left<=right){ int mid=left+(right-left)/2; if(x.compareTo(ele[mid])==0)return mid; if(x.compareTo(ele[mid])>0)left=mid+1; else right=mid-1; } if(left ==n)return -1; return left; } public int upper_bound(T x){ //Returns the highest element lss than equal to the current element int left=0; int right=n-1; while(left<=right){ int mid=left+(right-left)/2; if(x.compareTo(ele[mid])==0)return mid; if(x.compareTo(ele[mid])>0)left=mid+1; else right=mid-1; } return right; } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } class Data implements Comparable<Data>{ int num; public Data(int num){ this.num=num; } public int compareTo(Data o){ return -o.num+num; } public String toString(){ return num+" "; } } class Binary{ public String convertToBinaryString(long ele){ StringBuffer res=new StringBuffer(); while(ele>0){ if(ele%2==0)res.append(0+""); else res.append(1+""); ele=ele/2; } return res.reverse().toString(); } } class FenwickTree{ int bit[]; int size; FenwickTree(int n){ this.size=n; bit=new int[size]; } public void modify(int index,int value){ while(index<size){ bit[index]+=value; index=(index|(index+1)); } } public int get(int index){ int ans=0; while(index>=0){ ans+=bit[index]; index=(index&(index+1))-1; } return ans; } } class PAndC{ long c[][]; long mod; public PAndC(int n,long mod){ c=new long[n+1][n+1]; this.mod=mod; build(n); } public void build(int n){ for(int i=0;i<=n;i++){ c[i][0]=1; c[i][i]=1; for(int j=1;j<i;j++){ c[i][j]=(c[i-1][j]+c[i-1][j-1])%mod; } } } } class Trie{ int trie[][]; int revind[]; int root[]; int tind,n; int sz[]; int drev[]; public Trie(){ trie=new int[1000000][2]; root=new int[600000]; sz=new int[1000000]; tind=0; n=0; revind=new int[1000000]; drev=new int[20]; } public void add(int ele){ // System.out.println(root[n]+" "); n++; tind++; revind[tind]=n; root[n]=tind; addimpl(root[n-1],root[n],ele); } public void addimpl(int prev_root,int cur_root,int ele){ for(int i=18;i>=0;i--){ int edge=(ele&(1<<i))>0?1:0; trie[cur_root][1-edge]=trie[prev_root][1-edge]; sz[cur_root]=sz[trie[cur_root][1-edge]]; tind++; drev[i]=cur_root; revind[tind]=n; trie[cur_root][edge]=tind; cur_root=tind; prev_root=trie[prev_root][edge]; } sz[cur_root]+=sz[prev_root]+1; for(int i=0;i<=18;i++){ sz[drev[i]]=sz[trie[drev[i]][0]]+sz[trie[drev[i]][1]]; } } public void findmaxxor(int l,int r,int x){ int ans=0; int cur_root=root[r]; for(int i=18;i>=0;i--){ int edge=(x&(1<<i))>0?1:0; if(revind[trie[cur_root][1-edge]]>=l){ cur_root=trie[cur_root][1-edge]; ans+=(1-edge)*(1<<i); }else{ cur_root=trie[cur_root][edge]; ans+=(edge)*(1<<i); } } System.out.println(ans); } public void findKthStatistic(int l,int r,int k){ //System.out.println("In 3"); int curr=root[r]; int curl=root[l-1]; int ans=0; for(int i=18;i>=0;i--){ for(int j=0;j<2;j++){ if(sz[trie[curr][j]]-sz[trie[curl][j]]<k) k-=sz[trie[curr][j]]-sz[trie[curl][j]]; else{ curr=trie[curr][j]; curl=trie[curl][j]; ans+=(j)*(1<<i); break; } } } System.out.println(ans); } public void findSmallest(int l,int r,int x){ //System.out.println("In 4"); int curr=root[r]; int curl=root[l-1]; int countl=0,countr=0; // System.out.println(curl+" "+curr); for(int i=18;i>=0;i--){ int edge=(x&(1<<i))>0?1:0; // System.out.println(trie[curl][edge]+" "+trie[curr][edge]+" "+sz[curl]+" "+sz[curr]); if(edge==1){ countr+=sz[trie[curr][0]]; countl+=sz[trie[curl][0]]; } curr=trie[curr][edge]; curl=trie[curl][edge]; } countl+=sz[curl]; countr+=sz[curr]; System.out.println(countr-countl); } } class Printer{ public <T> T printArray(T obj[] ,String details){ System.out.println(details); for(int i=0;i<obj.length;i++) System.out.print(obj[i]+" "); System.out.println(); return obj[0]; } public <T> void print(T obj,String details){ System.out.println(details+" "+obj); } } class Node{ long weight; int vertex; public Node(int vertex,long weight){ this.vertex=vertex; this.weight=weight; } public String toString(){ return vertex+" "+weight; } } class Graph{ int nv; //0 indexing i.e vertices starts from 0 input as 1 indexed for add Edge List<List<Node>> adj; boolean visited[]; public Graph(int n){ adj=new ArrayList<>(); this.nv=n; // visited=new boolean[nv]; for(int i=0;i<n;i++) adj.add(new ArrayList<Node>()); } public void addEdge(int u,int v,long weight){ u--;v--; Node first=new Node(v,weight); Node second=new Node(u,weight); adj.get(v).add(second); adj.get(u).add(first); } public void dfscheck(int u,long curweight){ visited[u]=true; for(Node i:adj.get(u)){ if(visited[i.vertex]==false&&(i.weight|curweight)==curweight) dfscheck(i.vertex,curweight); } } long maxweight; public void clear(){ this.adj=null; this.nv=0; } public void solve() { maxweight=(1l<<32)-1; dfsutil(31); System.out.println(maxweight); } public void dfsutil(int msb){ if(msb<0)return; maxweight-=(1l<<msb); visited=new boolean[nv]; dfscheck(0,maxweight); for(int i=0;i<nv;i++) { if(visited[i]==false) {maxweight+=(1<<msb); break;} } dfsutil(msb-1); } // public boolean TopologicalSort() { // top=new int[nv]; // int cnt=0; // int indegree[]=new int[nv]; // for(int i=0;i<nv;i++){ // for(int j:adj.get(i)){ // indegree[j]++; // } // } // Deque<Integer> q=new LinkedList<Integer>(); // for(int i=0;i<nv;i++){ // if(indegree[i]==0){ // q.addLast(i); // } // } // while(q.size()>0){ // int tele=q.pop(); // top[tele]=cnt++; // for(int j:adj.get(tele)){ // indegree[j]--; // if(indegree[j]==0) // q.addLast(j); // } // } // return cnt==nv; // } // public boolean isBipartiteGraph(){ // col=new Integer[nv]; // visited=new boolean[nv]; // for(int i=0;i<nv;i++){ // if(visited[i]==false){ // col[i]=0; // dfs(i); // } // } } class DSU{ int []parent; int rank[]; int n; public DSU(int n){ this.n=n; parent=new int[n]; rank=new int[n]; for(int i=0;i<n;i++) { parent[i]=i; rank[i]=1; } } public int find(int i){ if(parent[i]==i)return i; return parent[i]=find(parent[i]); } public boolean union(int a,int b){ int pa=find(a); int pb=find(b); if(pa==pb)return false; if(rank[pa]>rank[pb]){ parent[pb]=pa; rank[pa]+=rank[pb]; } else{ parent[pa]=pb; rank[pb]+=rank[pa]; } return true; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
834a68aa79c9507c95aaba898de6364f
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Armchairs { public static PrintWriter out; public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); // out.print("heelo"); /* int n = sc.nextInt(); // read input as integer long k = sc.nextLong(); // read input as long double d = sc.nextDouble(); // read input as double String str = sc.next(); // read input as String String s = sc.nextLine(); // read whole line as String int result = 3*n; out.println(result); // print via PrintWriter */ int n= sc.nextInt(); int ar1[] = new int[5001]; int ar2[] =new int[5001]; int c1=0,c2=0; for(int i=0;i<n;i++) { int x = sc.nextInt(); if (x==1)ar1[c1++] = i; else ar2[c2++] = i; } int[][] dp = new int[c1+1][c2+1]; for(int i=0;i<=c1;i++)for(int j=0;j<=c2;j++)dp[i][j] = i==0? 0:Integer.MAX_VALUE; for(int i=1;i<=c1;i++){ for(int j=1;j<=c2;j++) { if(dp[i-1][j-1] != Integer.MAX_VALUE) { dp[i][j] = Math.min(dp[i][j-1], Math.abs(ar1[i-1]- ar2[j-1]) + dp[i-1][j-1]); } } } out.println(dp[c1][c2]); out.flush(); out.close(); } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
1bd7cd1d074d10e537c4ed44792fb28c
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class c731 { public static void main(String[] args) throws IOException { BufferedWriter out = new BufferedWriter( new OutputStreamWriter(System.out)); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); PrintWriter pt = new PrintWriter(System.out); FastReader sc = new FastReader(); // int t = sc.nextInt(); //for(int o = 0; o<t;o++){ // //} int n = sc.nextInt(); int[] arr = new int[n]; for(int i = 0 ; i<n;i++) { arr[i] = sc.nextInt(); } ArrayList<Integer> al1 = new ArrayList<Integer>(); ArrayList<Integer> al2 = new ArrayList<Integer>(); for(int i = 0 ; i<n;i++) { if(arr[i] == 1) { al1.add(i); }else { al2.add(i); } } int m = al1.size(); int k = al2.size(); int[][] dp = new int[m+1][k+1]; for(int i = 0 ; i<=m;i++) { for(int j = 0 ; j<=k;j++) { dp[i][j] = Integer.MAX_VALUE; } } for(int i = 0 ;i<=m;i++) { for(int j =i ; j<=k;j++) { if(i== 0 ) { dp[i][j] = 0; continue; } if(j == 0) { continue; } dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j-1] + Math.abs(al1.get(i-1)- al2.get(j-1))); } } //for(int i = 0 ; i<=m;i++) { // for(int j = 0 ; j<=k;j++) { // System.out.print(dp[i][j] + " "); // } //System.out.println(); //} //System.out.println(); System.out.println(dp[m][k]); } //------------------------------------------------------------------------------------------------------------------------------------------------ public static int dfs(int[][][] dp , int i , int j , int k,int[][] arr , int[][] brr,int n , int m) { if(k == 0) { return 0; } if(dp[i][j][k]!=-1) { return dp[i][j][k]; } int ans = Integer.MAX_VALUE; if(i>0) { ans = Math.min(ans, brr[i-1][j] + dfs(dp, i-1, j, k-1, arr, brr,n,m)); } if(i<n-1) { ans = Math.min(ans, brr[i][j] + dfs(dp, i+1, j, k-1, arr, brr,n,m)); } if(j>0) { ans = Math.min(ans, arr[i][j-1] + dfs(dp, i, j-1, k-1, arr, brr,n,m)); } if(j<m-1) { ans = Math.min(ans, arr[i][j] + dfs(dp, i, j+1, k-1, arr, brr,n,m)); } dp[i][j][k] = ans; return ans; } public static int cnt_set(long x) { long v = 1l; int c =0; int f = 0; while(v<=x) { if((v&x)!=0) { c++; } v = v<<1; } return c; } public static void dfs(int s , HashMap<Integer, ArrayList<Integer>> map, boolean[] vis) { vis[s] = true; for(int x : map.get(s)) { if(!vis[x]) { dfs(x, map, vis); } } } //public static int lis(int[] arr) { // int n = arr.length; // ArrayList<Integer> al = new ArrayList<Integer>(); // al.add(arr[0]); // for(int i = 1 ; i<n;i++) { // int x = al.get(al.size()-1); // if(arr[i]>=x) { // al.add(arr[i]); // }else { // int v = upper_bound(al, 0, al.size(), arr[i]); // al.set(v, arr[i]); // } // } //return al.size(); //} static int cntDivisors(int n){ int cnt = 0; for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i) cnt++; else cnt+=2; } } return cnt; } public static long power(long x, long y, long p){ long res = 1; x = x % p; if (x == 0) return 0; while (y > 0){ if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static long ncr(long[] fac, int n , int r , long m) { if(r>n) { return 0; } return fac[n]*(modInverse(fac[r], m))%m *(modInverse(fac[n-r], m))%m; } public static int lower_bound(ArrayList<Long> arr,int lo , int hi, int k) { int s=lo; int e=hi; while (s !=e) { int mid = s+e>>1; if (arr.get(mid) <k) { s=mid+1; } else { e=mid; } } if(s==arr.size()) { return -1; } return s; } public static int upper_bound(ArrayList<Long> arr,int lo , int hi, int k) { int s=lo; int e=hi; while (s !=e) { int mid = s+e>>1; if (arr.get(mid) <=k) { s=mid+1; } else { e=mid; } } if(s==arr.size()) { return -1; } return s; } // ----------------------------------------------------------------------------------------------------------------------------------------------- public static int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a); } //-------------------------------------------------------------------------------------------------------------------------------------------------------- public static long modInverse(long a, long m){ long m0 = m; long y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient long q = a / m; long t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } //_________________________________________________________________________________________________________________________________________________________________ // private static int[] parent; // private static int[] size; public static int find(int[] parent, int u) { while(u != parent[u]) { parent[u] = parent[parent[u]]; u = parent[u]; } return u; } private static void union(int[] parent,int[] size,int u, int v) { int rootU = find(parent,u); int rootV = find(parent,v); if(rootU == rootV) { return; } if(size[rootU] < size[rootV]) { parent[rootU] = rootV; size[rootV] += size[rootU]; } else { parent[rootV] = rootU; size[rootU] += size[rootV]; } } //----------------------------------------------------------------------------------------------------------------------------------- //segment tree //for finding minimum in range public static void build(boolean [] seg,boolean []arr,int idx, int lo , int hi) { if(lo == hi) { seg[idx] = arr[lo]; return; } int mid = (lo + hi)/2; build(seg,arr,2*idx+1, lo, mid); build(seg,arr,idx*2+2, mid +1, hi); // seg[idx] = Math.min(seg[2*idx+1],seg[2*idx+2]); // seg[idx] = seg[idx*2+1]+ seg[idx*2+2]; // seg[idx] = Math.min(seg[idx*2+1], seg[idx*2+2]); seg[idx] = seg[idx*2+1] && seg[idx*2+2]; } //for finding minimum in range public static boolean query(boolean[]seg,int idx , int lo , int hi , int l , int r) { if(lo>=l && hi<=r) { return seg[idx]; } if(hi<l || lo>r) { return true; } int mid = (lo + hi)/2; boolean left = query(seg,idx*2 +1, lo, mid, l, r); boolean right = query(seg,idx*2 + 2, mid + 1, hi, l, r); // return Math.min(left, right); //return gcd(left, right); // return Math.min(left, right); return left && right; } // // for sum // //public static void update(int[]seg,int idx, int lo , int hi , int node , int val) { // if(lo == hi) { // seg[idx] += val; // }else { //int mid = (lo + hi )/2; //if(node<=mid && node>=lo) { // update(seg, idx * 2 +1, lo, mid, node, val); //}else { // update(seg, idx*2 + 2, mid + 1, hi, node, val); //} //seg[idx] = seg[idx*2 + 1] + seg[idx*2 + 2]; // //} //} //--------------------------------------------------------------------------------------------------------------------------------------- // static void shuffleArray(int[] ar) { // If running on Java 6 or older, use `new Random()` on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } static void shuffleArray(coup[] ar) { // If running on Java 6 or older, use `new Random()` on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap coup a = ar[index]; ar[index] = ar[i]; ar[i] = 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; } } //------------------------------------------------------------------------------------------------------------------------------------------------------------ //----------------------------------------------------------------------------------------------------------------------------------------------------------- class coup{ int a; int b; public coup(int a , int b) { this.a = a; this.b = b; } } class trip{ int a , b, c; public trip(int a , int b, int c) { this.a = a; this.b = b; this.c = c; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
d652cfaa37e6fd25481b6fdaa683360d
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 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.StringTokenizer; public class App { public String getGreeting() { return "Hello World!"; } static int []a; static ArrayList<Integer> f; static int n; static int m; static long [][]dp; static long solve(int pos,int j){ if(pos<0){ if(j<0){ return 0; } else return Integer.MAX_VALUE; } else if(j<0){ return 0; } else if(dp[pos][j]!=-1) return dp[pos][j]; long ans=Integer.MAX_VALUE; if(a[pos]==1) ans=solve(pos-1,j); else if(a[pos]==0){ int cost=Math.abs(f.get(j)-pos); ans=Math.min(solve(pos-1,j-1)+cost,solve(pos-1, j)); } return dp[pos][j]=ans; } public static void main(String[] args) { FastScanner fs=new FastScanner(); n=fs.nextInt(); a=fs.readArray(n); f=new ArrayList<Integer>(); for(int i=0;i<n;i++) if(a[i]==1)f.add(i); m=f.size(); dp=new long[n+1][m+1]; for(int i=0;i<n;i++)for(int j=0;j<m;j++)dp[i][j]=-1; long ans=solve(n-1,m-1); System.out.println(ans); } static final long mod=1_000_000_007; static long mul(long a, long b) { return a*b%mod; } static long add(long a, long b) { return (a+b)%mod; } static long fastPow(long base, long e) { if (e==0) return 1; long half=fastPow(base, e/2); if (e%2==0) return mul(half, half); return mul(half, mul(half, base)); } static long[] facts, invFacts; static void precomp() { facts=new long[1_100_000]; invFacts=new long[1_100_000]; facts[0]=invFacts[0]=1; for (int i=1; i<facts.length; i++) { facts[i]=mul(i, facts[i-1]); } invFacts[invFacts.length-1]=fastPow(facts[facts.length-1], mod-2); for (int i=invFacts.length-2; i>=0; i--) { invFacts[i]=mul(invFacts[i+1], i+1); } if (mul(facts[6], invFacts[6])!=1) throw null; } static long nCk(int n, int k) { return mul(facts[n], mul(invFacts[k], invFacts[n-k])); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sortLong(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readLongArray(int n){ long[]a =new long[n]; for(int i=0;i<n;i++){ a[i]=nextLong(); } return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
f37fd11e3f62037a312d3d32558a553c
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; // Solution public class new1{ public static int func(ArrayList<Integer> full, ArrayList<Integer> empty, int x, int y, int[][] dp) { int n = full.size(); int m = empty.size(); if(x == n) return 0; if(dp[x][y] != -1) return dp[x][y]; int a = 0; int b = Integer.MAX_VALUE; a = func(full, empty, x + 1, y + 1, dp) + Math.abs(full.get(x) - empty.get(y)); if(n - x < m - y) b = func(full, empty, x, y + 1, dp); int ans = Math.min(a, b); dp[x][y] = ans; //System.out.println(x + " " + y + " " + ans); return ans; } public static void main(String[] args) throws IOException{ //BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); FastReader s = new FastReader(); int t = 1;//s.nextInt(); for(int z = 0; z < t; z++) { int n = s.nextInt(); ArrayList<Integer> full = new ArrayList<Integer>(); ArrayList<Integer> empty = new ArrayList<Integer>(); for(int i = 0; i < n; i++) { if(s.nextInt() == 0) empty.add(i); else full.add(i); } n = full.size(); int m = empty.size(); int[][] dp = new int[n][m]; for(int i = 0; i < n; i++) Arrays.fill(dp[i], -1); int ans = func(full, empty, 0, 0, dp); System.out.println(ans); } //output.flush(); } } 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(); } public int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; }}
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
30e351e6eec411b7a35095464c45d25e
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; // CFPS -> CodeForcesProblemSet public final class CFPS { static FastReader fr = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static final int gigamod = 1000000007; static int t = 1; static double epsilon = 0.0000001; public static void main(String[] args) { OUTER: for (int tc = 0; tc < t; tc++) { int n = fr.nextInt(); int[] arr = fr.nextIntArray(n); // Observations: // 1. The task is to determine the total time required to get // every initially filled chair empty by moving all seated // persons. // 2. "For a fixed set of final positions, the total time will // be the same regardless of the order of moves or the mapping // provided that everything is done optimally. // 3. This seems like a DP problem. // State: (i, j) // i -- The next person to be placed is person 'i'. // j -- The positions [j, n - 1] are under consideration. // Value: dp[i][j] -- Min time spent after placing (i-1) people in chairs [0, j]. // Answer: min(dp[n][]) // Transitions: // (i, j) -> (i, j + 1) -- we discard chair 'j' // (i, j) -> (i + 1, j + 1) -- we place 'i' on 'j'. // Alternatively, // (i, j) <- (i, j - 1) // (i, j) <- (i - 1, j - 1) // Mathematical: // dp[i][j] = dp[i][j - 1] -- since the person didn't make a move // dp[i][j] = dp[i - 1][j - 1] + Math.abs((j - 1) - (i - 1)) // Base case: // dp[0][] = 0 // Order of eval: // j -> i ArrayList<Integer> personIdxs = new ArrayList<>(); for (int i = 0; i < n; i++) if (arr[i] == 1) personIdxs.add(i); int s = personIdxs.size(); long[][] dp = new long[s + 1][n + 1]; for (int i = 0; i < s + 1; i++) Arrays.fill(dp[i], Long.MAX_VALUE / 100000); for (int j = 0; j < n + 1; j++) dp[0][j] = 0; for (int i = 1; i < s + 1; i++) for (int j = 1; j < n + 1; j++) { dp[i][j] = Math.min(dp[i][j], dp[i][j - 1]); // We can sit (i-1)th person on (j-1)th chair only if it wasn't occupied. if (arr[j - 1] != 1) dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + Math.abs((j - 1) - personIdxs.get(i - 1))); } long minTime = Long.MAX_VALUE; for (int j = 0; j < n + 1; j++) minTime = Math.min(minTime, dp[s][j]); out.println(minTime); // Being able to solve a problem is only a part of the problem's story. // Learning out of its every single ounce is the real deal. } out.close(); } // Manual implementation of RB-BST for C++ PBDS functionality. // Modification required according to requirements. public static final class RedBlackCountSet { // Colors for Nodes: private static final boolean RED = true; private static final boolean BLACK = false; // Pointer to the root: private Node root; // Public constructor: public RedBlackCountSet() { root = null; } // Node class for storing key value pairs: private class Node { long key; long value; Node left, right; boolean color; long size; // Size of the subtree rooted at that node. public Node(long key, long value, boolean color) { this.key = key; this.value = value; this.left = this.right = null; this.color = color; this.size = value; } } /***** Invariant Maintenance functions: *****/ // When a temporary 4 node is formed: private Node flipColors(Node node) { node.left.color = node.right.color = BLACK; node.color = RED; return node; } // When there's a right leaning red link and it is not a 3 node: private Node rotateLeft(Node node) { Node rn = node.right; node.right = rn.left; rn.left = node; rn.color = node.color; node.color = RED; return rn; } // When there are 2 red links in a row: private Node rotateRight(Node node) { Node ln = node.left; node.left = ln.right; ln.right = node; ln.color = node.color; node.color = RED; return ln; } /***** Invariant Maintenance functions end *****/ // Public functions: public void put(long key) { root = put(root, key); root.color = BLACK; // One of the invariants. } private Node put(Node node, long key) { // Standard insertion procedure: if (node == null) return new Node(key, 1, RED); // Recursing: int cmp = Long.compare(key, node.key); if (cmp < 0) node.left = put(node.left, key); else if (cmp > 0) node.right = put(node.right, key); else node.value++; // Invariant maintenance: if (node.left != null && node.right != null) { if (node.right.color = RED && node.left.color == BLACK) node = rotateLeft(node); if (node.left.color == RED && node.left.left.color == RED) node = rotateRight(node); if (node.left.color == RED && node.right.color == RED) node = flipColors(node); } // Property maintenance: node.size = node.value + size(node.left) + size(node.right); return node; } private long size(Node node) { if (node == null) return 0; else return node.size; } public long rank(long key) { return rank(root, key); } // Modify according to requirements. private long rank(Node node, long key) { if (node == null) return 0; int cmp = Long.compare(key, node.key); if (cmp < 0) return rank(node.left, key); else if (cmp > 0) return node.value + size(node.left) + rank(node.right, key); else return size(node.left); } } static long modDiv(long a, long b) { return mod(a * power(b, gigamod - 2)); } static class SegTree { // Setting up the parameters. int n; long[] sumTree; long[] ogArr; long[] maxTree; long[] minTree; public static final int sumMode = 0; public static final int maxMode = 1; public static final int minMode = 2; // Constructor public SegTree(long[] arr, int mode) { if (mode == sumMode) { Arrays.fill(sumTree = new long[4 * (n = ((ogArr = arr.clone()).length))], -1); buildSum(0, n - 1, 0); } else if (mode == maxMode) { Arrays.fill(maxTree = new long[4 * (n = ((ogArr = arr.clone()).length))], -1); buildMax(0, n - 1, 0); } else if (mode == minMode) { Arrays.fill(minTree = new long[4 * (n = ((ogArr = arr.clone()).length))], Long.MAX_VALUE - 1); buildMin(0, n - 1, 0); } } /**********Code for sum***********/ /*********************************/ // Build the segment tree node-by-node private long buildSum(int l, int r, int segIdx) { return sumTree[segIdx] = (l == r) ? ogArr[l] : (buildSum(l, l + (r - l) / 2, 2 * segIdx + 1) + buildSum((l + (r - l) / 2) + 1, r, 2 * segIdx + 2)); } // Change a single element public void changeForSum(int idx, long to) { changeForSum(idx, to, 0, n - 1, 0); } private long changeForSum(int idx, long to, int l, int r, int segIdx) { return sumTree[segIdx] = ((l == r) ? (ogArr[idx] = to) : ((0 * ((idx <= (l + (r - l) / 2)) ? changeForSum(idx, to, l, l + (r - l) / 2, 2 * segIdx + 1) : changeForSum(idx, to, (l + (r - l) / 2) + 1, r, 2 * segIdx + 2))) + sumTree[2 * segIdx + 1] + sumTree[2 * segIdx + 2])); } // Return the sum arr[l, r] public long segSum(int l, int r) { if (l > r) return 0; return segSum(l, r, 0, n - 1, 0); } private long segSum(int segL, int segR, int l, int r, int segIdx) { if (segL == l && segR == r) return sumTree[segIdx]; if (segR <= l + (r - l) / 2) return segSum(segL, segR, l, l + (r - l) / 2, 2 * segIdx + 1); if (segL >= l + (r - l) / 2 + 1) return segSum(segL, segR, l + (r - l) / 2 + 1, r, 2 * segIdx + 2); return segSum(segL, l + (r - l) / 2, l, l + (r - l) / 2, 2 * segIdx + 1) + segSum(l + (r - l) / 2 + 1, segR, l + (r - l) / 2 + 1, r, 2 * segIdx + 2); } /********End of code for sum********/ /***********************************/ /*******Start of code for max*******/ /***********************************/ // Build the max tree node-by-node private long buildMax(int l, int r, int segIdx) { return maxTree[segIdx] = (l == r) ? ogArr[l] : Math.max(buildMax(l, (l + (r - l) / 2), 2 * segIdx + 1), buildMax(l + (r - l) / 2 + 1, r, 2 * segIdx + 2)); } // Change a single element public void changeForMax(int idx, long to) { changeForMax(0, n - 1, idx, to, 0); } private long changeForMax(int l, int r, int idx, long to, int segIdx) { return maxTree[segIdx] = (l == r && l == idx) ? (ogArr[idx] = to) : Math.max(changeForMax(l, l + (r - l) / 2, idx, to, 2 * segIdx + 1), changeForMax(l + (r - l) / 2 + 1, r, idx, to, 2 * segIdx + 2)); } public long segMax(int segL, int segR) { if (segL > segR) return 0; return segMax(0, n - 1, segL, segR, 0); } private long segMax(int l, int r, int segL, int segR, int segIdx) { int midL = l + (r - l) / 2; if (segL == segR && segL == l) return ogArr[segL]; if (segR <= midL) return segMax(l, midL, segL, segR, 2 * segIdx + 1); if (segL >= midL + 1) return segMax(midL + 1, r, segL, segR, 2 * segIdx + 2); return Math.max(segMax(l, midL, segL, midL, 2 * segIdx + 1), segMax(midL + 1, r, midL + 1, segR, 2 * segIdx + 2)); } /*******End of code for max*********/ /***********************************/ /*******Start of code for min*******/ /***********************************/ private long buildMin(int l, int r, int segIdx) { return minTree[segIdx] = (l == r) ? ogArr[l] : Math.min(buildMin(l, (l + (r - l) / 2), 2 * segIdx + 1), buildMin(l + (r - l) / 2 + 1, r, 2 * segIdx + 2)); } // Change a single element public void changeForMin(int idx, long to) { changeForMin(0, n - 1, idx, to, 0); } private long changeForMin(int l, int r, int idx, long to, int segIdx) { return minTree[segIdx] = (l == r && l == idx) ? (ogArr[idx] = to) : Math.min(changeForMin(l, l + (r - l) / 2, idx, to, 2 * segIdx + 1), changeForMin(l + (r - l) / 2 + 1, r, idx, to, 2 * segIdx + 2)); } public long segMin(int segL, int segR) { if (segL > segR) return 0; return segMin(0, n - 1, segL, segR, 0); } private long segMin(int l, int r, int segL, int segR, int segIdx) { int midL = l + (r - l) / 2; if (segL == segR && segL == l) return ogArr[segL]; if (segR <= midL) return segMin(l, midL, segL, segR, 2 * segIdx + 1); if (segL >= midL + 1) return segMin(midL + 1, r, segL, segR, 2 * segIdx + 2); return Math.min(segMin(l, midL, segL, midL, 2 * segIdx + 1), segMin(midL + 1, r, midL + 1, segR, 2 * segIdx + 2)); } /*******End of code for min*********/ /***********************************/ public String toString() { return CFPS.toString(minTree); } } static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) { if (m > limit) return; if (m <= limit && n <= limit) coprimes.add(new Point(m, n)); if (coprimes.size() > numCoprimes) return; coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes); coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes); coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes); } // Returns the length of the longest prefix that is also // a suffix (no overlap). static int longestPrefixSuffix(String s) { int n = s.length(); int[] arr = new int[n]; arr[0] = 0; int len = 0; for (int i = 1; i < n;) { if (s.charAt(len) == s.charAt(i)) { len++; arr[i++] = len; } else { if (len != 0) { len = arr[len - 1]; } else { arr[i] = 0; i++; } } } return arr[n - 1]; } static long hash(long i) { return (i * 2654435761L % gigamod); } static long hash2(long key) { long h = Long.hashCode(key); h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4); return h & (gigamod-1); } static long power(long x, long y) { // int p = 998244353; int p = gigamod; long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long power2(long x, long y) { // int p = 998244353; // int p = gigamod; long res = 1; // Initialize result // x = x /*% p*/; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) /*% p*/; // y must be even now y = y >> 1; // y = y/2 x = (x * x) /*% p*/; } return res; } // Maps elements in a 2D matrix serially to elements in // a 1D array. static int mapTo1D(int row, int col, int n, int m) { return row * m + col; } // Inverse of what the one above does. static int[] mapTo2D(int idx, int n, int m) { int[] rnc = new int[2]; rnc[0] = idx / m; rnc[1] = idx % m; return rnc; } // Checks if s has subsequence t. static boolean hasSubsequence(String s, String t) { char[] schars = s.toCharArray(); char[] tchars = t.toCharArray(); int slen = schars.length, tlen = tchars.length; int tctr = 0; if (slen < tlen) return false; for (int i = 0; i < slen || i < tlen; i++) { if (tctr == tlen) break; if (schars[i] == tchars[tctr]) { tctr++; } } if (tctr == tlen) return true; return false; } // Returns the binary string of length at least bits. static String toBinaryString(long num, int bits) { StringBuilder sb = new StringBuilder(Long.toBinaryString(num)); sb.reverse(); for (int i = sb.length(); i < bits; i++) sb.append('0'); return sb.reverse().toString(); } @SuppressWarnings("serial") static class CountMap<T> extends TreeMap<T, Integer>{ CountMap() { } CountMap(T[] arr) { this.putCM(arr); } public Integer putCM(T key) { if (super.containsKey(key)) { return super.put(key, super.get(key) + 1); } else { return super.put(key, 1); } } public Integer removeCM(T key) { Integer count = super.get(key); if (count == null) return -1; if (count == 1) return super.remove(key); else return super.put(key, super.get(key) - 1); } public Integer getCM(T key) { Integer count = super.get(key); if (count == null) return 0; return count; } public void putCM(T[] arr) { for (T l : arr) this.putCM(l); } } static class Point implements Comparable<Point> { long x; long y; int id; Point() { x = y = id = 0; } Point(Point p) { this.x = p.x; this.y = p.y; this.id = p.id; } /*Point(double a, double b) { x = a; y = b; }*/ Point(long a, long b, int id) { this.x = a; this.y = b; this.id = id; } Point(long a, long b) { this.x = a; this.y = b; } @Override public int compareTo(Point o) { if (this.x > o.x) return 1; if (this.x < o.x) return -1; if (this.y > o.y) return 1; if (this.y < o.y) return -1; return 0; } public boolean equals(Point that) { return this.compareTo(that) == 0; } } static class PointComparator implements Comparator<Point> { @Override public int compare(Point o1, Point o2) { // Comparision will be done on the basis of the start // of the segment and then on the length of the segment. if (o1.id > o2.id) return -1; if (o1.id < o2.id) return 1; return 0; } } static double distToOrigin(Point p1) { return Math.sqrt(Math.pow(p1.y, 2) + Math.pow(p1.x, 2)); } static double distance(Point p1, Point p2) { double y2 = p2.y, y1 = p1.y; double x2 = p2.x, x1 = p1.x; double distance = Math.sqrt(Math.pow(y2-y1, 2) + Math.pow(x2-x1, 2)); return distance; } // Returns the largest power of k that fits into n. static int largestFittingPower(long n, long k) { int lo = 0, hi = logk(Long.MAX_VALUE, 3); int largestPower = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; long val = (long) Math.pow(k, mid); if (val <= n) { largestPower = mid; lo = mid + 1; } else { hi = mid - 1; } } return largestPower; } // Returns map of factor and its power in the number. static HashMap<Long, Integer> primeFactorization(long num) { HashMap<Long, Integer> map = new HashMap<>(); while (num % 2 == 0) { num /= 2; Integer pwrCnt = map.get(2L); map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1); } for (long i = 3; i * i <= num; i += 2) { while (num % i == 0) { num /= i; Integer pwrCnt = map.get(i); map.put(i, pwrCnt != null ? pwrCnt + 1 : 1); } } // If the number is prime, we have to add it to the // map. if (num != 1) map.put(num, 1); return map; } // Returns map of factor and its power in the number. static HashMap<Integer, Integer> primeFactorization(int num) { HashMap<Integer, Integer> map = new HashMap<>(); while (num % 2 == 0) { num /= 2; Integer pwrCnt = map.get(2); map.put(2, pwrCnt != null ? pwrCnt + 1 : 1); } for (int i = 3; i * i <= num; i += 2) { while (num % i == 0) { num /= i; Integer pwrCnt = map.get(i); map.put(i, pwrCnt != null ? pwrCnt + 1 : 1); } } // If the number is prime, we have to add it to the // map. if (num != 1) map.put(num, 1); return map; } static HashSet<Long> divisors(long num) { HashSet<Long> divisors = new HashSet<Long>(); divisors.add(1L); divisors.add(num); for (long i = 2; i * i <= num; i++) { if (num % i == 0) { divisors.add(num/i); divisors.add(i); } } return divisors; } // Returns the index of the first element // larger than or equal to val. static int bsearch(int[] arr, int val, int lo, int hi) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { idx = mid; hi = mid - 1; } else lo = mid + 1; } return idx; } static int bsearch(long[] arr, long val, int lo, int hi) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { idx = mid; hi = mid - 1; } else lo = mid + 1; } return idx; } // Returns the index of the last element // smaller than or equal to val. static int bsearch(long[] arr, long val, int lo, int hi, boolean sMode) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] > val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static int bsearch(int[] arr, long val, int lo, int hi, boolean sMode) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] > val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static long factorial(long n) { if (n <= 1) return 1; long factorial = 1; for (int i = 1; i <= n; i++) factorial = mod(factorial * i); return factorial; } static long factorialInDivision(long a, long b) { if (a == b) return 1; if (b < a) { long temp = a; a = b; b = temp; } long factorial = 1; for (long i = a + 1; i <= b; i++) factorial = mod(factorial * i); return factorial; } static BigInteger factorialInDivision(BigInteger a, BigInteger b) { if (a.equals(b)) return BigInteger.ONE; return a.multiply(factorialInDivision(a.subtract(BigInteger.ONE), b)); } static long nCr(long n, long r) { long p = gigamod; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r long fac[] = new long[(int)n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long power(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1)==1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long nPr(long n, long r) { return factorialInDivision(n, n - r); } static int log2(long n) { return (int)(Math.log(n) / Math.log(2)); } static double log2(long n, boolean doubleMode) { return (Math.log(n) / Math.log(2)); } static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); } // Sieve of Eratosthenes: static boolean[] primeGenerator(int upto) { boolean[] isPrime = new boolean[upto + 1]; Arrays.fill(isPrime, true); isPrime[1] = isPrime[0] = false; for (long i = 2; i * i < upto + 1; i++) if (isPrime[(int) i]) // Mark all the multiples greater than or equal // to the square of i to be false. for (long j = i; j * i < upto + 1; j++) isPrime[(int) j * (int) i] = false; return isPrime; } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(int[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(int a, int b) { return (a * b)/gcd(a, b); } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; } static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } private static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (long i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static String toString(int[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + " "); return sb.toString(); } static String toString(boolean[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + " "); return sb.toString(); } static String toString(long[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + " "); return sb.toString(); } static String toString(char[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + ""); return sb.toString(); } static String toString(int[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static String toString(long[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static String toString(double[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static String toString(char[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static char toChar(int i) { return (char) (i + 48); } static long mod(long a, long m) { return (a%m + m) % m; } static long mod(long num) { return (num % gigamod + gigamod) % gigamod; } // Uses weighted quick-union with path compression. static class UnionFind { private int[] parent; // parent[i] = parent of i private int[] size; // size[i] = number of sites in tree rooted at i // Note: not necessarily correct if i is not a root node private int count; // number of components public UnionFind(int n) { count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } // Number of connected components. public int count() { return count; } // Find the root of p. public int find(int p) { int root = p; while (root != parent[root]) root = parent[root]; while (p != root) { int newp = parent[p]; parent[p] = root; p = newp; } return root; } public boolean connected(int p, int q) { return find(p) == find(q); } public int numConnectedTo(int node) { return size[find(node)]; } // Weighted union. public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make smaller root point to larger one if (size[rootP] < size[rootQ]) { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } else { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } count--; } public static int[] connectedComponents(UnionFind uf) { // We can do this in nlogn. int n = uf.size.length; int[] compoColors = new int[n]; for (int i = 0; i < n; i++) compoColors[i] = uf.find(i); HashMap<Integer, Integer> oldToNew = new HashMap<>(); int newCtr = 0; for (int i = 0; i < n; i++) { int thisOldColor = compoColors[i]; Integer thisNewColor = oldToNew.get(thisOldColor); if (thisNewColor == null) thisNewColor = newCtr++; oldToNew.put(thisOldColor, thisNewColor); compoColors[i] = thisNewColor; } return compoColors; } } static class UGraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; public UGraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); adj[to].add(from); } public HashSet<Integer> adj(int from) { return adj[from]; } public int degree(int v) { return adj[v].size(); } public int V() { return adj.length; } public int E() { return E; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int current, boolean[] marked, UGraph g) { if (marked[current]) return; marked[current] = true; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) { if (marked[current]) return; marked[current] = true; if (from != -1) distTo[current] = distTo[from] + 1; HashSet<Integer> adj = g.adj(current); int alreadyMarkedCtr = 0; for (int adjc : adj) { if (marked[adjc]) alreadyMarkedCtr++; dfsMark(adjc, current, distTo, marked, g, endPoints); } if (alreadyMarkedCtr == adj.size()) endPoints.add(current); } public static void bfsOrder(int current, UGraph g) { } public static void dfsMark(int current, int[] colorIds, int color, UGraph g) { if (colorIds[current] != -1) return; colorIds[current] = color; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, colorIds, color, g); } public static int[] connectedComponents(UGraph g) { int n = g.V(); int[] componentId = new int[n]; Arrays.fill(componentId, -1); int colorCtr = 0; for (int i = 0; i < n; i++) { if (componentId[i] != -1) continue; dfsMark(i, componentId, colorCtr, g); colorCtr++; } return componentId; } public static boolean hasCycle(UGraph ug) { int n = ug.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, ug, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = ug.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, ug, marked, hasCycleFirst, current); } } } static class Digraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; public Digraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); } public HashSet<Integer> adj(int from) { return adj[from]; } public int V() { return adj.length; } public int E() { return E; } public Digraph reversed() { Digraph dg = new Digraph(V()); for (int i = 0; i < V(); i++) for (int adjVert : adj(i)) dg.addEdge(adjVert, i); return dg; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int source, boolean[] marked, Digraph g) { if (marked[source]) return; marked[source] = true; Iterable<Integer> adj = g.adj(source); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void bfsOrder(int source, Digraph g) { } public static int[] KosarajuSharirSCC(Digraph dg) { int[] id = new int[dg.V()]; Digraph reversed = dg.reversed(); // Gotta perform topological sort on this one to get the stack. Stack<Integer> revStack = Digraph.topologicalSort(reversed); // Initializing id and idCtr. id = new int[dg.V()]; int idCtr = -1; // Creating a 'marked' array. boolean[] marked = new boolean[dg.V()]; while (!revStack.isEmpty()) { int vertex = revStack.pop(); if (!marked[vertex]) sccDFS(dg, vertex, marked, ++idCtr, id); } return id; } private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) { marked[source] = true; id[source] = idCtr; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id); } public static Stack<Integer> topologicalSort(Digraph dg) { // dg has to be a directed acyclic graph. // We'll have to run dfs on the digraph and push the deepest nodes on stack first. // We'll need a Stack<Integer> and a int[] marked. Stack<Integer> topologicalStack = new Stack<Integer>(); boolean[] marked = new boolean[dg.V()]; // Calling dfs for (int i = 0; i < dg.V(); i++) if (!marked[i]) runDfs(dg, topologicalStack, marked, i); return topologicalStack; } static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) { marked[source] = true; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) runDfs(dg, topologicalStack, marked, adjVertex); topologicalStack.add(source); } public static boolean hasCycle(Digraph dg) { int n = dg.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, dg, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, Digraph dg, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = dg.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, dg, marked, hasCycleFirst, current); } } } static class Edge { int from; int to; long weight; public Edge(int from, int to, long weight) { this.from = from; this.to = to; this.weight = weight; } } static class WeightedUGraph { // Adjacency list. private HashSet<Edge>[] adj; private static final String NEWLINE = "\n"; private int E; public WeightedUGraph(int V) { adj = (HashSet<Edge>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Edge>(); } public void addEdge(int from, int to, int weight) { if (adj[from].contains(new Edge(from, to, weight))) return; E++; adj[from].add(new Edge(from, to, weight)); adj[to].add(new Edge(to, from, weight)); } public HashSet<Edge> adj(int from) { return adj[from]; } public int degree(int v) { return adj[v].size(); } public int V() { return adj.length; } public int E() { return E; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (Edge w : adj[v]) { s.append(w.toString() + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int current, boolean[] marked, UGraph g) { if (marked[current]) return; marked[current] = true; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) { if (marked[current]) return; marked[current] = true; if (from != -1) distTo[current] = distTo[from] + 1; HashSet<Integer> adj = g.adj(current); int alreadyMarkedCtr = 0; for (int adjc : adj) { if (marked[adjc]) alreadyMarkedCtr++; dfsMark(adjc, current, distTo, marked, g, endPoints); } if (alreadyMarkedCtr == adj.size()) endPoints.add(current); } public static void bfsOrder(int current, UGraph g) { } public static void dfsMark(int current, int[] colorIds, int color, UGraph g) { if (colorIds[current] != -1) return; colorIds[current] = color; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, colorIds, color, g); } public static int[] connectedComponents(UGraph g) { int n = g.V(); int[] componentId = new int[n]; Arrays.fill(componentId, -1); int colorCtr = 0; for (int i = 0; i < n; i++) { if (componentId[i] != -1) continue; dfsMark(i, componentId, colorCtr, g); colorCtr++; } return componentId; } public static boolean hasCycle(UGraph ug) { int n = ug.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, ug, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = ug.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, ug, marked, hasCycleFirst, current); } } } static class FastReader { private BufferedReader bfr; private StringTokenizer st; public FastReader() { bfr = new BufferedReader(new InputStreamReader(System.in)); } String next() { if (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bfr.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()); } char nextChar() { return next().toCharArray()[0]; } String nextString() { return next(); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } double[] nextDoubleArray(int n) { double[] arr = new double[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextDouble(); return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } int[][] nextIntGrid(int n, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { char[] line = fr.next().toCharArray(); for (int j = 0; j < m; j++) grid[i][j] = line[j] - 48; } return grid; } } } // NOTES: // ASCII VALUE OF 'A': 65 // ASCII VALUE OF 'a': 97 // Range of long: 9 * 10^18 // ASCII VALUE OF '0': 48 // Primes upto 'n' can be given by (n / (logn)).
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
f1fa79dc3da5147fca0806991dc16271
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; // CFPS -> CodeForcesProblemSet public final class CFPS { static FastReader fr = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static final int gigamod = 1000000007; static int t = 1; static double epsilon = 0.0000001; public static void main(String[] args) { OUTER: for (int tc = 0; tc < t; tc++) { int n = fr.nextInt(); int[] arr = fr.nextIntArray(n); // Observations: // 1. The task is to determine the total time required to get // every initially filled chair empty by moving all seated // persons. // 2. "For a fixed set of final positions, the total time will // be the same regardless of the order of moves or the mapping // provided that everything is done optimally. // 3. This seems like a DP problem. // State: (i, j) // i -- The next person to be placed is person 'i'. // j -- The positions [j, n - 1] are under consideration. // Value: dp[i][j] -- Min time spent after placing (i-1) people in chairs [0, j]. // Answer: min(dp[n][]) // Transitions: // (i, j) -> (i, j + 1) -- we discard chair 'j' // (i, j) -> (i + 1, j + 1) -- we place 'i' on 'j'. // Alternatively, // (i, j) <- (i, j - 1) // (i, j) <- (i - 1, j - 1) // Mathematical: // dp[i][j] = dp[i][j - 1] -- since the person didn't make a move // dp[i][j] = dp[i - 1][j - 1] + Math.abs((j - 1) - (i - 1)) // Base case: // dp[0][] = 0 // Order of eval: // j -> i ArrayList<Integer> personIdxs = new ArrayList<>(); for (int i = 0; i < n; i++) if (arr[i] == 1) personIdxs.add(i); int s = personIdxs.size(); long[][] dp = new long[s + 1][n + 1]; for (int i = 0; i < s + 1; i++) Arrays.fill(dp[i], Long.MAX_VALUE / 100000); for (int j = 0; j < n + 1; j++) dp[0][j] = 0; for (int i = 1; i < s + 1; i++) for (int j = 1; j < n + 1; j++) { dp[i][j] = Math.min(dp[i][j], dp[i][j - 1]); // We can sit (i-1)th person on (j-1)th chair only if it wasn't occupied. if (arr[j - 1] != 1) dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + Math.abs((j - 1) - personIdxs.get(i - 1))); } long minTime = Long.MAX_VALUE; for (int j = 0; j < n + 1; j++) minTime = Math.min(minTime, dp[s][j]); out.println(minTime); // out.println(toString(dp)); } out.close(); } // Manual implementation of RB-BST for C++ PBDS functionality. // Modification required according to requirements. public static final class RedBlackCountSet { // Colors for Nodes: private static final boolean RED = true; private static final boolean BLACK = false; // Pointer to the root: private Node root; // Public constructor: public RedBlackCountSet() { root = null; } // Node class for storing key value pairs: private class Node { long key; long value; Node left, right; boolean color; long size; // Size of the subtree rooted at that node. public Node(long key, long value, boolean color) { this.key = key; this.value = value; this.left = this.right = null; this.color = color; this.size = value; } } /***** Invariant Maintenance functions: *****/ // When a temporary 4 node is formed: private Node flipColors(Node node) { node.left.color = node.right.color = BLACK; node.color = RED; return node; } // When there's a right leaning red link and it is not a 3 node: private Node rotateLeft(Node node) { Node rn = node.right; node.right = rn.left; rn.left = node; rn.color = node.color; node.color = RED; return rn; } // When there are 2 red links in a row: private Node rotateRight(Node node) { Node ln = node.left; node.left = ln.right; ln.right = node; ln.color = node.color; node.color = RED; return ln; } /***** Invariant Maintenance functions end *****/ // Public functions: public void put(long key) { root = put(root, key); root.color = BLACK; // One of the invariants. } private Node put(Node node, long key) { // Standard insertion procedure: if (node == null) return new Node(key, 1, RED); // Recursing: int cmp = Long.compare(key, node.key); if (cmp < 0) node.left = put(node.left, key); else if (cmp > 0) node.right = put(node.right, key); else node.value++; // Invariant maintenance: if (node.left != null && node.right != null) { if (node.right.color = RED && node.left.color == BLACK) node = rotateLeft(node); if (node.left.color == RED && node.left.left.color == RED) node = rotateRight(node); if (node.left.color == RED && node.right.color == RED) node = flipColors(node); } // Property maintenance: node.size = node.value + size(node.left) + size(node.right); return node; } private long size(Node node) { if (node == null) return 0; else return node.size; } public long rank(long key) { return rank(root, key); } // Modify according to requirements. private long rank(Node node, long key) { if (node == null) return 0; int cmp = Long.compare(key, node.key); if (cmp < 0) return rank(node.left, key); else if (cmp > 0) return node.value + size(node.left) + rank(node.right, key); else return size(node.left); } } static long modDiv(long a, long b) { return mod(a * power(b, gigamod - 2)); } static class SegTree { // Setting up the parameters. int n; long[] sumTree; long[] ogArr; long[] maxTree; long[] minTree; public static final int sumMode = 0; public static final int maxMode = 1; public static final int minMode = 2; // Constructor public SegTree(long[] arr, int mode) { if (mode == sumMode) { Arrays.fill(sumTree = new long[4 * (n = ((ogArr = arr.clone()).length))], -1); buildSum(0, n - 1, 0); } else if (mode == maxMode) { Arrays.fill(maxTree = new long[4 * (n = ((ogArr = arr.clone()).length))], -1); buildMax(0, n - 1, 0); } else if (mode == minMode) { Arrays.fill(minTree = new long[4 * (n = ((ogArr = arr.clone()).length))], Long.MAX_VALUE - 1); buildMin(0, n - 1, 0); } } /**********Code for sum***********/ /*********************************/ // Build the segment tree node-by-node private long buildSum(int l, int r, int segIdx) { return sumTree[segIdx] = (l == r) ? ogArr[l] : (buildSum(l, l + (r - l) / 2, 2 * segIdx + 1) + buildSum((l + (r - l) / 2) + 1, r, 2 * segIdx + 2)); } // Change a single element public void changeForSum(int idx, long to) { changeForSum(idx, to, 0, n - 1, 0); } private long changeForSum(int idx, long to, int l, int r, int segIdx) { return sumTree[segIdx] = ((l == r) ? (ogArr[idx] = to) : ((0 * ((idx <= (l + (r - l) / 2)) ? changeForSum(idx, to, l, l + (r - l) / 2, 2 * segIdx + 1) : changeForSum(idx, to, (l + (r - l) / 2) + 1, r, 2 * segIdx + 2))) + sumTree[2 * segIdx + 1] + sumTree[2 * segIdx + 2])); } // Return the sum arr[l, r] public long segSum(int l, int r) { if (l > r) return 0; return segSum(l, r, 0, n - 1, 0); } private long segSum(int segL, int segR, int l, int r, int segIdx) { if (segL == l && segR == r) return sumTree[segIdx]; if (segR <= l + (r - l) / 2) return segSum(segL, segR, l, l + (r - l) / 2, 2 * segIdx + 1); if (segL >= l + (r - l) / 2 + 1) return segSum(segL, segR, l + (r - l) / 2 + 1, r, 2 * segIdx + 2); return segSum(segL, l + (r - l) / 2, l, l + (r - l) / 2, 2 * segIdx + 1) + segSum(l + (r - l) / 2 + 1, segR, l + (r - l) / 2 + 1, r, 2 * segIdx + 2); } /********End of code for sum********/ /***********************************/ /*******Start of code for max*******/ /***********************************/ // Build the max tree node-by-node private long buildMax(int l, int r, int segIdx) { return maxTree[segIdx] = (l == r) ? ogArr[l] : Math.max(buildMax(l, (l + (r - l) / 2), 2 * segIdx + 1), buildMax(l + (r - l) / 2 + 1, r, 2 * segIdx + 2)); } // Change a single element public void changeForMax(int idx, long to) { changeForMax(0, n - 1, idx, to, 0); } private long changeForMax(int l, int r, int idx, long to, int segIdx) { return maxTree[segIdx] = (l == r && l == idx) ? (ogArr[idx] = to) : Math.max(changeForMax(l, l + (r - l) / 2, idx, to, 2 * segIdx + 1), changeForMax(l + (r - l) / 2 + 1, r, idx, to, 2 * segIdx + 2)); } public long segMax(int segL, int segR) { if (segL > segR) return 0; return segMax(0, n - 1, segL, segR, 0); } private long segMax(int l, int r, int segL, int segR, int segIdx) { int midL = l + (r - l) / 2; if (segL == segR && segL == l) return ogArr[segL]; if (segR <= midL) return segMax(l, midL, segL, segR, 2 * segIdx + 1); if (segL >= midL + 1) return segMax(midL + 1, r, segL, segR, 2 * segIdx + 2); return Math.max(segMax(l, midL, segL, midL, 2 * segIdx + 1), segMax(midL + 1, r, midL + 1, segR, 2 * segIdx + 2)); } /*******End of code for max*********/ /***********************************/ /*******Start of code for min*******/ /***********************************/ private long buildMin(int l, int r, int segIdx) { return minTree[segIdx] = (l == r) ? ogArr[l] : Math.min(buildMin(l, (l + (r - l) / 2), 2 * segIdx + 1), buildMin(l + (r - l) / 2 + 1, r, 2 * segIdx + 2)); } // Change a single element public void changeForMin(int idx, long to) { changeForMin(0, n - 1, idx, to, 0); } private long changeForMin(int l, int r, int idx, long to, int segIdx) { return minTree[segIdx] = (l == r && l == idx) ? (ogArr[idx] = to) : Math.min(changeForMin(l, l + (r - l) / 2, idx, to, 2 * segIdx + 1), changeForMin(l + (r - l) / 2 + 1, r, idx, to, 2 * segIdx + 2)); } public long segMin(int segL, int segR) { if (segL > segR) return 0; return segMin(0, n - 1, segL, segR, 0); } private long segMin(int l, int r, int segL, int segR, int segIdx) { int midL = l + (r - l) / 2; if (segL == segR && segL == l) return ogArr[segL]; if (segR <= midL) return segMin(l, midL, segL, segR, 2 * segIdx + 1); if (segL >= midL + 1) return segMin(midL + 1, r, segL, segR, 2 * segIdx + 2); return Math.min(segMin(l, midL, segL, midL, 2 * segIdx + 1), segMin(midL + 1, r, midL + 1, segR, 2 * segIdx + 2)); } /*******End of code for min*********/ /***********************************/ public String toString() { return CFPS.toString(minTree); } } static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) { if (m > limit) return; if (m <= limit && n <= limit) coprimes.add(new Point(m, n)); if (coprimes.size() > numCoprimes) return; coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes); coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes); coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes); } // Returns the length of the longest prefix that is also // a suffix (no overlap). static int longestPrefixSuffix(String s) { int n = s.length(); int[] arr = new int[n]; arr[0] = 0; int len = 0; for (int i = 1; i < n;) { if (s.charAt(len) == s.charAt(i)) { len++; arr[i++] = len; } else { if (len != 0) { len = arr[len - 1]; } else { arr[i] = 0; i++; } } } return arr[n - 1]; } static long hash(long i) { return (i * 2654435761L % gigamod); } static long hash2(long key) { long h = Long.hashCode(key); h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4); return h & (gigamod-1); } static long power(long x, long y) { // int p = 998244353; int p = gigamod; long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long power2(long x, long y) { // int p = 998244353; // int p = gigamod; long res = 1; // Initialize result // x = x /*% p*/; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) /*% p*/; // y must be even now y = y >> 1; // y = y/2 x = (x * x) /*% p*/; } return res; } // Maps elements in a 2D matrix serially to elements in // a 1D array. static int mapTo1D(int row, int col, int n, int m) { return row * m + col; } // Inverse of what the one above does. static int[] mapTo2D(int idx, int n, int m) { int[] rnc = new int[2]; rnc[0] = idx / m; rnc[1] = idx % m; return rnc; } // Checks if s has subsequence t. static boolean hasSubsequence(String s, String t) { char[] schars = s.toCharArray(); char[] tchars = t.toCharArray(); int slen = schars.length, tlen = tchars.length; int tctr = 0; if (slen < tlen) return false; for (int i = 0; i < slen || i < tlen; i++) { if (tctr == tlen) break; if (schars[i] == tchars[tctr]) { tctr++; } } if (tctr == tlen) return true; return false; } // Returns the binary string of length at least bits. static String toBinaryString(long num, int bits) { StringBuilder sb = new StringBuilder(Long.toBinaryString(num)); sb.reverse(); for (int i = sb.length(); i < bits; i++) sb.append('0'); return sb.reverse().toString(); } @SuppressWarnings("serial") static class CountMap<T> extends TreeMap<T, Integer>{ CountMap() { } CountMap(T[] arr) { this.putCM(arr); } public Integer putCM(T key) { if (super.containsKey(key)) { return super.put(key, super.get(key) + 1); } else { return super.put(key, 1); } } public Integer removeCM(T key) { Integer count = super.get(key); if (count == null) return -1; if (count == 1) return super.remove(key); else return super.put(key, super.get(key) - 1); } public Integer getCM(T key) { Integer count = super.get(key); if (count == null) return 0; return count; } public void putCM(T[] arr) { for (T l : arr) this.putCM(l); } } static class Point implements Comparable<Point> { long x; long y; int id; Point() { x = y = id = 0; } Point(Point p) { this.x = p.x; this.y = p.y; this.id = p.id; } /*Point(double a, double b) { x = a; y = b; }*/ Point(long a, long b, int id) { this.x = a; this.y = b; this.id = id; } Point(long a, long b) { this.x = a; this.y = b; } @Override public int compareTo(Point o) { if (this.x > o.x) return 1; if (this.x < o.x) return -1; if (this.y > o.y) return 1; if (this.y < o.y) return -1; return 0; } public boolean equals(Point that) { return this.compareTo(that) == 0; } } static class PointComparator implements Comparator<Point> { @Override public int compare(Point o1, Point o2) { // Comparision will be done on the basis of the start // of the segment and then on the length of the segment. if (o1.id > o2.id) return -1; if (o1.id < o2.id) return 1; return 0; } } static double distToOrigin(Point p1) { return Math.sqrt(Math.pow(p1.y, 2) + Math.pow(p1.x, 2)); } static double distance(Point p1, Point p2) { double y2 = p2.y, y1 = p1.y; double x2 = p2.x, x1 = p1.x; double distance = Math.sqrt(Math.pow(y2-y1, 2) + Math.pow(x2-x1, 2)); return distance; } // Returns the largest power of k that fits into n. static int largestFittingPower(long n, long k) { int lo = 0, hi = logk(Long.MAX_VALUE, 3); int largestPower = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; long val = (long) Math.pow(k, mid); if (val <= n) { largestPower = mid; lo = mid + 1; } else { hi = mid - 1; } } return largestPower; } // Returns map of factor and its power in the number. static HashMap<Long, Integer> primeFactorization(long num) { HashMap<Long, Integer> map = new HashMap<>(); while (num % 2 == 0) { num /= 2; Integer pwrCnt = map.get(2L); map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1); } for (long i = 3; i * i <= num; i += 2) { while (num % i == 0) { num /= i; Integer pwrCnt = map.get(i); map.put(i, pwrCnt != null ? pwrCnt + 1 : 1); } } // If the number is prime, we have to add it to the // map. if (num != 1) map.put(num, 1); return map; } // Returns map of factor and its power in the number. static HashMap<Integer, Integer> primeFactorization(int num) { HashMap<Integer, Integer> map = new HashMap<>(); while (num % 2 == 0) { num /= 2; Integer pwrCnt = map.get(2); map.put(2, pwrCnt != null ? pwrCnt + 1 : 1); } for (int i = 3; i * i <= num; i += 2) { while (num % i == 0) { num /= i; Integer pwrCnt = map.get(i); map.put(i, pwrCnt != null ? pwrCnt + 1 : 1); } } // If the number is prime, we have to add it to the // map. if (num != 1) map.put(num, 1); return map; } static HashSet<Long> divisors(long num) { HashSet<Long> divisors = new HashSet<Long>(); divisors.add(1L); divisors.add(num); for (long i = 2; i * i <= num; i++) { if (num % i == 0) { divisors.add(num/i); divisors.add(i); } } return divisors; } // Returns the index of the first element // larger than or equal to val. static int bsearch(int[] arr, int val, int lo, int hi) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { idx = mid; hi = mid - 1; } else lo = mid + 1; } return idx; } static int bsearch(long[] arr, long val, int lo, int hi) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { idx = mid; hi = mid - 1; } else lo = mid + 1; } return idx; } // Returns the index of the last element // smaller than or equal to val. static int bsearch(long[] arr, long val, int lo, int hi, boolean sMode) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] > val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static int bsearch(int[] arr, long val, int lo, int hi, boolean sMode) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] > val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static long factorial(long n) { if (n <= 1) return 1; long factorial = 1; for (int i = 1; i <= n; i++) factorial = mod(factorial * i); return factorial; } static long factorialInDivision(long a, long b) { if (a == b) return 1; if (b < a) { long temp = a; a = b; b = temp; } long factorial = 1; for (long i = a + 1; i <= b; i++) factorial = mod(factorial * i); return factorial; } static BigInteger factorialInDivision(BigInteger a, BigInteger b) { if (a.equals(b)) return BigInteger.ONE; return a.multiply(factorialInDivision(a.subtract(BigInteger.ONE), b)); } static long nCr(long n, long r) { long p = gigamod; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r long fac[] = new long[(int)n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long power(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1)==1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long nPr(long n, long r) { return factorialInDivision(n, n - r); } static int log2(long n) { return (int)(Math.log(n) / Math.log(2)); } static double log2(long n, boolean doubleMode) { return (Math.log(n) / Math.log(2)); } static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); } // Sieve of Eratosthenes: static boolean[] primeGenerator(int upto) { boolean[] isPrime = new boolean[upto + 1]; Arrays.fill(isPrime, true); isPrime[1] = isPrime[0] = false; for (long i = 2; i * i < upto + 1; i++) if (isPrime[(int) i]) // Mark all the multiples greater than or equal // to the square of i to be false. for (long j = i; j * i < upto + 1; j++) isPrime[(int) j * (int) i] = false; return isPrime; } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(int[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(int a, int b) { return (a * b)/gcd(a, b); } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; } static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } private static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (long i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static String toString(int[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + " "); return sb.toString(); } static String toString(boolean[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + " "); return sb.toString(); } static String toString(long[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + " "); return sb.toString(); } static String toString(char[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + ""); return sb.toString(); } static String toString(int[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static String toString(long[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static String toString(double[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static String toString(char[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static char toChar(int i) { return (char) (i + 48); } static long mod(long a, long m) { return (a%m + m) % m; } static long mod(long num) { return (num % gigamod + gigamod) % gigamod; } // Uses weighted quick-union with path compression. static class UnionFind { private int[] parent; // parent[i] = parent of i private int[] size; // size[i] = number of sites in tree rooted at i // Note: not necessarily correct if i is not a root node private int count; // number of components public UnionFind(int n) { count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } // Number of connected components. public int count() { return count; } // Find the root of p. public int find(int p) { int root = p; while (root != parent[root]) root = parent[root]; while (p != root) { int newp = parent[p]; parent[p] = root; p = newp; } return root; } public boolean connected(int p, int q) { return find(p) == find(q); } public int numConnectedTo(int node) { return size[find(node)]; } // Weighted union. public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make smaller root point to larger one if (size[rootP] < size[rootQ]) { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } else { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } count--; } public static int[] connectedComponents(UnionFind uf) { // We can do this in nlogn. int n = uf.size.length; int[] compoColors = new int[n]; for (int i = 0; i < n; i++) compoColors[i] = uf.find(i); HashMap<Integer, Integer> oldToNew = new HashMap<>(); int newCtr = 0; for (int i = 0; i < n; i++) { int thisOldColor = compoColors[i]; Integer thisNewColor = oldToNew.get(thisOldColor); if (thisNewColor == null) thisNewColor = newCtr++; oldToNew.put(thisOldColor, thisNewColor); compoColors[i] = thisNewColor; } return compoColors; } } static class UGraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; public UGraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); adj[to].add(from); } public HashSet<Integer> adj(int from) { return adj[from]; } public int degree(int v) { return adj[v].size(); } public int V() { return adj.length; } public int E() { return E; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int current, boolean[] marked, UGraph g) { if (marked[current]) return; marked[current] = true; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) { if (marked[current]) return; marked[current] = true; if (from != -1) distTo[current] = distTo[from] + 1; HashSet<Integer> adj = g.adj(current); int alreadyMarkedCtr = 0; for (int adjc : adj) { if (marked[adjc]) alreadyMarkedCtr++; dfsMark(adjc, current, distTo, marked, g, endPoints); } if (alreadyMarkedCtr == adj.size()) endPoints.add(current); } public static void bfsOrder(int current, UGraph g) { } public static void dfsMark(int current, int[] colorIds, int color, UGraph g) { if (colorIds[current] != -1) return; colorIds[current] = color; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, colorIds, color, g); } public static int[] connectedComponents(UGraph g) { int n = g.V(); int[] componentId = new int[n]; Arrays.fill(componentId, -1); int colorCtr = 0; for (int i = 0; i < n; i++) { if (componentId[i] != -1) continue; dfsMark(i, componentId, colorCtr, g); colorCtr++; } return componentId; } public static boolean hasCycle(UGraph ug) { int n = ug.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, ug, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = ug.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, ug, marked, hasCycleFirst, current); } } } static class Digraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; public Digraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); } public HashSet<Integer> adj(int from) { return adj[from]; } public int V() { return adj.length; } public int E() { return E; } public Digraph reversed() { Digraph dg = new Digraph(V()); for (int i = 0; i < V(); i++) for (int adjVert : adj(i)) dg.addEdge(adjVert, i); return dg; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int source, boolean[] marked, Digraph g) { if (marked[source]) return; marked[source] = true; Iterable<Integer> adj = g.adj(source); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void bfsOrder(int source, Digraph g) { } public static int[] KosarajuSharirSCC(Digraph dg) { int[] id = new int[dg.V()]; Digraph reversed = dg.reversed(); // Gotta perform topological sort on this one to get the stack. Stack<Integer> revStack = Digraph.topologicalSort(reversed); // Initializing id and idCtr. id = new int[dg.V()]; int idCtr = -1; // Creating a 'marked' array. boolean[] marked = new boolean[dg.V()]; while (!revStack.isEmpty()) { int vertex = revStack.pop(); if (!marked[vertex]) sccDFS(dg, vertex, marked, ++idCtr, id); } return id; } private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) { marked[source] = true; id[source] = idCtr; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id); } public static Stack<Integer> topologicalSort(Digraph dg) { // dg has to be a directed acyclic graph. // We'll have to run dfs on the digraph and push the deepest nodes on stack first. // We'll need a Stack<Integer> and a int[] marked. Stack<Integer> topologicalStack = new Stack<Integer>(); boolean[] marked = new boolean[dg.V()]; // Calling dfs for (int i = 0; i < dg.V(); i++) if (!marked[i]) runDfs(dg, topologicalStack, marked, i); return topologicalStack; } static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) { marked[source] = true; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) runDfs(dg, topologicalStack, marked, adjVertex); topologicalStack.add(source); } public static boolean hasCycle(Digraph dg) { int n = dg.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, dg, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, Digraph dg, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = dg.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, dg, marked, hasCycleFirst, current); } } } static class Edge { int from; int to; long weight; public Edge(int from, int to, long weight) { this.from = from; this.to = to; this.weight = weight; } } static class WeightedUGraph { // Adjacency list. private HashSet<Edge>[] adj; private static final String NEWLINE = "\n"; private int E; public WeightedUGraph(int V) { adj = (HashSet<Edge>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Edge>(); } public void addEdge(int from, int to, int weight) { if (adj[from].contains(new Edge(from, to, weight))) return; E++; adj[from].add(new Edge(from, to, weight)); adj[to].add(new Edge(to, from, weight)); } public HashSet<Edge> adj(int from) { return adj[from]; } public int degree(int v) { return adj[v].size(); } public int V() { return adj.length; } public int E() { return E; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (Edge w : adj[v]) { s.append(w.toString() + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int current, boolean[] marked, UGraph g) { if (marked[current]) return; marked[current] = true; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) { if (marked[current]) return; marked[current] = true; if (from != -1) distTo[current] = distTo[from] + 1; HashSet<Integer> adj = g.adj(current); int alreadyMarkedCtr = 0; for (int adjc : adj) { if (marked[adjc]) alreadyMarkedCtr++; dfsMark(adjc, current, distTo, marked, g, endPoints); } if (alreadyMarkedCtr == adj.size()) endPoints.add(current); } public static void bfsOrder(int current, UGraph g) { } public static void dfsMark(int current, int[] colorIds, int color, UGraph g) { if (colorIds[current] != -1) return; colorIds[current] = color; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, colorIds, color, g); } public static int[] connectedComponents(UGraph g) { int n = g.V(); int[] componentId = new int[n]; Arrays.fill(componentId, -1); int colorCtr = 0; for (int i = 0; i < n; i++) { if (componentId[i] != -1) continue; dfsMark(i, componentId, colorCtr, g); colorCtr++; } return componentId; } public static boolean hasCycle(UGraph ug) { int n = ug.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, ug, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = ug.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, ug, marked, hasCycleFirst, current); } } } static class FastReader { private BufferedReader bfr; private StringTokenizer st; public FastReader() { bfr = new BufferedReader(new InputStreamReader(System.in)); } String next() { if (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bfr.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()); } char nextChar() { return next().toCharArray()[0]; } String nextString() { return next(); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } double[] nextDoubleArray(int n) { double[] arr = new double[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextDouble(); return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } int[][] nextIntGrid(int n, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { char[] line = fr.next().toCharArray(); for (int j = 0; j < m; j++) grid[i][j] = line[j] - 48; } return grid; } } } // NOTES: // ASCII VALUE OF 'A': 65 // ASCII VALUE OF 'a': 97 // Range of long: 9 * 10^18 // ASCII VALUE OF '0': 48 // Primes upto 'n' can be given by (n / (logn)).
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
5ad604a072cb25e808b76a2d2321b041
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { //BufferedReader f = new BufferedReader(new FileReader("uva.in")); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = Integer.parseInt(f.readLine()); StringTokenizer st = new StringTokenizer(f.readLine()); ArrayList<Integer> occ = new ArrayList<>(); ArrayList<Integer> emp = new ArrayList<>(); for(int i = 0; i < n; i++) { if(Integer.parseInt(st.nextToken()) == 1) { occ.add(i); } else { emp.add(i); } } long[][] dp = new long[emp.size()+1][occ.size()+1]; for(long[] i: dp) { Arrays.fill(i, 25000000); } for(int i = 0; i <= emp.size(); i++) { dp[i][0] = 0; } for(int i = 1; i <= emp.size(); i++) { for(int j = 1; j <= occ.size(); j++) { dp[i][j] = Math.min(dp[i-1][j], dp[i-1][j-1]+Math.abs(occ.get(j-1)-emp.get(i-1))); } } out.println(dp[emp.size()][occ.size()]); f.close(); out.close(); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
ea837b12b3adf8eec677b2d88b07157a
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.Scanner; import java.util.ArrayList; import java.lang.Math; public class fell { private static final Scanner cin = new Scanner(System.in); private static final int maxVal = 1000000000; public static void main(String[] args) { int n = cin.nextInt(); ArrayList<Integer> a = new ArrayList<>(); ArrayList<Integer> b = new ArrayList<>(); for (int i = 0; i < n; i++) { int t = cin.nextInt(); if (t == 0) a.add(i); else b.add(i); } if (a.size() == n) { System.out.println(0); return; } int[][] dp = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (i == 0) dp[i][j] = 0; else dp[i][j] = maxVal; } for (int i = 0; i < a.size(); i++) { for (int j = 0; j < Math.min(i + 1, b.size() + 1); j++) { dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j]); if (j == b.size()) continue; dp[i + 1][j + 1] = Math.min(dp[i + 1][j + 1], dp[i][j] + Math.abs(a.get(i) - b.get(j))); } } System.out.println(dp[a.size()][b.size()]); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
70691c1ed2eb240507992bb5f2c7bfe6
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
// package FinalGrind; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class Problem9 { public static void main(String[] args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); int a[]=new int[n+1]; StringTokenizer st=new StringTokenizer(br.readLine()); ArrayList<Integer> ones=new ArrayList<>(); ArrayList<Integer> zeros=new ArrayList<>(); for(int i=1;i<=n;i++){ a[i]=Integer.parseInt(st.nextToken()); if(a[i]==1){ ones.add(i); } else{ zeros.add(i); } } if(ones.size()==0){ System.out.println(0); return; } int dp[]=new int[zeros.size()]; for(int i=0;i<dp.length;i++){ int time=Math.abs(zeros.get(i)-ones.get(0)); if(i==0){ dp[i]=time; } else{ dp[i]=Math.min(dp[i-1],time); } } for(int i=1;i<ones.size();i++){ int temp[]=dp.clone(); for(int j=i;j<zeros.size();j++){ int time=Math.abs(ones.get(i)-zeros.get(j)); if(j==i){ dp[j]=temp[j-1]+time; } else{ dp[j]=Math.min(dp[j-1],temp[j-1]+time); } } } System.out.println(dp[dp.length-1]); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
14802a890b1f82eac09538e4a42ed834
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; public class Main { static PrintWriter pw; static Scanner sc; static long ceildiv(long x, long y) { return (x+y-1)/y; } static int mod(long x, int m) { return (int)((x%m+m)%m); } static void put(TreeMap<Integer, Integer> map, Integer p){if(map.containsKey(p)) map.replace(p, map.get(p)+1); else map.put(p, 1); } static void rem(TreeMap<Integer, Integer> map, Integer p){ if(map.get(p)==1) map.remove(p);else map.replace(p, map.get(p)-1); } static void printf(double x, int dig){ String s="%."+dig+"f"; pw.printf(s, x); } static int Int(boolean x){ return x?1:0; } static final int inf=(int)1e9, mod= 998244353; static final long infL=inf*1l*inf; static final double eps=1e-9; public static long gcd(long x, long y) { return y==0? x: gcd(y, x%y); } public static void main(String[] args) throws Exception { sc = new Scanner(System.in); pw = new PrintWriter(System.out); // int t = sc.nextInt(); // while (t-- > 0) testcase(); pw.close(); } static long[][] dp; static void testcase() throws IOException { int n=sc.nextInt(), arr[]=sc.nextArr(n); ArrayList<Integer> ones=new ArrayList<>(), zeros=new ArrayList<>(); for (int i = 0; i < n; i++) { if(arr[i] == 1) ones.add(i); else zeros.add(i); } dp=new long[ones.size()][zeros.size()]; for (int i = 0; i < dp.length; i++) Arrays.fill(dp[i], -1); pw.println(solve(0, 0, ones, zeros)); } static long solve(int oneIdx, int zeroIdx, ArrayList<Integer> ones, ArrayList<Integer> zeros){ if(oneIdx == dp.length) return 0; if(zeroIdx == dp[oneIdx].length) return infL; if(dp[oneIdx][zeroIdx] == -1){ long take = solve(oneIdx+1, zeroIdx+1, ones, zeros) + Math.abs(ones.get(oneIdx) - zeros.get(zeroIdx)); long skip = solve(oneIdx, zeroIdx+1, ones, zeros); dp[oneIdx][zeroIdx] = Math.min(take, skip); } return dp[oneIdx][zeroIdx]; } static int divisors(int x){ int ans = 1; for(int pow: linearPrimeFact(x).values()) ans*= pow+1; return ans; } static int[] least; static TreeSet<Integer> prime; static void linearsieve(int x){ least=new int[x+1]; prime=new TreeSet<Integer>(); for(int i=2; i<=x; i++){ if(least[i]==0){ least[i]=i; prime.add(i); } for(int y :prime) { if(i*y<=x) least[i*y]=y; else break; } } } static TreeMap<Integer, Integer> linearPrimeFact(int x){ TreeMap<Integer, Integer> ans=new TreeMap<>(); while(x>1){ int a=least[x]; int pow=0; while(x%a==0){ x/=a; pow++; } ans.put(a, pow); } return ans; } static void printArr(int[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printArr(long[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printArr(double[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printArr(Integer[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printArr(ArrayList list) { for (int i = 0; i < list.size(); i++) pw.print(list.get(i)+" "); pw.println(); } static void printArr(boolean[] arr) { StringBuilder sb=new StringBuilder(); for(boolean b: arr) sb.append(Int(b)); pw.println(sb); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextDigits() throws IOException{ String s=nextLine(); int[] arr=new int[s.length()]; for(int i=0; i<arr.length; i++) arr[i]=s.charAt(i)-'0'; return arr; } public int[] nextArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextInt(); return arr; } public Integer[] nextsort(int n) throws IOException{ Integer[] arr=new Integer[n]; for(int i=0; i<n; i++) arr[i]=nextInt(); return arr; } public Pair nextPair() throws IOException{ return new Pair(nextInt(), nextInt()); } public long[] nextLongArr(int n) throws IOException{ long[] arr=new long[n]; for (int i = 0; i < n; i++) arr[i]=sc.nextLong(); return arr; } public Pair[] nextPairArr(int n) throws IOException{ Pair[] arr=new Pair[n]; for(int i=0; i<n; i++) arr[i]=nextPair(); return arr; } public boolean hasNext() throws IOException { return (st!=null && st.hasMoreTokens()) || br.ready(); } } static class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } public Pair(Map.Entry<Integer, Integer> a) { x = a.getKey(); y = a.getValue(); } public boolean contains(int a) { return x == a || y == a; } public int hashCode() { return (this.x * 1000000000 + this.y); } public int compareTo(Pair p) { if (x == p.x) return y - p.y; return x - p.x; } public boolean equals(Object obj) { if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Pair p = (Pair) obj; return this.x == p.x && this.y == p.y; } public Pair clone() { return new Pair(x, y); } public String toString() { return this.x + " " + this.y; } public void add(Pair p) { x += p.x; y += p.y; } } static class LP implements Comparable<LP>{ long x, y; public LP(long a, long b){ x=a; y=b; } public void add(LP p){ x+=p.x; y+=p.y; } public boolean equals(LP p){ return p.x==x && y==p.y; } public String toString(){ return this.x+" "+this.y; } public int compareTo(LP p){ int a=Long.compare(x, p.x); if(a!=0) return a; return Long.compare(y, p.y); } } static class Triple implements Comparable<Triple>{ int x, y, z; public Triple(int a, int b, int c){ x=a; y=b; z=c; } public int compareTo(Triple t){ if(this.y!=t.y) return y-t.y; return x-t.x; } public String toString(){ return x+" "+y+" "+z; } public int hashCode(){ return new Pair(x, y).hashCode()*1000000000 + z; } public boolean equals(Object o){ if(o instanceof Triple){ Triple t= (Triple) o; return t.x==x && t.y==y && t.z==z; } return false; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
3065e1ab5551a61f06ce6b53bfa42165
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; public class Longjumps { public static void main(String[] args){ Scanner sc=new Scanner(System.in); ArrayList<Integer> o=new ArrayList<Integer>(), e=new ArrayList<Integer>(); int n = sc.nextInt(); for(int i=1;i<=n;i++){ int x=sc.nextInt(); if(x==1)o.add(i); else e.add(i); } int dp[][]=new int[o.size()+1][e.size()+1]; for(int i=1;i<=o.size();i++){ dp[i][i]=dp[i-1][i-1]+Math.abs(o.get(i-1)-e.get(i-1)); for(int j=i+1;j<=e.size();j++) dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(o.get(i-1)-e.get(j-1))); } System.out.println(dp[o.size()][e.size()]); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
f2fd6cebd16dc1a0a99358c973f4fc5c
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
// Don't place your source in a package import javax.swing.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int T=1; for(int t=0;t<T;t++){ int n=Int(); int A[]=Arr(n); Solution sol=new Solution(out); sol.solution(A); } out.close(); } public static int[] Arr(int n){ int A[]=new int[n]; for(int i=0;i<n;i++)A[i]=Int(); return A; } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution{ PrintWriter out; public Solution(PrintWriter out){ this.out=out; } int INF=Integer.MAX_VALUE; public void solution(int A[]){ List<Integer>one=new ArrayList<>(); List<Integer>zero=new ArrayList<>(); for(int i=0;i<A.length;i++){ if(A[i]==0)zero.add(i); else one.add(i); } int dp[][]=new int[one.size()+1][zero.size()+1]; for(int i=1;i<dp.length;i++){ Arrays.fill(dp[i],INF); } // System.out.println(one+" "+zero); for(int i=1;i<dp.length;i++){ for(int j=i;j<dp[0].length;j++){ dp[i][j]=Math.min(dp[i][j],dp[i-1][j-1]+Math.abs(one.get(i-1)-zero.get(j-1))); dp[i][j]=Math.min(dp[i][j],dp[i][j-1]); } } //for(int p[]:dp){ // System.out.println(Arrays.toString(p)); // } out.println(dp[dp.length-1][dp[0].length-1]); } } /* ;\ |' \ _ ; : ; / `-. /: : | | ,-.`-. ,': : | \ : `. `. ,'-. : | \ ; ; `-.__,' `-.| \ ; ; ::: ,::'`:. `. \ `-. : ` :. `. \ \ \ , ; ,: (\ \ :., :. ,'o)): ` `-. ,/,' ;' ,::"'`.`---' `. `-._ ,/ : ; '" `;' ,--`. ;/ :; ; ,:' ( ,:) ,.,:. ; ,:., ,-._ `. \""'/ '::' `:'` ,'( \`._____.-'"' ;, ; `. `. `._`-. \\ ;:. ;: `-._`-.\ \`. '`:. : |' `. `\ ) \ -hrr- ` ;: | `--\__,' '` ,' ,-' free bug dog */
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
7777b6b4db012852e8d186f5a8a5cfdb
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; public class Solution { static long res; public static void main(String[] args) throws Exception { FastReader fr=new FastReader(); int n=fr.nextInt(); ArrayList<Integer> oc=new ArrayList<>(); ArrayList<Integer> em=new ArrayList<>(); res=Long.MAX_VALUE; for(int i=0;i<n;i++) { int v=fr.nextInt(); if(v==1) oc.add(i); else em.add(i); } Collections.sort(oc); Collections.sort(em); long dp[][]=new long[5001][5001]; for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[i].length;j++) { dp[i][j]=-1; } } System.out.println(getMin(oc,em,0,0,dp)); } public static long getMin(ArrayList<Integer> oc,ArrayList<Integer> em,int idx,int j,long dp[][]) { if(idx==oc.size()) return 0; long available=em.size()-j; long req=oc.size()-idx; if(available<req) return Integer.MAX_VALUE; if(dp[idx][j]!=-1) return dp[idx][j]; long ch1=getMin(oc,em,idx,j+1,dp); long ch2=getMin(oc,em,idx+1,j+1,dp)+Math.abs(em.get(j)-oc.get(idx)); return dp[idx][j]=Math.min(ch1,ch2); } public static String lcs(String a,String b) { int dp[][]=new int[a.length()+1][b.length()+1]; for(int i=0;i<=a.length();i++) { for(int j=0;j<=b.length();j++) { if(i==0||j==0) dp[i][j]=0; } } for(int i=1;i<=a.length();i++) { for(int j=1;j<=b.length();j++) { if(a.charAt(i-1)==b.charAt(j-1)) dp[i][j]=1+dp[i-1][j-1]; else dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]); } } int i=a.length(); int j=b.length(); String lcs=""; while(i>0&&j>0) { if(a.charAt(i-1)==b.charAt(j-1)) { lcs=a.charAt(i-1)+lcs; i--; j--; } else { if(dp[i-1][j]>dp[i][j-1]) i--; else j--; } } return lcs; } public static long facto(long n) { if(n==1||n==0) return 1; return n*facto(n-1); } public static long gcd(long n1,long n2) { if (n2 == 0) { return n1; } return gcd(n2, n1 % n2); } public static boolean isPali(String s) { int i=0; int j=s.length()-1; while(i<=j) { if(s.charAt(i)!=s.charAt(j)) return false; i++; j--; } return true; } public static String reverse(String s) { String res=""; for(int i=0;i<s.length();i++) { res+=s.charAt(i); } return res; } public static int bsearch(long suf[],long val) { int i=0; int j=suf.length-1; while(i<=j) { int mid=(i+j)/2; if(suf[mid]==val) return mid; else if(suf[mid]<val) j=mid-1; else i=mid+1; } return -1; } public static int[] getFreq(String s) { int a[]=new int[26]; for(int i=0;i<s.length();i++) { a[s.charAt(i)-'a']++; } return a; } public static boolean isPrime(int n) { for(int i=2;(i*i)<=n;i++) { if(n%i==0) return false; } return true; } } class Pair{ long i; long j; Pair(long num,long freq){ this.i=num; this.j=freq; } } 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\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
b2b64f13b7c9874b1b75f85c1e37c2ca
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.math.BigInteger; //import static java.lang.Math.max; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Vector; import java.util.Scanner; public class ahh { //trihund static Scanner scn = new Scanner(System.in); static boolean vis[][]; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader s = new FastReader(); static int MOD = 1000000007; public static void main(String[] args) { int n=scn.nextInt(),count=0; int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=scn.nextInt(); } ArrayList<Integer>zer=new ArrayList<Integer>(),one=new ArrayList<Integer>(); for(int i=0;i<n;i++) { if(arr[i]==0) zer.add(i); else one.add(i); } count=one.size(); long memo[][]=new long[one.size()+1][zer.size()+1]; for(int i=0;i<=one.size();i++) { for(int j=0;j<=zer.size();j++) memo[i][j]=-1; } System.out.println(arm(one, zer, 0, 0, count,memo)); } public static long arm(ArrayList<Integer>one,ArrayList<Integer>zer,int i,int j,int count,long memo[][]) { if(count==0) return 0; if(i==one.size()||j==zer.size()) return Integer.MAX_VALUE; if(memo[i][j]!=-1) return memo[i][j]; long a=Integer.MAX_VALUE,b=Integer.MAX_VALUE; a=arm(one, zer, i+1, j+1,count-1,memo)+Math.abs(one.get(i)-zer.get(j)); b=arm(one, zer, i, j+1,count,memo); memo[i][j]=Math.min(a, b); return Math.min(a, b); } public static void fac(int n) { BigInteger b = new BigInteger("1"); for (int i = 1; i <= n; i++) { b = b.multiply(BigInteger.valueOf(i)); } System.out.println(b); } static void ruffleSort(long[] a) { int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n); long temp = a[i]; a[i] = a[oi]; a[oi] = temp; } Arrays.sort(a); } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } } class pm { int ini, fin; pm(int a, int b) { this.ini = a; this.fin = b; } } class surt implements Comparator<pm> { @Override public int compare(pm o1, pm o2) { // TODO Auto-generated method stub int a = o1.ini - o2.ini, b = o1.fin - o2.fin; if (a < 0) return -1; if (a == 0) { if (b < 0) return -1; else return 1; } else return 1; } } class pair { int x, y; pair(int a, int b) { this.x = a; this.y = b; } public int hashCode() { return x * 31 + y * 31; } public boolean equals(Object other) { if (this == other) return true; if (other instanceof pair) { pair pt = (pair) other; return pt.x == this.x && pt.y == this.y; } else return false; } } class sort implements Comparator<pair> { @Override public int compare(pair o1, pair o2) { // TODO Auto-generated method stub long a = o1.x - o2.x, b = o1.y - o2.y; if (b < 0) return -1; else if (a == 0) { if (a < 0) return -1; else return 1; } else return 1; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
9828f1e328fe35b2b24cfba6a8354c13
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*;import java.io.*;import java.math.*; public class CF1525D { static final Random random=new Random(); static boolean memory = true; static void ruffleSort(int[] a) { int n = a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } ArrayList<Integer> lst = new ArrayList<>(); for(int i : a) lst.add(i); Collections.sort(lst); for(int i = 0; i < n; i++) a[i] = lst.get(i); } static void ruffleSort(long[] a) { int n = a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } ArrayList<Long> lst = new ArrayList<>(); for(long i : a) lst.add(i); Collections.sort(lst); for(int i = 0; i < n; i++) a[i] = lst.get(i); } static int[][] dp; static ArrayList<Integer> zero, one; static int solve(int p1, int p0){ if(p1 == one.size()) return 0; if(one.size() - p1 > zero.size() - p0) return Integer.MAX_VALUE; if(dp[p1][p0] != -1) return dp[p1][p0]; return dp[p1][p0] = Math.min(solve(p1, p0+1), Math.abs(zero.get(p0)-one.get(p1)) + solve(p1+1, p0+1)); } public static void process()throws IOException { int n = ni(); int[] a = nai(n); zero = new ArrayList<>(); one = new ArrayList<>(); int c = 0; for(int i : a){ if(i == 0) zero.add(c); else one.add(c); c++; } int p = one.size(), q = zero.size(); dp = new int[p][q]; for(int i = 0; i < p; i++) for(int j = 0; j < q; j++) dp[i][j] = -1; int ans = solve(0, 0); pn(ans); } static AnotherReader sc; static PrintWriter out; public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new CF1525D().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 28).start(); else new CF1525D().run(); } void run()throws Exception { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} long s = System.currentTimeMillis(); int t=1; //t=ni(); //int k = t; while(t-->0) {/*p("Case #"+ (k-t) + ": ")*/;process();} out.flush(); System.err.println(System.currentTimeMillis()-s+"ms"); out.close(); } static long power(long k, long c, long mod){ long y = 1; while(c > 0){ if(c%2 == 1) y = y * k % mod; c = c/2; k = k * k % mod; } return y; } static int power(int x, int y, int p){ int res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static int log2(int N) { int result = (int)(Math.log(N) / Math.log(2)); return result; } static void pn(Object o){out.println(o);} static void pn(int[] a){for(int i : a)out.print(i+" ");pn("");} static void pn(long[] a){for(long i : a)out.print(i+" ");pn("");} static void p(Object o){out.print(o);} static void YES(){out.println("YES");} static void NO(){out.println("NO");} static void yes(){out.println("yes");} static void no(){out.println("no");} static void p(int[] a){for(int i : a)out.print(i+" ");} static void p(long[] a){for(long i : a)out.print(i+" ");} static void pni(Object o){out.println(o);out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static String ns()throws IOException{return sc.next();} static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
9a299d5d4265afbaf0922710d447f56e
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; public class CodeForces1525C{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); ArrayList<Integer> o=new ArrayList<Integer>(), e=new ArrayList<Integer>(); int n = sc.nextInt(),dp[][]=new int[n+1][n+1]; for(int i=1;i<=n;i++){ int x=sc.nextInt(); if(x==1)o.add(i); else e.add(i); } for(int i=1;i<=o.size();i++){ dp[i][i]=dp[i-1][i-1]+Math.abs(o.get(i-1)-e.get(i-1)); for(int j=i+1;j<=e.size();j++) dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(o.get(i-1)-e.get(j-1))); } System.out.println(dp[o.size()][e.size()]); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
c594e7ef93ff166a26b8fed9b46e54f7
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); ArrayList<Integer> pos=new ArrayList<>(n); for(int i=0;i<n;i++) if(a[i]==1) pos.add(i); int k=pos.size(); int[][] dp=new int[n+1][k+1]; for(int i=0;i<n+1;i++) Arrays.fill(dp[i], Integer.MAX_VALUE); dp[0][0]=0; for(int i=0;i<n;i++) for(int j=0;j<=k;j++) { if(dp[i][j]==Integer.MAX_VALUE) continue; dp[i+1][j]=Math.min(dp[i+1][j], dp[i][j]); if(j<k && a[i]==0) dp[i+1][j+1]=Math.min(dp[i+1][j+1], dp[i][j]+Math.abs(pos.get(j)-i)); } System.out.println(dp[n][k]); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
537a0f859241b0f8cd72a2cba7fa80c0
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.Arrays; import java.util.Scanner; public class A { static Scanner scan = new Scanner(System.in); public static void slove(){ int n = scan.nextInt(); int[] a = new int[n+10]; int[] b = new int[n+10]; int[] c = new int[n+10]; int c1 = 1,c2 = 1; for(int i=1;i<=n;i++){ a[i] = scan.nextInt(); if(a[i]==0){ b[c1++] = i; }else{ c[c2++] = i; } } int[][] dp = new int[n+10][n+10]; for(int i=0;i<=n;i++) Arrays.fill(dp[i],0x3f3f3f3f); for(int i=0;i<=n;i++) dp[i][0] = 0; for(int i=1;i<c1;i++){ for(int j=1;j<c2;j++){ dp[i][j] = Math.min(dp[i-1][j],dp[i-1][j-1] + Math.abs(b[i]-c[j])); } } System.out.println(dp[c1-1][c2-1]); } public static void main(String[] args) { // int T = scan.nextInt(); //while(T-->0){ slove(); //} } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
aac9a0c989bbfdfdb6a756fc9e4c6a22
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; import java.math.*; /** * * @Har_Har_Mahadev */ /** * Main , Solution , Remove Public */ public class A { private static long[][] dp; private static ArrayList<Integer> lis1,lis0; public static void process() throws IOException { int n = sc.nextInt(); int arr[] = sc.readArray(n); lis1 = new ArrayList<Integer>(); lis0 = new ArrayList<Integer>(); for(int i = 0; i<n; i++) { if(arr[i] == 1)lis1.add(i+1); else lis0.add(i+1); } Collections.sort(lis0); Collections.sort(lis1); int n0 = lis0.size(); int n1 = lis1.size(); dp = new long[n0+1][n1+1]; for(int i = 0; i<=n0; i++) { Arrays.fill(dp[i], -1); } long ans = solve(0,0,n0,n1); println(ans); } private static long solve(int i, int j, int n0, int n1) { if(j == n1)return 0; if(i == n0)return INF; if(dp[i][j] != -1)return dp[i][j]; long ans = solve(i+1, j, n0, n1); ans = min(ans,abs(lis0.get(i) - lis1.get(j)) + solve(i+1, j+1, n0, n1)); return dp[i][j] = ans; } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; private static void google(int tt) { System.out.print("Case #" + (tt) + ": "); } static FastScanner sc; static PrintWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new PrintWriter(System.out); } else { sc = new FastScanner(100); out = new PrintWriter("output.txt"); } int t = 1; // t = sc.nextInt(); int TTT = 1; while (t-- > 0) { // google(TTT++); process(); } out.flush(); out.close(); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } // @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; // } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static void println(Object o) { out.println(o); } static void println() { out.println(); } static void print(Object o) { out.print(o); } static void pflush(Object o) { out.println(o); out.flush(); } static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static int max(int x, int y) { return Math.max(x, y); } static int min(int x, int y) { return Math.min(x, y); } static int abs(int x) { return Math.abs(x); } static long abs(long x) { return Math.abs(x); } static long sqrt(long z) { long sqz = (long) Math.sqrt(z); while (sqz * 1L * sqz < z) { sqz++; } while (sqz * 1L * sqz > z) { sqz--; } return sqz; } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } static long max(long x, long y) { return Math.max(x, y); } static long min(long x, long y) { return Math.min(x, y); } public static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } public static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(System.in)); } FastScanner(int a) throws FileNotFoundException { br = new BufferedReader(new FileReader("input.txt")); } String next() throws IOException { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) throws IOException { int[] A = new int[n]; for (int i = 0; i != n; i++) { A[i] = sc.nextInt(); } return A; } long[] readArrayLong(int n) throws IOException { long[] A = new long[n]; for (int i = 0; i != n; i++) { A[i] = sc.nextLong(); } return A; } } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
55a4ad8045a8e33bc2aac1aea30aee5b
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public class EdC { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; public static void main(String[] havish) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); int n = sc.nextInt(); int[] arr = readArrayInt(n); int[] prefix = new int[n]; prefix[0] = arr[0]; for(int j = 1;j<n;j++){ prefix[j] = prefix[j-1] + arr[j]; } int[] positions = new int[prefix[n-1]]; int temp = 0; for(int i=0;i<n;i++){ if (arr[i] == 1) { positions[temp] = i; temp++; } } int[][] dp = new int[n][n+1]; //size, number of things to match for(int j = 0;j<n;j++){ Arrays.fill(dp[j], Integer.MAX_VALUE); } for(int j = 0;j<n;j++){ dp[j][0] = 0; } if (arr[0] == 0 && prefix[n-1] > 0) { dp[0][1] = positions[0]; } for(int j = 1;j<n;j++){ int numZeros = j + 1 - prefix[j]; for(int c = 1;c<=prefix[n-1];c++){ if (c > numZeros) continue; dp[j][c] = Math.min(dp[j][c], dp[j-1][c]); if (arr[j] == 0) dp[j][c] = Math.min(dp[j][c], dp[j-1][c-1] + Math.abs(positions[c-1] - j)); } } out.println(dp[n-1][prefix[n-1]]); out.close(); } public static void sort(int[] array){ ArrayList<Integer> copy = new ArrayList<>(); for (int i : array) copy.add(i); Collections.sort(copy); for(int i = 0;i<array.length;i++) array[i] = copy.get(i); } static String[] readArrayString(int n){ String[] array = new String[n]; for(int j =0 ;j<n;j++) array[j] = sc.next(); return array; } static int[] readArrayInt(int n){ int[] array = new int[n]; for(int j = 0;j<n;j++) array[j] = sc.nextInt(); return array; } static int[] readArrayInt1(int n){ int[] array = new int[n+1]; for(int j = 1;j<=n;j++){ array[j] = sc.nextInt(); } return array; } static long[] readArrayLong(int n){ long[] array = new long[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextLong(); return array; } static double[] readArrayDouble(int n){ double[] array = new double[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextDouble(); return array; } static int minIndex(int[] array){ int minValue = Integer.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(long[] array){ long minValue = Long.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(double[] array){ double minValue = Double.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static long power(long x, long y){ if (y == 0) return 1; if (y%2 == 1) return (x*power(x, y-1))%mod; return power((x*x)%mod, y/2)%mod; } static void verdict(boolean a){ out.println(a ? "YES" : "NO"); } 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; } } } //StringJoiner sj = new StringJoiner(" "); //sj.add(strings) //sj.toString() gives string of those stuff w spaces or whatever that sequence is
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
2ac42449d21bd4825208466ae23873db
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; /** * Created by Brandon on 4/29/2021, 11:04 AM. */ public class Main { static long mod = 998244353; public static void solve() { // string: //char** vals = new char* [n]; //for (int i = 0; i < n; i++) { // string str = ""; // cin >> str; // vals[i] = new char[n]; // for (int j = 0; j < n; j++) { // vals[i][j] = str[j]; // } //} int n; Scanner sc = new Scanner(System.in); n = Integer.parseInt(sc.next()); int[] arr = new int[n]; ArrayList<Integer> ones = new ArrayList<>(); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(sc.next()); if (arr[i] == 1) { ones.add(i); } } if (ones.size() == 0) { System.out.println("0\n"); return; } int[] zeroes = new int[n - ones.size()]; int cur = 0; for (int i = 0; i < n; i++) { if (arr[i] == 0) { zeroes[cur] = i; cur++; } } int[][] dp = new int[ones.size()][n-ones.size()]; for (int i = 1; i < ones.size(); i++) { dp[i][0] = 100000000; } dp[0][0] = Math.abs(ones.get(0) - zeroes[0]); for (int i = 1; i < n - ones.size(); i++) { dp[0][i] = Math.min(dp[0][i - 1], Math.abs(ones.get(0) - zeroes[i])); } // dp[i][j] is number where you only have to move first i but max position you can put is j for (int i = 1; i < ones.size(); i++) { for (int j = 1; j < n - ones.size(); j++) { dp[i][j] = Math.min(dp[i][j - 1], dp[i-1][j-1] + Math.abs(zeroes[j] - ones.get(i))); } } System.out.println(dp[ones.size()-1][n-ones.size()-1] + "\n"); } public static void main(String[] args) { solve(); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
ec935aefaa02132a84edce22611a285d
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; public class Main{ static int[][]memo; static int[]z,o; static int dp(int p0,int p1) { if(p1==o.length) { //all ones are matched already return 0; } if(p0==z.length) { //all zeros are finished and there is still unmatched one return 1000000000; } if(memo[p0][p1]!=-1)return memo[p0][p1]; int match=Math.abs(z[p0]-o[p1])+dp(p0+1, p1+1); int dontMatch=dp(p0+1, p1); return memo[p0][p1]=Math.min(match, dontMatch); } static void main() throws Exception{ int n=sc.nextInt(); int[]in=sc.intArr(n); int[]cnt=new int[2]; for(int i=0;i<n;i++) { cnt[in[i]]++; } z=new int[cnt[0]]; o=new int[cnt[1]]; int[]idx=new int[2]; for(int i=0;i<n;i++) { if(in[i]==0) { z[idx[0]++]=i; } else { o[idx[1]++]=i; } } memo=new int[z.length][o.length]; for(int i=0;i<z.length;i++) { for(int j=0;j<o.length;j++)memo[i][j]=-1; } pw.println(dp(0, 0)); } public static void main(String[] args) throws Exception{ sc=new MScanner(System.in); pw = new PrintWriter(System.out); int tc=1; // tc=sc.nextInt(); for(int i=1;i<=tc;i++) { main(); } pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void sort(int[]in) { shuffle(in); Arrays.sort(in); } static void sort(long[]in) { shuffle(in); Arrays.sort(in); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
c8a98fe10ed58c47827b11ffa27521e7
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.awt.Point; public class Main { //static final long MOD = 1000000007L; //static final long MOD2 = 1000000009L; static final long MOD = 998244353L; //static final long INF = 500000000000L; static final int INF = 1000000005; //static final int NINF = -1000000005; //static final long INF = 1000000000000000000L; static FastScanner sc; static PrintWriter pw; static final int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}}; public static void main(String[] args) { sc = new FastScanner(); pw = new PrintWriter(System.out); int N = sc.ni(); ArrayList<Integer> A = new ArrayList<Integer>(); ArrayList<Integer> B = new ArrayList<Integer>(); A.add(Integer.MAX_VALUE); B.add(Integer.MAX_VALUE); for (int i = 0; i < N; i++) { if (sc.ni()==1) { A.add(i); } else { B.add(i); } } int[][] dp = new int[A.size()][B.size()]; for (int i = 0; i < A.size(); i++) { for (int j = 0; j < i; j++) { dp[i][j] = INF; } } for (int i = 1; i < A.size(); i++) { for (int j = i; j < B.size(); j++) { dp[i][j] = Math.abs(A.get(i)-B.get(j))+dp[i-1][j-1]; dp[i][j] = Math.min(dp[i][j],dp[i][j-1]); } } pw.println(dp[A.size()-1][B.size()-1]); pw.close(); } public static long gcd(long a, long b) { if (a < b) return gcd(b,a); if (b == 0) return a; else return gcd(b,a%b); } public static void sort(int[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); int temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } public static void sort(long[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); long temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } //Sort an array (immune to quicksort TLE) public static void sort(int[][] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); int[] temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { return a[0]-b[0]; } }); } public static void sort(long[][] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); long[] temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr, new Comparator<long[]>() { @Override public int compare(long[] a, long[] b) { if (a[0] > b[0]) return 1; else if (a[0] < b[0]) return -1; else return 0; //Ascending order. } }); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[][] graph(int N, int[][] edges) { int[][] graph = new int[N][]; int[] sz = new int[N]; for (int[] e: edges) { sz[e[0]] += 1; sz[e[1]] += 1; } for (int i = 0; i < N; i++) { graph[i] = new int[sz[i]]; } int[] cur = new int[N]; for (int[] e: edges) { graph[e[0]][cur[e[0]]] = e[1]; graph[e[1]][cur[e[1]]] = e[0]; cur[e[0]] += 1; cur[e[1]] += 1; } return graph; } int[] intArray(int N, int mod) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = ni()+mod; return ret; } long nl() { return Long.parseLong(next()); } long[] longArray(int N, long mod) { long[] ret = new long[N]; for (int i = 0; i < N; i++) ret[i] = nl()+mod; return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
25eef509ef7afc65abd1aa00b8459545
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.text.DecimalFormat; import java.util.*; public class Main { private static final long MOD = 1000000007; private static final int MAX_VALUE = 1000000000; public static final DecimalFormat DF_2 = new DecimalFormat("0.0000"); static int[] readArray(int size, InputReader in, boolean subOne) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = in.nextInt() + (subOne ? -1 : 0); } return a; } static class State { private final int[] m; public State(int[] m) { this.m = m; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; State state = (State) o; return m[0] == state.m[0] && m[1] == state.m[1] && m[2] == state.m[2]; } @Override public int hashCode() { return Objects.hash(m[0], m[1], m[2]); } } public static void main(String[] args) throws FileNotFoundException { long startTime = System.currentTimeMillis(); // InputReader in = new InputReader(new FileInputStream("input.txt")); // PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream("boards.out"))); InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = in.nextInt(); int[] a = readArray(n, in, false); int[] dpSuff = new int[n]; Arrays.fill(dpSuff, -1); out.println(solve(0, a, dpSuff)); out.close(); } private static int solve(int from, int[] a, int[] dpSuff) { int n = a.length; if (n == from) { return 0; } if (dpSuff[from] >= 0) { return dpSuff[from]; } if (a[from] == 1) { List<Integer> oneStack = new ArrayList<>(); oneStack.add(from); int i = from + 1; dpSuff[from] = 0; for (; i < n && !oneStack.isEmpty(); i++) { if (a[i] == 1) { oneStack.add(i); } else { int top = oneStack.remove(oneStack.size() - 1); dpSuff[from] += i - top; } } if (oneStack.isEmpty()) { dpSuff[from] += solve(i, a, dpSuff); } else { dpSuff[from] = 1000000000; } } else { List<Integer> zeroStack = new ArrayList<>(); zeroStack.add(from); int ans = 0; dpSuff[from] = 1000000000; for (int i = from + 1; i < n ; i++) { if (a[i] == 0) { zeroStack.add(i); } else { dpSuff[from] = Math.min(dpSuff[from], ans + solve(i, a, dpSuff)); if (!zeroStack.isEmpty()) { int top = zeroStack.remove(zeroStack.size() - 1); ans += i - top; } else { return dpSuff[from]; } } } dpSuff[from] = Math.min(dpSuff[from], ans); } return dpSuff[from]; } private static void outputArray(int[] ans, PrintWriter out, boolean addOne) { StringBuilder str = new StringBuilder(); for (int i = 0; i < ans.length; i++) { long an = ans[i] + (addOne ? 1 : 0); str.append(an); if (i < ans.length - 1) { str.append(" "); } } out.println(str); } private static long fromBinary(int[] binary) { long res = 0; long d = 1; for (int i = 0; i < binary.length; i++) { if (binary[i] == 1) { res = res | d; } d = d << 1; } return res; } private static int[] getBinary(long a, int size) { int[] result = new int[size]; for (int i = 0; i < size; i++) { result[i] = (int) ((a >> i) & 1); } return result; } private 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 String nextString() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public char nextChar() { return next().charAt(0); } public String nextWord() { return next(); } private List<Integer>[] readTree(int n) { return readGraph(n, n - 1); } private List<Integer>[] readGraph(int n, int m) { List<Integer>[] result = new ArrayList[n]; for (int i = 0; i < n; i++) { result[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; result[u].add(v); result[v].add(u); } return result; } private Map<Integer, Integer>[] readWeightedGraph(int n, int m, List<int[]> edges) { Map<Integer, Integer>[] result = new HashMap[n]; for (int i = 0; i < n; i++) { result[i] = new HashMap<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = nextInt(); result[u].put(v, w); result[v].put(u, w); edges.add(new int[]{w, v, u}); } return result; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
e7e5bca63739257b3b0de745cd65850c
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; import java.util.stream.IntStream; public class Main { static long startTime = System.currentTimeMillis(); // for global initializations and methods starts here // global initialisations and methods end here static void run(){ boolean tc = false; AdityaFastIO r = new AdityaFastIO(); //FastReader r = new FastReader(); try (OutputStream out = new BufferedOutputStream(System.out)) { //long startTime = System.currentTimeMillis(); int testcases = tc ? r.ni() : 1; int tcCounter = 1; // Hold Here Sparky------------------->>> // Solution Starts Here start : while (testcases --> 0) { int n = r.ni(); int[] arr = new int[n]; List<Integer> one = new ArrayList<>(); List<Integer> zero = new ArrayList<>(); for (int i = 0; i < n; i++) { arr[i] = r.ni(); if (arr[i] == 1) one.add(i); else zero.add(i); } long[][] dp = new long[n + 2][n + 2]; for (int i = 1; i <= one.size(); i++) dp[i][zero.size() + 1] = (long) (1e15); dp[one.size() + 1][zero.size() + 1] = 0; for (int i = one.size(); i > 0; i--) { for (int j = zero.size(); j > 0; j--) { if (i <= one.size() && j <= zero.size()) dp[i][j] = Math.min(Math.abs(one.get(i - 1) - zero.get(j - 1)) + dp[i + 1][j + 1], dp[i][j + 1]); } } out.write((dp[1][1] + " ").getBytes()); } // Solution Ends Here } catch (IOException e) { e.printStackTrace(); } } static class AdityaFastIO{ final private int BUFFER_SIZE = 1<<16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public BufferedReader br; public StringTokenizer st; public AdityaFastIO() { br = new BufferedReader(new InputStreamReader(System.in)); din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public AdityaFastIO(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String word() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String line() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public String readLine() throws IOException { byte[] buf = new byte[100000001]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int ni() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nl() throws IOException { long ret = 0;byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret;return ret; } public double nd() throws IOException { double ret = 0, div = 1;byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret;return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws Exception {run();} static long mod = 998244353; static long modInv(long base, long e) { long result = 1; base %= mod; while (e>0) { if ((e & 1)>0) result = result * base % mod; base = base * base % mod; e >>= 1; } return result; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String word() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String line() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int ni() { return Integer.parseInt(word()); } long nl() { return Long.parseLong(word()); } double nd() { return Double.parseDouble(word()); } } static int MOD = (int) (1e9 + 7); static long powerLL(long x, long n) { long result = 1; while (n > 0) { if (n % 2 == 1) result = result * x % MOD; n = n / 2;x = x * x % MOD; } return result; } static long powerStrings(int i1, int i2) { String sa = String.valueOf(i1); String sb = String.valueOf(i2); long a = 0, b = 0; for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa.charAt(i) - '0')) % MOD; for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1); return powerLL(a, b); } static long gcd(long a, long b) { if (a == 0) return b;else return gcd(b % a, a); } static long lcm(long a, long b) { return (a * b) / gcd(a, b); } static long lower_bound(List<Long> list, long k) { int s = 0; int e = list.size(); while (s != e) { int mid = (s + e) >> 1; if (list.get(mid) < k) s = mid + 1; else e = mid; } if (s == list.size()) return -1; return s; } static int upper_bound(List<Long> list, long k) { int s = 0; int e = list.size(); while (s != e) { int mid = (s + e) >> 1; if (list.get(mid) <= k) s = mid + 1; else e = mid; } if (s == list.size()) return -1; return s; } static void addEdge(ArrayList<ArrayList<Integer>> graph, int edge1, int edge2) { graph.get(edge1).add(edge2);graph.get(edge2).add(edge1); } public static class Pair implements Comparable<Pair> { int first;int second; public Pair(int first, int second) { this.first = first;this.second = second; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(Pair o) { // TODO Auto-generated method stub if(this.first!=o.first) return (int) (this.first - o.first); else return(int)(this.second-o.second); } } public static class PairC<X,Y> implements Comparable<PairC> { X first;Y second; public PairC(X first, Y second) { this.first = first;this.second = second; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(PairC o) { // TODO Auto-generated method stub return o.compareTo((PairC) first); } } static boolean isCollectionsSorted(List<Long> list) { if (list.size() == 0 || list.size() == 1) return true; for (int i = 1; i < list.size(); i++) if (list.get(i) <= list.get(i - 1)) return false; return true; } static boolean isCollectionsSortedReverseOrder(List<Long> list) { if (list.size() == 0 || list.size() == 1) return true; for (int i = 1; i < list.size(); i++) if (list.get(i) >= list.get(i - 1)) return false; return true; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
f92c0dda278d294b59889e9f2e134809
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public class code{ static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static int GCD(int a, int b) { if (b == 0) return a; return GCD(b, a % b); } public static void main(String[] arg) throws IOException{ //Reader in=new Reader(); Scanner in=new Scanner(System.in); int n=in.nextInt(); int[] arr=new int[n]; ArrayList<Integer> zero=new ArrayList<Integer>(); ArrayList<Integer> one=new ArrayList<Integer>(); for(int i=0;i<n;i++){ arr[i]=in.nextInt(); if(arr[i]==0) zero.add(i); else one.add(i); } if(one.size()==0) { System.out.println(0); } else{ int[][] dp=new int[one.size()][zero.size()]; for(int i=0;i<one.size();i++){ for(int j=0;j<zero.size();j++){ if(i==0 && j==0) dp[i][j]=Math.abs(one.get(i)-zero.get(j)); else if(j==0) dp[i][j]=Integer.MAX_VALUE/2; else if(i==0) dp[i][j]=Math.min(dp[i][j-1],Math.abs(one.get(i)-zero.get(j))); else{ dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(one.get(i)-zero.get(j))); } } } System.out.println(dp[one.size()-1][zero.size()-1]); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
af652ca6c0132ad2a9b0d0562e0a8edf
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public class Main2 { static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){br = new BufferedReader(new InputStreamReader(System.in));} String next(){while (st == null || !st.hasMoreElements()){try{st = new StringTokenizer(br.readLine());} catch (IOException e){e.printStackTrace();}}return st.nextToken();} int nextInt(){ return Integer.parseInt(next());}long nextLong(){return Long.parseLong(next());}double nextDouble(){return Double.parseDouble(next());} String nextLine(){String str = ""; try{str = br.readLine(); } catch (IOException e) {e.printStackTrace();} return str; } } static long mod = 998244353; // static Scanner sc = new Scanner(System.in); static FastReader sc = new FastReader(); static PrintWriter out = new PrintWriter(System.out); public static void main (String[] args) { int t = 1; // t = sc.nextInt(); z : while(t-->0) { int n = sc.nextInt(); int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = sc.nextInt(); List<Integer> a1 = new ArrayList<>(); ArrayList<Integer> a2 = new ArrayList<>(); for (int i = 0; i < n; i++) { if(a[i] == 0) a1.add(i); else a2.add(i); } long dp[][] = new long[n+1][n+1]; for (int i = 0; i <= n; i++) { Arrays.fill(dp[i],-1); } out.write(find(0,0,a1,a2,dp)+"\n"); } out.close(); } private static long find(int i, int j, List<Integer> a1, ArrayList<Integer> a2, long[][] dp) { if(j == a2.size()) return 0; int req = a2.size()-j; int ava = a1.size()-i; if(ava<req) return Integer.MAX_VALUE/2; if(dp[i][j] != -1) return dp[i][j]; long ans1 = find(i+1,j,a1,a2,dp); long ans2 = Math.abs(a1.get(i)-a2.get(j)) + find(i+1,j+1,a1,a2,dp); return dp[i][j] = Math.min(ans1, ans2); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
7e8a24e5f1aa6f577fde6ce43cd5ca12
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pranay2516 */ 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); DArmchairs solver = new DArmchairs(); solver.solve(1, in, out); out.close(); } static class DArmchairs { ArrayList<Integer>[] arr; long[][] dp; public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); int[] a = in.readArray(n); int mx = 5001; dp = new long[mx][mx]; for (int i = 0; i < mx; ++i) { Arrays.fill(dp[i], -1); } arr = new ArrayList[2]; for (int i = 0; i < 2; ++i) { arr[i] = new ArrayList<>(); } for (int i = 0; i < n; ++i) { arr[a[i]].add(i); } out.println(go(0, 0)); } long go(int i, int j) { if (i == arr[1].size()) return 0; if (j == arr[0].size()) return (long) 1e9; if (dp[i][j] != -1) return dp[i][j]; long pick = Math.abs(arr[0].get(j) - arr[1].get(i)) + go(i + 1, j + 1); long leave = go(i, j + 1); dp[i][j] = Math.min(leave, pick); return dp[i][j]; } } 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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] readArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = nextInt(); return array; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
58ebe40bcf186dec2087c4459bbd25ed
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) throws java.io.IOException { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int[] arr=new int[n]; int[][] dp=new int[n][n]; int[][] min=new int[n][n]; ArrayList<Integer> ones=new ArrayList<>(); ArrayList<Integer> zero=new ArrayList<>(); for(int i=0;i<n;++i) { arr[i] = sc.nextInt(); if(arr[i]==1) ones.add(i); else zero.add(i); } for(int i=0;i<n;++i) for(int j=0;j<n;++j) { min[i][j] = Integer.MAX_VALUE; dp[i][j] = Integer.MAX_VALUE; } int len=ones.size(); int zlen=zero.size(); int minn=0; for(int i=0;i<len;++i) { int cur = ones.get(i); for(int j=i;j<zlen;j++) { int curz = zero.get(j); int cost = Math.abs(cur-curz); if(i!=0 && curz-1>=0) { cost+=min[i-1][curz-1]; } dp[i][curz]=cost; } minn=Integer.MAX_VALUE; for(int j=0;j<n;++j) { if(dp[i][j]<minn) minn=dp[i][j]; min[i][j]=minn; } } System.out.println(minn); } } // 1 0 1 1 0 0 1
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
5aab8e23ded1aff86c05230659347c8d
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.List; import java.util.*; public class realfast implements Runnable { private static final int INF = (int) 1e9; long in= 1000000007; long fac[]= new long[1000001]; long inv[]=new long[1000001]; public void solve() throws IOException { //int t = readInt(); int n = readInt(); int arr[]=new int[n+1]; for(int i=1;i<=n;i++) arr[i]=readInt(); ArrayList <Integer> con=new ArrayList<Integer>(); ArrayList <Integer> free=new ArrayList<Integer>(); for(int i=1;i<=n;i++) { if(arr[i]==1) { con.add(i); } else free.add(i); } int c= con.size(); int f= free.size(); int dp[][]=new int[con.size()+1][free.size()+1]; for(int i=1;i<=c;i++) { for(int j=0;j<=f;j++) { dp[i][j]=1000000000; } } for(int i=1;i<=c;i++) { int pal = con.get(i-1); for(int j=1;j<=f;j++) { int val = free.get(j-1); dp[i][j]=dp[i-1][j-1]+Math.abs(pal-val); dp[i][j]=Math.min(dp[i][j],dp[i][j-1]); } } out.println(dp[c][f]); } public void list(ArrayList<edge> odd, int ans[], int x[], int s[], int m , int n) { int stack[]=new int[n+1]; int top=-1; for(int i=0;i<odd.size();i++) { int ind = odd.get(i).u; //out.print(ind+" "); if(s[ind]==1) { top++; stack[top]= ind; } else { if(top==-1||s[stack[top]]==0) { top++; stack[top]= ind; } else { int val = x[ind]-x[stack[top]]; val = val/2; ans[ind]= val; ans[stack[top]]=val; top--; //out.println(val); } } } // out.println(); int start=0; int end = top; while(start<=end-1) { if(s[stack[start]]==0&&s[stack[start+1]]==0) { int val = x[stack[start]]; val = val + (x[stack[start+1]]-x[stack[start]])/2; ans[stack[start]]= val; ans[stack[start+1]]=val; } else break; start=start+2; } while(end-1>=start) { if(s[stack[end-1]]==1&&s[stack[end]]==1) { int val = m- x[stack[end]]; val = val + (x[stack[end]]-x[stack[end-1]])/2; ans[stack[end]]= val; ans[stack[end-1]]=val; } else break; end=end-2; } //out.println(start+" "+end); if(start+1<=end) { int val = Math.max(m-x[stack[end]],x[stack[start]]); int pal= (m- Math.max(m-x[stack[end]],x[stack[start]])+Math.min(m-x[stack[end]],x[stack[start]]))/2; val= val+pal; ans[stack[start]]=val; ans[stack[end]]=val; } } public int value (int seg[], int left , int right ,int index, int l, int r) { if(left>right) { return -100000000; } if(right<l||left>r) return -100000000; if(left>=l&&right<=r) return seg[index]; int mid = left+(right-left)/2; int val = value(seg,left,mid,2*index+1,l,r); int val2 = value(seg,mid+1,right,2*index+2,l,r); return Math.max(val,val2); } public int gcd(int a , int b ) { if(a<b) { int t =a; a=b; b=t; } if(a%b==0) return b ; return gcd(b,a%b); } public long pow(long n , long p,long m) { if(p==0) return 1; long val = pow(n,p/2,m);; val= (val*val)%m; if(p%2==0) return val; else return (val*n)%m; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int u ; int v; int dir; edge(int u, int v, int dir) { this.u=u; this.v=v; this.dir=dir; } public int compareTo(edge e) { return this.v-e.v; } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
b72deeb9f772ce3c47547781cc2b352c
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.InputMismatchException; import java.util.List; public class Main { public static void main(String[] args) { if (args.length > 0 && args[0].toLowerCase().equals("local")) { try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream(new File("output.txt"))); } catch (IOException exc) { } } Task task = new Task(); task.solve(); } public static class Task { static final long MOD = (long) 1e9 + 7; static final PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int[][] dp; List<Integer> ones, zeros; public void solve() { try { Scan sc = new Scan(); int n = (int) sc.scanLong(); int[] arr = new int[n]; ones = new ArrayList<>(); zeros = new ArrayList<>(); for (int i = 0; i < n; ++i) { arr[i] = (int) sc.scanLong(); if (arr[i] == 0) { zeros.add(i); } else { ones.add(i); } } Collections.sort(zeros); Collections.sort(ones); int l = zeros.size(); int m = ones.size(); dp = new int[m][l]; for (int i = 0; i < m; ++i) { Arrays.fill(dp[i], -1); } out.println(solve(m - 1, l - 1)); } finally { out.close(); } } private int solve(int x, int y) { if (x == -1) return 0; if (x > y) { return Integer.MAX_VALUE; } if (dp[x][y] != -1) { return dp[x][y]; } return dp[x][y] = Math.min(Math.abs(ones.get(x) - zeros.get(y)) + solve(x - 1, y - 1), solve(x, y - 1)); } private void debug(Object... x) { StringBuilder sb = new StringBuilder(); for (Object o : x) sb.append(String.valueOf(o)).append(" "); out.println(sb); } } public static class Scan { private byte[] buf = new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in = System.in; } public int scan() { if (total < 0) throw new InputMismatchException(); if (index >= total) { index = 0; try { total = in.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (total <= 0) return -1; } return buf[index++]; } public long scanLong() { long integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } else throw new InputMismatchException(); } return neg * integer; } public double scanDouble() { double doub = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n) && n != '.') { if (n >= '0' && n <= '9') { doub *= 10; doub += n - '0'; n = scan(); } else throw new InputMismatchException(); } if (n == '.') { n = scan(); double temp = 1; while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { temp /= 10; doub += (n - '0') * temp; n = scan(); } else throw new InputMismatchException(); } } return doub * neg; } public String scanString() { StringBuilder sb = new StringBuilder(); int n = scan(); while (isWhiteSpace(n)) n = scan(); while (!isWhiteSpace(n)) { sb.append((char) n); n = scan(); } return sb.toString(); } public char scanChar() { int n = scan(); while (isWhiteSpace(n)) n = scan(); return (char) n; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; return false; } } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
c1e4d73e9237baedb49659860642f207
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class D2 { static int[] a, b; static int[][] dp; static int x, y; static final int INF = (int) 1e9; public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(); x = 0; y = 0; a = new int[n]; b = new int[n]; for (int i = 0; i < n; i++) { int val = in.nextInt(); if (val == 1) { a[x++] = i; } else { b[y++] = i; } } dp = new int[x][y]; for (int[] row : dp) { Arrays.fill(row, -1); } pw.println(solve(0, 0)); pw.close(); } static int solve(int i, int j) { if (i == x) { return 0; } if (j == y) { return INF; } if (dp[i][j] != -1) { return dp[i][j]; } int res = abs(a[i] - b[j]) + solve(i + 1, j + 1); res = min(res, solve(i, j + 1)); return dp[i][j] = res; } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
e51ae3e1f1dd24f566f163af52d542ee
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.util.*; import java.io.*; public class Main { static Reader in = new Reader(System.in); static StringBuilder stringBuilder = new StringBuilder(); public static void main(String[] args) { int t = 1; while (t-- > 0) { int n = in.nextInt(); int[] a = new int[n]; int count = 0; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); if (a[i] == 1) { count ++; } } int[] occ = new int[count]; int[] empty = new int[n - count]; int c = 0, c1 = 0; for (int i = 0; i < n; i++) { if (a[i] == 1) { occ[c++] = i; } else { empty[c1++] = i; } } n = occ.length; int m = empty.length; int[][] dp = new int[n + 1][m + 1]; int[][] min = new int[n + 1][m + 1]; int inf = Integer.MAX_VALUE / 55; for (int i = 0; i <= n; i++) { Arrays.fill(dp[i], inf); Arrays.fill(min[i], inf); } for (int i = 0; i <= m; i++) { dp[0][i] = 0; min[0][i] = 0; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { dp[i][j] = Math.abs(occ[i - 1] - empty[j - 1]) + min[i - 1][j - 1]; min[i][j] = Math.min(min[i][j - 1], dp[i][j]); } } stringBuilder.append(min[n][m]).append("\n"); } System.out.println(stringBuilder); } } class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 8
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
7546324820e5460f98271ed9ada2d0f9
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; /* getOrDefault valueOf char[] arr=st.nextToken().toCharArray(); System.out.println(); List<Integer> l=new ArrayList<>(); List<int[]> l=new ArrayList<>(); Set<Integer> set=new HashSet<>(); Map<Integer,Integer> map=new HashMap<>(); Map<Integer,List<Integer>> map=new HashMap<>(); for(int i=1;i<=n;i++) map.put(i,new ArrayList<>()); Map<Integer,List<int[]>> map=new HashMap<>(); Deque<Integer> d=new ArrayDeque<>(); PriorityQueue<Integer> pq=new PriorityQueue<>(); st = new StringTokenizer(infile.readLine()); int x=Integer.parseInt(st.nextToken()); int y=Integer.parseInt(st.nextToken()); int z=Integer.parseInt(st.nextToken()); */ public class Solution{ //static int[][] dir={{0,1},{0,-1},{1,0},{-1,0}}; //static Map<Integer,Integer> map=new HashMap<>(); //static Map<Integer,List<Integer>> map=new HashMap<>(); //static Map<Integer,List<int[]>> map=new HashMap<>(); //static List<int[]> l=new ArrayList<>(); //static List<Integer> l=new ArrayList<>(); //static PriorityQueue<Integer> pq=new PriorityQueue<>(); //static Deque<Integer> d=new ArrayDeque<>(); //static Set<Integer> set=new HashSet<>(); //static StringBuilder sb=new StringBuilder(); static BufferedReader infile; static StringTokenizer st; public static void main(String []args) throws Exception { /* infile = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(infile.readLine()); int T=Integer.parseInt(st.nextToken()); for(int zz=1;zz<=T;zz++) solve(zz); */ solve(); } public static void solve() throws Exception{ infile = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(infile.readLine()); int n=Integer.parseInt(st.nextToken()); int[] a=new int[n+1]; st = new StringTokenizer(infile.readLine()); int[] free=new int[n+1]; Map<Integer,Integer> mp=new HashMap<>(); int id=0; for(int i=1;i<=n;i++){ a[i]=Integer.parseInt(st.nextToken()); free[i]=free[i-1]; if(a[i]==0) free[i]++; else{ id++; mp.put(id,i); } } long[][] dp=new long[n+1][n+1]; for(int i=0;i<=n;i++){ for(int j=1;j<=n;j++) dp[i][j]=Long.MAX_VALUE/2; } for(int i=1;i<=n;i++){ for(int j=1;j<=Math.min(id,free[i]);j++){ if(a[i]==0){ dp[i][j]=Math.min(dp[i][j],dp[i-1][j]); dp[i][j]=Math.min(dp[i][j],dp[i-1][j-1]+Math.abs(i-mp.get(j))); } else{ dp[i][j]=dp[i-1][j]; } } } long res=Long.MAX_VALUE/2; for(int i=1;i<=n;i++) res=Math.min(res,dp[i][id]); System.out.println(res); } /* public static void solve(int zz) throws Exception{ st = new StringTokenizer(infile.readLine()); int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); //char[] arr=st.nextToken().toCharArray(); System.out.println("Case #"+zz+": "+res); } */ }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 17
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
8fa187e15627049a3364c7fca162e0ef
train_110.jsonl
1621152000
There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
512 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Main { private void solve(InputReader in, PrintWriter pw) { int n = in.nextInt(); int[] a = new int[n]; ArrayList<Integer> g = new ArrayList<>(); for (int i = 0; i < n; i++) { a[i] = in.nextInt(); if (a[i] == 1) { g.add(i); } } int m = g.size(); int[][] f = new int[n + 1][m + 1]; for (int i = 0; i <= n; i++) { Arrays.fill(f[i], 0x3f3f3f3f); } f[0][0] = 0; for (int i = 0; i < n; i++) { for (int j = 0; j <= m; j++) { if (f[i][j] == 0x3f3f3f3f) { continue; } f[i + 1][j] = Math.min(f[i + 1][j], f[i][j]); if (j + 1 <= m && a[i] == 0) { f[i + 1][j + 1] = Math.min(f[i + 1][j + 1], f[i][j] + abs(g.get(j) - i)); } } } pw.println(f[n][m]); pw.close(); } public static void main(String[] args) { new Main().solve(new InputReader(System.in), new PrintWriter(System.out)); } } class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { String str; try { str = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return str; } public boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String nextLine = null; try { nextLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (nextLine == null) { return false; } tokenizer = new StringTokenizer(nextLine); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
2 seconds
["3", "9", "0"]
NoteIn the first test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence: ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes; ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes; ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute; ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.
Java 17
standard input
[ "dp", "flows", "graph matchings", "greedy" ]
ff5abd7dfd6234ddaf0ee7d24e02c404
The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.
1,800
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
standard output
PASSED
b6c05159993399b26fdcf299ebc12271
train_110.jsonl
1621152000
Monocarp plays a computer game called "Goblins and Gnomes". In this game, he manages a large underground city of gnomes and defends it from hordes of goblins.The city consists of $$$n$$$ halls and $$$m$$$ one-directional tunnels connecting them. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall. The city will be attacked by $$$k$$$ waves of goblins; during the $$$i$$$-th wave, $$$i$$$ goblins attack the city. Monocarp's goal is to pass all $$$k$$$ waves.The $$$i$$$-th wave goes as follows: firstly, $$$i$$$ goblins appear in some halls of the city and pillage them; at most one goblin appears in each hall. Then, goblins start moving along the tunnels, pillaging all the halls in their path. Goblins are very greedy and cunning, so they choose their paths so that no two goblins pass through the same hall. Among all possible attack plans, they choose a plan which allows them to pillage the maximum number of halls. After goblins are done pillaging, they leave the city.If all halls are pillaged during the wave — Monocarp loses the game. Otherwise, the city is restored. If some hall is pillaged during a wave, goblins are still interested in pillaging it during the next waves.Before each wave, Monocarp can spend some time preparing to it. Monocarp doesn't have any strict time limits on his preparations (he decides when to call each wave by himself), but the longer he prepares for a wave, the fewer points he gets for passing it. If Monocarp prepares for the $$$i$$$-th wave for $$$t_i$$$ minutes, then he gets $$$\max(0, x_i - t_i \cdot y_i)$$$ points for passing it (obviously, if he doesn't lose in the process).While preparing for a wave, Monocarp can block tunnels. He can spend one minute to either block all tunnels leading from some hall or block all tunnels leading to some hall. If Monocarp blocks a tunnel while preparing for a wave, it stays blocked during the next waves as well.Help Monocarp to defend against all $$$k$$$ waves of goblins and get the maximum possible amount of points!
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { static MyScanner scanner; public static void main(String[] args) { scanner = new MyScanner(); new Main().goblinsAndGnomes(); } private void goblinsAndGnomes() { int n = scanner.nextInt(); int m = scanner.nextInt(); int k = scanner.nextInt(); boolean[][] graph = new boolean[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { graph[i][j] = false; } } for (int i = 0; i < m; i++) { graph[scanner.nextInt() - 1][scanner.nextInt() - 1] = true; } int[] xi = new int[k]; int[] yi = new int[k]; for (int i = 0; i < k; i++) { xi[i] = scanner.nextInt(); yi[i] = scanner.nextInt(); } //ArrayList<Integer> blockedHalls = new ArrayList<>(n); Queue<Integer> blockedHalls = new LinkedList<>(); int maxMatch = maximumMatching(graph); int matching = maxMatch; //System.out.println(maxMatch); while (n - matching <= k) { int index = 0; for (int i = 0; i < n; i++) { boolean[][] testGraph = new boolean[n][]; for (int j = 0; j < n; j++) testGraph[j] = Arrays.copyOf(graph[j], n); for (int j = 0; j < n; j++) testGraph[j][i] = false; if (maximumMatching(testGraph) < matching) index = -(i + 1); testGraph = new boolean[n][]; for (int j = 0; j < n; j++) testGraph[j] = Arrays.copyOf(graph[j], n); for (int j = 0; j < n; j++) testGraph[i][j] = false; if (maximumMatching(testGraph) < matching) index = i + 1; } blockedHalls.offer(index); matching--; boolean left = index > 0; index = Math.abs(index) - 1; for (int i = 0; i < n; i++) { if (left) graph[index][i] = false; else graph[i][index] = false; } } //blockedHalls.forEach(x -> System.out.print(x + " ")); int minMaxMatching = maximumMatching(graph); long[][] points = new long[k + 1][maxMatch + 1]; int[][] result = new int[k + 1][maxMatch + 1]; for (int i = 0; i < k + 1; i++) { for (int j = 0; j < maxMatch + 1; j++) { points[i][j] = Long.MIN_VALUE; } } points[0][maxMatch] = 0; for (int i = 0; i < k; i++) { for (int j = 0; j <= maxMatch; j++) { if (points[i][j] != Long.MIN_VALUE) { for (int l = minMaxMatching; l <= j; l++) { if (i + l + 1 < n) { int t = j - l; long p = Math.max(0, (long) xi[i] - (long) t * yi[i]); if (points[i + 1][l] < points[i][j] + p) { points[i + 1][l] = points[i][j] + p; result[i + 1][l] = j; } } } } } } ArrayList<Integer> finalSequence = new ArrayList<>(); int max = Integer.MIN_VALUE; int current = 0; for (int i = 0; i < maxMatch + 1; i++) { if (points[k][i] > max) { max = (int) points[k][i]; current = i; } } for (int i = k; i > 0; i--) { finalSequence.add(0); for (int j = result[i][current] - 1; j >= current; j--) { if (!blockedHalls.isEmpty()) finalSequence.add(blockedHalls.poll()); } current = result[i][current]; } //System.out.println(blockedHalls.size() + k); System.out.println(finalSequence.size()); ListIterator<Integer> iterator = finalSequence.listIterator(finalSequence.size()); while (iterator.hasPrevious()) { System.out.print(iterator.previous() + " "); } System.out.flush(); } private int maximumMatching(boolean[][] graph) { int n = graph.length; int[] matching = new int[n]; Arrays.fill(matching, -1); int matches = 0; for (int i = 0; i < n; i++) { if (findPath(graph, i, matching, new boolean[n])) matches++; } return matches; } private boolean findPath(boolean[][] graph, int x, int[] matching, boolean[] visited) { visited[x] = true; for (int i = 0; i < matching.length; i++) { int y = matching[i]; if (graph[x][i] && (y == -1 || !visited[y] && findPath(graph, y, matching, visited))) { matching[i] = x; return true; } } return false; } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5 4 4\n1 2\n2 3\n4 3\n5 3\n100 1\n200 5\n10 10\n100 1", "5 4 4\n1 2\n2 3\n4 3\n5 3\n100 100\n200 5\n10 10\n100 1", "5 10 1\n1 2\n1 3\n1 4\n1 5\n5 2\n5 3\n5 4\n4 2\n4 3\n2 3\n100 100"]
4 seconds
["6\n-2 -3 0 0 0 0", "6\n0 -3 0 0 1 0", "6\n1 2 3 4 5 0"]
NoteIn the first example, Monocarp, firstly, block all tunnels going in hall $$$2$$$, secondly — all tunnels going in hall $$$3$$$, and after that calls all waves. He spent two minutes to prepare to wave $$$1$$$, so he gets $$$98$$$ points for it. He didn't prepare after that, that's why he gets maximum scores for each of next waves ($$$200$$$, $$$10$$$ and $$$100$$$). In total, Monocarp earns $$$408$$$ points.In the second example, Monocarp calls for the first wave immediately and gets $$$100$$$ points. Before the second wave he blocks all tunnels going in hall $$$3$$$. He spent one minute preparing to the wave, so he gets $$$195$$$ points. Monocarp didn't prepare for the third wave, so he gets $$$10$$$ points by surviving it. Before the fourth wave he blocks all tunnels going out from hall $$$1$$$. He spent one minute, so he gets $$$99$$$ points for the fourth wave. In total, Monocarp earns $$$404$$$ points.In the third example, it doesn't matter how many minutes Monocarp will spend before the wave, since he won't get any points for it. That's why he decides to block all tunnels in the city, spending $$$5$$$ minutes. He survived the wave though without getting any points.
Java 11
standard input
[ "brute force", "dp", "flows", "graph matchings" ]
3ab4973d5b1c91fb76d5c918551ba9f7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$; $$$0 \le m \le \frac{n(n - 1)}{2}$$$; $$$1 \le k \le n - 1$$$) — the number of halls in the city, the number of tunnels and the number of goblin waves, correspondely. Next $$$m$$$ lines describe tunnels. The $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$). It means that the tunnel goes from hall $$$u_i$$$ to hall $$$v_i$$$. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall. There is at most one tunnel between each pair of halls. Next $$$k$$$ lines describe the scoring system. The $$$i$$$-th line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le 10^9$$$; $$$1 \le y_i \le 10^9$$$). If Monocarp prepares for the $$$i$$$-th wave for $$$t_i$$$ minutes, then he gets $$$\max(0, x_i - t_i \cdot y_i)$$$ points for passing it.
2,800
Print the optimal Monocarp's strategy in the following format: At first, print one integer $$$a$$$ ($$$k \le a \le 2n + k$$$) — the number of actions Monocarp will perform. Next, print actions themselves in the order Monocarp performs them. The $$$i$$$-th action is described by a single integer $$$b_i$$$ ($$$-n \le b_i \le n$$$) using the following format: if $$$b_i &gt; 0$$$ then Monocarp blocks all tunnels going out from the hall $$$b_i$$$; if $$$b_i &lt; 0$$$ then Monocarp blocks all tunnels going into the hall $$$|b_i|$$$; if $$$b_i = 0$$$ then Monocarp calls the next goblin wave. You can't repeat the same block action $$$b_i$$$ several times. Monocarp must survive all waves he calls (goblins shouldn't be able to pillage all halls). Monocarp should call exactly $$$k$$$ waves and earn the maximum possible number of points in total. If there are several optimal strategies — print any of them.
standard output
PASSED
561ba69ec34dd7e1a574dbf48597de4a
train_110.jsonl
1621152000
Monocarp plays a computer game called "Goblins and Gnomes". In this game, he manages a large underground city of gnomes and defends it from hordes of goblins.The city consists of $$$n$$$ halls and $$$m$$$ one-directional tunnels connecting them. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall. The city will be attacked by $$$k$$$ waves of goblins; during the $$$i$$$-th wave, $$$i$$$ goblins attack the city. Monocarp's goal is to pass all $$$k$$$ waves.The $$$i$$$-th wave goes as follows: firstly, $$$i$$$ goblins appear in some halls of the city and pillage them; at most one goblin appears in each hall. Then, goblins start moving along the tunnels, pillaging all the halls in their path. Goblins are very greedy and cunning, so they choose their paths so that no two goblins pass through the same hall. Among all possible attack plans, they choose a plan which allows them to pillage the maximum number of halls. After goblins are done pillaging, they leave the city.If all halls are pillaged during the wave — Monocarp loses the game. Otherwise, the city is restored. If some hall is pillaged during a wave, goblins are still interested in pillaging it during the next waves.Before each wave, Monocarp can spend some time preparing to it. Monocarp doesn't have any strict time limits on his preparations (he decides when to call each wave by himself), but the longer he prepares for a wave, the fewer points he gets for passing it. If Monocarp prepares for the $$$i$$$-th wave for $$$t_i$$$ minutes, then he gets $$$\max(0, x_i - t_i \cdot y_i)$$$ points for passing it (obviously, if he doesn't lose in the process).While preparing for a wave, Monocarp can block tunnels. He can spend one minute to either block all tunnels leading from some hall or block all tunnels leading to some hall. If Monocarp blocks a tunnel while preparing for a wave, it stays blocked during the next waves as well.Help Monocarp to defend against all $$$k$$$ waves of goblins and get the maximum possible amount of points!
512 megabytes
import java.io.*; import java.util.*; public class F { InputStream is; FastWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(), K = ni(); boolean[][] g = new boolean[n][n]; long ina = 0; long outa = 0; for(int i = 0;i < m;i++){ int a = ni()-1, b = ni()-1; g[a][b] = true; ina |= 1L<<a; outa |= 1L<<b; } int[] xs = new int[K]; int[] ys = new int[K]; for(int i = 0;i < K;i++){ xs[i] = ni(); ys[i] = ni(); } int mat = doBipartiteMatchingHK(g); int[] need = new int[n+1]; Deque<Integer> er = new ArrayDeque<>(); outer: while(mat > 0) { for (int i = 0; i < n; i++) { if(ina<<~i>=0)continue; boolean[] temp = new boolean[n]; for (int j = 0; j < n; j++) { temp[j] = g[i][j]; g[i][j] = false; } int nmat = doBipartiteMatchingHK(g); if (nmat < mat) { need[nmat] = need[mat] + 1; mat = nmat; ina ^= 1L<<i; er.add((i+1)); continue outer; } for (int j = 0; j < n; j++) { g[i][j] = temp[j]; } } for (int i = 0; i < n; i++) { if(outa<<~i>=0)continue; boolean[] temp = new boolean[n]; for (int j = 0; j < n; j++) { temp[j] = g[j][i]; g[j][i] = false; } int nmat = doBipartiteMatchingHK(g); if (nmat < mat) { need[nmat] = need[mat] + 1; mat = nmat; outa ^= 1L<<i; er.add(-(i+1)); continue outer; } for (int j = 0; j < n; j++) { g[j][i] = temp[j]; } } for (int i = 0; i < n; i++) { if(ina<<~i>=0)continue; boolean[] temp1 = new boolean[n]; for (int j = 0; j < n; j++) { temp1[j] = g[i][j]; g[i][j] = false; } for(int k = 0;k < n;k++){ if(outa<<~k>=0)continue; boolean[] temp2 = new boolean[n]; for (int j = 0; j < n; j++) { temp2[j] = g[j][k]; g[j][k] = false; } int nmat = doBipartiteMatchingHK(g); if (nmat < mat) { need[nmat] = need[mat] + 2; mat = nmat; ina ^= 1L<<i; outa ^= 1L<<k; er.add((i+1)); er.add(-(k+1)); continue outer; } for (int j = 0; j < n; j++) { g[j][k] = temp2[j]; } } for (int j = 0; j < n; j++) { g[i][j] = temp1[j]; } } assert false; } // n-2-i long[][] dp = new long[K+1][2*n+1]; int[][] prev = new int[K+1][2*n+1]; for(int i = 0;i <= K;i++){ Arrays.fill(dp[i], Long.MIN_VALUE / 2); } dp[0][0] = 0; for(int i = 0;i < K;i++){ for(int j = 0;j <= 2*n;j++){ for(int k = Math.max(j, need[n-2-i]);k <= 2*n;k++){ long nv = dp[i][j] + Math.max(0, xs[i] - (long)ys[i] * (k-j)); if(nv > dp[i+1][k]){ dp[i+1][k] = nv; prev[i+1][k] = j; } } } } long max = -1; int arg = -1; for(int j = 0;j <= 2*n;j++){ if(dp[K][j] > max){ max = dp[K][j]; arg = j; } } Deque<Integer> route = new ArrayDeque<>(); for(int i = K;i >= 1;i--){ route.addFirst(0); int pre = prev[i][arg]; int cha = arg - pre; for(int j = 0;j < cha;j++){ route.addFirst(er.pollLast()); } arg = pre; } // out.println(max); out.println(route.size()); for(int u : route){ out.print(u + " "); } out.println(); } public static int doBipartiteMatchingHK(boolean[][] g) { int n = g.length; if(n == 0)return 0; int m = g[0].length; int[] from = new int[m]; int[] to = new int[n]; Arrays.fill(to, -1); Arrays.fill(from, n); int[] d = new int[n+1]; int mat = 0; while(true){ Arrays.fill(d, -1); int[] q = new int[n]; int r = 0; for(int i = 0;i < n;i++){ if(to[i] == -1){ d[i] = 0; q[r++] = i; } } for(int p = 0;p < r;p++) { int cur = q[p]; for(int adj = 0;adj < m;adj++){ if(g[cur][adj]){ int nex = from[adj]; if(d[nex] == -1) { if(nex != n)q[r++] = nex; d[nex] = d[cur] + 1; } } } } if(d[n] == -1)break; for(int i = 0;i < n;i++){ if(to[i] == -1){ if(dfsHK(d, g, n, m, to, from, i))mat++; } } } return mat; } static boolean dfsHK(int[] d, boolean[][] g, int n, int m, int[] to, int[] from, int cur) { if(cur == n)return true; for(int adj = 0;adj < m;adj++){ if(g[cur][adj]){ int nex = from[adj]; if(d[nex] == d[cur] + 1 && dfsHK(d, g, n, m, to, from, nex)){ to[cur] = adj; from[adj] = cur; return true; } } } d[cur] = -1; return false; } void run() throws Exception { // int n = 50, m = n*(n-1)/2, K = n-1; // Random gen = new Random(); // StringBuilder sb = new StringBuilder(); // sb.append(n + " "); // sb.append(m + " "); // sb.append(K + " "); // for (int i = 0; i < n; i++) { // for(int j = i+1;j < n;j++){ // sb.append((i+1) + " " + (j+1) + "\n"); // } // } // for(int i = 0;i < K;i++){ // sb.append(gen.nextInt(1000000000)+1 + " " + (gen.nextInt(1000000000)+1) + "\n"); // } // INPUT = sb.toString(); is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new FastWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new F().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 int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for(int i = 0;i < n;i++)a[i] = nl(); return a; } private 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[][] nmi(int n, int m) { int[][] map = new int[n][]; for(int i = 0;i < n;i++)map[i] = na(m); return map; } private int ni() { return (int)nl(); } 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(); } } public static class FastWriter { private static final int BUF_SIZE = 1<<13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter(){out = null;} public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if(ptr == BUF_SIZE)innerflush(); return this; } public FastWriter write(char c) { return write((byte)c); } public FastWriter write(char[] s) { for(char c : s){ buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if(x == Integer.MIN_VALUE){ return write((long)x); } if(ptr + 12 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if(x == Long.MIN_VALUE){ return write("" + x); } if(ptr + 21 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if(x < 0){ write('-'); x = -x; } x += Math.pow(10, -precision)/2; // if(x < 0){ x = 0; } write((long)x).write("."); x -= (long)x; for(int i = 0;i < precision;i++){ x *= 10; write((char)('0'+(int)x)); x -= (int)x; } return this; } public FastWriter writeln(char c){ return write(c).writeln(); } public FastWriter writeln(int x){ return write(x).writeln(); } public FastWriter writeln(long x){ return write(x).writeln(); } public FastWriter writeln(double x, int precision){ return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for(int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for(long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte)'\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for(char[] line : map)write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c){ return writeln(c); } public FastWriter println(int x){ return writeln(x); } public FastWriter println(long x){ return writeln(x); } public FastWriter println(double x, int precision){ return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } public void trnz(int... o) { for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" "); System.out.println(); } // print ids which are 1 public void trt(long... o) { Queue<Integer> stands = new ArrayDeque<>(); for(int i = 0;i < o.length;i++){ for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x)); } System.out.println(stands); } public void tf(boolean... r) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } public void tf(boolean[]... b) { for(boolean[] r : b) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } System.out.println(); } public void tf(long[]... b) { if(INPUT.length() != 0) { for (long[] r : b) { for (long x : r) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } System.out.println(); } } public void tf(long... b) { if(INPUT.length() != 0) { for (long x : b) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5 4 4\n1 2\n2 3\n4 3\n5 3\n100 1\n200 5\n10 10\n100 1", "5 4 4\n1 2\n2 3\n4 3\n5 3\n100 100\n200 5\n10 10\n100 1", "5 10 1\n1 2\n1 3\n1 4\n1 5\n5 2\n5 3\n5 4\n4 2\n4 3\n2 3\n100 100"]
4 seconds
["6\n-2 -3 0 0 0 0", "6\n0 -3 0 0 1 0", "6\n1 2 3 4 5 0"]
NoteIn the first example, Monocarp, firstly, block all tunnels going in hall $$$2$$$, secondly — all tunnels going in hall $$$3$$$, and after that calls all waves. He spent two minutes to prepare to wave $$$1$$$, so he gets $$$98$$$ points for it. He didn't prepare after that, that's why he gets maximum scores for each of next waves ($$$200$$$, $$$10$$$ and $$$100$$$). In total, Monocarp earns $$$408$$$ points.In the second example, Monocarp calls for the first wave immediately and gets $$$100$$$ points. Before the second wave he blocks all tunnels going in hall $$$3$$$. He spent one minute preparing to the wave, so he gets $$$195$$$ points. Monocarp didn't prepare for the third wave, so he gets $$$10$$$ points by surviving it. Before the fourth wave he blocks all tunnels going out from hall $$$1$$$. He spent one minute, so he gets $$$99$$$ points for the fourth wave. In total, Monocarp earns $$$404$$$ points.In the third example, it doesn't matter how many minutes Monocarp will spend before the wave, since he won't get any points for it. That's why he decides to block all tunnels in the city, spending $$$5$$$ minutes. He survived the wave though without getting any points.
Java 11
standard input
[ "brute force", "dp", "flows", "graph matchings" ]
3ab4973d5b1c91fb76d5c918551ba9f7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$; $$$0 \le m \le \frac{n(n - 1)}{2}$$$; $$$1 \le k \le n - 1$$$) — the number of halls in the city, the number of tunnels and the number of goblin waves, correspondely. Next $$$m$$$ lines describe tunnels. The $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$). It means that the tunnel goes from hall $$$u_i$$$ to hall $$$v_i$$$. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall. There is at most one tunnel between each pair of halls. Next $$$k$$$ lines describe the scoring system. The $$$i$$$-th line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le 10^9$$$; $$$1 \le y_i \le 10^9$$$). If Monocarp prepares for the $$$i$$$-th wave for $$$t_i$$$ minutes, then he gets $$$\max(0, x_i - t_i \cdot y_i)$$$ points for passing it.
2,800
Print the optimal Monocarp's strategy in the following format: At first, print one integer $$$a$$$ ($$$k \le a \le 2n + k$$$) — the number of actions Monocarp will perform. Next, print actions themselves in the order Monocarp performs them. The $$$i$$$-th action is described by a single integer $$$b_i$$$ ($$$-n \le b_i \le n$$$) using the following format: if $$$b_i &gt; 0$$$ then Monocarp blocks all tunnels going out from the hall $$$b_i$$$; if $$$b_i &lt; 0$$$ then Monocarp blocks all tunnels going into the hall $$$|b_i|$$$; if $$$b_i = 0$$$ then Monocarp calls the next goblin wave. You can't repeat the same block action $$$b_i$$$ several times. Monocarp must survive all waves he calls (goblins shouldn't be able to pillage all halls). Monocarp should call exactly $$$k$$$ waves and earn the maximum possible number of points in total. If there are several optimal strategies — print any of them.
standard output
PASSED
61253c78af366d4c2ab37419bed38c35
train_110.jsonl
1621152000
Monocarp plays a computer game called "Goblins and Gnomes". In this game, he manages a large underground city of gnomes and defends it from hordes of goblins.The city consists of $$$n$$$ halls and $$$m$$$ one-directional tunnels connecting them. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall. The city will be attacked by $$$k$$$ waves of goblins; during the $$$i$$$-th wave, $$$i$$$ goblins attack the city. Monocarp's goal is to pass all $$$k$$$ waves.The $$$i$$$-th wave goes as follows: firstly, $$$i$$$ goblins appear in some halls of the city and pillage them; at most one goblin appears in each hall. Then, goblins start moving along the tunnels, pillaging all the halls in their path. Goblins are very greedy and cunning, so they choose their paths so that no two goblins pass through the same hall. Among all possible attack plans, they choose a plan which allows them to pillage the maximum number of halls. After goblins are done pillaging, they leave the city.If all halls are pillaged during the wave — Monocarp loses the game. Otherwise, the city is restored. If some hall is pillaged during a wave, goblins are still interested in pillaging it during the next waves.Before each wave, Monocarp can spend some time preparing to it. Monocarp doesn't have any strict time limits on his preparations (he decides when to call each wave by himself), but the longer he prepares for a wave, the fewer points he gets for passing it. If Monocarp prepares for the $$$i$$$-th wave for $$$t_i$$$ minutes, then he gets $$$\max(0, x_i - t_i \cdot y_i)$$$ points for passing it (obviously, if he doesn't lose in the process).While preparing for a wave, Monocarp can block tunnels. He can spend one minute to either block all tunnels leading from some hall or block all tunnels leading to some hall. If Monocarp blocks a tunnel while preparing for a wave, it stays blocked during the next waves as well.Help Monocarp to defend against all $$$k$$$ waves of goblins and get the maximum possible amount of points!
512 megabytes
import java.io.*; import java.util.*; public class F { InputStream is; FastWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(), K = ni(); boolean[][] g = new boolean[n][n]; long ina = 0; long outa = 0; for(int i = 0;i < m;i++){ int a = ni()-1, b = ni()-1; g[a][b] = true; ina |= 1L<<a; outa |= 1L<<b; } int[] xs = new int[K]; int[] ys = new int[K]; for(int i = 0;i < K;i++){ xs[i] = ni(); ys[i] = ni(); } int mat = doBipartiteMatchingHK(g); int[] need = new int[n+1]; Deque<Integer> er = new ArrayDeque<>(); outer: while(mat > 0) { for (int i = 0; i < n; i++) { if(ina<<~i>=0)continue; boolean[] temp = new boolean[n]; for (int j = 0; j < n; j++) { temp[j] = g[i][j]; g[i][j] = false; } int nmat = doBipartiteMatchingHK(g); if (nmat < mat) { need[nmat] = need[mat] + 1; mat = nmat; ina ^= 1L<<i; er.add((i+1)); continue outer; } for (int j = 0; j < n; j++) { g[i][j] = temp[j]; } } for (int i = 0; i < n; i++) { if(outa<<~i>=0)continue; boolean[] temp = new boolean[n]; for (int j = 0; j < n; j++) { temp[j] = g[j][i]; g[j][i] = false; } int nmat = doBipartiteMatchingHK(g); if (nmat < mat) { need[nmat] = need[mat] + 1; mat = nmat; outa ^= 1L<<i; er.add(-(i+1)); continue outer; } for (int j = 0; j < n; j++) { g[j][i] = temp[j]; } } for (int i = 0; i < n; i++) { if(ina<<~i>=0)continue; boolean[] temp1 = new boolean[n]; for (int j = 0; j < n; j++) { temp1[j] = g[i][j]; g[i][j] = false; } for(int k = 0;k < n;k++){ if(outa<<~k>=0)continue; boolean[] temp2 = new boolean[n]; for (int j = 0; j < n; j++) { temp2[j] = g[j][k]; g[j][k] = false; } int nmat = doBipartiteMatchingHK(g); if (nmat < mat) { need[nmat] = need[mat] + 2; mat = nmat; ina ^= 1L<<i; outa ^= 1L<<k; er.add((i+1)); er.add(-(k+1)); continue outer; } for (int j = 0; j < n; j++) { g[j][k] = temp2[j]; } } for (int j = 0; j < n; j++) { g[i][j] = temp1[j]; } } assert false; } // n-2-i long[][] dp = new long[K+1][2*n+1]; int[][] prev = new int[K+1][2*n+1]; for(int i = 0;i <= K;i++){ Arrays.fill(dp[i], Long.MIN_VALUE / 2); } dp[0][0] = 0; for(int i = 0;i < K;i++){ for(int j = 0;j <= 2*n;j++){ for(int k = Math.max(j, need[n-2-i]);k <= 2*n;k++){ long nv = dp[i][j] + Math.max(0, xs[i] - (long)ys[i] * (k-j)); if(nv > dp[i+1][k]){ dp[i+1][k] = nv; prev[i+1][k] = j; } } } } long max = -1; int arg = -1; for(int j = 0;j <= 2*n;j++){ if(dp[K][j] > max){ max = dp[K][j]; arg = j; } } Deque<Integer> route = new ArrayDeque<>(); for(int i = K;i >= 1;i--){ route.addFirst(0); int pre = prev[i][arg]; int cha = arg - pre; for(int j = 0;j < cha;j++){ route.addFirst(er.pollLast()); } arg = pre; } // out.println(max); out.println(route.size()); for(int u : route){ out.print(u + " "); } out.println(); } public static int doBipartiteMatchingHK(boolean[][] g) { int n = g.length; if(n == 0)return 0; int m = g[0].length; int[] from = new int[m]; int[] to = new int[n]; Arrays.fill(to, -1); Arrays.fill(from, n); int[] d = new int[n+1]; int mat = 0; while(true){ Arrays.fill(d, -1); int[] q = new int[n]; int r = 0; for(int i = 0;i < n;i++){ if(to[i] == -1){ d[i] = 0; q[r++] = i; } } for(int p = 0;p < r;p++) { int cur = q[p]; for(int adj = 0;adj < m;adj++){ if(g[cur][adj]){ int nex = from[adj]; if(d[nex] == -1) { if(nex != n)q[r++] = nex; d[nex] = d[cur] + 1; } } } } if(d[n] == -1)break; for(int i = 0;i < n;i++){ if(to[i] == -1){ if(dfsHK(d, g, n, m, to, from, i))mat++; } } } return mat; } static boolean dfsHK(int[] d, boolean[][] g, int n, int m, int[] to, int[] from, int cur) { if(cur == n)return true; for(int adj = 0;adj < m;adj++){ if(g[cur][adj]){ int nex = from[adj]; if(d[nex] == d[cur] + 1 && dfsHK(d, g, n, m, to, from, nex)){ to[cur] = adj; from[adj] = cur; return true; } } } d[cur] = -1; return false; } void run() throws Exception { // int n = 50, m = n*(n-1)/2, K = n-1; // Random gen = new Random(); // StringBuilder sb = new StringBuilder(); // sb.append(n + " "); // sb.append(m + " "); // sb.append(K + " "); // for (int i = 0; i < n; i++) { // for(int j = i+1;j < n;j++){ // sb.append((i+1) + " " + (j+1) + "\n"); // } // } // for(int i = 0;i < K;i++){ // sb.append(gen.nextInt(1000000000)+1 + " " + (gen.nextInt(1000000000)+1) + "\n"); // } // INPUT = sb.toString(); is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new FastWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new F().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 int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for(int i = 0;i < n;i++)a[i] = nl(); return a; } private 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[][] nmi(int n, int m) { int[][] map = new int[n][]; for(int i = 0;i < n;i++)map[i] = na(m); return map; } private int ni() { return (int)nl(); } 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(); } } public static class FastWriter { private static final int BUF_SIZE = 1<<13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter(){out = null;} public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if(ptr == BUF_SIZE)innerflush(); return this; } public FastWriter write(char c) { return write((byte)c); } public FastWriter write(char[] s) { for(char c : s){ buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if(x == Integer.MIN_VALUE){ return write((long)x); } if(ptr + 12 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if(x == Long.MIN_VALUE){ return write("" + x); } if(ptr + 21 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if(x < 0){ write('-'); x = -x; } x += Math.pow(10, -precision)/2; // if(x < 0){ x = 0; } write((long)x).write("."); x -= (long)x; for(int i = 0;i < precision;i++){ x *= 10; write((char)('0'+(int)x)); x -= (int)x; } return this; } public FastWriter writeln(char c){ return write(c).writeln(); } public FastWriter writeln(int x){ return write(x).writeln(); } public FastWriter writeln(long x){ return write(x).writeln(); } public FastWriter writeln(double x, int precision){ return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for(int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for(long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte)'\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for(char[] line : map)write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c){ return writeln(c); } public FastWriter println(int x){ return writeln(x); } public FastWriter println(long x){ return writeln(x); } public FastWriter println(double x, int precision){ return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } public void trnz(int... o) { for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" "); System.out.println(); } // print ids which are 1 public void trt(long... o) { Queue<Integer> stands = new ArrayDeque<>(); for(int i = 0;i < o.length;i++){ for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x)); } System.out.println(stands); } public void tf(boolean... r) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } public void tf(boolean[]... b) { for(boolean[] r : b) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } System.out.println(); } public void tf(long[]... b) { if(INPUT.length() != 0) { for (long[] r : b) { for (long x : r) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } System.out.println(); } } public void tf(long... b) { if(INPUT.length() != 0) { for (long x : b) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5 4 4\n1 2\n2 3\n4 3\n5 3\n100 1\n200 5\n10 10\n100 1", "5 4 4\n1 2\n2 3\n4 3\n5 3\n100 100\n200 5\n10 10\n100 1", "5 10 1\n1 2\n1 3\n1 4\n1 5\n5 2\n5 3\n5 4\n4 2\n4 3\n2 3\n100 100"]
4 seconds
["6\n-2 -3 0 0 0 0", "6\n0 -3 0 0 1 0", "6\n1 2 3 4 5 0"]
NoteIn the first example, Monocarp, firstly, block all tunnels going in hall $$$2$$$, secondly — all tunnels going in hall $$$3$$$, and after that calls all waves. He spent two minutes to prepare to wave $$$1$$$, so he gets $$$98$$$ points for it. He didn't prepare after that, that's why he gets maximum scores for each of next waves ($$$200$$$, $$$10$$$ and $$$100$$$). In total, Monocarp earns $$$408$$$ points.In the second example, Monocarp calls for the first wave immediately and gets $$$100$$$ points. Before the second wave he blocks all tunnels going in hall $$$3$$$. He spent one minute preparing to the wave, so he gets $$$195$$$ points. Monocarp didn't prepare for the third wave, so he gets $$$10$$$ points by surviving it. Before the fourth wave he blocks all tunnels going out from hall $$$1$$$. He spent one minute, so he gets $$$99$$$ points for the fourth wave. In total, Monocarp earns $$$404$$$ points.In the third example, it doesn't matter how many minutes Monocarp will spend before the wave, since he won't get any points for it. That's why he decides to block all tunnels in the city, spending $$$5$$$ minutes. He survived the wave though without getting any points.
Java 11
standard input
[ "brute force", "dp", "flows", "graph matchings" ]
3ab4973d5b1c91fb76d5c918551ba9f7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$; $$$0 \le m \le \frac{n(n - 1)}{2}$$$; $$$1 \le k \le n - 1$$$) — the number of halls in the city, the number of tunnels and the number of goblin waves, correspondely. Next $$$m$$$ lines describe tunnels. The $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$). It means that the tunnel goes from hall $$$u_i$$$ to hall $$$v_i$$$. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall. There is at most one tunnel between each pair of halls. Next $$$k$$$ lines describe the scoring system. The $$$i$$$-th line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le 10^9$$$; $$$1 \le y_i \le 10^9$$$). If Monocarp prepares for the $$$i$$$-th wave for $$$t_i$$$ minutes, then he gets $$$\max(0, x_i - t_i \cdot y_i)$$$ points for passing it.
2,800
Print the optimal Monocarp's strategy in the following format: At first, print one integer $$$a$$$ ($$$k \le a \le 2n + k$$$) — the number of actions Monocarp will perform. Next, print actions themselves in the order Monocarp performs them. The $$$i$$$-th action is described by a single integer $$$b_i$$$ ($$$-n \le b_i \le n$$$) using the following format: if $$$b_i &gt; 0$$$ then Monocarp blocks all tunnels going out from the hall $$$b_i$$$; if $$$b_i &lt; 0$$$ then Monocarp blocks all tunnels going into the hall $$$|b_i|$$$; if $$$b_i = 0$$$ then Monocarp calls the next goblin wave. You can't repeat the same block action $$$b_i$$$ several times. Monocarp must survive all waves he calls (goblins shouldn't be able to pillage all halls). Monocarp should call exactly $$$k$$$ waves and earn the maximum possible number of points in total. If there are several optimal strategies — print any of them.
standard output
PASSED
1c9edae212e17a14471c10e0781a9146
train_110.jsonl
1621152000
Monocarp plays a computer game called "Goblins and Gnomes". In this game, he manages a large underground city of gnomes and defends it from hordes of goblins.The city consists of $$$n$$$ halls and $$$m$$$ one-directional tunnels connecting them. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall. The city will be attacked by $$$k$$$ waves of goblins; during the $$$i$$$-th wave, $$$i$$$ goblins attack the city. Monocarp's goal is to pass all $$$k$$$ waves.The $$$i$$$-th wave goes as follows: firstly, $$$i$$$ goblins appear in some halls of the city and pillage them; at most one goblin appears in each hall. Then, goblins start moving along the tunnels, pillaging all the halls in their path. Goblins are very greedy and cunning, so they choose their paths so that no two goblins pass through the same hall. Among all possible attack plans, they choose a plan which allows them to pillage the maximum number of halls. After goblins are done pillaging, they leave the city.If all halls are pillaged during the wave — Monocarp loses the game. Otherwise, the city is restored. If some hall is pillaged during a wave, goblins are still interested in pillaging it during the next waves.Before each wave, Monocarp can spend some time preparing to it. Monocarp doesn't have any strict time limits on his preparations (he decides when to call each wave by himself), but the longer he prepares for a wave, the fewer points he gets for passing it. If Monocarp prepares for the $$$i$$$-th wave for $$$t_i$$$ minutes, then he gets $$$\max(0, x_i - t_i \cdot y_i)$$$ points for passing it (obviously, if he doesn't lose in the process).While preparing for a wave, Monocarp can block tunnels. He can spend one minute to either block all tunnels leading from some hall or block all tunnels leading to some hall. If Monocarp blocks a tunnel while preparing for a wave, it stays blocked during the next waves as well.Help Monocarp to defend against all $$$k$$$ waves of goblins and get the maximum possible amount of points!
512 megabytes
//package ecr109; import java.io.*; import java.util.*; public class F { InputStream is; FastWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(), K = ni(); boolean[][] g = new boolean[n][n]; long ina = 0; long outa = 0; for(int i = 0;i < m;i++){ int a = ni()-1, b = ni()-1; g[a][b] = true; ina |= 1L<<a; outa |= 1L<<b; } int[] xs = new int[K]; int[] ys = new int[K]; for(int i = 0;i < K;i++){ xs[i] = ni(); ys[i] = ni(); } int mat = doBipartiteMatchingHK(g); int[] need = new int[n+1]; Deque<Integer> er = new ArrayDeque<>(); outer: while(mat > 0) { for (int i = 0; i < n; i++) { if(ina<<~i>=0)continue; boolean[] temp = new boolean[n]; for (int j = 0; j < n; j++) { temp[j] = g[i][j]; g[i][j] = false; } int nmat = doBipartiteMatchingHK(g); if (nmat < mat) { need[nmat] = need[mat] + 1; mat = nmat; ina ^= 1L<<i; er.add((i+1)); continue outer; } for (int j = 0; j < n; j++) { g[i][j] = temp[j]; } } for (int i = 0; i < n; i++) { if(outa<<~i>=0)continue; boolean[] temp = new boolean[n]; for (int j = 0; j < n; j++) { temp[j] = g[j][i]; g[j][i] = false; } int nmat = doBipartiteMatchingHK(g); if (nmat < mat) { need[nmat] = need[mat] + 1; mat = nmat; outa ^= 1L<<i; er.add(-(i+1)); continue outer; } for (int j = 0; j < n; j++) { g[j][i] = temp[j]; } } for (int i = 0; i < n; i++) { if(ina<<~i>=0)continue; boolean[] temp1 = new boolean[n]; for (int j = 0; j < n; j++) { temp1[j] = g[i][j]; g[i][j] = false; } for(int k = 0;k < n;k++){ if(outa<<~k>=0)continue; boolean[] temp2 = new boolean[n]; for (int j = 0; j < n; j++) { temp2[j] = g[j][k]; g[j][k] = false; } int nmat = doBipartiteMatchingHK(g); if (nmat < mat) { need[nmat] = need[mat] + 2; mat = nmat; ina ^= 1L<<i; outa ^= 1L<<k; er.add((i+1)); er.add(-(k+1)); continue outer; } for (int j = 0; j < n; j++) { g[j][k] = temp2[j]; } } for (int j = 0; j < n; j++) { g[i][j] = temp1[j]; } } assert false; } // n-2-i long[][] dp = new long[K+1][2*n+1]; int[][] prev = new int[K+1][2*n+1]; for(int i = 0;i <= K;i++){ Arrays.fill(dp[i], Long.MIN_VALUE / 2); } dp[0][0] = 0; for(int i = 0;i < K;i++){ for(int j = 0;j <= 2*n;j++){ for(int k = Math.max(j, need[n-2-i]);k <= 2*n;k++){ long nv = dp[i][j] + Math.max(0, xs[i] - (long)ys[i] * (k-j)); if(nv > dp[i+1][k]){ dp[i+1][k] = nv; prev[i+1][k] = j; } } } } long max = -1; int arg = -1; for(int j = 0;j <= 2*n;j++){ if(dp[K][j] > max){ max = dp[K][j]; arg = j; } } Deque<Integer> route = new ArrayDeque<>(); for(int i = K;i >= 1;i--){ route.addFirst(0); int pre = prev[i][arg]; int cha = arg - pre; for(int j = 0;j < cha;j++){ route.addFirst(er.pollLast()); } arg = pre; } // out.println(max); out.println(route.size()); for(int u : route){ out.print(u + " "); } out.println(); } public static int doBipartiteMatchingHK(boolean[][] g) { int n = g.length; if(n == 0)return 0; int m = g[0].length; int[] from = new int[m]; int[] to = new int[n]; Arrays.fill(to, -1); Arrays.fill(from, n); int[] d = new int[n+1]; int mat = 0; while(true){ Arrays.fill(d, -1); int[] q = new int[n]; int r = 0; for(int i = 0;i < n;i++){ if(to[i] == -1){ d[i] = 0; q[r++] = i; } } for(int p = 0;p < r;p++) { int cur = q[p]; for(int adj = 0;adj < m;adj++){ if(g[cur][adj]){ int nex = from[adj]; if(d[nex] == -1) { if(nex != n)q[r++] = nex; d[nex] = d[cur] + 1; } } } } if(d[n] == -1)break; for(int i = 0;i < n;i++){ if(to[i] == -1){ if(dfsHK(d, g, n, m, to, from, i))mat++; } } } return mat; } static boolean dfsHK(int[] d, boolean[][] g, int n, int m, int[] to, int[] from, int cur) { if(cur == n)return true; for(int adj = 0;adj < m;adj++){ if(g[cur][adj]){ int nex = from[adj]; if(d[nex] == d[cur] + 1 && dfsHK(d, g, n, m, to, from, nex)){ to[cur] = adj; from[adj] = cur; return true; } } } d[cur] = -1; return false; } void run() throws Exception { // int n = 50, m = n*(n-1)/2, K = n-1; // Random gen = new Random(); // StringBuilder sb = new StringBuilder(); // sb.append(n + " "); // sb.append(m + " "); // sb.append(K + " "); // for (int i = 0; i < n; i++) { // for(int j = i+1;j < n;j++){ // sb.append((i+1) + " " + (j+1) + "\n"); // } // } // for(int i = 0;i < K;i++){ // sb.append(gen.nextInt(1000000000)+1 + " " + (gen.nextInt(1000000000)+1) + "\n"); // } // INPUT = sb.toString(); is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new FastWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new F().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 int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for(int i = 0;i < n;i++)a[i] = nl(); return a; } private 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[][] nmi(int n, int m) { int[][] map = new int[n][]; for(int i = 0;i < n;i++)map[i] = na(m); return map; } private int ni() { return (int)nl(); } 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(); } } public static class FastWriter { private static final int BUF_SIZE = 1<<13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter(){out = null;} public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if(ptr == BUF_SIZE)innerflush(); return this; } public FastWriter write(char c) { return write((byte)c); } public FastWriter write(char[] s) { for(char c : s){ buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if(x == Integer.MIN_VALUE){ return write((long)x); } if(ptr + 12 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if(x == Long.MIN_VALUE){ return write("" + x); } if(ptr + 21 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if(x < 0){ write('-'); x = -x; } x += Math.pow(10, -precision)/2; // if(x < 0){ x = 0; } write((long)x).write("."); x -= (long)x; for(int i = 0;i < precision;i++){ x *= 10; write((char)('0'+(int)x)); x -= (int)x; } return this; } public FastWriter writeln(char c){ return write(c).writeln(); } public FastWriter writeln(int x){ return write(x).writeln(); } public FastWriter writeln(long x){ return write(x).writeln(); } public FastWriter writeln(double x, int precision){ return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for(int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for(long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte)'\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for(char[] line : map)write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c){ return writeln(c); } public FastWriter println(int x){ return writeln(x); } public FastWriter println(long x){ return writeln(x); } public FastWriter println(double x, int precision){ return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } public void trnz(int... o) { for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" "); System.out.println(); } // print ids which are 1 public void trt(long... o) { Queue<Integer> stands = new ArrayDeque<>(); for(int i = 0;i < o.length;i++){ for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x)); } System.out.println(stands); } public void tf(boolean... r) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } public void tf(boolean[]... b) { for(boolean[] r : b) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } System.out.println(); } public void tf(long[]... b) { if(INPUT.length() != 0) { for (long[] r : b) { for (long x : r) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } System.out.println(); } } public void tf(long... b) { if(INPUT.length() != 0) { for (long x : b) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5 4 4\n1 2\n2 3\n4 3\n5 3\n100 1\n200 5\n10 10\n100 1", "5 4 4\n1 2\n2 3\n4 3\n5 3\n100 100\n200 5\n10 10\n100 1", "5 10 1\n1 2\n1 3\n1 4\n1 5\n5 2\n5 3\n5 4\n4 2\n4 3\n2 3\n100 100"]
4 seconds
["6\n-2 -3 0 0 0 0", "6\n0 -3 0 0 1 0", "6\n1 2 3 4 5 0"]
NoteIn the first example, Monocarp, firstly, block all tunnels going in hall $$$2$$$, secondly — all tunnels going in hall $$$3$$$, and after that calls all waves. He spent two minutes to prepare to wave $$$1$$$, so he gets $$$98$$$ points for it. He didn't prepare after that, that's why he gets maximum scores for each of next waves ($$$200$$$, $$$10$$$ and $$$100$$$). In total, Monocarp earns $$$408$$$ points.In the second example, Monocarp calls for the first wave immediately and gets $$$100$$$ points. Before the second wave he blocks all tunnels going in hall $$$3$$$. He spent one minute preparing to the wave, so he gets $$$195$$$ points. Monocarp didn't prepare for the third wave, so he gets $$$10$$$ points by surviving it. Before the fourth wave he blocks all tunnels going out from hall $$$1$$$. He spent one minute, so he gets $$$99$$$ points for the fourth wave. In total, Monocarp earns $$$404$$$ points.In the third example, it doesn't matter how many minutes Monocarp will spend before the wave, since he won't get any points for it. That's why he decides to block all tunnels in the city, spending $$$5$$$ minutes. He survived the wave though without getting any points.
Java 11
standard input
[ "brute force", "dp", "flows", "graph matchings" ]
3ab4973d5b1c91fb76d5c918551ba9f7
The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$; $$$0 \le m \le \frac{n(n - 1)}{2}$$$; $$$1 \le k \le n - 1$$$) — the number of halls in the city, the number of tunnels and the number of goblin waves, correspondely. Next $$$m$$$ lines describe tunnels. The $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$). It means that the tunnel goes from hall $$$u_i$$$ to hall $$$v_i$$$. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall. There is at most one tunnel between each pair of halls. Next $$$k$$$ lines describe the scoring system. The $$$i$$$-th line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le 10^9$$$; $$$1 \le y_i \le 10^9$$$). If Monocarp prepares for the $$$i$$$-th wave for $$$t_i$$$ minutes, then he gets $$$\max(0, x_i - t_i \cdot y_i)$$$ points for passing it.
2,800
Print the optimal Monocarp's strategy in the following format: At first, print one integer $$$a$$$ ($$$k \le a \le 2n + k$$$) — the number of actions Monocarp will perform. Next, print actions themselves in the order Monocarp performs them. The $$$i$$$-th action is described by a single integer $$$b_i$$$ ($$$-n \le b_i \le n$$$) using the following format: if $$$b_i &gt; 0$$$ then Monocarp blocks all tunnels going out from the hall $$$b_i$$$; if $$$b_i &lt; 0$$$ then Monocarp blocks all tunnels going into the hall $$$|b_i|$$$; if $$$b_i = 0$$$ then Monocarp calls the next goblin wave. You can't repeat the same block action $$$b_i$$$ several times. Monocarp must survive all waves he calls (goblins shouldn't be able to pillage all halls). Monocarp should call exactly $$$k$$$ waves and earn the maximum possible number of points in total. If there are several optimal strategies — print any of them.
standard output
PASSED
b4f8a8be58e8d919db9bfc4972ae7f88
train_110.jsonl
1621152000
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.Monocarp's empire has $$$n$$$ cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.Monocarp has $$$m$$$ points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most $$$1$$$ to this city. Next turn, the Monument controls all points at distance at most $$$2$$$, the turn after — at distance at most $$$3$$$, and so on. Monocarp will build $$$n$$$ Monuments in $$$n$$$ turns and his empire will conquer all points that are controlled by at least one Monument.Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among $$$m$$$ of them) he will conquer at the end of turn number $$$n$$$. Help him to calculate the expected number of conquered points!
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class e1525 { public static void main(String[] args) { Scanner s = new Scanner(System.in); init(20); solve(s.nextInt(), s.nextInt(), s); } static long fact[]; static void init(int l) { fact = new long[l + 1]; fact[0] = 1; for (int i = 1; i <= l; i++) { fact[i] = (fact[i - 1] * i) % mod; } } static long inv(long a) { if (a == 1) return 1; return inv(mod%a) * (mod - mod/a) % mod; } public static long mod = 998244353; public static void solve(int c, int m, Scanner s) { long count = 0; int input[][] = new int[m][c]; for (int i = 0; i < c; i++) { for (int j = 0; j < m; j++) { input[j][i] = s.nextInt(); } } for (int i = 0; i < m; i++) { count = (count + expected(input[i])) % mod; } System.out.println(((count * inv(fact[c])) % mod + mod) % mod); } public static long expected(int dist[]) { Arrays.sort(dist); int before = -1; long e = 1; for (int i = 0; i < dist.length; i++) { if (i == 0) { before = dist[0]; } else { before += dist[i] - dist[i - 1]; } e = (e * --before) % mod; } return fact[dist.length] - e; } }
Java
["3 5\n1 4 4 3 4\n1 4 1 4 2\n1 4 4 4 3"]
2 seconds
["166374062"]
NoteLet's look at all possible orders of cities Monuments will be build in: $$$[1, 2, 3]$$$: the first city controls all points at distance at most $$$3$$$, in other words, points $$$1$$$ and $$$4$$$; the second city controls all points at distance at most $$$2$$$, or points $$$1$$$, $$$3$$$ and $$$5$$$; the third city controls all points at distance at most $$$1$$$, or point $$$1$$$. In total, $$$4$$$ points are controlled. $$$[1, 3, 2]$$$: the first city controls points $$$1$$$ and $$$4$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 1, 3]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 3, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[3, 1, 2]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. $$$[3, 2, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. The expected number of controlled points is $$$\frac{4 + 3 + 3 + 3 + 3 + 3}{6}$$$ $$$=$$$ $$$\frac{19}{6}$$$ or $$$19 \cdot 6^{-1}$$$ $$$\equiv$$$ $$$19 \cdot 166374059$$$ $$$\equiv$$$ $$$166374062$$$ $$$\pmod{998244353}$$$
Java 11
standard input
[ "combinatorics", "dp", "math", "probabilities", "two pointers" ]
81f709b914ca1821b254f07b2464fbf2
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 20$$$; $$$1 \le m \le 5 \cdot 10^4$$$) — the number of cities and the number of points. Next $$$n$$$ lines contains $$$m$$$ integers each: the $$$j$$$-th integer of the $$$i$$$-th line $$$d_{i, j}$$$ ($$$1 \le d_{i, j} \le n + 1$$$) is the distance between the $$$i$$$-th city and the $$$j$$$-th point.
2,100
It can be shown that the expected number of points Monocarp conquers at the end of the $$$n$$$-th turn can be represented as an irreducible fraction $$$\frac{x}{y}$$$. Print this fraction modulo $$$998\,244\,353$$$, i. e. value $$$x \cdot y^{-1} \bmod 998244353$$$ where $$$y^{-1}$$$ is such number that $$$y \cdot y^{-1} \bmod 998244353 = 1$$$.
standard output
PASSED
564383fed234dbd01599aab7ba562983
train_110.jsonl
1621152000
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.Monocarp's empire has $$$n$$$ cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.Monocarp has $$$m$$$ points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most $$$1$$$ to this city. Next turn, the Monument controls all points at distance at most $$$2$$$, the turn after — at distance at most $$$3$$$, and so on. Monocarp will build $$$n$$$ Monuments in $$$n$$$ turns and his empire will conquer all points that are controlled by at least one Monument.Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among $$$m$$$ of them) he will conquer at the end of turn number $$$n$$$. Help him to calculate the expected number of conquered points!
256 megabytes
import java.math.BigInteger; import java.util.*; import java.io.*; public class Div716 { static int n, m, a[][]; static int mod = 998244353; static long[] fact; static long[] inv; static void preprocess() { fact = new long[n + 1]; inv = new long[n + 1]; fact[0] = fact[1] = inv[0] = inv[1] = 1; for (int i = 2; i <= n; i++) { fact[i] = (fact[i - 1] * i) % mod; inv[i] = inv(fact[i]); } } static long inv(long a) { int e = mod - 2; long res = 1; while (e > 0) { if (e % 2 == 1) res = (res * a) % mod; a = (a * a) % mod; e >>= 1; } return res; } static long ncr(int n, int r) { if (r > n || n < 0 || r < 0) return 0; long res = fact[n] * inv[r]; res %= mod; return (res * inv[n - r]) % mod; } static long solve() { long res = 0; for (int i = 0; i < m; i++) { long cur = 1; Arrays.sort(a[i]); for (int j = 0; j < n; j++) { int size = a[i][j] - j - 1; size = Math.max(size, 0); cur *= size; cur %= mod; } res += (mod + fact[n] - cur); res %= mod; } return res; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); n = sc.nextInt(); m = sc.nextInt(); a = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) a[j][i] = sc.nextInt(); } preprocess(); pw.println((solve() * inv[n]) % mod); pw.flush(); } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] nextIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3 5\n1 4 4 3 4\n1 4 1 4 2\n1 4 4 4 3"]
2 seconds
["166374062"]
NoteLet's look at all possible orders of cities Monuments will be build in: $$$[1, 2, 3]$$$: the first city controls all points at distance at most $$$3$$$, in other words, points $$$1$$$ and $$$4$$$; the second city controls all points at distance at most $$$2$$$, or points $$$1$$$, $$$3$$$ and $$$5$$$; the third city controls all points at distance at most $$$1$$$, or point $$$1$$$. In total, $$$4$$$ points are controlled. $$$[1, 3, 2]$$$: the first city controls points $$$1$$$ and $$$4$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 1, 3]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 3, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[3, 1, 2]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. $$$[3, 2, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. The expected number of controlled points is $$$\frac{4 + 3 + 3 + 3 + 3 + 3}{6}$$$ $$$=$$$ $$$\frac{19}{6}$$$ or $$$19 \cdot 6^{-1}$$$ $$$\equiv$$$ $$$19 \cdot 166374059$$$ $$$\equiv$$$ $$$166374062$$$ $$$\pmod{998244353}$$$
Java 11
standard input
[ "combinatorics", "dp", "math", "probabilities", "two pointers" ]
81f709b914ca1821b254f07b2464fbf2
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 20$$$; $$$1 \le m \le 5 \cdot 10^4$$$) — the number of cities and the number of points. Next $$$n$$$ lines contains $$$m$$$ integers each: the $$$j$$$-th integer of the $$$i$$$-th line $$$d_{i, j}$$$ ($$$1 \le d_{i, j} \le n + 1$$$) is the distance between the $$$i$$$-th city and the $$$j$$$-th point.
2,100
It can be shown that the expected number of points Monocarp conquers at the end of the $$$n$$$-th turn can be represented as an irreducible fraction $$$\frac{x}{y}$$$. Print this fraction modulo $$$998\,244\,353$$$, i. e. value $$$x \cdot y^{-1} \bmod 998244353$$$ where $$$y^{-1}$$$ is such number that $$$y \cdot y^{-1} \bmod 998244353 = 1$$$.
standard output
PASSED
16c9499f7da3c09f301e356c634b3211
train_110.jsonl
1621152000
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.Monocarp's empire has $$$n$$$ cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.Monocarp has $$$m$$$ points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most $$$1$$$ to this city. Next turn, the Monument controls all points at distance at most $$$2$$$, the turn after — at distance at most $$$3$$$, and so on. Monocarp will build $$$n$$$ Monuments in $$$n$$$ turns and his empire will conquer all points that are controlled by at least one Monument.Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among $$$m$$$ of them) he will conquer at the end of turn number $$$n$$$. Help him to calculate the expected number of conquered points!
256 megabytes
import java.util.*; import java.io.*; public class Sol{ static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static FastReader in=new FastReader(inputStream); static PrintWriter out=new PrintWriter(outputStream); static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } 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 long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //----------------------------------------------------------------------------------------------// //----------------S T A R T ---------------------------------------------------------------// //----------------------------------------------------------------------------------------------// /*linear sieve nlogn int n=(int)Math.pow(10,6)+100; long mod=998244353; long d[]=new long[n]; for(int i=1;i<n;i++){ for(int j=i; j<n; j+=i){ d[j] += 1; }} long pre[]=new long[n]; pre[1]=1;d[1]=1; for(int i=2;i<n;i++){d[i]+=pre[i-1]%mod;pre[i] += (pre[i-1]+d[i])%mod;}*/ static class Pair { int id;long val; public Pair(int id,long val) { this.id=id; this.val=val; } } /*----------DFS------------- static void DFS(int v,int p){ dp[0][v]=0;dp[1][v]=0; for(int u:adj[v]){ if(u==p)continue; DFS(u,v); dp[0][v]+=Math.max(Math.abs(A[0][u]-A[0][v]) + dp[0][u], Math.abs(A[1][u]-A[0][v]) + dp[1][u] ); dp[1][v]+=Math.max(Math.abs(A[0][u]-A[1][v]) + dp[0][u], Math.abs(A[1][u]-A[1][v]) + dp[1][u] ); } } static int N=(int)Math.pow(10,5)+10; static ArrayList<Integer> adj[]=new ArrayList[N]; static long dp[][]=new long[2][N]; static long A[][]=new long[2][N]; -----------DFS-------------- */ /*static class Edge implements Comparable<Edge>{ int destination;long cost; Edge(int destination,long cost){this.cost=cost;this.destination=destination;} @Override public int compareTo(Edge o) { return Long.compare(cost, o.cost); } } */ static long mod = 998244353; // Function to return the GCD of given numbers static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } // Recursive function to return (x ^ n) % m static long modexp(long x, long n) { if (n == 0) { return 1; } else if (n % 2 == 0) { return modexp((x * x) % mod, n / 2); } else { return (x * modexp((x * x) % mod, (n - 1) / 2) % mod); } } // Function to return the fraction modulo mod static long getFractionModulo(long a, long b) { long c = gcd(a, b); a = a / c; b = b / c; // (b ^ m-2) % m long d = modexp(b, mod - 2); // Final answer long ans = ((a % mod) * (d % mod)) % mod; return ans; } /*----------nCx--------------- long Comb[][]=new long[61][61]; for(int i=1;i<=60;i++){Comb[i][0]=1;} for(int i=1;i<=60;i++){Comb[i][1]=i;Comb[i][i]=1;} for(int i=2;i<=60;i++){for(int j=1;j<i;j++){Comb[i][j]=Comb[i-1][j]+Comb[i-1][j-1];}} ----------nCx------------------ */ public static void main(String []args){ int t=1; while(t-->0){ int n=in.nextInt();int m=in.nextInt(); long x=1; long b=1; while(x<=n){b*=x; x++;} long dp[][]=new long[m+1][n+1]; for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){dp[j][i]=in.nextLong();}} long a=0; for(int i=1;i<=m;i++){ Arrays.sort(dp[i]); long count=0;long res=1; for(int j=1;j<=n;j++){ res*=( dp[i][j]-1-count );res%=mod;count++; } a+=b-res; a%=mod; } b%=mod; //out.println(a+" "+b); out.println(getFractionModulo(a,b)); }out.close();}}
Java
["3 5\n1 4 4 3 4\n1 4 1 4 2\n1 4 4 4 3"]
2 seconds
["166374062"]
NoteLet's look at all possible orders of cities Monuments will be build in: $$$[1, 2, 3]$$$: the first city controls all points at distance at most $$$3$$$, in other words, points $$$1$$$ and $$$4$$$; the second city controls all points at distance at most $$$2$$$, or points $$$1$$$, $$$3$$$ and $$$5$$$; the third city controls all points at distance at most $$$1$$$, or point $$$1$$$. In total, $$$4$$$ points are controlled. $$$[1, 3, 2]$$$: the first city controls points $$$1$$$ and $$$4$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 1, 3]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 3, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[3, 1, 2]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. $$$[3, 2, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. The expected number of controlled points is $$$\frac{4 + 3 + 3 + 3 + 3 + 3}{6}$$$ $$$=$$$ $$$\frac{19}{6}$$$ or $$$19 \cdot 6^{-1}$$$ $$$\equiv$$$ $$$19 \cdot 166374059$$$ $$$\equiv$$$ $$$166374062$$$ $$$\pmod{998244353}$$$
Java 11
standard input
[ "combinatorics", "dp", "math", "probabilities", "two pointers" ]
81f709b914ca1821b254f07b2464fbf2
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 20$$$; $$$1 \le m \le 5 \cdot 10^4$$$) — the number of cities and the number of points. Next $$$n$$$ lines contains $$$m$$$ integers each: the $$$j$$$-th integer of the $$$i$$$-th line $$$d_{i, j}$$$ ($$$1 \le d_{i, j} \le n + 1$$$) is the distance between the $$$i$$$-th city and the $$$j$$$-th point.
2,100
It can be shown that the expected number of points Monocarp conquers at the end of the $$$n$$$-th turn can be represented as an irreducible fraction $$$\frac{x}{y}$$$. Print this fraction modulo $$$998\,244\,353$$$, i. e. value $$$x \cdot y^{-1} \bmod 998244353$$$ where $$$y^{-1}$$$ is such number that $$$y \cdot y^{-1} \bmod 998244353 = 1$$$.
standard output
PASSED
a9fbe5de67f234b59620eb04e5d00e03
train_110.jsonl
1621152000
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.Monocarp's empire has $$$n$$$ cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.Monocarp has $$$m$$$ points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most $$$1$$$ to this city. Next turn, the Monument controls all points at distance at most $$$2$$$, the turn after — at distance at most $$$3$$$, and so on. Monocarp will build $$$n$$$ Monuments in $$$n$$$ turns and his empire will conquer all points that are controlled by at least one Monument.Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among $$$m$$$ of them) he will conquer at the end of turn number $$$n$$$. Help him to calculate the expected number of conquered points!
256 megabytes
import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; public class Main { private static void run() throws IOException { int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[j][i] = in.nextInt(); } } long all = 1; for (int i = 0; i < n; i++) { all = all * (i + 1); } long ans = 0; for (int i = 0; i < m; i++) { Arrays.sort(a[i]); long sum = 1; for (int j = 0; j < n; j++) { int now = Math.min(a[i][j] - 1, n); sum = sum * (now - j); } long diff = (all - sum) % mod; ans = (ans + diff) % mod; } for (int i = 2; i <= n; i++) { ans = (ans * pow_mod(i, mod - 2)) % mod; } out.println(ans); } public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(new OutputStreamWriter(System.out)); // int t = in.nextInt(); // for (int i = 0; i < t; i++) { // } run(); out.flush(); in.close(); out.close(); } private static int gcd(int a, int b) { if (a == 0 || b == 0) return 0; while (b != 0) { int tmp; tmp = a % b; a = b; b = tmp; } return a; } static final long mod = 998244353L; static long pow_mod(long a, long b) { long result = 1; while (b != 0) { if ((b & 1) != 0) { result = (result * a) % mod; } a = (a * a) % mod; b >>= 1; } return result; } private static long multiplied_mod(long... longs) { long ans = 1; for (long now : longs) { ans = (ans * now) % mod; } return ans; } @SuppressWarnings("FieldCanBeLocal") private static Reader in; private static PrintWriter out; private static int[] read_int_array(int len) throws IOException { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = in.nextInt(); } return a; } private static long[] read_long_array(int len) throws IOException { long[] a = new long[len]; for (int i = 0; i < len; i++) { a[i] = in.nextLong(); } return a; } private static void print_array(int[] array) { for (int now : array) { out.print(now); out.print(' '); } out.println(); } private static void print_array(long[] array) { for (long now : array) { out.print(now); out.print(' '); } out.println(); } static class Reader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { final byte[] buf = new byte[1024]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextSign() throws IOException { byte c = read(); while ('+' != c && '-' != c) { c = read(); } return '+' == c ? 0 : 1; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() throws IOException { int b; // noinspection ALL while ((b = read()) != -1 && isSpaceChar(b)) { ; } return b; } public char nc() throws IOException { return (char) skip(); } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; } } private byte read() throws IOException { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } public void close() throws IOException { din.close(); } } }
Java
["3 5\n1 4 4 3 4\n1 4 1 4 2\n1 4 4 4 3"]
2 seconds
["166374062"]
NoteLet's look at all possible orders of cities Monuments will be build in: $$$[1, 2, 3]$$$: the first city controls all points at distance at most $$$3$$$, in other words, points $$$1$$$ and $$$4$$$; the second city controls all points at distance at most $$$2$$$, or points $$$1$$$, $$$3$$$ and $$$5$$$; the third city controls all points at distance at most $$$1$$$, or point $$$1$$$. In total, $$$4$$$ points are controlled. $$$[1, 3, 2]$$$: the first city controls points $$$1$$$ and $$$4$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 1, 3]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 3, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[3, 1, 2]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. $$$[3, 2, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. The expected number of controlled points is $$$\frac{4 + 3 + 3 + 3 + 3 + 3}{6}$$$ $$$=$$$ $$$\frac{19}{6}$$$ or $$$19 \cdot 6^{-1}$$$ $$$\equiv$$$ $$$19 \cdot 166374059$$$ $$$\equiv$$$ $$$166374062$$$ $$$\pmod{998244353}$$$
Java 11
standard input
[ "combinatorics", "dp", "math", "probabilities", "two pointers" ]
81f709b914ca1821b254f07b2464fbf2
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 20$$$; $$$1 \le m \le 5 \cdot 10^4$$$) — the number of cities and the number of points. Next $$$n$$$ lines contains $$$m$$$ integers each: the $$$j$$$-th integer of the $$$i$$$-th line $$$d_{i, j}$$$ ($$$1 \le d_{i, j} \le n + 1$$$) is the distance between the $$$i$$$-th city and the $$$j$$$-th point.
2,100
It can be shown that the expected number of points Monocarp conquers at the end of the $$$n$$$-th turn can be represented as an irreducible fraction $$$\frac{x}{y}$$$. Print this fraction modulo $$$998\,244\,353$$$, i. e. value $$$x \cdot y^{-1} \bmod 998244353$$$ where $$$y^{-1}$$$ is such number that $$$y \cdot y^{-1} \bmod 998244353 = 1$$$.
standard output
PASSED
c2a458b05936deb8f761f942ecf47a93
train_110.jsonl
1621152000
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.Monocarp's empire has $$$n$$$ cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.Monocarp has $$$m$$$ points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most $$$1$$$ to this city. Next turn, the Monument controls all points at distance at most $$$2$$$, the turn after — at distance at most $$$3$$$, and so on. Monocarp will build $$$n$$$ Monuments in $$$n$$$ turns and his empire will conquer all points that are controlled by at least one Monument.Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among $$$m$$$ of them) he will conquer at the end of turn number $$$n$$$. Help him to calculate the expected number of conquered points!
256 megabytes
import java.io.*; import java.util.*; public class E1525 { public static void main(String[] args) throws IOException, FileNotFoundException { // Scanner in = new Scanner(new File("test.in")); Kattio in = new Kattio(); int N = in.nextInt(); int M = in.nextInt(); int[][] dist = new int[N][M]; for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ dist[i][j] = in.nextInt(); } } int MOD = 998244353; long fac = 1; for(int i = 1; i <= N; i++){ fac *= i; fac %= MOD; } long invFac = 1; for(int i = 1; i <= N; i++){ invFac *= modInverse(i, MOD); invFac %= MOD; } long ans = 0; for(int point = 0; point < M; point++){ int[] count = new int[N + 1]; for(int city = 0; city < N; city++){ count[N + 1 - dist[city][point]]++; } // System.out.println(Arrays.toString(count)); long sum = 0; long[] d = new long[N + 1]; d[0] = 1; for(int i = 0; i < N; i++){ sum += count[i]; // the value at this positio is value - n d[i + 1] = (d[i + 1] + (d[i] * sum)) % MOD; sum = Math.max(sum - 1, 0); } ans = ans + 1 - (d[N] * invFac % MOD) + MOD; ans %= MOD; } // System.out.println(ans); in.println(ans); in.close(); } static int modInverse(int a, int m){ int m0 = m; int y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient int q = a / m; int t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in,System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(problemName+".out"); r = new BufferedReader(new FileReader(problemName+".in")); } // returns null if no more input public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(r.readLine()); return st.nextToken(); } catch (Exception e) {} return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3 5\n1 4 4 3 4\n1 4 1 4 2\n1 4 4 4 3"]
2 seconds
["166374062"]
NoteLet's look at all possible orders of cities Monuments will be build in: $$$[1, 2, 3]$$$: the first city controls all points at distance at most $$$3$$$, in other words, points $$$1$$$ and $$$4$$$; the second city controls all points at distance at most $$$2$$$, or points $$$1$$$, $$$3$$$ and $$$5$$$; the third city controls all points at distance at most $$$1$$$, or point $$$1$$$. In total, $$$4$$$ points are controlled. $$$[1, 3, 2]$$$: the first city controls points $$$1$$$ and $$$4$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 1, 3]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 3, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[3, 1, 2]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. $$$[3, 2, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. The expected number of controlled points is $$$\frac{4 + 3 + 3 + 3 + 3 + 3}{6}$$$ $$$=$$$ $$$\frac{19}{6}$$$ or $$$19 \cdot 6^{-1}$$$ $$$\equiv$$$ $$$19 \cdot 166374059$$$ $$$\equiv$$$ $$$166374062$$$ $$$\pmod{998244353}$$$
Java 11
standard input
[ "combinatorics", "dp", "math", "probabilities", "two pointers" ]
81f709b914ca1821b254f07b2464fbf2
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 20$$$; $$$1 \le m \le 5 \cdot 10^4$$$) — the number of cities and the number of points. Next $$$n$$$ lines contains $$$m$$$ integers each: the $$$j$$$-th integer of the $$$i$$$-th line $$$d_{i, j}$$$ ($$$1 \le d_{i, j} \le n + 1$$$) is the distance between the $$$i$$$-th city and the $$$j$$$-th point.
2,100
It can be shown that the expected number of points Monocarp conquers at the end of the $$$n$$$-th turn can be represented as an irreducible fraction $$$\frac{x}{y}$$$. Print this fraction modulo $$$998\,244\,353$$$, i. e. value $$$x \cdot y^{-1} \bmod 998244353$$$ where $$$y^{-1}$$$ is such number that $$$y \cdot y^{-1} \bmod 998244353 = 1$$$.
standard output
PASSED
adba7aeb1425137283a5d24c8faaea93
train_110.jsonl
1621152000
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.Monocarp's empire has $$$n$$$ cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.Monocarp has $$$m$$$ points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most $$$1$$$ to this city. Next turn, the Monument controls all points at distance at most $$$2$$$, the turn after — at distance at most $$$3$$$, and so on. Monocarp will build $$$n$$$ Monuments in $$$n$$$ turns and his empire will conquer all points that are controlled by at least one Monument.Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among $$$m$$$ of them) he will conquer at the end of turn number $$$n$$$. Help him to calculate the expected number of conquered points!
256 megabytes
import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; public class Main { private static void run() throws IOException { int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[j][i] = in.nextInt(); } } long all = 1; for (int i = 0; i < n; i++) { all = all * (i + 1); } long ans = 0; for (int i = 0; i < m; i++) { Arrays.sort(a[i]); long sum = 1; for (int j = 0; j < n; j++) { int now = Math.min(a[i][j] - 1, n); sum = sum * (now - j); } long diff = (all - sum) % mod; ans = (ans + diff) % mod; } for (int i = 2; i <= n; i++) { ans = (ans * pow_mod(i, mod - 2)) % mod; } out.println(ans); } public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(new OutputStreamWriter(System.out)); // int t = in.nextInt(); // for (int i = 0; i < t; i++) { // } run(); out.flush(); in.close(); out.close(); } private static int gcd(int a, int b) { if (a == 0 || b == 0) return 0; while (b != 0) { int tmp; tmp = a % b; a = b; b = tmp; } return a; } static final long mod = 998244353L; static long pow_mod(long a, long b) { long result = 1; while (b != 0) { if ((b & 1) != 0) { result = (result * a) % mod; } a = (a * a) % mod; b >>= 1; } return result; } private static long multiplied_mod(long... longs) { long ans = 1; for (long now : longs) { ans = (ans * now) % mod; } return ans; } @SuppressWarnings("FieldCanBeLocal") private static Reader in; private static PrintWriter out; private static int[] read_int_array(int len) throws IOException { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = in.nextInt(); } return a; } private static long[] read_long_array(int len) throws IOException { long[] a = new long[len]; for (int i = 0; i < len; i++) { a[i] = in.nextLong(); } return a; } private static void print_array(int[] array) { for (int now : array) { out.print(now); out.print(' '); } out.println(); } private static void print_array(long[] array) { for (long now : array) { out.print(now); out.print(' '); } out.println(); } static class Reader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { final byte[] buf = new byte[1024]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextSign() throws IOException { byte c = read(); while ('+' != c && '-' != c) { c = read(); } return '+' == c ? 0 : 1; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() throws IOException { int b; // noinspection ALL while ((b = read()) != -1 && isSpaceChar(b)) { ; } return b; } public char nc() throws IOException { return (char) skip(); } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; } } private byte read() throws IOException { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } public void close() throws IOException { din.close(); } } }
Java
["3 5\n1 4 4 3 4\n1 4 1 4 2\n1 4 4 4 3"]
2 seconds
["166374062"]
NoteLet's look at all possible orders of cities Monuments will be build in: $$$[1, 2, 3]$$$: the first city controls all points at distance at most $$$3$$$, in other words, points $$$1$$$ and $$$4$$$; the second city controls all points at distance at most $$$2$$$, or points $$$1$$$, $$$3$$$ and $$$5$$$; the third city controls all points at distance at most $$$1$$$, or point $$$1$$$. In total, $$$4$$$ points are controlled. $$$[1, 3, 2]$$$: the first city controls points $$$1$$$ and $$$4$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 1, 3]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 3, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[3, 1, 2]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. $$$[3, 2, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. The expected number of controlled points is $$$\frac{4 + 3 + 3 + 3 + 3 + 3}{6}$$$ $$$=$$$ $$$\frac{19}{6}$$$ or $$$19 \cdot 6^{-1}$$$ $$$\equiv$$$ $$$19 \cdot 166374059$$$ $$$\equiv$$$ $$$166374062$$$ $$$\pmod{998244353}$$$
Java 11
standard input
[ "combinatorics", "dp", "math", "probabilities", "two pointers" ]
81f709b914ca1821b254f07b2464fbf2
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 20$$$; $$$1 \le m \le 5 \cdot 10^4$$$) — the number of cities and the number of points. Next $$$n$$$ lines contains $$$m$$$ integers each: the $$$j$$$-th integer of the $$$i$$$-th line $$$d_{i, j}$$$ ($$$1 \le d_{i, j} \le n + 1$$$) is the distance between the $$$i$$$-th city and the $$$j$$$-th point.
2,100
It can be shown that the expected number of points Monocarp conquers at the end of the $$$n$$$-th turn can be represented as an irreducible fraction $$$\frac{x}{y}$$$. Print this fraction modulo $$$998\,244\,353$$$, i. e. value $$$x \cdot y^{-1} \bmod 998244353$$$ where $$$y^{-1}$$$ is such number that $$$y \cdot y^{-1} \bmod 998244353 = 1$$$.
standard output
PASSED
52cae434f2f4380a53099040ae883784
train_110.jsonl
1621152000
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.Monocarp's empire has $$$n$$$ cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.Monocarp has $$$m$$$ points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most $$$1$$$ to this city. Next turn, the Monument controls all points at distance at most $$$2$$$, the turn after — at distance at most $$$3$$$, and so on. Monocarp will build $$$n$$$ Monuments in $$$n$$$ turns and his empire will conquer all points that are controlled by at least one Monument.Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among $$$m$$$ of them) he will conquer at the end of turn number $$$n$$$. Help him to calculate the expected number of conquered points!
256 megabytes
import java.util.*; import java.io.*; public class _1525_E { static long MOD = 998244353; static long[] fact = new long[25]; static long[] inv_fact = new long[25]; public static void main(String[] args) throws IOException { fact[0] = 1; inv_fact[0] = 1; for(int i = 1; i < 25; i++) { fact[i] = modmult(fact[i - 1], i); inv_fact[i] = modmult(inv_fact[i - 1], modinv(i)); } BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer line = new StringTokenizer(in.readLine()); int n = Integer.parseInt(line.nextToken()); int m = Integer.parseInt(line.nextToken()); int[][] d = new int[m][n]; for(int i = 0; i < n; i++) { line = new StringTokenizer(in.readLine()); for(int j = 0; j < m; j++) { d[j][i] = Integer.parseInt(line.nextToken()); } } long res = 0; for(int i = 0; i < m; i++) { res = modadd(res, calc_prob(d[i])); } out.println(res); in.close(); out.close(); } static long calc_prob(int[] dists) { long ways = 1; Arrays.sort(dists); int filled = 0; for(int i = 0; i < dists.length; i++) { int left = dists[i] - 1 - filled; if(left <= 0) { ways = 0; break; } ways = modmult(ways, left); filled++; } return modadd(1, -modmult(ways, inv_fact[dists.length])); } static long binom(int n, int k) { return modmult(modmult(fact[n], inv_fact[n - k]), inv_fact[k]); } static long modadd(long a, long b) { return (a + b + MOD) % MOD; } static long modmult(long a, long b) { return a * b % MOD; } static long modinv(long a) { return binpow(a, MOD - 2); } static long binpow(long a, long b) { if(b == 0) { return 1; } long small = binpow(a, b / 2); if(b % 2 == 0) { return modmult(small, small); }else { return modmult(modmult(small, small), a); } } }
Java
["3 5\n1 4 4 3 4\n1 4 1 4 2\n1 4 4 4 3"]
2 seconds
["166374062"]
NoteLet's look at all possible orders of cities Monuments will be build in: $$$[1, 2, 3]$$$: the first city controls all points at distance at most $$$3$$$, in other words, points $$$1$$$ and $$$4$$$; the second city controls all points at distance at most $$$2$$$, or points $$$1$$$, $$$3$$$ and $$$5$$$; the third city controls all points at distance at most $$$1$$$, or point $$$1$$$. In total, $$$4$$$ points are controlled. $$$[1, 3, 2]$$$: the first city controls points $$$1$$$ and $$$4$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 1, 3]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 3, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[3, 1, 2]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. $$$[3, 2, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. The expected number of controlled points is $$$\frac{4 + 3 + 3 + 3 + 3 + 3}{6}$$$ $$$=$$$ $$$\frac{19}{6}$$$ or $$$19 \cdot 6^{-1}$$$ $$$\equiv$$$ $$$19 \cdot 166374059$$$ $$$\equiv$$$ $$$166374062$$$ $$$\pmod{998244353}$$$
Java 11
standard input
[ "combinatorics", "dp", "math", "probabilities", "two pointers" ]
81f709b914ca1821b254f07b2464fbf2
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 20$$$; $$$1 \le m \le 5 \cdot 10^4$$$) — the number of cities and the number of points. Next $$$n$$$ lines contains $$$m$$$ integers each: the $$$j$$$-th integer of the $$$i$$$-th line $$$d_{i, j}$$$ ($$$1 \le d_{i, j} \le n + 1$$$) is the distance between the $$$i$$$-th city and the $$$j$$$-th point.
2,100
It can be shown that the expected number of points Monocarp conquers at the end of the $$$n$$$-th turn can be represented as an irreducible fraction $$$\frac{x}{y}$$$. Print this fraction modulo $$$998\,244\,353$$$, i. e. value $$$x \cdot y^{-1} \bmod 998244353$$$ where $$$y^{-1}$$$ is such number that $$$y \cdot y^{-1} \bmod 998244353 = 1$$$.
standard output
PASSED
5bc0b179ab4a016a4928e15dba80ef5a
train_110.jsonl
1621152000
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.Monocarp's empire has $$$n$$$ cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.Monocarp has $$$m$$$ points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most $$$1$$$ to this city. Next turn, the Monument controls all points at distance at most $$$2$$$, the turn after — at distance at most $$$3$$$, and so on. Monocarp will build $$$n$$$ Monuments in $$$n$$$ turns and his empire will conquer all points that are controlled by at least one Monument.Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among $$$m$$$ of them) he will conquer at the end of turn number $$$n$$$. Help him to calculate the expected number of conquered points!
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; import java.io.File; import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.UncheckedIOException; import java.lang.Thread.State; import java.lang.reflect.Field; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.CharsetEncoder; import java.nio.charset.StandardCharsets; public class Main { static final long MOD1=1000000007; static final long MOD=998244353; static int ans=Integer.MAX_VALUE; static long[] sum; public static void main(String[] args){ PrintWriter out = new PrintWriter(System.out); InputReader sc=new InputReader(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][] d = new int[n][m]; for (int i = 0; i < d.length; i++) { d[i] = sc.nextIntArray(m); } long ans = 0; long n_fact = 1; for (long i = 2; i <= n; i++) { n_fact *= i; n_fact %= MOD; } long n_fact_inv = modInv(n_fact); for (int i = 0; i < m; i++){ int[] c = new int[n+1]; for (int j = 0; j < n; j++){ c[d[j][i]-1]++; } long x = 1; long now = 0;//選べる数 for (int j = n; j >= 1; j--){ now += c[j]; x *= now; x %= MOD; now --; } x *= n_fact_inv; x %= MOD; x = (1 - x + MOD)%MOD; ans += x; ans %= MOD; } System.out.println(ans); } static long modPow(long x, long y) { long z = 1; while (y > 0) { if (y % 2 == 0) { x = (x * x) % MOD; y /= 2; } else { z = (z * x) % MOD; y--; } } return z; }//xのy乗mod static long modInv(long x) { return modPow(x, MOD - 2); }//xのmodでの逆元 static class MaxFlow { public class CapEdge { private final int from, to; private long cap; private final int rev; CapEdge(int from, int to, long cap, int rev) { this.from = from; this.to = to; this.cap = cap; this.rev = rev; } public int getFrom() {return from;} public int getTo() {return to;} public long getCap() {return cap;} public long getFlow() {return g[to][rev].cap;} } private static final long INF = Long.MAX_VALUE; private final int n; private int m; private final java.util.ArrayList<CapEdge> edges; private final int[] count; private final CapEdge[][] g; public MaxFlow(int n) { this.n = n; this.edges = new java.util.ArrayList<>(); this.count = new int[n]; this.g = new CapEdge[n][]; } public int addEdge(int from, int to, long cap) { rangeCheck(from, 0, n); rangeCheck(to, 0, n); nonNegativeCheck(cap, "Capacity"); CapEdge e = new CapEdge(from, to, cap, count[to]); count[from]++; count[to]++; edges.add(e); return m++; } public CapEdge getEdge(int i) { rangeCheck(i, 0, m); return edges.get(i); } public java.util.ArrayList<CapEdge> getEdges() { return edges; } public void changeEdge(int i, long newCap, long newFlow) { rangeCheck(i, 0, m); nonNegativeCheck(newCap, "Capacity"); if (newFlow > newCap) { throw new IllegalArgumentException( String.format("Flow %d is greater than capacity %d.", newCap, newFlow) ); } CapEdge e = edges.get(i); CapEdge er = g[e.to][e.rev]; e.cap = newCap - newFlow; er.cap = newFlow; } private void buildGraph() { for (int i = 0; i < n; i++) { g[i] = new CapEdge[count[i]]; } int[] idx = new int[n]; for (CapEdge e : edges) { g[e.to][idx[e.to]++] = new CapEdge(e.to, e.from, 0, idx[e.from]); g[e.from][idx[e.from]++] = e; } } public long maxFlow(int s, int t) { return flow(s, t, INF); } public long flow(int s, int t, long flowLimit) { rangeCheck(s, 0, n); rangeCheck(t, 0, n); buildGraph(); long flow = 0; int[] level = new int[n]; int[] que = new int[n]; int[] iter = new int[n]; while (true) { java.util.Arrays.fill(level, -1); dinicBFS(s, t, level, que); if (level[t] < 0) return flow; java.util.Arrays.fill(iter, 0); while (true) { long d = dinicDFS(t, s, flowLimit - flow, iter, level); if (d <= 0) break; flow += d; } } } private void dinicBFS(int s, int t, int[] level, int[] que) { int hd = 0, tl = 0; que[tl++] = s; level[s] = 0; while (tl > hd) { int u = que[hd++]; for (CapEdge e : g[u]) { int v = e.to; if (e.cap <= 0 || level[v] >= 0) continue; level[v] = level[u] + 1; if (v == t) return; que[tl++] = v; } } } private long dinicDFS(int cur, int s, long f, int[] iter, int[] level) { if (cur == s) return f; long res = 0; while (iter[cur] < count[cur]) { CapEdge er = g[cur][iter[cur]++]; int u = er.to; CapEdge e = g[u][er.rev]; if (level[u] >= level[cur] || e.cap <= 0) continue; long d = dinicDFS(u, s, Math.min(f - res, e.cap), iter, level); if (d <= 0) continue; e.cap -= d; er.cap += d; res += d; if (res == f) break; } return res; } public long fordFulkersonMaxFlow(int s, int t) { return fordFulkersonFlow(s, t, INF); } public long fordFulkersonFlow(int s, int t, long flowLimit) { rangeCheck(s, 0, n); rangeCheck(t, 0, n); buildGraph(); boolean[] used = new boolean[n]; long flow = 0; while (true) { java.util.Arrays.fill(used, false); long f = fordFulkersonDFS(s, t, flowLimit - flow, used); if (f <= 0) return flow; flow += f; } } private long fordFulkersonDFS(int cur, int t, long f, boolean[] used) { if (cur == t) return f; used[cur] = true; for (CapEdge e : g[cur]) { if (used[e.to] || e.cap <= 0) continue; long d = fordFulkersonDFS(e.to, t, Math.min(f, e.cap), used); if (d <= 0) continue; e.cap -= d; g[e.to][e.rev].cap += d; return d; } return 0; } public boolean[] minCut(int s) { rangeCheck(s, 0, n); boolean[] reachable = new boolean[n]; int[] stack = new int[n]; int ptr = 0; stack[ptr++] = s; reachable[s] = true; while (ptr > 0) { int u = stack[--ptr]; for (CapEdge e : g[u]) { int v = e.to; if (reachable[v] || e.cap <= 0) continue; reachable[v] = true; stack[ptr++] = v; } } return reachable; } private void rangeCheck(int i, int minInlusive, int maxExclusive) { if (i < 0 || i >= maxExclusive) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, maxExclusive) ); } } private void nonNegativeCheck(long cap, java.lang.String attribute) { if (cap < 0) { throw new IllegalArgumentException( String.format("%s %d is negative.", attribute, cap) ); } } } 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 int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); 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
["3 5\n1 4 4 3 4\n1 4 1 4 2\n1 4 4 4 3"]
2 seconds
["166374062"]
NoteLet's look at all possible orders of cities Monuments will be build in: $$$[1, 2, 3]$$$: the first city controls all points at distance at most $$$3$$$, in other words, points $$$1$$$ and $$$4$$$; the second city controls all points at distance at most $$$2$$$, or points $$$1$$$, $$$3$$$ and $$$5$$$; the third city controls all points at distance at most $$$1$$$, or point $$$1$$$. In total, $$$4$$$ points are controlled. $$$[1, 3, 2]$$$: the first city controls points $$$1$$$ and $$$4$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 1, 3]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 3, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[3, 1, 2]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. $$$[3, 2, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. The expected number of controlled points is $$$\frac{4 + 3 + 3 + 3 + 3 + 3}{6}$$$ $$$=$$$ $$$\frac{19}{6}$$$ or $$$19 \cdot 6^{-1}$$$ $$$\equiv$$$ $$$19 \cdot 166374059$$$ $$$\equiv$$$ $$$166374062$$$ $$$\pmod{998244353}$$$
Java 11
standard input
[ "combinatorics", "dp", "math", "probabilities", "two pointers" ]
81f709b914ca1821b254f07b2464fbf2
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 20$$$; $$$1 \le m \le 5 \cdot 10^4$$$) — the number of cities and the number of points. Next $$$n$$$ lines contains $$$m$$$ integers each: the $$$j$$$-th integer of the $$$i$$$-th line $$$d_{i, j}$$$ ($$$1 \le d_{i, j} \le n + 1$$$) is the distance between the $$$i$$$-th city and the $$$j$$$-th point.
2,100
It can be shown that the expected number of points Monocarp conquers at the end of the $$$n$$$-th turn can be represented as an irreducible fraction $$$\frac{x}{y}$$$. Print this fraction modulo $$$998\,244\,353$$$, i. e. value $$$x \cdot y^{-1} \bmod 998244353$$$ where $$$y^{-1}$$$ is such number that $$$y \cdot y^{-1} \bmod 998244353 = 1$$$.
standard output
PASSED
2eb7d85d4904e17cf877167fb871f270
train_110.jsonl
1621152000
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.Monocarp's empire has $$$n$$$ cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.Monocarp has $$$m$$$ points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most $$$1$$$ to this city. Next turn, the Monument controls all points at distance at most $$$2$$$, the turn after — at distance at most $$$3$$$, and so on. Monocarp will build $$$n$$$ Monuments in $$$n$$$ turns and his empire will conquer all points that are controlled by at least one Monument.Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among $$$m$$$ of them) he will conquer at the end of turn number $$$n$$$. Help him to calculate the expected number of conquered points!
256 megabytes
import java.io.*; import java.util.*; public class Contest1525E { static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { // reads in the next string while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { // reads in the next int return Integer.parseInt(next()); } public long nextLong() { // reads in the next long return Long.parseLong(next()); } public double nextDouble() { // reads in the next double return Double.parseDouble(next()); } } static InputReader r = new InputReader(System.in); static PrintWriter pw = new PrintWriter(System.out); static long mod = 998244353; public static void main(String[] args) { int n = r.nextInt(); int m = r.nextInt(); int[][] dist = new int[m][n]; for (int i = 0; i < n; i ++) { for (int j = 0; j< m; j ++) { dist[j][i] = r.nextInt(); } } long fact = 1; for (int i = 1; i <= n; i ++) { fact *= i; } long total = 0; long num; for (int i = 0; i < m; i ++) { num = 1; Arrays.sort(dist[i]); for (int j = 0; j < n; j ++) { num=num*(Math.max(0,dist[i][j]-1-j)); num%=mod; } total += (fact-num); total%=mod; } pw.println((total*modInverse(fact))%mod); pw.close(); } public static long binpow(long x, long n) { assert(n >= 0); x %= mod; // note: m * m must be less than 2^63 to avoid ll overflow long res = 1; while (n > 0) { if (n % 2 == 1) // if n is odd res = res * x % mod; x = x * x % mod; n /= 2; // divide by two } return res; } public static long modInverse(long x) { return binpow(x,mod-2); } }
Java
["3 5\n1 4 4 3 4\n1 4 1 4 2\n1 4 4 4 3"]
2 seconds
["166374062"]
NoteLet's look at all possible orders of cities Monuments will be build in: $$$[1, 2, 3]$$$: the first city controls all points at distance at most $$$3$$$, in other words, points $$$1$$$ and $$$4$$$; the second city controls all points at distance at most $$$2$$$, or points $$$1$$$, $$$3$$$ and $$$5$$$; the third city controls all points at distance at most $$$1$$$, or point $$$1$$$. In total, $$$4$$$ points are controlled. $$$[1, 3, 2]$$$: the first city controls points $$$1$$$ and $$$4$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 1, 3]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[2, 3, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — point $$$1$$$. In total, $$$3$$$ points. $$$[3, 1, 2]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$ and $$$3$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. $$$[3, 2, 1]$$$: the first city controls point $$$1$$$; the second city — points $$$1$$$, $$$3$$$ and $$$5$$$; the third city — points $$$1$$$ and $$$5$$$. In total, $$$3$$$ points. The expected number of controlled points is $$$\frac{4 + 3 + 3 + 3 + 3 + 3}{6}$$$ $$$=$$$ $$$\frac{19}{6}$$$ or $$$19 \cdot 6^{-1}$$$ $$$\equiv$$$ $$$19 \cdot 166374059$$$ $$$\equiv$$$ $$$166374062$$$ $$$\pmod{998244353}$$$
Java 11
standard input
[ "combinatorics", "dp", "math", "probabilities", "two pointers" ]
81f709b914ca1821b254f07b2464fbf2
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 20$$$; $$$1 \le m \le 5 \cdot 10^4$$$) — the number of cities and the number of points. Next $$$n$$$ lines contains $$$m$$$ integers each: the $$$j$$$-th integer of the $$$i$$$-th line $$$d_{i, j}$$$ ($$$1 \le d_{i, j} \le n + 1$$$) is the distance between the $$$i$$$-th city and the $$$j$$$-th point.
2,100
It can be shown that the expected number of points Monocarp conquers at the end of the $$$n$$$-th turn can be represented as an irreducible fraction $$$\frac{x}{y}$$$. Print this fraction modulo $$$998\,244\,353$$$, i. e. value $$$x \cdot y^{-1} \bmod 998244353$$$ where $$$y^{-1}$$$ is such number that $$$y \cdot y^{-1} \bmod 998244353 = 1$$$.
standard output