exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
7f50457727cc64fdbeffc09a0bf21f9d
train_002.jsonl
1587653100
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length $$$k$$$ ($$$k \ge 3$$$). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.Mountains are described by a sequence of heights $$$a_1, a_2, \dots, a_n$$$ in order from left to right ($$$k \le n$$$). It is guaranteed that neighboring heights are not equal to each other (that is, $$$a_i \ne a_{i+1}$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$).Peaks of mountains on the segment $$$[l,r]$$$ (from $$$l$$$ to $$$r$$$) are called indexes $$$i$$$ such that $$$l < i < r$$$, $$$a_{i - 1} < a_i$$$ and $$$a_i > a_{i + 1}$$$. It is worth noting that the boundary indexes $$$l$$$ and $$$r$$$ for the segment are not peaks. For example, if $$$n=8$$$ and $$$a=[3,1,4,1,5,9,2,6]$$$, then the segment $$$[1,8]$$$ has only two peaks (with indexes $$$3$$$ and $$$6$$$), and there are no peaks on the segment $$$[3, 6]$$$.To break the door, Nastya throws it to a segment $$$[l,l+k-1]$$$ of consecutive mountains of length $$$k$$$ ($$$1 \le l \le n-k+1$$$). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to $$$p+1$$$, where $$$p$$$ is the number of peaks on the segment $$$[l,l+k-1]$$$.Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains $$$[l, l+k-1]$$$ that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value $$$l$$$ is minimal.Formally, you need to choose a segment of mountains $$$[l, l+k-1]$$$ that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value $$$l$$$.
256 megabytes
import java.util.*; import java.io.*; public class Solution { static InputReader in=new InputReader(System.in); static OutputWriter out=new OutputWriter(System.out); static StringBuilder sb=new StringBuilder(); static long MOD = (long)(1e9+7); // Main Class Starts Here public static void main(String args[])throws IOException { // Write your code. int t = in(); while(t-->0) { int n=in(); int k=in(); int a[]=an(n); int np[]=new int[n+1]; int noPeak = 0; int ip[]=new int[n+1]; for(int i=1;i<n-1;i++) { if(a[i] > a[i-1] && a[i] > a[i+1]) { np[i] = 1; ip[i] = 1; noPeak = 1; } } if(noPeak == 0) { app(1+" "+1+"\n"); continue; } for(int i=np.length-2; i>=0 ;i--) { np[i] += np[i+1]; } int index= 0; int max =-1; for(int i=n-1;(i-k+1) >= 0;i--) { int diff = np[i-k+2] - np[i]; if(max <= diff) { max = diff; index = i-k+1; } } app((max+1)+" "+(index+1)+"\n"); } out.printLine(sb); out.close(); } public static long rev(long n) { if(n<10L) return n; long rev = 0L; while(n != 0L) { long a = n % 10L; rev = a + rev*10L; n /= 10L; } return rev; } public static long pow(long a,long b) { if(b==0) return 1L; if(b==1) return a % MOD; long f = a * a; if(f > MOD) f %= MOD; long val = pow(f, b/2) % MOD; if(b % 2 == 0) return val; else { long temp = val * (a % MOD); if(temp > MOD) temp = temp % MOD; return temp; } } public static int gcd(int a,int b) { if(b==0) return a; return gcd(b, a%b); } public static int[] an(int n) { int ar[]=new int[n]; for(int i=0;i<n;i++) ar[i]=in(); return ar; } public static int in() { return in.readInt(); } public static long lin() { return in.readLong(); } public static String sn() { return in.readString(); } public static void prln(Object o) { out.printLine(o); } public static void prn(Object o) { out.print(o); } public static int getMax(int a[]) { int n = a.length; int max = a[0]; for(int i=1; i < n; i++) { max = Math.max(max, a[i]); } return max; } public static int getMin(int a[]) { int n = a.length; int min = a[0]; for(int i=1; i < n; i++) { min = Math.min(min, a[i]); } return min; } public static void display(int a[]) { out.printLine(Arrays.toString(a)); } public static HashMap<Integer,Integer> hm(int a[]){ HashMap<Integer,Integer> map=new HashMap<>(); for(int i=0; i < a.length;i++) { int keep = (int)map.getOrDefault(a[i],0); map.put(a[i],++keep); } return map; } public static void app(Object o) { sb.append(o); } public static long calcManhattanDist(int x1,int y1,int x2,int y2) { long xa = Math.abs(x1-x2); long ya = Math.abs(y1-y2); return (xa+ya); } static class Point { int x; int y; String dir; public Point(int x,int y,String dir) { this.x=x; this.y=y; this.dir=dir; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["5\n8 6\n1 2 4 1 2 4 1 2\n5 3\n3 2 3 2 1\n10 4\n4 3 4 3 2 3 2 1 0 1\n15 7\n3 7 4 8 2 3 4 5 21 2 3 4 2 1 3\n7 5\n1 2 3 4 5 6 1"]
1 second
["3 2\n2 2\n2 1\n3 1\n2 3"]
NoteIn the first example, you need to select a segment of mountains from $$$2$$$ to $$$7$$$. In this segment, the indexes $$$3$$$ and $$$6$$$ are peaks, so the answer is $$$3$$$ (only $$$2$$$ peaks, so the door will break into $$$3$$$ parts). It is not difficult to notice that the mountain segments $$$[1, 6]$$$ and $$$[3, 8]$$$ are not suitable since they only have a $$$1$$$ peak (for the first segment, the $$$6$$$ index is not a peak, and for the second segment, the $$$3$$$ index is not a peak).In the second example, you need to select a segment of mountains from $$$2$$$ to $$$4$$$. In this segment, the index $$$3$$$ is a peak, so the answer is $$$2$$$ (only $$$1$$$ peak, so the door will break into $$$2$$$ parts).In the third example, you need to select a segment of mountains from $$$1$$$ to $$$4$$$. In this segment, the index $$$3$$$ is a peak, so the answer is $$$2$$$ (only $$$1$$$ peak, so the door will break into $$$2$$$ parts). You can see that on the segments $$$[2, 5]$$$, $$$[4, 7]$$$ and $$$[5, 8]$$$ the number of peaks is also $$$1$$$, but these segments have a left border greater than the segment $$$[1, 4]$$$, so they are not the correct answer.
Java 8
standard input
[ "implementation", "greedy" ]
8e182e0acb621c86901fb94b56ff991e
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. Then the descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$3 \leq k \leq n \leq 2 \cdot 10^5$$$)  — the number of mountains and the length of the door. The second line of the input data set contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 10 ^ 9$$$, $$$a_i \neq a_{i + 1}$$$)  — the heights of mountains. It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$2 \cdot 10^5$$$.
1,300
For each test case, output two integers $$$t$$$ and $$$l$$$  — the maximum number of parts that the door can split into, and the left border of the segment of length $$$k$$$ that the door should be reset to.
standard output
PASSED
61cd016f44a91f3dcbaf885c7ae78aa3
train_002.jsonl
1587653100
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length $$$k$$$ ($$$k \ge 3$$$). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.Mountains are described by a sequence of heights $$$a_1, a_2, \dots, a_n$$$ in order from left to right ($$$k \le n$$$). It is guaranteed that neighboring heights are not equal to each other (that is, $$$a_i \ne a_{i+1}$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$).Peaks of mountains on the segment $$$[l,r]$$$ (from $$$l$$$ to $$$r$$$) are called indexes $$$i$$$ such that $$$l &lt; i &lt; r$$$, $$$a_{i - 1} &lt; a_i$$$ and $$$a_i &gt; a_{i + 1}$$$. It is worth noting that the boundary indexes $$$l$$$ and $$$r$$$ for the segment are not peaks. For example, if $$$n=8$$$ and $$$a=[3,1,4,1,5,9,2,6]$$$, then the segment $$$[1,8]$$$ has only two peaks (with indexes $$$3$$$ and $$$6$$$), and there are no peaks on the segment $$$[3, 6]$$$.To break the door, Nastya throws it to a segment $$$[l,l+k-1]$$$ of consecutive mountains of length $$$k$$$ ($$$1 \le l \le n-k+1$$$). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to $$$p+1$$$, where $$$p$$$ is the number of peaks on the segment $$$[l,l+k-1]$$$.Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains $$$[l, l+k-1]$$$ that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value $$$l$$$ is minimal.Formally, you need to choose a segment of mountains $$$[l, l+k-1]$$$ that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value $$$l$$$.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc = new Scanner(System.in); int t = sc.nextInt() ; while(t-- > 0){ int n = sc.nextInt() ; int k= sc.nextInt() ; int arr[] = new int[n] ; for(int i = 0 ;i < n;i++ ) arr[i] = sc.nextInt() ; int pref[] = new int[n] ; for( int i = 1 ; i < n-1; i++ ){ if( arr[i] > arr[i-1] && arr[i] > arr[i+1] ) pref[i] = 1 ; pref[i] += pref[i-1] ; } int peak = 0 , l = 0 ; for(int i = 0 ;i <= n-k ;i++){ int temp = pref[i+k-2] - pref[i] ; if( temp > peak ){ peak = temp ; l= i; } } System.out.println((peak+1)+" "+(l+1)) ; } } }
Java
["5\n8 6\n1 2 4 1 2 4 1 2\n5 3\n3 2 3 2 1\n10 4\n4 3 4 3 2 3 2 1 0 1\n15 7\n3 7 4 8 2 3 4 5 21 2 3 4 2 1 3\n7 5\n1 2 3 4 5 6 1"]
1 second
["3 2\n2 2\n2 1\n3 1\n2 3"]
NoteIn the first example, you need to select a segment of mountains from $$$2$$$ to $$$7$$$. In this segment, the indexes $$$3$$$ and $$$6$$$ are peaks, so the answer is $$$3$$$ (only $$$2$$$ peaks, so the door will break into $$$3$$$ parts). It is not difficult to notice that the mountain segments $$$[1, 6]$$$ and $$$[3, 8]$$$ are not suitable since they only have a $$$1$$$ peak (for the first segment, the $$$6$$$ index is not a peak, and for the second segment, the $$$3$$$ index is not a peak).In the second example, you need to select a segment of mountains from $$$2$$$ to $$$4$$$. In this segment, the index $$$3$$$ is a peak, so the answer is $$$2$$$ (only $$$1$$$ peak, so the door will break into $$$2$$$ parts).In the third example, you need to select a segment of mountains from $$$1$$$ to $$$4$$$. In this segment, the index $$$3$$$ is a peak, so the answer is $$$2$$$ (only $$$1$$$ peak, so the door will break into $$$2$$$ parts). You can see that on the segments $$$[2, 5]$$$, $$$[4, 7]$$$ and $$$[5, 8]$$$ the number of peaks is also $$$1$$$, but these segments have a left border greater than the segment $$$[1, 4]$$$, so they are not the correct answer.
Java 8
standard input
[ "implementation", "greedy" ]
8e182e0acb621c86901fb94b56ff991e
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. Then the descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$3 \leq k \leq n \leq 2 \cdot 10^5$$$)  — the number of mountains and the length of the door. The second line of the input data set contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 10 ^ 9$$$, $$$a_i \neq a_{i + 1}$$$)  — the heights of mountains. It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$2 \cdot 10^5$$$.
1,300
For each test case, output two integers $$$t$$$ and $$$l$$$  — the maximum number of parts that the door can split into, and the left border of the segment of length $$$k$$$ that the door should be reset to.
standard output
PASSED
0354ef9cad3720489d16fb1f86d79172
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.*; public class cf222a { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] v = new int[n]; for(int i=0; i<n; i++) v[i] = in.nextInt(); boolean ok = true; for(int i=k; i<n; i++) if(v[i] != v[k-1]) ok = false; if(!ok) { System.out.println("-1"); return; } int ans = k-1; while(ans >= 0 && v[ans] == v[k-1]) ans--; System.out.println(ans+1); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
3f2e5ad58bdddd915d0f7301e65c5049
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int[] nk = t_int_a(br, 2); int[] v = t_int_a(br, nk[0]); int k = nk[1]; int original = v[k - 1]; boolean correct = true; for (int i = k - 1; i < nk[0]; i++) { if (v[i] != original) { correct = false; break; } } int true_index = k - 1; while (true_index >= 0 && v[true_index] == original) { true_index--; } true_index++; System.out.println((correct) ? (true_index) : -1); br.close(); } public static int t_int(BufferedReader br) throws Exception { return Integer.parseInt(br.readLine()); } public static StringTokenizer t_st(BufferedReader br) throws Exception { return new StringTokenizer(br.readLine()); } public static int[] t_int_a(BufferedReader br, int n) throws Exception { StringTokenizer st = t_st(br); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(st.nextToken()); } return a; } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
c7cf6c7d6c1d3e0793d833e55fa956b9
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class test{ //ArrayList<Integer> lis = new ArrayList<Integer>(); //ArrayList<String> lis = new ArrayList<String>(); // // static long sum=0; //int a,b,c; //1000000007 (10^9+7) //static int mod = 1000000007; // static int d[][]; //static int dx[]={1,-1,0,0}; //static int dy[]={0,0,1,-1}; //static long H,L; public static void main(String[] args) throws Exception, IOException{ //String line=""; throws Exception, IOException //(line=br.readLine())!=null //Scanner sc =new Scanner(System.in); Reader sc = new Reader(System.in); // while( ){ int n=sc.nextInt(),k=sc.nextInt()-1,a[]=new int[n]; for(int t=0;t<n;t++)a[t]=sc.nextInt(); int x=a[k]; for(int t=k;t<n;t++)if(x!=a[t]){System.out.println(-1);return;} for(int t=k-1;0<=t; t--)if(x!=a[t]){System.out.println(t+1); return;} System.out.println(0); // } } static void db(Object... os){ System.err.println(Arrays.deepToString(os)); } } /* class P implements Comparable<P>{ // implements Comparable<P> int x; boolean b; P(int x,boolean b){ this.x=x; this.b=b; } public int compareTo(P y){ return x-y.x; } } //*/ class Reader { private BufferedReader x; private StringTokenizer st; public Reader(InputStream in) { x = new BufferedReader(new InputStreamReader(in)); st = null; } public String nextString() throws IOException { while( st==null || !st.hasMoreTokens() ) st = new StringTokenizer(x.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextString()); } public double nextDouble() throws IOException { return Double.parseDouble(nextString()); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
212984a8b3c7b14fa7c6736d7bdd81af
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) throws IOException { Scanner in=new Scanner(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); int n=in.nextInt(); int k=in.nextInt(); int[] mas=new int[n]; for(int i=0; i<k-1; i++){ int cur=in.nextInt(); mas[i]=cur; } int prev=-1; boolean check=true; for(int i=k-1; i<n; i++){ int cur=in.nextInt(); if(prev!=-1 && cur!=prev){ check=false; break; } prev=cur; mas[i]=cur; } if(check) { int i=k-1; while(i>0 && mas[i-1]==mas[i]) i--; out.println(i); } else out.println(-1); out.close(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
e5b7879d83a656a7ca17939e621db0a3
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main{ public static void main(String[] args) throws Exception{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine(); String s2[]=s.split(" "); int n=Integer.parseInt(s2[0]); int k=Integer.parseInt(s2[1]); s=br.readLine(); int arr[]=new int[n]; s2=s.split(" "); for(int i=0;i<n;i++) { arr[i]=Integer.parseInt(s2[i]); } int i=0; int flag=0; for(i=n-1;i>0;i--) { if(arr[i]!=arr[i-1]) { flag=1; break; } } if(flag==0) { System.out.println("0"); } else if(i<k) { System.out.println(i); } else if(i>=k) { System.out.println(-1); } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
31fdf4af6f8223dbbaf90deb40f0e489
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class problemA { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; boolean flag = true; int ind = 0; a[0] = in.nextInt(); if (n == 1) { System.out.println("0"); return; } int prev = a[0]; for (int i = 1; i < k; i++) { a[i] = in.nextInt(); if (a[i] == prev) { if (flag) ind = i - 1; flag = false; } else { ind = i; flag = true; } prev = a[i]; } for (int i = k; i < n; i++) { a[i] = in.nextInt(); if (a[i] != a[ind]) { System.out.println("-1"); return; } } System.out.println(ind); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
0ca6de4e92eae502c498433b0c045835
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class P222A { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int k = scanner.nextInt() - 1; int[] firsts = new int[k]; for (int i = 0; i < k; i++) { firsts[i] = scanner.nextInt(); } int good = scanner.nextInt(); for (int i = k + 1; i < n; i++) { if (good != scanner.nextInt()) { System.out.println(-1); System.exit(0); } } int needed = k; for (int i = k - 1; i >= 0; --i) { if (firsts[i] != good) { break; } needed--; } System.out.println(needed); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
631fb73fbe75efde12d2a07e87ab30f9
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
//Codeforces Round 137 (Div. 2 Only) //10 Sep 2012 import java.util.*; import java.lang.Math; import java.io.*; public class A { public static void main (String[] args) { InputStream inputStream = System.in; InputReader in = new InputReader(inputStream); int n = in.nextInt(); int k = in.nextInt(); int data[]; data = new int[100005]; for (int i = 1; i <= n; ++i) data[i] = in.nextInt(); boolean ok = true; boolean sama = true; for (int i = 1; i < n; ++i) { if (data[i] != data[i+1]) sama = false; } if (sama) { System.out.println(0); } else { for (int i = k + 1; i <= n; ++i) if (data[i] != data[k]) { System.out.println(-1); ok = false; break; } if (ok) { int ix = k; while (data[ix] == data[k]) --ix; System.out.println(ix); } } } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
43353e7755e9ec34c1262bdf1bd3df2b
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; public class ShooshunsAndSequence { public static void main(String[] args) throws Exception { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String[] sp = r.readLine().split("[ ]+"); int n = new Integer(sp[0]), k = new Integer(sp[1]) - 1; sp = r.readLine().split("[ ]+"); int[] arr = new int[5 * 100000]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) { arr[i] = new Integer(sp[i]); int v = 0; if (map.containsKey(arr[i])) { v = map.remove(arr[i]); } map.put(arr[i], v + 1); } if (map.size() == 1) { System.out.println(0); return; } int s = 0, e = n; for (int i = 0; i < 2*n+100; i++) { arr[e++] = arr[s + k]; int vv = map.remove(arr[s]); vv--; if (vv > 0) { map.put(arr[s], vv); } vv=0; if(map.containsKey(arr[s+k])) vv=map.remove(arr[s+k]); vv++; map.put(arr[s+k], vv); s++; if (map.size() == 1) { System.out.println(s); return; } } System.out.println(-1); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
bf02ff7cba5fc791525c6888c027d2dd
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.*; import java.io.*; public class Main{ BufferedReader in; StringTokenizer str = null; private String next() throws Exception{ if(str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return str.nextToken(); } private int nextInt() throws Exception{ return Integer.parseInt(next()); } public void run() throws Exception{ in = new BufferedReader(new InputStreamReader(System.in)); int n = nextInt(); int k = nextInt()-1; int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); for(int i=k+1;i<n;i++) if (a[k] != a[i]){ System.out.println(-1); return; } int ret = k+1; int idx = k; while(idx >= 0 && a[idx] == a[k]){ idx--; ret--; } System.out.println(ret); } public static void main(String args[]) throws Exception{ new Main().run(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
c1adb1f59c1c0233f0617f6d4c39af47
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.*; public class A { BufferedReader in; PrintStream out; StringTokenizer tok; public A() throws NumberFormatException, IOException { in = new BufferedReader(new InputStreamReader(System.in)); //in = new BufferedReader(new FileReader("in.txt")); out = System.out; run(); } void run() throws NumberFormatException, IOException { int n = nextInt(); int k = nextInt()-1; int[]num = new int[n]; for(int i = 0; i < n; i++) num[i] = nextInt(); int index = n-1; while(index > 0 && num[index-1]==num[index]) index--; if(k>=index) out.println(n-(n-index)); else out.println(-1); } public static void main(String[] args) throws NumberFormatException, IOException { new A(); } String nextToken() throws IOException { if(tok ==null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
3227651c322e5f747270483d1d862bcd
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class prog { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int k=scan.nextInt(); int numbers[]=new int[n]; for (int i = 0; i < n; i++) { numbers[i]=scan.nextInt(); } int check=0; for (int i = 1; i < n; i++) { if(numbers[0]!=numbers[i]){ check=1; break; } } if(check==0){ System.out.println(0); return; } for (int i = k-1; i < n-1; i++) { if(numbers[i]!=numbers[i+1]){ System.out.println(-1); return; } } for (int i = k-2; i >=0; i--) { if(numbers[i]!=numbers[k-1]){ System.out.println(i+1); return; } } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
14234d10cd61a41c1686069abd3cf1aa
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Reader kb = new Reader(System.in); int n = kb.nextInt(); int k = kb.nextInt(); int list[] = new int[n]; for (int i = 0; i < n; i++) list[i] = kb.nextInt(); int index = n; while (index-- > 1) if (list[index] != list[index - 1]) break; System.out.println(index < k ? index : "-1"); } } class Reader { private BufferedReader x; private StringTokenizer st; public Reader(InputStream in) { x = new BufferedReader(new InputStreamReader(in)); st = null; } public String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(x.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextString()); } public double nextDouble() throws IOException { return Double.parseDouble(nextString()); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
2e6563673d90f0cf51f7fbf79d2d4b83
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class A { static StreamTokenizer st; public static void main(String[] args) throws IOException{ st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); int n = nextInt(); int k = nextInt(); int[]a = new int[n+1]; for (int i = 1; i <= n; i++) { a[i] = nextInt(); } boolean f = true; for (int i = k+1; i <= n; i++) { if (a[i] != a[k]) { f = false; break; } } if (!f) System.out.println(-1); else { int ans = k-1; while (ans >= 1 && a[ans]==a[k]) ans--; System.out.println(ans); } } private static int nextInt() throws IOException{ st.nextToken(); return (int) st.nval; } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
126fa5d4fdf1ed18662279eba3b305c8
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class A_ShooshunsAndSequence { public static int getA(int[] array) { int count = array.length - 1; for (int i = array.length - 1; i > 0; i--) { if (array[i] != array[i - 1]) { break; } else count = i - 1; } return count; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt()-1; int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = in.nextInt(); int t=getA(array); if(k>=t&&k<n) System.out.println(n-(n-t)); else System.out.println(-1); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
e383ffc2de9f6519ce771782678d4695
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class A137 { BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; public void solve() throws IOException { int N = nextInt(); int K = nextInt(); int[] a = new int[N]; for(int i = 0; i < N; i++){ a[i] = nextInt(); } int num = a[K-1]; for(int i = K; i < N; i++){ if( a[i] != num) { out.println(-1); return; } } for(int i = K-2; i >= 0; i--){ if( a[i] != num ){ out.println(i+1); return; } } out.println(0); } /** * @param args */ public static void main(String[] args) { new A137().run(); } public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; out = new PrintWriter(System.out); solve(); reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
f220cabd645eb878dba247933232dd8f
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.*; import java.util.*; /** * * @author Rohan */ public class Main { /** * @param args the command line arguments */ static int[] arr=new int[100010]; public static void main(String[] args) throws IOException { // TODO code application logic here solve(); } public static void solve() throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); String[] s=br.readLine().split(" "); int n=Integer.parseInt(s[0]),k=Integer.parseInt(s[1]); s=br.readLine().split(" "); int res=0; for(int i=k;i<n;i++) if(Integer.parseInt(s[i])!=Integer.parseInt(s[i-1])){ res=-1; break; } if(res==0){ res=k-1; for(int i=k-2;i>=0;i--){ if(Integer.parseInt(s[i])!=Integer.parseInt(s[k-1])) break; else --res; } out.println(res); } else out.println(-1); out.flush(); out.close(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
30c02ba66ecdd660832ce6c7cd03ae9b
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedInputStream; import java.util.Arrays; public class C222A { public void solve() throws Exception { int n = nextInt(); int k = nextInt() - 1; int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) { arr[i] = nextInt(); } for (int i = k; i < arr.length - 1; i++) { if (arr[i] != arr[i + 1]) { println(-1); return; } } int r = arr[arr.length - 1]; for (int i = k - 1; i >= 0; i--) { if (r != arr[i]) { println(i + 1); return; } } println(0); } // ------------------------------------------------------ void debug(Object... os) { System.err.println(Arrays.deepToString(os)); } void print(Object... os) { if (os != null && os.length > 0) System.out.print(os[0].toString()); for (int i = 1; i < os.length; ++i) System.out.print(" " + os[i].toString()); } void println(Object... os) { print(os); System.out.println(); } BufferedInputStream bis = new BufferedInputStream(System.in); String nextWord() throws Exception { char c = (char) bis.read(); while (c <= ' ') c = (char) bis.read(); StringBuilder sb = new StringBuilder(); while (c > ' ') { sb.append(c); c = (char) bis.read(); } return new String(sb); } String nextLine() throws Exception { char c = (char) bis.read(); while (c <= ' ') c = (char) bis.read(); StringBuilder sb = new StringBuilder(); while (c != '\n' && c != '\r') { sb.append(c); c = (char) bis.read(); } return new String(sb); } int nextInt() throws Exception { return Integer.parseInt(nextWord()); } long nextLong() throws Exception { return Long.parseLong(nextWord()); } public static void main(String[] args) throws Exception { new C222A().solve(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
1c835986c0b819d3f0f199f68123e06e
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class hari { public int temp(int [] a,int k){ int x=a[k-1]; for(int i=k;i<a.length;i++){ if(x!=a[i]) { return -1; } } int count=0; for (int i = k-1; i >=0; i--) { if(x!=a[i]) return i+1; } return 0; } public static void main(String args[]) throws IOException { //BufferedReader c = new BufferedReader(new InputStreamReader(System.in)); Scanner c=new Scanner(System.in); int T=c.nextInt(); int k=c.nextInt(); int [] a=new int[T]; for (int t = 0; t < T; t++) { a[t]=c.nextInt(); } hari m=new hari(); System.out.println(m.temp(a, k)); } } //must declare new clas
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
a4783fae2a89017f86016eb2867749a8
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int numbers = Integer.parseInt(tokenizer.nextToken()); int kNumber = Integer.parseInt(tokenizer.nextToken()) - 1; tokenizer = new StringTokenizer(reader.readLine()); int[] seq = new int[numbers]; for (int i = 0; i < numbers; i++) { seq[i] = Integer.parseInt(tokenizer.nextToken()); } int numberOfMove = -1; for (int i = kNumber; i < numbers; i++) { if(seq[i] == seq[kNumber]){ numberOfMove = seq[i]; } else { numberOfMove = -1; break; } } if(numberOfMove == -1){ System.out.println(-1); } else { int result = 0; for(int k=kNumber;k>=0;k--){ if(seq[k]!=seq[kNumber]){ result = k+1; break; } } System.out.println(result); } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
2e6dc97c19bbfd1cc563c29dfd9d825b
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class A { static Scanner in; static int next() throws Exception {return in.nextInt();}; // static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;} // static BufferedReader in; static PrintWriter out; public static void main(String[] args) throws Exception { in = new Scanner(System.in); // in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = next(), k = next(); int a[] = new int[n]; for (int i = 0;i < n;i++) a[i] = next(); int r = n-1; while (r > 0 && a[r] == a[r-1]) r--; if (r < k) out.println(r); else out.println(-1); out.println(); out.close(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
b15568a40e6857771645b41e88d0ae97
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.*; import java.util.*; public class Main { Scanner in; PrintWriter out; void solve() { int n = in.nextInt(); int k = in.nextInt(); int sequence[] = new int[n]; for (int i = 0; i < n; i++) { sequence[i] = in.nextInt(); } for (int i = n - 2; i >= 0; i--) { if (sequence[i] != sequence[n - 1]) { if (1 + i < k) { out.println(1 + i); } else { out.println(-1); } return; } } out.println(0); } void run() { in = new Scanner(System.in); out = new PrintWriter(System.out); try { solve(); } finally { out.close(); } } public static void main(String[] args) { new Main().run(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
5f9029b355c59a76a9bb340541e1626e
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputReader r = new InputReader(System.in); int d = -1; int N = r.nextInt(); int K = r.nextInt(); int[] a = new int[N]; for(int i = 0; i < N; i++){ a[i] = r.nextInt(); } for(int i = K - 1; i < N; i++){ if(d == -1 || d == a[i]){ d = a[i]; }else{ System.out.println(-1); return; } } int best = 0; for(int i = K - 2; i >= 0; i--){ if(d != a[i]){ best = i + 1; break; } } System.out.println(best); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine(){ try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return 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
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
adcfd30affb5da3ae7c6b1483c3453ec
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.*; import java.util.*; public class pr137A implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer str; public void solve() throws IOException { int n = nextInt(); int k = nextInt(); int a[] = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = nextInt(); } while ((k >= 2) && (a[k - 1] == a[k - 2])) k--; boolean f = true; for (int i = k - 1; i < n - 1; i++) { if (a[i] != a[i + 1]) { f = false; } } if (f) out.println(k - 1); else out.println(-1); } public String nextToken() throws IOException { while (str == null || !str.hasMoreTokens()) { str = new StringTokenizer(in.readLine()); } return str.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (IOException e) { } } public static void main(String[] args) { new Thread(new pr137A()).start(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
e31a6ef63333d46ecff3ebd9279d680d
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
public class ABC { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub java.util.Scanner sc=new java.util.Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); int[] a=new int[n] ; Boolean flag=true; Boolean flagK=true; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(i>0&&flag==true&&a[i]!=a[i-1]) flag=false; if(i>=k&&flagK==true&&a[i]!=a[i-1]) flagK=false; } if(flag==true) { System.out.println("0"); return; } else if(flagK==false) { System.out.println("-1"); return; } else { int pos=k-2; while(true) { if(a[k-1]!=a[pos]) { System.out.println(pos+1); return; } else pos--; } } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
d049af8e92511a6a0dcd587b666f767f
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.*; public class A222 { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int a[] = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = in.nextInt(); if (n == 1) { System.out.println(0); return; } for (int i = k + 1; i <= n; i++) { if (a[i] != a[k]) { System.out.println(-1); return; } } for (int i = n - 1; i > 0; i--) { if (a[i] != a[n]) { System.out.println(i); return; } } System.out.println(0); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
96b42b54e739763633fe7116c6c98508
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; public class CF { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N =sc.nextInt(); int K = sc.nextInt()-1; int[] array = new int[N]; for(int a=0;a<N;a++)array[a]=sc.nextInt(); HashSet<Integer> HS = new HashSet<Integer>(); for(int a=K;a<N;a++){ HS.add(array[a]); } if(HS.size()!=1)System.out.println("-1"); else{ int ans = K; while(ans>0&&array[ans-1]==array[K])ans--; System.out.println(ans); } } private static boolean done(LinkedList<Integer> LL) { HashSet<Integer> HS = new HashSet<Integer>(); for(Integer x : LL){ HS.add(x); } return HS.size()==1; } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
4e0d321043bba32b0cc10063e9ea7b31
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import static java.lang.Math.*; import java.io.*; import java.math.BigInteger; import java.util.*; public class a implements Runnable { public void run() { int n = nextInt(), k = nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } int a = arr[k - 1]; for (int i = k; i < n; i++) { if (a != arr[i]) { System.out.println(-1); return; } } int ans = k - 1; for (int i = k - 2; i >= 0; i--) { if (a == arr[i]) ans--; else break; } System.out.println(ans); // -------------------------------------------------------------------------------------------- out.close(); System.exit(0); } private static boolean fileIOMode = false; private static String problemName = "yyy"; private static BufferedReader in; private static PrintWriter out; private static StringTokenizer tokenizer; public static void main(String[] args) throws Exception { if (fileIOMode) { in = new BufferedReader(new FileReader(problemName + ".in")); out = new PrintWriter(problemName + ".out"); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } tokenizer = new StringTokenizer(""); new Thread(new a()).start(); } private static String nextLine() { try { return in.readLine(); } catch (IOException e) { return null; } } private static String nextToken() { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(nextLine()); } return tokenizer.nextToken(); } private static int nextInt() { return Integer.parseInt(nextToken()); } private static long nextLong() { return Long.parseLong(nextToken()); } private static double nextDouble() { return Double.parseDouble(nextToken()); } private static BigInteger nextBigInteger() { return new BigInteger(nextToken()); } private static void print(Object o) { if (fileIOMode) { System.out.print(o); } out.print(o); } private static void println(Object o) { if (fileIOMode) { System.out.println(o); } out.println(o); } private static void printf(String s, Object... o) { if (fileIOMode) { System.out.printf(s, o); } out.printf(s, o); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
ead4186f6298ac43a9b8aa03432789dd
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; import java.util.Collections; import java.util.ArrayList; public class A222 { int[]num; public static void main(String[]arg) { new A222().solve(); } public void solve(){ Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int n = in.nextInt(); int k = in.nextInt(); num = new int[n]; for(int i = 0; i < n; i++) { num[i] = in.nextInt(); } int on = 0; int index = 0; /*while(k > 0) { if(equElem(num.size()- 1)) break; else { num.add(num.get(k)); num.remove(0); int i = num.get(0); int i2 = num.get(1); int i3 = num.get(2); index++; on++; } k--; }*/ int i = n - 1; k --; while(i > 0) { if(num[i] != num[i - 1]) break; i--; } if(i > k) on = -1;else on = i; System.out.printf("%d",on); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
83c02ee7c9f0a93752f82c448c915f9d
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner scan = new Scanner(System.in); while (scan.hasNext()) { int n = scan.nextInt(); int k = scan.nextInt(); int[] array = new int[n]; for (int i = 0; i < array.length; i++) { array[i] = scan.nextInt(); } boolean we7esh = false; k--; for (int i = k; i < array.length - 1; i++) { if (array[i] != array[i + 1]) { we7esh = true; break; } } if (we7esh) System.out.println(-1); else { int res = 0; for (int i = k; i > 0; i--) { if (array[i] != array[i - 1]) { res = i; break; } } System.out.println(res); } } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
fbe55ffde99bcf8231610ae14eb75453
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.*; import java.awt.geom.*; public class Main{ private void doit(){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ int n = sc.nextInt(); int k = sc.nextInt(); ArrayList<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < n; i++){ list.add(sc.nextInt()); } boolean flg2 = true; int kvalue = list.get(k-1); for(int i = k; i < n; i++){ if(kvalue != list.get(i)){ flg2 = false; break; } } if(! flg2){ System.out.println(-1); } else{ int count = 0; int value = list.get(k-1); for(int i = k-2; i >= 0; i--){ if(value == list.get(i)){ count++; } else{ break; } } //System.out.println("c = " + count + "k = " + k ); count += n - k + 1; System.out.println(n - count); } } } public static void main(String [] args){ new Main().doit(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
c4df4e4a552a23ce6581655bb356f36e
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.util.ArrayDeque; import java.io.PrintWriter; import java.util.Deque; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt() - 1; int[] a = new int[n]; Deque<Integer> deque = new ArrayDeque<Integer>(); int[] cnt = new int[100001]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); cnt[a[i]]++; if (cnt[a[i]] == n) { out.println(0); return; } deque.addLast(a[i]); } int pos = k; for (int it = 1; it <= n; it++) { int front = deque.pollFirst(); cnt[front]--; int end = a[pos++]; deque.addLast(end); if (++cnt[end] == n) { out.println(it); return; } if (pos == n) pos = k; } out.println(-1); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
178d60c78385b8ebdcd31c89ac2ff2c7
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class shoo { public static void main(String args[]) throws IOException { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); int k=sc.nextInt(); k--; int a[]=new int[t]; for(int i=0;i<t;i++) a[i]=sc.nextInt(); boolean fi=false; for(int i=k;i<t-1;i++) { if(a[i]!=a[i+1]) { fi=true; break; } else; } if(fi) System.out.println("-1"); else { int temp=a[k]; int i=k; while(i>=0 && temp==a[i] ) { i--; } System.out.println(i+1); } } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
36ef53ff81abf76413cfe9f7f935e94a
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class A137 { public void solve() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int i = 0, j = 0; int a[] = new int[n]; int test[] = new int[n]; int dis = 0; Set set = new HashSet(); for (i = 0; i < n; ++i) { a[i] = sc.nextInt(); test[i] = a[i]; set.add(a[i]); } for (i = k; i < n; ++i) { if (a[k - 1] != a[i]) { System.out.println("-1"); System.exit(0); } } int count = 0; for (i = k - 2; i > -1; --i) { if (a[k - 1] == a[i]) { count++; } else { break; } } System.out.println((k-1)- count); } public static void main(String[] args) { new A137().solve(); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
ea6af137d54ee54c5af721009a761a50
train_002.jsonl
1347291900
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
256 megabytes
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); int p=0,ans=0; int a[] = new int [2*n]; for (int i = 1; i <= n; i++) { a[i]=sc.nextInt(); } for (int i = 1; i <= n-1; i++) { if(a[i]==a[i+1])p++; } if(p==n-1){ System.out.println("0"); return; } p=0; for (int i = k; i <=n-1; i++) { if(a[i]!=a[i+1]){ System.out.println("-1"); return; } } for (int i = k-1; i >=1; i--) { if(a[k]!=a[i]){ans=i;break;} } System.out.println(ans); } }
Java
["3 2\n3 1 1", "3 1\n3 1 1"]
2 seconds
["1", "-1"]
NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
Java 6
standard input
[ "implementation", "brute force" ]
bcee233ddb1509a14f2bd9fd5ec58798
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
1,200
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
standard output
PASSED
c8cf078da2ab0824ef380b56f54080e1
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class CF_237E { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String t = scan.next(); int n = scan.nextInt(); int[][] charFreq = new int[n+1][26]; int[] cap = new int[n]; for(int i=0;i<=n;i++) { String line = i == n ? t : scan.next(); if(i < n) { cap[i] = scan.nextInt(); } for(int j=0;j<line.length();j++) charFreq[i][line.charAt(j)-'a']++; } // 1 source + n words + 26 letters + sink MinCostMaxFlow flow = new MinCostMaxFlow(1+n+26+1, n + 26*n + 26, 0,1+n+26); for(int word=0;word<n;word++) { flow.add(0, 1+word, cap[word], 0); for(int letter=0;letter<26;letter++) { if(charFreq[word][letter] == 0 || charFreq[n][letter] == 0) continue; flow.add(word+1, 1+n+letter, charFreq[word][letter], word+1); } } for(int letter=0;letter<26;letter++) { if(charFreq[n][letter] == 0) continue; flow.add(1+n+letter,1+n+26,charFreq[n][letter],0); } flow.push(); if(flow.pushedFlow < t.length()) { System.out.println(-1); return; } System.out.println(flow.pushedCost); } static class MinCostMaxFlow { public static final int inf = Integer.MAX_VALUE; int n, cnt; int m; int head[], next[], to[], flow[], cost[], capacity[], phi[], parent[], parentEdge[], dist[]; boolean used[]; int s, t; int pushedFlow = 0, pushedCost = 0; public MinCostMaxFlow(int n, int m, int s, int t) { this.s = s; this.t = t; this.n = n; m = 2*m; this.m = m; // int m = n * n; head = new int[n]; next = new int[m]; to = new int[m]; flow = new int[m]; cost = new int[m]; capacity = new int[m]; phi = new int[n]; parent = new int[n]; parentEdge = new int[n]; dist = new int[n]; used = new boolean[n]; clear(); } void clear() { cnt = 0; Arrays.fill(head, -1); } void add(int u, int v, int cap, int cos) { to[cnt] = v; cost[cnt] = cos; capacity[cnt] = cap; next[cnt] = head[u]; head[u] = cnt++; to[cnt] = u; cost[cnt] = -cos; capacity[cnt] = 0; next[cnt] = head[v]; head[v] = cnt++; } void calcPhi() { Arrays.fill(phi, 0, n, 0); for (int k = 0; k < n; ++k) for (int v = 0; v < n; ++v) for (int i = head[v]; i >= 0; i = next[i]) phi[to[i]] = Math.min(phi[to[i]], phi[v] + cost[i]); } void push() { calcPhi(); while (true) { Arrays.fill(dist, 0, n, inf); Arrays.fill(used, 0, n, false); parent[t] = parent[s] = -1; dist[s] = 0; for (int iter = 0; iter < n; ++iter) { int u = -1; for (int i = 0; i < n; ++i) if (!used[i] && dist[i] != inf && (u == -1 || dist[u] > dist[i])) u = i; if (u == -1 || u == t) break; used[u] = true; for (int i = head[u]; i > -1; i = next[i]) if (flow[i] < capacity[i]) { int v = to[i]; if (dist[v] > dist[u] + phi[u] - phi[v] + cost[i]) { dist[v] = dist[u] + phi[u] - phi[v] + cost[i]; parent[v] = u; parentEdge[v] = i; } } } if (parent[t] == -1) break; int addF = inf; for (int v = t; v != s; v = parent[v]) { int i = parentEdge[v]; addF = Math.min(addF, capacity[i] - flow[i]); } // System.err.println(addF); pushedFlow += addF; for (int v = t; v != s; v = parent[v]) { int i = parentEdge[v]; flow[i] += addF; flow[i ^ 1] -= addF; pushedCost += addF * cost[i]; } for (int i = 0; i < n; ++i) phi[i] += dist[i]; } } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
639446c3236026da53d5580fb4aacb19
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
//package practice.E; import java.io.*; import java.util.*; public class CF237E { static ArrayList<Edge>[] adj; public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); char[] t = sc.next().toCharArray(); int N = 26; int n = sc.nextInt(); int M = n; String[] strings = new String[n]; int[] max = new int[n]; for (int i = 0; i < n; i++) { strings[i] = sc.next(); max[i] = sc.nextInt(); } int[] freq = new int[26]; for (int i = 0; i < t.length; i++) freq[t[i]-'a']++; adj = new ArrayList[N + 2*M + 10]; for (int i = 0; i < adj.length; i++) { adj[i] = new ArrayList<>(); } int S = 0; int T = adj.length-1; int inf = 1000000; for (int st = 1; st <= n; st++) { addEdge(adj, st+N, T, max[st-1], 0); // System.err.println(st+N + " " + T + " " + max[st-1]); } for (int i = 0; i < N; i++) { addEdge(adj, S, i+1, freq[i], 0); // System.err.println(S + " " + (i+1) + " " + freq[i]); for (int j = 0; j < M; j++) { if(strings[j].contains((char)(i+'a')+"")){ int[] freq2 = new int[26]; for (int k = 0; k < strings[j].length(); k++) { freq2[strings[j].charAt(k)-'a']++; } addEdge(adj, i+1, j+1+N, freq2[i], j+1); // System.err.println(i+1 + " " + (j+1+N) + " " + freq2[i]); } } } long[] ans = minCostFlow(adj, S, T, inf); // System.err.println(ans[0]); if(ans[0] < t.length) pw.println(-1); else pw.println(ans[1]); pw.flush(); pw.close(); } static class Edge { int to, f, cap, cost, rev; Edge(int to, int cap, int cost, int rev) { this.to = to; this.cap = cap; this.cost = cost; this.rev = rev; } } public static void addEdge(List<Edge>[] graph, int s, int t, int cap, int cost) { graph[s].add(new Edge(t, cap, cost, graph[t].size())); graph[t].add(new Edge(s, 0, -cost, graph[s].size() - 1)); } static void bellmanFord(List<Edge>[] graph, int s, int[] dist) { int n = graph.length; Arrays.fill(dist, Integer.MAX_VALUE); dist[s] = 0; boolean[] inqueue = new boolean[n]; int[] q = new int[n]; int qt = 0; q[qt++] = s; for (int qh = 0; (qh - qt) % n != 0; qh++) { int u = q[qh % n]; inqueue[u] = false; for (int i = 0; i < graph[u].size(); i++) { Edge e = graph[u].get(i); if (e.cap <= e.f) continue; int v = e.to; int ndist = dist[u] + e.cost; if (dist[v] > ndist) { dist[v] = ndist; if (!inqueue[v]) { inqueue[v] = true; q[qt++ % n] = v; } } } } } public static long[] minCostFlow(List<Edge>[] graph, int s, int t, int maxf) { int n = graph.length; int[] prio = new int[n]; int[] curflow = new int[n]; int[] prevedge = new int[n]; int[] prevnode = new int[n]; int[] pot = new int[n]; bellmanFord(graph, s, pot); // bellmanFord invocation can be skipped if edges costs are non-negative long flow = 0; long flowCost = 0; while (flow < maxf) { PriorityQueue<Long> q = new PriorityQueue<>(); q.add((long) s); Arrays.fill(prio, Integer.MAX_VALUE); prio[s] = 0; boolean[] finished = new boolean[n]; curflow[s] = Integer.MAX_VALUE; while (!finished[t] && !q.isEmpty()) { long cur = q.remove(); int u = (int) (cur & 0xFFFF_FFFFL); int priou = (int) (cur >>> 32); if (priou != prio[u]) continue; finished[u] = true; for (int i = 0; i < graph[u].size(); i++) { Edge e = graph[u].get(i); if (e.f >= e.cap) continue; int v = e.to; int nprio = prio[u] + e.cost + pot[u] - pot[v]; if (prio[v] > nprio) { prio[v] = nprio; q.add(((long) nprio << 32) + v); prevnode[v] = u; prevedge[v] = i; curflow[v] = Math.min(curflow[u], e.cap - e.f); } } } if (prio[t] == Integer.MAX_VALUE) break; for (int i = 0; i < n; i++) if (finished[i]) pot[i] += prio[i] - prio[t]; int df = Math.min(curflow[t], maxf - (int)flow); flow += df; for (int v = t; v != s; v = prevnode[v]) { Edge e = graph[prevnode[v]].get(prevedge[v]); e.f += df; graph[v].get(e.rev).f -= df; flowCost += (long)df * e.cost; } } return new long[] {flow, flowCost}; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s)));} public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();} public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
5943ccf599b64d5d19b8f93bf32f411e
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
//package practice.E; import java.io.*; import java.util.*; public class CF237E { static ArrayList<Edge>[] adj; public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); char[] t = sc.next().toCharArray(); int N = 26; int n = sc.nextInt(); int M = n; String[] strings = new String[n]; int[] max = new int[n]; for (int i = 0; i < n; i++) { strings[i] = sc.next(); max[i] = sc.nextInt(); } int[] freq = new int[26]; for (int i = 0; i < t.length; i++) freq[t[i]-'a']++; adj = new ArrayList[N + M + 10]; for (int i = 0; i < adj.length; i++) { adj[i] = new ArrayList<>(); } int S = 0; int T = adj.length-1; int inf = 1000000; for (int st = 1; st <= n; st++) { addEdge(adj, st+N, T, max[st-1], 0); // System.err.println(st+N + " " + T + " " + max[st-1]); } for (int i = 0; i < N; i++) { addEdge(adj, S, i+1, freq[i], 0); // System.err.println(S + " " + (i+1) + " " + freq[i]); for (int j = 0; j < M; j++) { if(strings[j].contains((char)(i+'a')+"")){ int[] freq2 = new int[26]; for (int k = 0; k < strings[j].length(); k++) { freq2[strings[j].charAt(k)-'a']++; } addEdge(adj, i+1, j+1+N, freq2[i], j+1); // System.err.println(i+1 + " " + (j+1+N) + " " + freq2[i]); } } } long[] ans = minCostFlow(adj, S, T, inf); // System.err.println(ans[0]); if(ans[0] < t.length) pw.println(-1); else pw.println(ans[1]); pw.flush(); pw.close(); } static class Edge { int to, f, cap, cost, rev; Edge(int to, int cap, int cost, int rev) { this.to = to; this.cap = cap; this.cost = cost; this.rev = rev; } } public static void addEdge(List<Edge>[] graph, int s, int t, int cap, int cost) { graph[s].add(new Edge(t, cap, cost, graph[t].size())); graph[t].add(new Edge(s, 0, -cost, graph[s].size() - 1)); } static void bellmanFord(List<Edge>[] graph, int s, int[] dist) { int n = graph.length; Arrays.fill(dist, Integer.MAX_VALUE); dist[s] = 0; boolean[] inqueue = new boolean[n]; int[] q = new int[n]; int qt = 0; q[qt++] = s; for (int qh = 0; (qh - qt) % n != 0; qh++) { int u = q[qh % n]; inqueue[u] = false; for (int i = 0; i < graph[u].size(); i++) { Edge e = graph[u].get(i); if (e.cap <= e.f) continue; int v = e.to; int ndist = dist[u] + e.cost; if (dist[v] > ndist) { dist[v] = ndist; if (!inqueue[v]) { inqueue[v] = true; q[qt++ % n] = v; } } } } } public static long[] minCostFlow(List<Edge>[] graph, int s, int t, int maxf) { int n = graph.length; int[] prio = new int[n]; int[] curflow = new int[n]; int[] prevedge = new int[n]; int[] prevnode = new int[n]; int[] pot = new int[n]; bellmanFord(graph, s, pot); // bellmanFord invocation can be skipped if edges costs are non-negative long flow = 0; long flowCost = 0; while (flow < maxf) { PriorityQueue<Long> q = new PriorityQueue<>(); q.add((long) s); Arrays.fill(prio, Integer.MAX_VALUE); prio[s] = 0; boolean[] finished = new boolean[n]; curflow[s] = Integer.MAX_VALUE; while (!finished[t] && !q.isEmpty()) { long cur = q.remove(); int u = (int) (cur & 0xFFFF_FFFFL); int priou = (int) (cur >>> 32); if (priou != prio[u]) continue; finished[u] = true; for (int i = 0; i < graph[u].size(); i++) { Edge e = graph[u].get(i); if (e.f >= e.cap) continue; int v = e.to; int nprio = prio[u] + e.cost + pot[u] - pot[v]; if (prio[v] > nprio) { prio[v] = nprio; q.add(((long) nprio << 32) + v); prevnode[v] = u; prevedge[v] = i; curflow[v] = Math.min(curflow[u], e.cap - e.f); } } } if (prio[t] == Integer.MAX_VALUE) break; for (int i = 0; i < n; i++) if (finished[i]) pot[i] += prio[i] - prio[t]; int df = Math.min(curflow[t], maxf - (int)flow); flow += df; for (int v = t; v != s; v = prevnode[v]) { Edge e = graph[prevnode[v]].get(prevedge[v]); e.f += df; graph[v].get(e.rev).f -= df; flowCost += (long)df * e.cost; } } return new long[] {flow, flowCost}; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s)));} public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();} public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
cc992a2b2a224b91875c0084e3ad13ab
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; /* * Heart beats fast * Colors and promises * How to be brave * How can I love when I am afraid... */ //read the question correctly (is y a vowel? what are the exact constraints?) //look out for SPECIAL CASES (n=1?) and overflow (ll vs int?) //always declare multidimensional arrays as [2][n] not [n][2] //it can lead to upto 2-3x diff in runtime //declare int/long tries with 16 array size due to object overhead :D public class Main { static int infi=1000000000; //augementing path finder using bellman ford static boolean sendaunitofflowmyboy() { int[]holala=new int[n+28]; Arrays.fill(holala, infi); holala[0]=0; int[]pred=new int[n+28]; for(int k=0; k<=n+27; k++) for(int i=0; i<=n+27; i++) for(int j=0; j<=n+27; j++) if(cap[i][j]>0&&holala[j]>holala[i]+cost[i][j]) { holala[j]=holala[i]+cost[i][j]; pred[j]=i; } int te=n+27; while(te!=0) { cap[pred[te]][te]--; cap[te][pred[te]]++; te=pred[te]; } if(holala[n+27]!=infi) { count++; fincost+=holala[n+27]; return true; } return false; } static int fincost=0,count=0; static int[][]cap; static int[][]cost; static int n; public static void main(String[] args) throws Exception { String s=ns(); n=ni(); int[][]hola=new int[n+1][26]; cap=new int[n+28][n+28]; cost=new int[n+28][n+28]; for(int i=1; i<=n; i++) { String te=ns(); for(int j=0; j<te.length(); j++) hola[i][te.charAt(j)-'a']++; cap[0][i]=ni(); cost[0][i]=0; for(int j=0; j<26; j++) { cap[i][n+j+1]=hola[i][j]; cost[n+j+1][i]=-i; cost[i][n+j+1]=i; } } int ct[]=new int[26]; for(int i=0; i<s.length(); i++) ct[s.charAt(i)-'a']++; for(int i=n+1; i<=n+26; i++) { cap[i][n+27]=ct[i-n-1]; cost[i][n+27]=0; } while(Main.sendaunitofflowmyboy()&&count!=s.length()); if(count==s.length()) pr(fincost); else pr(-1); System.out.print(output); } /////////////////////////////////////////// /////////////////////////////////////////// ///template from here static class pair { int a, b; pair(){} pair(int c,int d){a=c;b=d;} } static interface combiner { public int combine(int a, int b); } static final int mod=1000000007; static final double eps=1e-9; static final long inf=100000000000000000L; static Reader in=new Reader(); static StringBuilder output=new StringBuilder(); static Random rn=new Random(); static void reverse(int[]a){for(int i=0; i<a.length/2; i++){a[i]^=a[a.length-i-1];a[a.length-i-1]^=a[i];a[i]^=a[a.length-i-1];}} static void sort(int[]a) { int te; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); } static void sort(long[]a) { int te; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); } static void sort(double[]a) { int te; double te1; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { te1=a[te]; a[te]=a[i]; a[i]=te1; } } Arrays.sort(a); } static void sort(int[][]a) { Arrays.sort(a, new Comparator<int[]>() { public int compare(int[]a,int[]b) { if(a[0]>b[0]) return -1; if(b[0]>a[0]) return 1; return 0; } }); } static void sort(pair[]a) { Arrays.sort(a,new Comparator<pair>() { @Override public int compare(pair a,pair b) { if(a.a>b.a) return 1; if(b.a>a.a) return -1; return 0; } }); } static int log2n(long a) { int te=0; while(a>0) { a>>=1; ++te; } return te; } static class vectorl implements Iterable<Long> { long a[]; int size; vectorl(){a=new long[10];size=0;} vectorl(int n){a=new long[n];size=0;} public void add(long b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;} public void sort(){Arrays.sort(a, 0, size);} public void sort(int l, int r){Arrays.sort(a, l, r);} @Override public Iterator<Long> iterator() { Iterator<Long> hola=new Iterator<Long>() { int cur=0; @Override public boolean hasNext() { return cur<size; } @Override public Long next() { return a[cur++]; } }; return hola; } } static class vector implements Iterable<Integer> { int a[],size; vector(){a=new int[10];size=0;} vector(int n){a=new int[n];size=0;} public void add(int b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;} public void sort(){Arrays.sort(a, 0, size);} public void sort(int l, int r){Arrays.sort(a, l, r);} @Override public Iterator<Integer> iterator() { Iterator<Integer> hola=new Iterator<Integer>() { int cur=0; @Override public boolean hasNext() { return cur<size; } @Override public Integer next() { return a[cur++]; } }; return hola; } } //output functions//////////////// static void pr(Object a){output.append(a+"\n");} static void pr(){output.append("\n");} static void p(Object a){output.append(a);} static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");} static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");} static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");} static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");} static void sop(Object a){System.out.println(a);} static void flush(){System.out.println(output);output=new StringBuilder();} ////////////////////////////////// //input functions///////////////// static int ni(){return Integer.parseInt(in.next());} static long nl(){return Long.parseLong(in.next());} static String ns(){return in.next();} static double nd(){return Double.parseDouble(in.next());} static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;} static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;} static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;} static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;} static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;} ////////////////////////////////// //some utility functions static void exit(){System.out.print(output);System.exit(0);} static int min(int... a){int min=a[0];for(int i:a)min=Math.min(min, i);return min;} static int max(int... a){int max=a[0];for(int i:a)max=Math.max(max, i);return max;} static int gcd(int... a){int gcd=a[0];for(int i:a)gcd=gcd(gcd, i);return gcd;} static long min(long... a){long min=a[0];for(long i:a)min=Math.min(min, i);return min;} static long max(long... a){long max=a[0];for(long i:a)max=Math.max(max, i);return max;} static long gcd(long... a){long gcd=a[0];for(long i:a)gcd=gcd(gcd, i);return gcd;} static String pr(String a, long b){String c="";while(b>0){if(b%2==1)c=c.concat(a);a=a.concat(a);b>>=1;}return c;} static long powm(long a, long b, long m){long an=1;long c=a;while(b>0){if(b%2==1)an=(an*c)%m;c=(c*c)%m;b>>=1;}return an;} static int gcd(int a, int b){if(b==0)return a;return gcd(b, a%b);} static long gcd(long a, long b){if(b==0)return a;return gcd(b, a%b);} static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
a66f73f347007c18b5e961bd7117f405
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; /* * Heart beats fast * Colors and promises * How to be brave * How can I love when I am afraid... */ //read the question correctly (is y a vowel? what are the exact constraints?) //look out for SPECIAL CASES (n=1?) and overflow (ll vs int?) //always declare multidimensional arrays as [2][n] not [n][2] //it can lead to upto 2-3x diff in runtime //declare int/long tries with 16 array size due to object overhead :D public class Main { static int infi=1000000000; //augementing path finder using floyd warshall static boolean sendmultipleunitsofflowmyboy() { int[]holala=new int[n+28]; Arrays.fill(holala, infi); holala[0]=0; int[]pred=new int[n+28]; boolean improvement=true; for(int k=0; k<=n+27&&improvement; k++) { improvement=false; for(int i=0; i<=n+27; i++) for(int j=0; j<=n+27; j++) if(cap[i][j]>0&&holala[j]>holala[i]+cost[i][j]) { holala[j]=holala[i]+cost[i][j]; pred[j]=i; improvement=true; } } int te=n+27; int max=10000; while(te!=0) { max=min(max,cap[pred[te]][te]); te=pred[te]; } te=n+27; while(te!=0) { cap[pred[te]][te]-=max; cap[te][pred[te]]+=max; te=pred[te]; } if(holala[n+27]!=infi) { count+=max; fincost+=max*holala[n+27]; return true; } return false; } static int fincost=0,count=0; static int[][]cap; static int[][]cost; static int n; public static void main(String[] args) throws Exception { String s=ns(); n=ni(); int[][]hola=new int[n+1][26]; cap=new int[n+28][n+28]; cost=new int[n+28][n+28]; for(int i=1; i<=n; i++) { String te=ns(); for(int j=0; j<te.length(); j++) hola[i][te.charAt(j)-'a']++; cap[0][i]=ni(); cost[0][i]=0; for(int j=0; j<26; j++) { cap[i][n+j+1]=hola[i][j]; cost[n+j+1][i]=-i; cost[i][n+j+1]=i; } } int ct[]=new int[26]; for(int i=0; i<s.length(); i++) ct[s.charAt(i)-'a']++; for(int i=n+1; i<=n+26; i++) { cap[i][n+27]=ct[i-n-1]; cost[i][n+27]=0; } while(Main.sendmultipleunitsofflowmyboy()&&count!=s.length()); if(count==s.length()) pr(fincost); else pr(-1); System.out.print(output); } /////////////////////////////////////////// /////////////////////////////////////////// ///template from here static class pair { int a, b; pair(){} pair(int c,int d){a=c;b=d;} } static interface combiner { public int combine(int a, int b); } static final int mod=1000000007; static final double eps=1e-9; static final long inf=100000000000000000L; static Reader in=new Reader(); static StringBuilder output=new StringBuilder(); static Random rn=new Random(); static void reverse(int[]a){for(int i=0; i<a.length/2; i++){a[i]^=a[a.length-i-1];a[a.length-i-1]^=a[i];a[i]^=a[a.length-i-1];}} static void sort(int[]a) { int te; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); } static void sort(long[]a) { int te; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); } static void sort(double[]a) { int te; double te1; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { te1=a[te]; a[te]=a[i]; a[i]=te1; } } Arrays.sort(a); } static void sort(int[][]a) { Arrays.sort(a, new Comparator<int[]>() { public int compare(int[]a,int[]b) { if(a[0]>b[0]) return -1; if(b[0]>a[0]) return 1; return 0; } }); } static void sort(pair[]a) { Arrays.sort(a,new Comparator<pair>() { @Override public int compare(pair a,pair b) { if(a.a>b.a) return 1; if(b.a>a.a) return -1; return 0; } }); } static int log2n(long a) { int te=0; while(a>0) { a>>=1; ++te; } return te; } static class vectorl implements Iterable<Long> { long a[]; int size; vectorl(){a=new long[10];size=0;} vectorl(int n){a=new long[n];size=0;} public void add(long b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;} public void sort(){Arrays.sort(a, 0, size);} public void sort(int l, int r){Arrays.sort(a, l, r);} @Override public Iterator<Long> iterator() { Iterator<Long> hola=new Iterator<Long>() { int cur=0; @Override public boolean hasNext() { return cur<size; } @Override public Long next() { return a[cur++]; } }; return hola; } } static class vector implements Iterable<Integer> { int a[],size; vector(){a=new int[10];size=0;} vector(int n){a=new int[n];size=0;} public void add(int b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;} public void sort(){Arrays.sort(a, 0, size);} public void sort(int l, int r){Arrays.sort(a, l, r);} @Override public Iterator<Integer> iterator() { Iterator<Integer> hola=new Iterator<Integer>() { int cur=0; @Override public boolean hasNext() { return cur<size; } @Override public Integer next() { return a[cur++]; } }; return hola; } } //output functions//////////////// static void pr(Object a){output.append(a+"\n");} static void pr(){output.append("\n");} static void p(Object a){output.append(a);} static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");} static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");} static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");} static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");} static void sop(Object a){System.out.println(a);} static void flush(){System.out.println(output);output=new StringBuilder();} ////////////////////////////////// //input functions///////////////// static int ni(){return Integer.parseInt(in.next());} static long nl(){return Long.parseLong(in.next());} static String ns(){return in.next();} static double nd(){return Double.parseDouble(in.next());} static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;} static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;} static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;} static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;} static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;} ////////////////////////////////// //some utility functions static void exit(){System.out.print(output);System.exit(0);} static int min(int... a){int min=a[0];for(int i:a)min=Math.min(min, i);return min;} static int max(int... a){int max=a[0];for(int i:a)max=Math.max(max, i);return max;} static int gcd(int... a){int gcd=a[0];for(int i:a)gcd=gcd(gcd, i);return gcd;} static long min(long... a){long min=a[0];for(long i:a)min=Math.min(min, i);return min;} static long max(long... a){long max=a[0];for(long i:a)max=Math.max(max, i);return max;} static long gcd(long... a){long gcd=a[0];for(long i:a)gcd=gcd(gcd, i);return gcd;} static String pr(String a, long b){String c="";while(b>0){if(b%2==1)c=c.concat(a);a=a.concat(a);b>>=1;}return c;} static long powm(long a, long b, long m){long an=1;long c=a;while(b>0){if(b%2==1)an=(an*c)%m;c=(c*c)%m;b>>=1;}return an;} static int gcd(int a, int b){if(b==0)return a;return gcd(b, a%b);} static long gcd(long a, long b){if(b==0)return a;return gcd(b, a%b);} static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
dcb01d3080a92a294911782595a22698
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; /* * Heart beats fast * Colors and promises * How to be brave * How can I love when I am afraid... */ //read the question correctly (is y a vowel? what are the exact constraints?) //look out for SPECIAL CASES (n=1?) and overflow (ll vs int?) //always declare multidimensional arrays as [2][n] not [n][2] //it can lead to upto 2-3x diff in runtime //declare int/long tries with 16 array size due to object overhead :D public class Main { static int infi=1000000000; //augementing path finder using floyd warshall static boolean sendaunitofflowmyboy() { int[]holala=new int[n+28]; Arrays.fill(holala, infi); holala[0]=0; int[]pred=new int[n+28]; boolean improvement=true; for(int k=0; k<=n+27&&improvement; k++) { improvement=false; for(int i=0; i<=n+27; i++) for(int j=0; j<=n+27; j++) if(cap[i][j]>0&&holala[j]>holala[i]+cost[i][j]) { holala[j]=holala[i]+cost[i][j]; pred[j]=i; improvement=true; } } int te=n+27; while(te!=0) { cap[pred[te]][te]--; cap[te][pred[te]]++; te=pred[te]; } if(holala[n+27]!=infi) { count++; fincost+=holala[n+27]; return true; } return false; } static int fincost=0,count=0; static int[][]cap; static int[][]cost; static int n; public static void main(String[] args) throws Exception { String s=ns(); n=ni(); int[][]hola=new int[n+1][26]; cap=new int[n+28][n+28]; cost=new int[n+28][n+28]; for(int i=1; i<=n; i++) { String te=ns(); for(int j=0; j<te.length(); j++) hola[i][te.charAt(j)-'a']++; cap[0][i]=ni(); cost[0][i]=0; for(int j=0; j<26; j++) { cap[i][n+j+1]=hola[i][j]; cost[n+j+1][i]=-i; cost[i][n+j+1]=i; } } int ct[]=new int[26]; for(int i=0; i<s.length(); i++) ct[s.charAt(i)-'a']++; for(int i=n+1; i<=n+26; i++) { cap[i][n+27]=ct[i-n-1]; cost[i][n+27]=0; } while(Main.sendaunitofflowmyboy()&&count!=s.length()); if(count==s.length()) pr(fincost); else pr(-1); System.out.print(output); } /////////////////////////////////////////// /////////////////////////////////////////// ///template from here static class pair { int a, b; pair(){} pair(int c,int d){a=c;b=d;} } static interface combiner { public int combine(int a, int b); } static final int mod=1000000007; static final double eps=1e-9; static final long inf=100000000000000000L; static Reader in=new Reader(); static StringBuilder output=new StringBuilder(); static Random rn=new Random(); static void reverse(int[]a){for(int i=0; i<a.length/2; i++){a[i]^=a[a.length-i-1];a[a.length-i-1]^=a[i];a[i]^=a[a.length-i-1];}} static void sort(int[]a) { int te; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); } static void sort(long[]a) { int te; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); } static void sort(double[]a) { int te; double te1; for(int i=0; i<a.length; i+=2) { te=rn.nextInt(a.length); if(i!=te) { te1=a[te]; a[te]=a[i]; a[i]=te1; } } Arrays.sort(a); } static void sort(int[][]a) { Arrays.sort(a, new Comparator<int[]>() { public int compare(int[]a,int[]b) { if(a[0]>b[0]) return -1; if(b[0]>a[0]) return 1; return 0; } }); } static void sort(pair[]a) { Arrays.sort(a,new Comparator<pair>() { @Override public int compare(pair a,pair b) { if(a.a>b.a) return 1; if(b.a>a.a) return -1; return 0; } }); } static int log2n(long a) { int te=0; while(a>0) { a>>=1; ++te; } return te; } static class vectorl implements Iterable<Long> { long a[]; int size; vectorl(){a=new long[10];size=0;} vectorl(int n){a=new long[n];size=0;} public void add(long b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;} public void sort(){Arrays.sort(a, 0, size);} public void sort(int l, int r){Arrays.sort(a, l, r);} @Override public Iterator<Long> iterator() { Iterator<Long> hola=new Iterator<Long>() { int cur=0; @Override public boolean hasNext() { return cur<size; } @Override public Long next() { return a[cur++]; } }; return hola; } } static class vector implements Iterable<Integer> { int a[],size; vector(){a=new int[10];size=0;} vector(int n){a=new int[n];size=0;} public void add(int b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;} public void sort(){Arrays.sort(a, 0, size);} public void sort(int l, int r){Arrays.sort(a, l, r);} @Override public Iterator<Integer> iterator() { Iterator<Integer> hola=new Iterator<Integer>() { int cur=0; @Override public boolean hasNext() { return cur<size; } @Override public Integer next() { return a[cur++]; } }; return hola; } } //output functions//////////////// static void pr(Object a){output.append(a+"\n");} static void pr(){output.append("\n");} static void p(Object a){output.append(a);} static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");} static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");} static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");} static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");} static void sop(Object a){System.out.println(a);} static void flush(){System.out.println(output);output=new StringBuilder();} ////////////////////////////////// //input functions///////////////// static int ni(){return Integer.parseInt(in.next());} static long nl(){return Long.parseLong(in.next());} static String ns(){return in.next();} static double nd(){return Double.parseDouble(in.next());} static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;} static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;} static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;} static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;} static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;} ////////////////////////////////// //some utility functions static void exit(){System.out.print(output);System.exit(0);} static int min(int... a){int min=a[0];for(int i:a)min=Math.min(min, i);return min;} static int max(int... a){int max=a[0];for(int i:a)max=Math.max(max, i);return max;} static int gcd(int... a){int gcd=a[0];for(int i:a)gcd=gcd(gcd, i);return gcd;} static long min(long... a){long min=a[0];for(long i:a)min=Math.min(min, i);return min;} static long max(long... a){long max=a[0];for(long i:a)max=Math.max(max, i);return max;} static long gcd(long... a){long gcd=a[0];for(long i:a)gcd=gcd(gcd, i);return gcd;} static String pr(String a, long b){String c="";while(b>0){if(b%2==1)c=c.concat(a);a=a.concat(a);b>>=1;}return c;} static long powm(long a, long b, long m){long an=1;long c=a;while(b>0){if(b%2==1)an=(an*c)%m;c=(c*c)%m;b>>=1;}return an;} static int gcd(int a, int b){if(b==0)return a;return gcd(b, a%b);} static long gcd(long a, long b){if(b==0)return a;return gcd(b, a%b);} static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
3860acb84345acdc740a3fd841bc39b5
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class Main { public static void main(String[] args) throws IOException { new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); private void run() throws IOException { if (new File("input.txt").exists()) in = new BufferedReader(new FileReader("input.txt")); else in = new BufferedReader(new InputStreamReader(System.in)); if (new File("output.txt").exists()) out = new PrintWriter("output.txt"); else out = new PrintWriter(System.out); solve(); in.close(); out.close(); } final int ALPHABET = 'z' - 'a' + 1; final int MAX_N = ALPHABET + 100 + 2 + 100; final int MAX_M = MAX_N * MAX_N + 10; final int inf = Integer.MAX_VALUE / 2 - 1; char s[]; int cnt[] = new int[ALPHABET]; int n; char t[][]; int c[]; void solve() throws IOException { s = nextToken().toCharArray(); n = nextInt(); t = new char[n][]; c = new int[n]; for (int i = 0; i < n; ++i) { t[i] = nextToken().toCharArray(); c[i] = nextInt(); } for (int i = 0; i < s.length; ++i) cnt[s[i] - 'a']++; int S = 0, size = n + 2 + ALPHABET, T = size - 1; MinCostMaxFlow engine = new MinCostMaxFlow(size, S, T); for (int i = 1; i <= n; ++i) engine.add(S, i, c[i - 1], i); for (int i = 0; i < ALPHABET; ++i) if (cnt[i] != 0) engine.add(n + i + 1, T, cnt[i], 0); for (int i = 0; i < n; ++i) { fill(cnt, 0); for (int j = 0; j < t[i].length; ++j) cnt[t[i][j] - 'a']++; for (int j = 0; j < ALPHABET; ++j) if (cnt[j] != 0) engine.add(i + 1, n + j + 1, cnt[j], 0); } engine.push(); out.println((engine.pushedFlow == s.length) ? engine.pushedCost : -1); } class MinCostMaxFlow { int n, cnt; int head[] = new int[MAX_N], next[] = new int[MAX_M], to[] = new int[MAX_M], flow[] = new int[MAX_M], cost[] = new int[MAX_M], capacity[] = new int[MAX_M], phi[] = new int[MAX_N], parent[] = new int[MAX_N], parentEdge[] = new int[MAX_N], dist[] = new int[MAX_N]; boolean used[] = new boolean[MAX_N]; int s, t; int pushedFlow = 0, pushedCost = 0; public MinCostMaxFlow(int n, int s, int t) { this.s = s; this.t = t; this.n = n; clear(); } void clear() { cnt = 0; fill(head, -1); } void add(int u, int v, int cap, int cos) { to[cnt] = v; cost[cnt] = cos; capacity[cnt] = cap; next[cnt] = head[u]; head[u] = cnt++; to[cnt] = u; cost[cnt] = -cos; capacity[cnt] = 0; next[cnt] = head[v]; head[v] = cnt++; } void calcPhi() { fill(phi, 0, n, 0); for (int k = 0; k < n; ++k) for (int v = 0; v < n; ++v) for (int i = head[v]; i > -1; i = next[i]) phi[to[i]] = min(phi[to[i]], phi[v] + cost[i]); } void push() { calcPhi(); while (true) { fill(dist, 0, n, inf); fill(used, 0, n, false); parent[t] = parent[s] = -1; dist[s] = 0; for (int iter = 0; iter < n; ++iter) { int u = -1; for (int i = 0; i < n; ++i) if (!used[i] && dist[i] != inf && (u == -1 || dist[u] > dist[i])) u = i; if (u == -1 || u == t) break; used[u] = true; for (int i = head[u]; i > -1; i = next[i]) if (flow[i] < capacity[i]) { int v = to[i]; if (dist[v] > dist[u] + phi[u] - phi[v] + cost[i]) { dist[v] = dist[u] + phi[u] - phi[v] + cost[i]; parent[v] = u; parentEdge[v] = i; } } } if (parent[t] == -1) break; int addF = inf; for (int v = t; v != s; v = parent[v]) { int i = parentEdge[v]; addF = min(addF, capacity[i] - flow[i]); } // System.err.println(addF); pushedFlow += addF; for (int v = t; v != s; v = parent[v]) { int i = parentEdge[v]; flow[i] += addF; flow[i ^ 1] -= addF; pushedCost += addF * cost[i]; } for (int i = 0; i < n; ++i) phi[i] += dist[i]; } } } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } String nextToken() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String str = in.readLine(); if (str == null) return true; st = new StringTokenizer(str); } return false; } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
e7513002d614a985070915075e44d747
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
// practice with rainboy import java.io.*; import java.util.*; public class CF237E extends PrintWriter { CF237E() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF237E o = new CF237E(); o.main(); o.flush(); } static final int A = 26, INF = 0x3f3f3f3f; int[] next, hh; int l_ = 1; int link(int l, int h) { next[l_] = l; hh[l_] = h; return l_++; } int[] ao, pi, dd, ff; int[] ii, jj, cc, cost, cost_; int n_, m_; void init(int n, int m) { n_ = n; next = new int[1 + m * 2]; hh = new int[1 + m * 2]; ao = new int[n]; pi = new int[n]; dd = new int[n]; ff = new int[n]; ii = new int[m]; jj = new int[m]; cc = new int[m * 2]; cost = new int[m]; cost_ = new int[m]; } void add(int i, int j, int cap, int cos) { int h = m_++; ao[i] = link(ao[i], h << 1); ao[j] = link(ao[j], h << 1 | 1); ii[h] = i; jj[h] = j; cc[h << 1] = cap; cost[h] = cos; } boolean less(int u, int v) { return pi[u] < pi[v] || pi[u] == pi[v] && dd[u] < dd[v]; } int[] pq, iq; int cnt; int i2(int i) { return (i *= 2) > cnt ? 0 : i < cnt && less(pq[i + 1], pq[i]) ? i + 1 : i; } void pq_up(int u) { int i, j, v; for (i = iq[u]; (j = i / 2) != 0 && less(u, v = pq[j]); i = j) pq[iq[v] = i] = v; pq[iq[u] = i] = u; } void pq_dn(int u) { int i, j, v; for (i = iq[u]; (j = i2(i)) != 0 && less(v = pq[j], u); i = j) pq[iq[v] = i] = v; pq[iq[u] = i] = u; } void pq_add_last(int u) { iq[u] = ++cnt; } int pq_remove_first() { int u = pq[1], v = pq[cnt--]; iq[v] = 1; pq_dn(v); return u; } boolean dijkstra(int s, int t) { Arrays.fill(pi, INF); pi[s] = 0; pq_add_last(s); pq_up(s); while (cnt > 0) { int i = pq_remove_first(); int d = dd[i] + 1; for (int l = ao[i]; l != 0; l = next[l]) { int h_ = hh[l]; if (cc[h_] != 0) { int h = h_ >> 1; int j = i ^ ii[h] ^ jj[h]; int p = pi[i] + ((h_ & 1) == 0 ? cost_[h] : -cost_[h]); if (pi[j] > p || pi[j] == p && dd[j] > d) { if (pi[j] == INF) pq_add_last(j); pi[j] = p; dd[j] = d; ff[j] = h_; pq_up(j); } } } } return pi[t] != INF; } int push(int s, int t) { int c = INF, h_, h; for (int j = t; j != s; j ^= ii[h] ^ jj[h]) { h_ = ff[j]; h = h_ >> 1; c = Math.min(c, cc[h_]); } for (int j = t; j != s; j ^= ii[h] ^ jj[h]) { h_ = ff[j]; h = h_ >> 1; cc[h_] -= c; cc[h_ ^ 1] += c; } return c; } int edmonds_karp(int s, int t, int f) { pq = new int[1 + n_]; iq = new int[n_]; System.arraycopy(cost, 0, cost_, 0, m_); while (dijkstra(s, t)) { f -= push(s, t); for (int h = 0; h < m_; h++) { int i = ii[h], j = jj[h]; if (pi[i] != INF && pi[j] != INF) cost_[h] += pi[i] - pi[j]; // pi[j] <= pi[i] + cost_[h] } } if (f != 0) return -1; int c = 0; for (int h = 0; h < m_; h++) c += cost[h] * cc[h << 1 | 1]; return c; } void count(int[] kk, byte[] aa) { Arrays.fill(kk, 0); int n = aa.length; for (int i = 0; i < n; i++) kk[aa[i] - 'a']++; } void main() { byte[] aa = sc.next().getBytes(); int l = aa.length; int n = sc.nextInt(); init(1 + A + n + 1, A + A * n + n); int[] kk = new int[A]; count(kk, aa); for (int a = 0; a < A; a++) if (kk[a] > 0) add(0, 1 + a, kk[a], 0); for (int i = 0; i < n; i++) { aa = sc.next().getBytes(); int k = sc.nextInt(); count(kk, aa); for (int a = 0; a < A; a++) if (kk[a] > 0) add(1 + a, 1 + A + i, kk[a], 0); add(1 + A + i, 1 + A + n, k, i + 1); } println(edmonds_karp(0, 1 + A + n, l)); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
2f4692bb34acbfe49bd4c3f8927ff827
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; public class E237 implements Runnable { final static int INF = Integer.MAX_VALUE; class Edge { int from, to, capacity, cost, flow; Edge(int from, int to, int capacity, int cost) { this.from = from; this.to = to; this.capacity = capacity; this.cost = cost; } } void addEdge(int from, int to, int capacity, int cost, ArrayList<Integer>[] g, Edge[] edges, int last) { g[from].add(last); g[to].add(last + 1); edges[last] = new Edge(from, to, capacity, cost); edges[last + 1] = new Edge(to, from, 0, -cost); } void solve() throws Exception { String t = in.nextToken(); int n = in.nextInt(); String[] s = new String[n]; int[] a = new int[n]; for (int i = 0; i < n; i++) { s[i] = in.nextToken(); a[i] = in.nextInt(); } ArrayList<Integer>[] g = new ArrayList[n + 28]; for (int i = 0; i < n + 28; i++) g[i] = new ArrayList<Integer>(); int totalEdges = n + n * 26 + 26, nowEdges = -2; Edge[] edges = new Edge[totalEdges * 2]; for (int i = 1; i <= n; i++) addEdge(0, i, a[i - 1], i, g, edges, nowEdges += 2); int[] cnt = new int[26]; for (int i = 0; i < n; i++) { for (char c : s[i].toCharArray()) cnt[c - 'a']++; for (int j = 0; j < 26; j++) addEdge(i + 1, n + 1 + j, cnt[j], 0, g, edges, nowEdges += 2); Arrays.fill(cnt, 0); } for (char c : t.toCharArray()) cnt[c - 'a']++; for (int i = 0; i < 26; i++) addEdge(1 + n + i, 1 + n + 26, cnt[i], 0, g, edges, nowEdges += 2); long[] ans = minCostMaxFLow(0, 1 + n + 26, 1 + n + 26 + 1, g, edges); out.println(ans[0] == t.length() ? ans[1] : -1); } boolean djikstra(int s, int t, int n, ArrayList<Integer>[] g, Edge[] edges, final int[] d, int[] p, int[] phi, PriorityQueue<Integer> q, long[] answer) { Arrays.fill(d, INF); d[s] = 0; q.add(s); while (!q.isEmpty()) { int v = q.poll(); for (int id : g[v]) { Edge e = edges[id]; if (e.flow < e.capacity && d[e.to] > d[v] + e.cost + phi[v] - phi[e.to]) { d[e.to] = d[v] + e.cost + phi[v] - phi[e.to]; p[e.to] = id; q.add(e.to); } } } if (d[t] == INF) return false; int len = d[t] - phi[s] + phi[t], cur = t, flow = INF; while (cur != s) { Edge e = edges[p[cur]]; flow = Math.min(flow, e.capacity - e.flow); cur = e.from; } cur = t; while (cur != s) { Edge e = edges[p[cur]]; e.flow += flow; edges[p[cur] ^ 1].flow -= flow; cur = e.from; } answer[0] += flow; answer[1] += (long) len * flow; for (int i = 0; i < n; i++) if (d[i] < INF) phi[i] += d[i]; return true; } long[] minCostMaxFLow(int s, int t, int n, ArrayList<Integer>[] g, Edge[] edges) { long[] answer = new long[2]; // answer[0] = maxFlow, answer[1] = cost int[] p = new int[n], phi = new int[n]; final int[] d = new int[n]; PriorityQueue<Integer> q = new PriorityQueue<Integer>(new Comparator<Integer>() { public int compare(Integer a, Integer b) { return d[a] - d[b]; } }); Arrays.fill(phi, INF); phi[s] = 0; for (int i = 0; i < n - 1; i++) for (Edge e : edges) if (phi[e.from] != INF && phi[e.to] > phi[e.from] + e.cost) phi[e.to] = phi[e.from] + e.cost; while (djikstra(s, t, n, g, edges, d, p, phi, q, answer)); return answer; } public static void main(String[] args) { new E237().run(); } InputReader in; PrintWriter out; public void run() { try { File defaultInput = new File("input.txt"); if (defaultInput.exists()) { in = new InputReader("input.txt"); } else { in = new InputReader(); } out = new PrintWriter(System.out); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(261); } } class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader() { reader = new BufferedReader(new InputStreamReader(System.in)); } InputReader(String fileName) throws FileNotFoundException { reader = new BufferedReader(new FileReader(new File(fileName))); } String readLine() throws IOException { return reader.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(readLine()); return tokenizer.nextToken(); } boolean hasMoreTokens() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String s = readLine(); if (s == null) return false; tokenizer = new StringTokenizer(s); } return true; } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
ce7d06062e10da019a9abbff0ba56b81
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.awt.FlowLayout; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; //класс для описания транспортной сети public class Solution { private BufferedReader cin; private PrintWriter cout; private StringTokenizer tokenizer; protected final static int INF = 1000 * 1000 * 1000; //актуальная бесконечность private int n; //количество вершин в орграфе private int m; //количество дуг в орграфе public int getN() { return n; } protected void addVertexCount() { ++n; } public int getM() { return m; } protected void incrementRib() { ++m; } protected void decrementRib() { --m; } private int flowNetwork = 0; private int costNetwork = 0; public int getFlowNetwork() { return flowNetwork; } public int getCostNetwork() { return costNetwork; } //класс для описания дуги в транспортной сети class NetworkRib { private int u; //начало дуги private int v; //конец дуги private int cost; //стоимость дуги private int cap; //пропускная способность дуги private int flow; //величина потока, которая течет по дуге private int back; //индекс обратной дуги private int idx; //индекс дуги public int getU() { return u; } public int getV() { return v; } public int getCost() { return cost; } public int getCap() { return cap; } public int getFlow() { return flow; } //увеличение потока вдоль дуги (u, v) public void addFlow(int val) { flow += val; } //уменьшение потока вдоль дуги (u, v) public void subFlow(int val) { flow -= val; } public int getBack() { return back; } //остаточная пропускная способность public int getCP() { return cap - flow; } public NetworkRib(int u, int v, int back, int idx) { this.u = u; this.v = v; cost = 1; cap = 1; flow = 0; this.back = back; this.idx = idx; } public NetworkRib(int u, int v, int cost, int cap, int back, int idx) { this.u = u; this.v = v; this.cost = cost; this.cap = cap; flow = 0; this.back = back; this.idx = idx; } //изменение стоимости дуги public void setCost(int cost) { this.cost = cost; } public void clearFlow() { this.flow = 0; } public void printNetworkRib() { System.out.print("[(" + u + ", " + v + ") cost = " + cost + " cap = " + cap + " flow = " + flow + " idxBack = " + back + " idx = " + idx + "]"); } } //класс, описывающий вершину и ее путь от стартовой, //для реализации модифицированного алгоритма Дейкстры class Vertex implements Comparable<Vertex> { private int v; //номер вершины в орграфе private int weight; //расстояние от стартовой вершины в вершине v public int getV() { return v; } public int getWeight() { return weight; } //конструктор класса public Vertex(int v, int weight) { this.v = v; this.weight = weight; } //метод для сравнения двух вершин по расстоянию до них public int compareTo(Vertex vertex) { if (weight != vertex.getWeight()) { return Integer.compare(weight, vertex.getWeight()); } return Integer.compare(v, vertex.getV()); } @Override public int hashCode() { return weight * 57 + v; } @Override public boolean equals(Object arg0) { if (arg0 == null) { return false; } if (this == arg0) { return true; } Vertex vertex = (Vertex) arg0; return v == vertex.getV() && weight == vertex.getWeight(); } } private int sourse; //источник транспортной сети private int sink; //сток транспортной сети private ArrayList<ArrayList<NetworkRib>> adjNet; //список смежности дуг транспортной сети private ArrayList<Integer> dist = new ArrayList<Integer>(); //массив для описания расстояние минимальной стоимости от источника private ArrayList<Integer> pred = new ArrayList<Integer>(); //массив предков для вершин дуг транспортной сети private ArrayList<Integer> predRib = new ArrayList<Integer>(); //массив предков для дуг транспортной сети private ArrayList<Integer> phi = new ArrayList<Integer>(); //потенциалы вершин private Set<Vertex> queue = new TreeSet<Vertex>(); //очередь с приоритетами public int getSourse() { return sourse; } public void setSourse(int sourse) { if (sourse < 0 || sourse >= getN()) { System.err.println("Индекс источники " + sourse + " превышает количество вершин " + getN() + " в транспортной сети"); this.sourse = 0; } this.sourse = sourse; } public int getSink() { return sink; } public void setSink(int sink) { if (sink < 0 || sink >= getN()) { System.err.println("Индекс источники " + sink + " превышает количество вершин " + getN() + " в транспортной сети"); this.sink = 0; } this.sink = sink; } public ArrayList<ArrayList<NetworkRib>> getAdjNet() { return adjNet; } //конструктор по умолчанию public Solution() { adjNet = new ArrayList<ArrayList<NetworkRib>>(); } //добавление новой пустой вершины в орграф public void addNewVertex() { addVertexCount(); adjNet.add(new ArrayList<Solution.NetworkRib>()); dist.add(INF); pred.add(-1); predRib.add(-1); phi.add(0); } //добавление новой дуги в транспортную сеть с пропускной способностью и стоимостью 1 public void addNewRib(int u, int v, int idx) { if (u < 0 || u >= getN()) { System.err.println("Индекс начала " + u + " дуги превышает количество вершин " + getN() + " в графе"); return; } if (v < 0 || v >= getN()) { System.err.println("Индекс конца " + v + " дуги превышает количество вершин " + getN() + " в графе"); return; } incrementRib(); NetworkRib rib = new NetworkRib(u, v, adjNet.get(v).size(), idx); NetworkRib ribBack = new NetworkRib(v, u, -1, 0, adjNet.get(u).size(), idx); adjNet.get(u).add(rib); adjNet.get(v).add(ribBack); } //добавление новой дуги в транспортную сеть с заданной пропускной способностью и стоимостью public void addNewRib(int u, int v, int cost, int cap, int idx) { if (u < 0 || u >= getN()) { System.err.println("Индекс начала " + u + " дуги превышает количество вершин " + getN() + " в графе"); return; } if (v < 0 || v >= getN()) { System.err.println("Индекс конца " + v + " дуги превышает количество вершин " + getN() + " в графе"); return; } incrementRib(); NetworkRib rib = new NetworkRib(u, v, cost, cap, adjNet.get(v).size(), idx); NetworkRib ribBack = new NetworkRib(v, u, -cost, 0, adjNet.get(u).size(), idx); adjNet.get(u).add(rib); adjNet.get(v).add(ribBack); } //установка стоимости дуги в транспортной сети public boolean setRibCost(int u, int v, int cost) { if (u < 0 || u >= getN()) { System.err.println("Индекс начала " + u + " дуги превышает количество вершин " + getN() + " в графе"); return false; } if (v < 0 || v >= getN()) { System.err.println("Индекс конца " + v + " дуги превышает количество вершин " + getN() + " в графе"); return false; } //индекс вершины v в списке смежности adj[u] int idxv = -1; for (int i = 0; i < getAdjNet().get(u).size(); ++i) { if (getAdjNet().get(u).get(i).getV() == v) { idxv = i; break; } } if (idxv == -1) { return false; } int idxBack = getAdjNet().get(u).get(idxv).getBack(); getAdjNet().get(u).get(idxv).setCost(cost); getAdjNet().get(v).get(idxBack).setCost(-cost); return true; } //обнуление потока по всем дугам транспортной сети public void clearFlow() { for (int u = 0; u < getN(); ++u) { for (int i = 0; i < getAdjNet().get(u).size(); ++i) { getAdjNet().get(u).get(i).clearFlow(); } } } //подсчет потенциалов вершин private void calcPhi() { //вычисляем начальные значения потенциалов алгоритмом Форда-Беллмана Collections.fill(phi, INF); phi.set(sourse, 0); for (int k = 1; k < getN(); ++k) { boolean isOrtimize = false; for (int u = 0; u < getN(); ++u) if (phi.get(u) != INF) for (int i = 0; i < adjNet.get(u).size(); ++i) { int v = adjNet.get(u).get(i).getV(); //конец ребра int curCost = adjNet.get(u).get(i).getCost(); //стоимость дуги int curCP = adjNet.get(u).get(i).getCP(); //остаточная пропускная способность if (curCP > 0 && phi.get(v) > phi.get(u) + curCost) { phi.set(v, phi.get(u) + curCost); pred.set(v, u); predRib.set(v, i); isOrtimize = true; } } if (!isOrtimize) break; } } //процедура запуска алгоритма Дейкстры из стартовой вершины private void sparseDejkstra() { dist.set(sourse, 0); //кратчайшее расстояние до стартовой вершины равно 0 queue.add(new Vertex(sourse, dist.get(sourse))); while (!queue.isEmpty()) { /*for (int i_ = 0; i_ < getN(); ++i_) { System.out.print(dist.get(i_) + " "); } System.out.println(); try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //извлекаем вершину, которая находится вверху кучи int u = queue.iterator().next().getV(); int distU = queue.iterator().next().getWeight(); queue.remove(queue.iterator().next()); //рассматриваем все дуги, исходящие из вершины вверху кучи for (int i = 0; i < getAdjNet().get(u).size(); ++i) { if (getAdjNet().get(u).get(i).getCP() == 0) { continue; } int v = getAdjNet().get(u).get(i).getV(); int costV = getAdjNet().get(u).get(i).getCost(); //релаксация вершины if (dist.get(v) > distU + costV + phi.get(v) - phi.get(u)) { queue.remove(new Vertex(v, dist.get(v))); dist.set(v, distU + costV + phi.get(v) - phi.get(u)); pred.set(v, u); predRib.set(v, i); queue.add(new Vertex(v, dist.get(v))); } } } } //метод поиска максимального потока минимальной стоимости в орграфе public void minCostMaxFlow() { flowNetwork = 0; //величина максимального потока минимальной стоимости costNetwork = 0; while (true) { //находим увеличивающий путь методом Форда-Беллмана Collections.fill(dist, INF); Collections.fill(pred, -1); Collections.fill(predRib, -1); dist.set(sourse, 0); for (int k = 1; k < getN(); ++k) { boolean isOrtimize = false; for (int u = 0; u < getN(); ++u) if (dist.get(u) != INF) for (int i = 0; i < adjNet.get(u).size(); ++i) { int v = adjNet.get(u).get(i).getV(); //конец ребра int curCost = adjNet.get(u).get(i).getCost(); //стоимость дуги int curCP = adjNet.get(u).get(i).getCP(); //остаточная пропускная способность if (curCP > 0 && dist.get(v) > dist.get(u) + curCost) { dist.set(v, dist.get(u) + curCost); pred.set(v, u); predRib.set(v, i); isOrtimize = true; } } if (!isOrtimize) break; } //если поток нельзя увеличить при помощи жадной стратегии, то выходим из цикла if (dist.get(sink) == INF) { break; } //находим максимальную величину предпотока int curFlow = INF; for (int v = sink; v != sourse; v = pred.get(v)) { int predV = pred.get(v); int predRibIdx = predRib.get(v); curFlow = Math.min(curFlow, adjNet.get(predV).get(predRibIdx).getCP()); } //проталкиваем поток по дугам увеличивающего пути for (int v = sink; v != sourse; v = pred.get(v)) { int predV = pred.get(v); int predRibIdx = predRib.get(v); int back = adjNet.get(predV).get(predRibIdx).getBack(); adjNet.get(predV).get(predRibIdx).addFlow(curFlow); adjNet.get(v).get(back).subFlow(curFlow); costNetwork += curFlow * adjNet.get(predV).get(predRibIdx).getCost(); } flowNetwork += curFlow; } } //метод поиска максимального потока минимальной стоимости в орграфе public void minCostMaxFlow2() { flowNetwork = 0; //величина максимального потока минимальной стоимости costNetwork = 0; calcPhi(); /*for (int i_ = 0; i_ < getN(); ++i_) { System.out.print(phi.get(i_) + " "); } System.out.println();*/ if (phi.get(sink) == INF) { return; } while (true) { //находим увеличивающий путь используя алгоритм Дейкстры с потенциалами для разряженных графов Collections.fill(dist, INF); Collections.fill(pred, -1); Collections.fill(predRib, -1); sparseDejkstra(); //пересчитываем потенциалы for (int v = 0; v < getN(); ++v) { phi.set(v, dist.get(v) != INF ? dist.get(v) : dist.get(sink)); } //если поток нельзя увеличить при помощи жадной стратегии, то выходим из цикла if (dist.get(sink) == INF) { break; } //находим максимальную величину предпотока int curFlow = INF; for (int v = sink; v != sourse; v = pred.get(v)) { int predV = pred.get(v); int predRibIdx = predRib.get(v); curFlow = Math.min(curFlow, adjNet.get(predV).get(predRibIdx).getCP()); } //проталкиваем поток по дугам увеличивающего пути for (int v = sink; v != sourse; v = pred.get(v)) { int predV = pred.get(v); int predRibIdx = predRib.get(v); int back = adjNet.get(predV).get(predRibIdx).getBack(); adjNet.get(predV).get(predRibIdx).addFlow(curFlow); adjNet.get(v).get(back).subFlow(curFlow); costNetwork += curFlow * adjNet.get(predV).get(predRibIdx).getCost(); } flowNetwork += curFlow; } } public void printNetwork() { System.out.println("n = " + getN() + " m = " + getM()); System.out.println("sourse = " + getSourse() + " sink = " + getSink()); for (int u = 0; u < getN(); ++u) { System.out.print(u + ": "); for (int i = 0; i < getAdjNet().get(u).size(); ++i) { getAdjNet().get(u).get(i).printNetworkRib(); } System.out.println(); } } public void printNetwork2() { System.out.println("n = " + getN() + " m = " + getM()); System.out.println("sourse = " + getSourse() + " sink = " + getSink()); for (int u = 0; u < getN(); ++u) { System.out.print(u + ": "); for (int i = 0; i < getAdjNet().get(u).size(); ++i) { if (getAdjNet().get(u).get(i).getFlow() > 0) { getAdjNet().get(u).get(i).printNetworkRib(); } } System.out.println(); } } public void printWay(PrintWriter cout) { for (int ii = 0; ii < flowNetwork; ++ii) { ArrayList<Integer> way = new ArrayList<Integer>(); for (int v = sourse; v != sink; ) { for (int i = 0; i < adjNet.get(v).size(); ++i) { if (adjNet.get(v).get(i).getFlow() == 1) { adjNet.get(v).get(i).subFlow(1); way.add(adjNet.get(v).get(i).idx); v = adjNet.get(v).get(i).getV(); break; } } } cout.print(way.size() + " "); for (int i = 0; i < way.size(); ++i) { cout.print(way.get(i) + " "); } cout.println(); } } String t = null; int cnt = 0; int a[] = null; String s[] = null; //процедура считывания входных данных с консоли private void run() throws IOException { cin = new BufferedReader(new InputStreamReader(System.in)); cout = new PrintWriter(System.out); tokenizer = new StringTokenizer(cin.readLine()); t = tokenizer.nextToken(); tokenizer = new StringTokenizer(cin.readLine()); cnt = Integer.parseInt(tokenizer.nextToken()); a = new int[cnt]; s = new String[cnt]; for (int i = 0; i < cnt; ++i) { tokenizer = new StringTokenizer(cin.readLine()); s[i] = tokenizer.nextToken(); a[i] = Integer.parseInt(tokenizer.nextToken()); } int idx = 0; //источник addNewVertex(); sourse = 0; //1 слой for (int v = 0; v < cnt; ++v) { addNewVertex(); } for (int v = 1; v <= cnt; ++v) { addNewRib(sourse, v, v, a[v - 1], idx++); } //2 слой for (int i = 0; i < cnt; ++i) { //кол-во букв к каждой строке int letter[] = new int[26]; Arrays.fill(letter, 0); for (int j = 0; j < s[i].length(); ++j) { letter[s[i].charAt(j) - 'a']++; } for (int j = 0; j < 26; ++j) { addNewVertex(); } for (int j = 0; j < 26; ++j) { addNewRib(i + 1, 1 + cnt + j, 0, letter[j], idx++); } } //3 слой и сток //кол-во букв в строке t int letter[] = new int[26]; for (int j = 0; j < t.length(); ++j) { letter[t.charAt(j) - 'a']++; } for (int i = 0; i < 26; ++i) { addNewVertex(); } addNewVertex(); sink = getN() - 1; for (int i = 0; i < cnt; ++i) { for (int j = 0; j < 26; ++j) { addNewRib(1 + cnt + (i * 26) + j, 1 + cnt + (cnt * 26) + j, 0, INF, ++idx); } } for (int j = 0; j < 26; ++j) { addNewRib(1 + cnt + (cnt * 26) + j, sink, 0, letter[j], ++idx); } minCostMaxFlow2(); if (flowNetwork < t.length()) { cout.println("-1"); } else { cout.println(costNetwork); } cin.close(); cout.close(); } public static void main(String[] args) throws IOException { Solution solution = new Solution(); solution.run(); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
0463ae5c4bacfd2ee32f0c1e90c05bc0
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.awt.FlowLayout; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; //класс для описания транспортной сети public class Solution { private BufferedReader cin; private PrintWriter cout; private StringTokenizer tokenizer; protected final static int INF = 1000 * 1000 * 1000; //актуальная бесконечность private int n; //количество вершин в орграфе private int m; //количество дуг в орграфе public int getN() { return n; } protected void addVertexCount() { ++n; } public int getM() { return m; } protected void incrementRib() { ++m; } protected void decrementRib() { --m; } private int flowNetwork = 0; private int costNetwork = 0; public int getFlowNetwork() { return flowNetwork; } public int getCostNetwork() { return costNetwork; } //класс для описания дуги в транспортной сети class NetworkRib { private int u; //начало дуги private int v; //конец дуги private int cost; //стоимость дуги private int cap; //пропускная способность дуги private int flow; //величина потока, которая течет по дуге private int back; //индекс обратной дуги private int idx; //индекс дуги public int getU() { return u; } public int getV() { return v; } public int getCost() { return cost; } public int getCap() { return cap; } public int getFlow() { return flow; } //увеличение потока вдоль дуги (u, v) public void addFlow(int val) { flow += val; } //уменьшение потока вдоль дуги (u, v) public void subFlow(int val) { flow -= val; } public int getBack() { return back; } //остаточная пропускная способность public int getCP() { return cap - flow; } public NetworkRib(int u, int v, int back, int idx) { this.u = u; this.v = v; cost = 1; cap = 1; flow = 0; this.back = back; this.idx = idx; } public NetworkRib(int u, int v, int cost, int cap, int back, int idx) { this.u = u; this.v = v; this.cost = cost; this.cap = cap; flow = 0; this.back = back; this.idx = idx; } //изменение стоимости дуги public void setCost(int cost) { this.cost = cost; } public void clearFlow() { this.flow = 0; } public void printNetworkRib() { System.out.print("[(" + u + ", " + v + ") cost = " + cost + " cap = " + cap + " flow = " + flow + " idxBack = " + back + " idx = " + idx + "]"); } } //класс, описывающий вершину и ее путь от стартовой, //для реализации модифицированного алгоритма Дейкстры class Vertex implements Comparable<Vertex> { private int v; //номер вершины в орграфе private int weight; //расстояние от стартовой вершины в вершине v public int getV() { return v; } public int getWeight() { return weight; } //конструктор класса public Vertex(int v, int weight) { this.v = v; this.weight = weight; } //метод для сравнения двух вершин по расстоянию до них public int compareTo(Vertex vertex) { if (weight != vertex.getWeight()) { return Integer.compare(weight, vertex.getWeight()); } return Integer.compare(v, vertex.getV()); } @Override public int hashCode() { return weight * 57 + v; } @Override public boolean equals(Object arg0) { if (arg0 == null) { return false; } if (this == arg0) { return true; } Vertex vertex = (Vertex) arg0; return v == vertex.getV() && weight == vertex.getWeight(); } } private int sourse; //источник транспортной сети private int sink; //сток транспортной сети private ArrayList<ArrayList<NetworkRib>> adjNet; //список смежности дуг транспортной сети private ArrayList<Integer> dist = new ArrayList<Integer>(); //массив для описания расстояние минимальной стоимости от источника private ArrayList<Integer> pred = new ArrayList<Integer>(); //массив предков для вершин дуг транспортной сети private ArrayList<Integer> predRib = new ArrayList<Integer>(); //массив предков для дуг транспортной сети private ArrayList<Integer> phi = new ArrayList<Integer>(); //потенциалы вершин private Set<Vertex> queue = new TreeSet<Vertex>(); //очередь с приоритетами public int getSourse() { return sourse; } public void setSourse(int sourse) { if (sourse < 0 || sourse >= getN()) { System.err.println("Индекс источники " + sourse + " превышает количество вершин " + getN() + " в транспортной сети"); this.sourse = 0; } this.sourse = sourse; } public int getSink() { return sink; } public void setSink(int sink) { if (sink < 0 || sink >= getN()) { System.err.println("Индекс источники " + sink + " превышает количество вершин " + getN() + " в транспортной сети"); this.sink = 0; } this.sink = sink; } public ArrayList<ArrayList<NetworkRib>> getAdjNet() { return adjNet; } //конструктор по умолчанию public Solution() { adjNet = new ArrayList<ArrayList<NetworkRib>>(); } //добавление новой пустой вершины в орграф public void addNewVertex() { addVertexCount(); adjNet.add(new ArrayList<Solution.NetworkRib>()); dist.add(INF); pred.add(-1); predRib.add(-1); phi.add(0); } //добавление новой дуги в транспортную сеть с пропускной способностью и стоимостью 1 public void addNewRib(int u, int v, int idx) { if (u < 0 || u >= getN()) { System.err.println("Индекс начала " + u + " дуги превышает количество вершин " + getN() + " в графе"); return; } if (v < 0 || v >= getN()) { System.err.println("Индекс конца " + v + " дуги превышает количество вершин " + getN() + " в графе"); return; } incrementRib(); NetworkRib rib = new NetworkRib(u, v, adjNet.get(v).size(), idx); NetworkRib ribBack = new NetworkRib(v, u, -1, 0, adjNet.get(u).size(), idx); adjNet.get(u).add(rib); adjNet.get(v).add(ribBack); } //добавление новой дуги в транспортную сеть с заданной пропускной способностью и стоимостью public void addNewRib(int u, int v, int cost, int cap, int idx) { if (u < 0 || u >= getN()) { System.err.println("Индекс начала " + u + " дуги превышает количество вершин " + getN() + " в графе"); return; } if (v < 0 || v >= getN()) { System.err.println("Индекс конца " + v + " дуги превышает количество вершин " + getN() + " в графе"); return; } incrementRib(); NetworkRib rib = new NetworkRib(u, v, cost, cap, adjNet.get(v).size(), idx); NetworkRib ribBack = new NetworkRib(v, u, -cost, 0, adjNet.get(u).size(), idx); adjNet.get(u).add(rib); adjNet.get(v).add(ribBack); } //установка стоимости дуги в транспортной сети public boolean setRibCost(int u, int v, int cost) { if (u < 0 || u >= getN()) { System.err.println("Индекс начала " + u + " дуги превышает количество вершин " + getN() + " в графе"); return false; } if (v < 0 || v >= getN()) { System.err.println("Индекс конца " + v + " дуги превышает количество вершин " + getN() + " в графе"); return false; } //индекс вершины v в списке смежности adj[u] int idxv = -1; for (int i = 0; i < getAdjNet().get(u).size(); ++i) { if (getAdjNet().get(u).get(i).getV() == v) { idxv = i; break; } } if (idxv == -1) { return false; } int idxBack = getAdjNet().get(u).get(idxv).getBack(); getAdjNet().get(u).get(idxv).setCost(cost); getAdjNet().get(v).get(idxBack).setCost(-cost); return true; } //обнуление потока по всем дугам транспортной сети public void clearFlow() { for (int u = 0; u < getN(); ++u) { for (int i = 0; i < getAdjNet().get(u).size(); ++i) { getAdjNet().get(u).get(i).clearFlow(); } } } //подсчет потенциалов вершин private void calcPhi() { //вычисляем начальные значения потенциалов алгоритмом Форда-Беллмана Collections.fill(phi, INF); phi.set(sourse, 0); for (int k = 1; k < getN(); ++k) { boolean isOrtimize = false; for (int u = 0; u < getN(); ++u) if (phi.get(u) != INF) for (int i = 0; i < adjNet.get(u).size(); ++i) { int v = adjNet.get(u).get(i).getV(); //конец ребра int curCost = adjNet.get(u).get(i).getCost(); //стоимость дуги int curCP = adjNet.get(u).get(i).getCP(); //остаточная пропускная способность if (curCP > 0 && phi.get(v) > phi.get(u) + curCost) { phi.set(v, phi.get(u) + curCost); pred.set(v, u); predRib.set(v, i); isOrtimize = true; } } if (!isOrtimize) break; } } //процедура запуска алгоритма Дейкстры из стартовой вершины private void sparseDejkstra() { dist.set(sourse, 0); //кратчайшее расстояние до стартовой вершины равно 0 queue.add(new Vertex(sourse, dist.get(sourse))); while (!queue.isEmpty()) { /*for (int i_ = 0; i_ < getN(); ++i_) { System.out.print(dist.get(i_) + " "); } System.out.println(); try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //извлекаем вершину, которая находится вверху кучи int u = queue.iterator().next().getV(); int distU = queue.iterator().next().getWeight(); queue.remove(queue.iterator().next()); //рассматриваем все дуги, исходящие из вершины вверху кучи for (int i = 0; i < getAdjNet().get(u).size(); ++i) { if (getAdjNet().get(u).get(i).getCP() == 0) { continue; } int v = getAdjNet().get(u).get(i).getV(); int costV = getAdjNet().get(u).get(i).getCost(); //релаксация вершины if (dist.get(v) > distU + costV + phi.get(v) - phi.get(u)) { queue.remove(new Vertex(v, dist.get(v))); dist.set(v, distU + costV + phi.get(v) - phi.get(u)); pred.set(v, u); predRib.set(v, i); queue.add(new Vertex(v, dist.get(v))); } } } } //метод поиска максимального потока минимальной стоимости в орграфе public void minCostMaxFlow() { flowNetwork = 0; //величина максимального потока минимальной стоимости costNetwork = 0; while (true) { //находим увеличивающий путь методом Форда-Беллмана Collections.fill(dist, INF); Collections.fill(pred, -1); Collections.fill(predRib, -1); dist.set(sourse, 0); for (int k = 1; k < getN(); ++k) { boolean isOrtimize = false; for (int u = 0; u < getN(); ++u) if (dist.get(u) != INF) for (int i = 0; i < adjNet.get(u).size(); ++i) { int v = adjNet.get(u).get(i).getV(); //конец ребра int curCost = adjNet.get(u).get(i).getCost(); //стоимость дуги int curCP = adjNet.get(u).get(i).getCP(); //остаточная пропускная способность if (curCP > 0 && dist.get(v) > dist.get(u) + curCost) { dist.set(v, dist.get(u) + curCost); pred.set(v, u); predRib.set(v, i); isOrtimize = true; } } if (!isOrtimize) break; } //если поток нельзя увеличить при помощи жадной стратегии, то выходим из цикла if (dist.get(sink) == INF) { break; } //находим максимальную величину предпотока int curFlow = INF; for (int v = sink; v != sourse; v = pred.get(v)) { int predV = pred.get(v); int predRibIdx = predRib.get(v); curFlow = Math.min(curFlow, adjNet.get(predV).get(predRibIdx).getCP()); } //проталкиваем поток по дугам увеличивающего пути for (int v = sink; v != sourse; v = pred.get(v)) { int predV = pred.get(v); int predRibIdx = predRib.get(v); int back = adjNet.get(predV).get(predRibIdx).getBack(); adjNet.get(predV).get(predRibIdx).addFlow(curFlow); adjNet.get(v).get(back).subFlow(curFlow); costNetwork += curFlow * adjNet.get(predV).get(predRibIdx).getCost(); } flowNetwork += curFlow; } } //метод поиска максимального потока минимальной стоимости в орграфе public void minCostMaxFlow2(int maxFlow) { flowNetwork = 0; //величина максимального потока минимальной стоимости costNetwork = 0; calcPhi(); /*for (int i_ = 0; i_ < getN(); ++i_) { System.out.print(phi.get(i_) + " "); } System.out.println();*/ if (phi.get(sink) == INF) { return; } while (flowNetwork < maxFlow) { //находим увеличивающий путь используя алгоритм Дейкстры с потенциалами для разряженных графов Collections.fill(dist, INF); Collections.fill(pred, -1); Collections.fill(predRib, -1); sparseDejkstra(); //пересчитываем потенциалы for (int v = 0; v < getN(); ++v) { phi.set(v, dist.get(v) != INF ? dist.get(v) : dist.get(sink)); } //если поток нельзя увеличить при помощи жадной стратегии, то выходим из цикла if (dist.get(sink) == INF) { break; } //находим максимальную величину предпотока int curFlow = INF; for (int v = sink; v != sourse; v = pred.get(v)) { int predV = pred.get(v); int predRibIdx = predRib.get(v); curFlow = Math.min(curFlow, adjNet.get(predV).get(predRibIdx).getCP()); } //проталкиваем поток по дугам увеличивающего пути for (int v = sink; v != sourse; v = pred.get(v)) { int predV = pred.get(v); int predRibIdx = predRib.get(v); int back = adjNet.get(predV).get(predRibIdx).getBack(); adjNet.get(predV).get(predRibIdx).addFlow(curFlow); adjNet.get(v).get(back).subFlow(curFlow); costNetwork += curFlow * adjNet.get(predV).get(predRibIdx).getCost(); } flowNetwork += curFlow; } } public void printNetwork() { System.out.println("n = " + getN() + " m = " + getM()); System.out.println("sourse = " + getSourse() + " sink = " + getSink()); for (int u = 0; u < getN(); ++u) { System.out.print(u + ": "); for (int i = 0; i < getAdjNet().get(u).size(); ++i) { getAdjNet().get(u).get(i).printNetworkRib(); } System.out.println(); } } public void printNetwork2() { System.out.println("n = " + getN() + " m = " + getM()); System.out.println("sourse = " + getSourse() + " sink = " + getSink()); for (int u = 0; u < getN(); ++u) { System.out.print(u + ": "); for (int i = 0; i < getAdjNet().get(u).size(); ++i) { if (getAdjNet().get(u).get(i).getFlow() > 0) { getAdjNet().get(u).get(i).printNetworkRib(); } } System.out.println(); } } public void printWay(PrintWriter cout) { for (int ii = 0; ii < flowNetwork; ++ii) { ArrayList<Integer> way = new ArrayList<Integer>(); for (int v = sourse; v != sink; ) { for (int i = 0; i < adjNet.get(v).size(); ++i) { if (adjNet.get(v).get(i).getFlow() == 1) { adjNet.get(v).get(i).subFlow(1); way.add(adjNet.get(v).get(i).idx); v = adjNet.get(v).get(i).getV(); break; } } } cout.print(way.size() + " "); for (int i = 0; i < way.size(); ++i) { cout.print(way.get(i) + " "); } cout.println(); } } String t = null; int cnt = 0; int a[] = null; String s[] = null; //процедура считывания входных данных с консоли private void run() throws IOException { cin = new BufferedReader(new InputStreamReader(System.in)); cout = new PrintWriter(System.out); tokenizer = new StringTokenizer(cin.readLine()); t = tokenizer.nextToken(); tokenizer = new StringTokenizer(cin.readLine()); cnt = Integer.parseInt(tokenizer.nextToken()); a = new int[cnt]; s = new String[cnt]; for (int i = 0; i < cnt; ++i) { tokenizer = new StringTokenizer(cin.readLine()); s[i] = tokenizer.nextToken(); a[i] = Integer.parseInt(tokenizer.nextToken()); } int idx = 0; //источник addNewVertex(); sourse = 0; //1 слой for (int v = 0; v < cnt; ++v) { addNewVertex(); } for (int v = 1; v <= cnt; ++v) { addNewRib(sourse, v, v, a[v - 1], idx++); } //2 слой for (int i = 0; i < cnt; ++i) { //кол-во букв к каждой строке int letter[] = new int[26]; Arrays.fill(letter, 0); for (int j = 0; j < s[i].length(); ++j) { letter[s[i].charAt(j) - 'a']++; } for (int j = 0; j < 26; ++j) { addNewVertex(); } for (int j = 0; j < 26; ++j) { addNewRib(i + 1, 1 + cnt + j, 0, letter[j], idx++); } } //3 слой и сток //кол-во букв в строке t int letter[] = new int[26]; for (int j = 0; j < t.length(); ++j) { letter[t.charAt(j) - 'a']++; } for (int i = 0; i < 26; ++i) { addNewVertex(); } addNewVertex(); sink = getN() - 1; for (int i = 0; i < cnt; ++i) { for (int j = 0; j < 26; ++j) { addNewRib(1 + cnt + (i * 26) + j, 1 + cnt + (cnt * 26) + j, 0, INF, ++idx); } } for (int j = 0; j < 26; ++j) { addNewRib(1 + cnt + (cnt * 26) + j, sink, 0, letter[j], ++idx); } minCostMaxFlow(); if (flowNetwork < t.length()) { cout.println("-1"); } else { cout.println(costNetwork); } cin.close(); cout.close(); } public static void main(String[] args) throws IOException { Solution solution = new Solution(); solution.run(); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
35079870bc201d3f2cdf97edecd3b463
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.util.*; import java.io.*; public class tr0 { static PrintWriter out; static StringBuilder sb; static long mod = 1000000007; static int inf = (int) 1e15; static ArrayList<Integer>[] ad; static int n, cost, flow, s, t; static int[][] cap, val; static int[] dist, p; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); String h = sc.nextLine(); n = sc.nextInt(); s = 0; int k=h.length(); t = n + 26 + 4; int[] cnt = new int[26]; for (int i = 0; i < h.length(); i++) cnt[h.charAt(i) - 'a']++; ad = new ArrayList[n + 26 + 5]; val = new int[n + 5 + 26][n + 5 + 26]; cap = new int[n + 5 + 26][n + 5 + 26]; for (int i = 0; i < ad.length; i++) ad[i] = new ArrayList<>(); for (int i = 1; i <= 26; i++) { ad[i+n].add(t); ad[t].add(i+n); cap[i+n][t] = cnt[i - 1]; } for(int i=1;i<=n;i++) { h=sc.next(); int v=sc.nextInt(); ad[s].add(i); ad[i].add(s); val[s][i]=i; val[i][s]=-i; cap[s][i]=v; cnt=new int [26]; for (int j = 0; j < h.length(); j++) cnt[h.charAt(j) - 'a']++; for (int j = 1; j <= 26; j++) { ad[j+n].add(i); ad[i].add(j+n); cap[i][j+n] = cnt[j - 1]; } } MCMF(); // System.out.println(flow); if (flow == k) System.out.println(cost); else System.out.println(-1); out.flush(); } static void MCMF() { while (true) { belmanford(); // System.out.println(Arrays.toString(dist)); if (dist[t] == inf) return; int f = inf; int cur = t; while (cur != s) { f = Math.min(f, cap[p[cur]][cur]); cur = p[cur]; } flow += f; cost += f * dist[t]; cur=t; // System.out.println(flow+" "+cost); while (cur != s) { cap[p[cur]][cur] -= f; cap[cur][p[cur]] += f; cur = p[cur]; } } } static void belmanford() { dist = new int[n + 26 + 5]; Arrays.fill(dist, inf); boolean[] in = new boolean[n + 26 + 5]; Queue<Integer> q = new LinkedList<Integer>(); p = new int[n + 26 + 5]; int[] cnt = new int[n + 26 + 5]; Arrays.fill(p, -1); q.add(s); dist[s]=0; while (!q.isEmpty()) { int u = q.poll(); in[u] = false; for (int v : ad[u]) { if (cap[u][v] > 0 && dist[v] > dist[u] + val[u][v]) { dist[v] = dist[u] + val[u][v]; p[v] = u; if (!in[v]) { cnt[v]++; // if (cnt[v] > n + 5 + 26) // return; in[v] = true; q.add(v); } } } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
8d1fdc1a7c8bb6ee26a6f748658a9452
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.util.*; import java.io.*; public class tr0 { static PrintWriter out; static StringBuilder sb; static long mod = 1000000007; static int inf = (int) 1e15; static ArrayList<Integer>[] ad; static int n, cost, flow, s, t; static int[][] cap, val; static int[] dist, p; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); String h = sc.nextLine(); n = sc.nextInt(); s = 0; int k=h.length(); t = n + 26 + 4; int[] cnt = new int[26]; for (int i = 0; i < h.length(); i++) cnt[h.charAt(i) - 'a']++; ad = new ArrayList[n + 26 + 5]; val = new int[n + 5 + 26][n + 5 + 26]; cap = new int[n + 5 + 26][n + 5 + 26]; for (int i = 0; i < ad.length; i++) ad[i] = new ArrayList<>(); for (int i = 1; i <= 26; i++) { ad[i+n].add(t); ad[t].add(i+n); cap[i+n][t] = cnt[i - 1]; } for(int i=1;i<=n;i++) { h=sc.next(); int v=sc.nextInt(); ad[s].add(i); ad[i].add(s); val[s][i]=i; val[i][s]=-i; cap[s][i]=v; cnt=new int [26]; for (int j = 0; j < h.length(); j++) cnt[h.charAt(j) - 'a']++; for (int j = 1; j <= 26; j++) { ad[j+n].add(i); ad[i].add(j+n); cap[i][j+n] = cnt[j - 1]; } } MCMF(); // System.out.println(flow); if (flow == k) System.out.println(cost); else System.out.println(-1); out.flush(); } static void MCMF() { while (true) { belmanford(); // System.out.println(Arrays.toString(dist)); if (dist[t] == inf) return; int f = inf; int cur = t; while (cur != s) { f = Math.min(f, cap[p[cur]][cur]); cur = p[cur]; } flow += f; cost += f * dist[t]; cur=t; // System.out.println(flow+" "+cost); while (cur != s) { cap[p[cur]][cur] -= f; cap[cur][p[cur]] += f; cur = p[cur]; } } } static void belmanford() { dist = new int[n + 26 + 5]; Arrays.fill(dist, inf); boolean[] in = new boolean[n + 26 + 5]; Queue<Integer> q = new LinkedList<Integer>(); p = new int[n + 26 + 5]; int[] cnt = new int[n + 26 + 5]; Arrays.fill(p, -1); q.add(s); dist[s]=0; while (!q.isEmpty()) { int u = q.poll(); in[u] = false; for (int v : ad[u]) { if (cap[u][v] > 0 && dist[v] > dist[u] + val[u][v]) { dist[v] = dist[u] + val[u][v]; p[v] = u; if (!in[v]) { cnt[v]++; if (cnt[v] > n + 5 + 26) return; in[v] = true; q.add(v); } } } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
d409b7365cef6662e8bbc77e3d76fdcb
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.List; import java.math.BigInteger; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.Iterator; import java.io.IOException; import java.util.Arrays; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.function.Function; /** * Built using CHelper plug-in * Actual solution is at the top * @author Stanislav Pak */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { char[] s = in.readString().toCharArray(); int[] cnt = new int[26]; for (char c : s) { cnt[c - 'a']++; } int n = in.readInt(); int[][] count = new int[n][26]; int N = 26 + n + 2; Graph graph = new Graph(N, N * N); for (int i = 0; i < 26; ++i) { if (cnt[i] > 0) { graph.addFlowWeightedEdge(0, i + 1, 0, cnt[i]); } } for (int i = 0; i < n; ++i) { char[] ss = in.readString().toCharArray(); int limit = in.readInt(); for (char c : ss) { count[i][c - 'a']++; } graph.addFlowWeightedEdge(27 + i, N - 1, 0, limit); for (int j = 0; j < 26; ++j) { int capacity = Math.min(cnt[j], count[i][j]); if (capacity > 0) { graph.addFlowWeightedEdge(j + 1, 27 + i, i + 1, capacity); } } } MinCostFlow mcf = new MinCostFlow(graph, 0, N - 1, false); Pair<Long, Long> ans = mcf.minCostMaxFlow(); if (ans.second != s.length) { out.printLine(-1); } else { out.printLine(ans.first); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } public void printLine(int i) { writer.println(i); } } class Graph { public static final int REMOVED_BIT = 0; protected int vertexCount; protected int edgeCount; private int[] firstOutbound; private int[] firstInbound; private Edge[] edges; private int[] nextInbound; private int[] nextOutbound; private int[] from; private int[] to; private long[] weight; public long[] capacity; private int[] reverseEdge; private int[] flags; public Graph(int vertexCount, int edgeCapacity) { this.vertexCount = vertexCount; firstOutbound = new int[vertexCount]; Arrays.fill(firstOutbound, -1); from = new int[edgeCapacity]; to = new int[edgeCapacity]; nextOutbound = new int[edgeCapacity]; flags = new int[edgeCapacity]; } public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) { ensureEdgeCapacity(edgeCount + 1); if (firstOutbound[fromID] != -1) nextOutbound[edgeCount] = firstOutbound[fromID]; else nextOutbound[edgeCount] = -1; firstOutbound[fromID] = edgeCount; if (firstInbound != null) { if (firstInbound[toID] != -1) nextInbound[edgeCount] = firstInbound[toID]; else nextInbound[edgeCount] = -1; firstInbound[toID] = edgeCount; } this.from[edgeCount] = fromID; this.to[edgeCount] = toID; if (capacity != 0) { if (this.capacity == null) this.capacity = new long[from.length]; this.capacity[edgeCount] = capacity; } if (weight != 0) { if (this.weight == null) this.weight = new long[from.length]; this.weight[edgeCount] = weight; } if (reverseEdge != -1) { if (this.reverseEdge == null) { this.reverseEdge = new int[from.length]; Arrays.fill(this.reverseEdge, 0, edgeCount, -1); } this.reverseEdge[edgeCount] = reverseEdge; } if (edges != null) edges[edgeCount] = createEdge(edgeCount); return edgeCount++; } protected final GraphEdge createEdge(int id) { return new GraphEdge(id); } public final int addFlowWeightedEdge(int from, int to, long weight, long capacity) { if (capacity == 0) { return addEdge(from, to, weight, 0, -1); } else { int lastEdgeCount = edgeCount; addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge()); return addEdge(from, to, weight, capacity, lastEdgeCount); } } protected int entriesPerEdge() { return 1; } public final int vertexCount() { return vertexCount; } public final int firstOutbound(int vertex) { int id = firstOutbound[vertex]; while (id != -1 && isRemoved(id)) id = nextOutbound[id]; return id; } public final int nextOutbound(int id) { id = nextOutbound[id]; while (id != -1 && isRemoved(id)) id = nextOutbound[id]; return id; } public final int source(int id) { return from[id]; } public final int destination(int id) { return to[id]; } public final long weight(int id) { if (weight == null) return 0; return weight[id]; } public final long capacity(int id) { if (capacity == null) return 0; return capacity[id]; } public final long flow(int id) { if (reverseEdge == null) return 0; return capacity[reverseEdge[id]]; } public final void pushFlow(int id, long flow) { if (flow == 0) return; if (flow > 0) { if (capacity(id) < flow) throw new IllegalArgumentException("Not enough capacity"); } else { if (flow(id) < -flow) throw new IllegalArgumentException("Not enough capacity"); } capacity[id] -= flow; capacity[reverseEdge[id]] += flow; } public final boolean flag(int id, int bit) { return (flags[id] >> bit & 1) != 0; } public final boolean isRemoved(int id) { return flag(id, REMOVED_BIT); } protected void ensureEdgeCapacity(int size) { if (from.length < size) { int newSize = Math.max(size, 2 * from.length); if (edges != null) edges = resize(edges, newSize); from = resize(from, newSize); to = resize(to, newSize); nextOutbound = resize(nextOutbound, newSize); if (nextInbound != null) nextInbound = resize(nextInbound, newSize); if (weight != null) weight = resize(weight, newSize); if (capacity != null) capacity = resize(capacity, newSize); if (reverseEdge != null) reverseEdge = resize(reverseEdge, newSize); flags = resize(flags, newSize); } } protected final int[] resize(int[] array, int size) { int[] newArray = new int[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private long[] resize(long[] array, int size) { long[] newArray = new long[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } private Edge[] resize(Edge[] array, int size) { Edge[] newArray = new Edge[size]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } public final boolean isSparse() { return vertexCount == 0 || edgeCount * 20 / vertexCount <= vertexCount; } protected class GraphEdge implements Edge { protected int id; protected GraphEdge(int id) { this.id = id; } } } class MinCostFlow { private final Graph graph; private final int source; private final int destination; private final long[] phi; private final long[] dijkstraResult; private final int[] lastEdge; private final Heap heap; private final int vertexCount; private final int[] visited; private int visitIndex; public MinCostFlow(Graph graph, int source, int destination, boolean hasNegativeEdges) { this.graph = graph; this.source = source; this.destination = destination; vertexCount = graph.vertexCount(); phi = new long[vertexCount]; if (hasNegativeEdges) fordBellman(); dijkstraResult = new long[vertexCount]; lastEdge = new int[vertexCount]; if (graph.isSparse()) { heap = new Heap(vertexCount, new IntComparator() { public int compare(int first, int second) { return IntegerUtils.longCompare(dijkstraResult[first], dijkstraResult[second]); } }, vertexCount); visited = null; } else { heap = null; visited = new int[vertexCount]; } } private void fordBellman() { Arrays.fill(phi, Long.MAX_VALUE); phi[source] = 0; boolean[] inQueue = new boolean[vertexCount]; int[] queue = new int[vertexCount + 1]; queue[0] = source; inQueue[source] = true; int stepCount = 0; int head = 0; int end = 1; int maxSteps = 2 * vertexCount * vertexCount; while (head != end) { int vertex = queue[head++]; if (head == queue.length) head = 0; inQueue[vertex] = false; int edgeID = graph.firstOutbound(vertex); while (edgeID != -1) { long total = phi[vertex] + graph.weight(edgeID); int destination = graph.destination(edgeID); if (graph.capacity(edgeID) != 0 && phi[destination] > total) { phi[destination] = total; if (!inQueue[destination]) { queue[end++] = destination; inQueue[destination] = true; if (end == queue.length) end = 0; } } edgeID = graph.nextOutbound(edgeID); } if (++stepCount > maxSteps) throw new IllegalArgumentException("Graph contains negative cycle"); } } public Pair<Long, Long> minCostMaxFlow() { return minCostMaxFlow(Long.MAX_VALUE); } public Pair<Long, Long> minCostMaxFlow(long maxFlow) { long cost = 0; long flow = 0; while (maxFlow != 0) { if (graph.isSparse()) dijkstraAlgorithm(); else dijkstraAlgorithmFull(); if (lastEdge[destination] == -1) return Pair.makePair(cost, flow); for (int i = 0; i < dijkstraResult.length; i++) { if (dijkstraResult[i] != Long.MAX_VALUE) phi[i] += dijkstraResult[i]; } int vertex = destination; long currentFlow = maxFlow; long currentCost = 0; while (vertex != source) { int edgeID = lastEdge[vertex]; currentFlow = Math.min(currentFlow, graph.capacity(edgeID)); currentCost += graph.weight(edgeID); vertex = graph.source(edgeID); } maxFlow -= currentFlow; cost += currentCost * currentFlow; flow += currentFlow; vertex = destination; while (vertex != source) { int edgeID = lastEdge[vertex]; graph.pushFlow(edgeID, currentFlow); vertex = graph.source(edgeID); } } return Pair.makePair(cost, flow); } private void dijkstraAlgorithm() { Arrays.fill(dijkstraResult, Long.MAX_VALUE); Arrays.fill(lastEdge, -1); dijkstraResult[source] = 0; heap.add(source); while (!heap.isEmpty()) { int current = heap.poll(); int edgeID = graph.firstOutbound(current); while (edgeID != -1) { if (graph.capacity(edgeID) != 0) { int next = graph.destination(edgeID); long total = graph.weight(edgeID) - phi[next] + phi[current] + dijkstraResult[current]; if (dijkstraResult[next] > total) { dijkstraResult[next] = total; if (heap.getIndex(next) == -1) heap.add(next); else heap.shiftUp(heap.getIndex(next)); lastEdge[next] = edgeID; } } edgeID = graph.nextOutbound(edgeID); } } } private void dijkstraAlgorithmFull() { visitIndex++; Arrays.fill(dijkstraResult, Long.MAX_VALUE); lastEdge[destination] = -1; dijkstraResult[source] = 0; for (int i = 0; i < vertexCount; i++) { int index = -1; long length = Long.MAX_VALUE; for (int j = 0; j < vertexCount; j++) { if (visited[j] != visitIndex && dijkstraResult[j] < length) { length = dijkstraResult[j]; index = j; } } if (index == -1) { return; } visited[index] = visitIndex; int edgeID = graph.firstOutbound(index); while (edgeID != -1) { if (graph.capacity(edgeID) != 0) { int next = graph.destination(edgeID); if (visited[next] != visitIndex) { long total = graph.weight(edgeID) - phi[next] + phi[index] + length; if (dijkstraResult[next] > total) { dijkstraResult[next] = total; lastEdge[next] = edgeID; } } } edgeID = graph.nextOutbound(edgeID); } } } } class Pair<U, V> implements Comparable<Pair<U, V>> { public final U first; public final V second; public static<U, V> Pair<U, V> makePair(U first, V second) { return new Pair<U, V>(first, second); } private Pair(U first, V second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null); } public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(Pair<U, V> o) { int value = ((Comparable<U>)first).compareTo(o.first); if (value != 0) return value; return ((Comparable<V>)second).compareTo(o.second); } } interface Edge { } class Heap { private IntComparator comparator; private int size = 0; private int[] elements; private int[] at; public Heap(int capacity, IntComparator comparator, int maxElement) { this.comparator = comparator; elements = new int[capacity]; at = new int[maxElement]; Arrays.fill(at, -1); } public boolean isEmpty() { return size == 0; } public int add(int element) { ensureCapacity(size + 1); elements[size] = element; at[element] = size; shiftUp(size++); return at[element]; } public void shiftUp(int index) { // if (index < 0 || index >= size) // throw new IllegalArgumentException(); int value = elements[index]; while (index != 0) { int parent = (index - 1) >>> 1; int parentValue = elements[parent]; if (comparator.compare(parentValue, value) <= 0) { elements[index] = value; at[value] = index; return; } elements[index] = parentValue; at[parentValue] = index; index = parent; } elements[0] = value; at[value] = 0; } public void shiftDown(int index) { if (index < 0 || index >= size) throw new IllegalArgumentException(); while (true) { int child = (index << 1) + 1; if (child >= size) return; if (child + 1 < size && comparator.compare(elements[child], elements[child + 1]) > 0) child++; if (comparator.compare(elements[index], elements[child]) <= 0) return; swap(index, child); index = child; } } public int getIndex(int element) { return at[element]; } private void swap(int first, int second) { int temp = elements[first]; elements[first] = elements[second]; elements[second] = temp; at[elements[first]] = first; at[elements[second]] = second; } private void ensureCapacity(int size) { if (elements.length < size) { int[] oldElements = elements; elements = new int[Math.max(2 * elements.length, size)]; System.arraycopy(oldElements, 0, elements, 0, this.size); } } public int poll() { if (isEmpty()) throw new IndexOutOfBoundsException(); int result = elements[0]; at[result] = -1; if (size == 1) { size = 0; return result; } elements[0] = elements[--size]; at[elements[0]] = 0; shiftDown(0); return result; } } interface IntComparator { public int compare(int first, int second); } class IntegerUtils { public static int longCompare(long a, long b) { if (a < b) return -1; if (a > b) return 1; return 0; } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
c35fe0c2bdd63bf6413d0fccce990cfe
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class E_Round_147_Div2 { public static long MOD = 1000000007; static int min; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); String t = in.next(); int n = in.nextInt(); String[] data = new String[n]; int[] lim = new int[n]; for (int i = 0; i < n; i++) { data[i] = in.next(); lim[i] = in.nextInt(); } int total = 2 + n + 26 ; int first = 1 + n; int[][]flow = new int[total][total]; for(int i = 0; i < n; i++){ flow[0][i + 1] = lim[i]; int[]count = new int[26]; for(int j = 0; j < data[i].length(); j++){ count[data[i].charAt(j) - 'a']++; } for(int j = 0; j < 26; j++){ flow[i + 1][j + first] = count[j]; } } int[]count = new int[26]; for(int i = 0; i < t.length(); i++){ count[t.charAt(i) - 'a']++; } for(int i = 0; i < 26; i++){ flow[i + first][total - 1] = count[i]; } int[]pa = new int[total]; int[]dist = new int[total]; int c = 0; while(true){ PriorityQueue<Point> q= new PriorityQueue<>(); q.add(new Point(0,0)); Arrays.fill(pa , -1); Arrays.fill(dist, Integer.MAX_VALUE); pa[0] = 0; dist[0] = 0; while(!q.isEmpty()){ Point p = q.poll(); if(dist[p.y] == p.x){ for(int i = 0; i < total; i++){ if(flow[p.y][i] > 0){ int cst = cost(p.y, i, first, total); if(dist[i] > cst + p.x){ dist[i] = cst + p.x; q.add(new Point(dist[i], i)); pa[i] = p.y; } } } } } //System.out.println(dist[total - 1]); min = Integer.MAX_VALUE; if(pa[total - 1] == -1){ break; } update(total - 1, pa, flow); if(min == 0){ break; } c += min; } if(c < t.length()){ out.println(-1); }else{ int result = 0; for(int i = 0; i < n; i++){ result += (i + 1)*(lim[i] - flow[0][i + 1]); } out.println(result); } out.close(); } static void update(int index, int[]pa, int[][]flow){ if(pa[index] != index){ min = Math.min(min, flow[pa[index]][index]); update(pa[index], pa, flow); flow[pa[index]][index] -= min; flow[index][pa[index]] += min; } } public static int cost(int a, int b, int first, int total){ if(a == 0 && b < first){ return b; } else if(b == 0 && a < first){ return -b; } return 0; } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new // BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new // FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
3c4b0f35571591d9df018c87b415beac
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class E_Round_147_Div2 { public static long MOD = 1000000007; static int min; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); String t = in.next(); int n = in.nextInt(); String[] data = new String[n]; int[] lim = new int[n]; for (int i = 0; i < n; i++) { data[i] = in.next(); lim[i] = in.nextInt(); } int total = 2 + n + 26 + 26; int first = 1 + n; int second = 1 + n + 26; int[][]flow = new int[total][total]; for(int i = 0; i < n; i++){ flow[0][i + 1] = lim[i]; int[]count = new int[26]; for(int j = 0; j < data[i].length(); j++){ count[data[i].charAt(j) - 'a']++; } for(int j = 0; j < 26; j++){ flow[i + 1][j + first] = count[j]; flow[j + first][j + second] += count[j]; } } int[]count = new int[26]; for(int i = 0; i < t.length(); i++){ count[t.charAt(i) - 'a']++; } for(int i = 0; i < 26; i++){ flow[i + second][total - 1] = count[i]; } int[]pa = new int[total]; int[]dist = new int[total]; int c = 0; while(true){ PriorityQueue<Point> q= new PriorityQueue<>(); q.add(new Point(0,0)); Arrays.fill(pa , -1); Arrays.fill(dist, Integer.MAX_VALUE); pa[0] = 0; dist[0] = 0; while(!q.isEmpty()){ Point p = q.poll(); if(dist[p.y] == p.x){ for(int i = 0; i < total; i++){ if(flow[p.y][i] > 0){ int cst = cost(p.y, i, first, second, total); if(dist[i] > cst + p.x){ dist[i] = cst + p.x; q.add(new Point(dist[i], i)); pa[i] = p.y; } } } } } //System.out.println(dist[total - 1]); min = Integer.MAX_VALUE; if(pa[total - 1] == -1){ break; } update(total - 1, pa, flow); if(min == 0){ break; } c += min; } if(c < t.length()){ out.println(-1); }else{ int result = 0; for(int i = 0; i < n; i++){ result += (i + 1)*(lim[i] - flow[0][i + 1]); } out.println(result); } out.close(); } static void update(int index, int[]pa, int[][]flow){ if(pa[index] != index){ min = Math.min(min, flow[pa[index]][index]); update(pa[index], pa, flow); flow[pa[index]][index] -= min; flow[index][pa[index]] += min; } } public static int cost(int a, int b, int first, int second , int total){ if(a == 0 && b < first){ return b; } else if(b == 0 && a < first){ return -b; } return 0; } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new // BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new // FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
f8c13c15be1a7b9d1440763bb436064c
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.PriorityQueue; import java.util.AbstractQueue; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.AbstractCollection; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Sparsh Sanchorawala */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); EBuildString solver = new EBuildString(); solver.solve(1, in, out); out.close(); } static class EBuildString { List<Edge>[] createGraph(int n) { List<Edge>[] graph = new List[n]; for (int i = 0; i < n; i++) graph[i] = new ArrayList<>(); return graph; } void addEdge(List<Edge>[] graph, int s, int t, int cap, int cost) { graph[s].add(new Edge(t, cap, cost, graph[t].size())); graph[t].add(new Edge(s, 0, -cost, graph[s].size() - 1)); } int[] minCostFlow(List<Edge>[] graph, int s, int t, int maxf) { int n = graph.length; int[] prio = new int[n]; int[] curflow = new int[n]; int[] prevedge = new int[n]; int[] prevnode = new int[n]; int[] pot = new int[n]; // bellmanFord invocation can be skipped if edges costs are non-negative //bellmanFord(graph, s, pot); int flow = 0; int flowCost = 0; while (flow < maxf) { PriorityQueue<Long> q = new PriorityQueue<>(); q.add((long) s); Arrays.fill(prio, Integer.MAX_VALUE); prio[s] = 0; boolean[] finished = new boolean[n]; curflow[s] = Integer.MAX_VALUE; while (!finished[t] && !q.isEmpty()) { long cur = q.remove(); int u = (int) (cur & 0xFFFF_FFFFL); int priou = (int) (cur >>> 32); if (priou != prio[u]) continue; finished[u] = true; for (int i = 0; i < graph[u].size(); i++) { Edge e = graph[u].get(i); if (e.f >= e.cap) continue; int v = e.to; int nprio = prio[u] + e.cost + pot[u] - pot[v]; if (prio[v] > nprio) { prio[v] = nprio; q.add(((long) nprio << 32) + v); prevnode[v] = u; prevedge[v] = i; curflow[v] = Math.min(curflow[u], e.cap - e.f); } } } if (prio[t] == Integer.MAX_VALUE) break; for (int i = 0; i < n; i++) if (finished[i]) pot[i] += prio[i] - prio[t]; int df = Math.min(curflow[t], maxf - flow); flow += df; for (int v = t; v != s; v = prevnode[v]) { Edge e = graph[prevnode[v]].get(prevedge[v]); e.f += df; graph[v].get(e.rev).f -= df; flowCost += df * e.cost; } } return new int[]{flow, flowCost}; } public void solve(int testNumber, InputReader s, PrintWriter w) { int[] fr = new int[26]; char[] str = s.next().toCharArray(); int flow = str.length; for (char i : str) fr[i - 'a']++; int n = s.nextInt(); int[][] f = new int[n][26]; int[] c = new int[n]; for (int i = 0; i < n; i++) { str = s.next().toCharArray(); for (char j : str) f[i][j - 'a']++; c[i] = s.nextInt(); } int src = 0; int sink = (1 + n + 26 * n + 26 + 1) - 1; List<Edge>[] graph = createGraph(1 + n + 26 * n + 26 + 1); for (int i = 0; i < n; i++) addEdge(graph, src, 1 + i, c[i], 0); for (int i = 0; i < n; i++) { for (int j = 0; j < 26; j++) { if (f[i][j] > 0) { addEdge(graph, 1 + i, 1 + n + 26 * i + j, f[i][j], 1 + i); addEdge(graph, 1 + n + 26 * i + j, 1 + n + 26 * n + j, Integer.MAX_VALUE, 0); } } } for (int i = 0; i < 26; i++) { if (fr[i] > 0) addEdge(graph, 1 + n + 26 * n + i, sink, fr[i], 0); } int[] res = minCostFlow(graph, src, sink, flow); if (flow == res[0]) w.println(res[1]); else w.println(-1); } class Edge { int to; int f; int cap; int cost; int rev; Edge(int v, int cap, int cost, int rev) { this.to = v; this.cap = cap; this.cost = cost; this.rev = rev; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
336e3cb9503899c034a8ea46a8c783b4
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.*; import java.util.function.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.util.stream.IntStream.*; import static java.util.stream.Collectors.*; public class Main { public static void main(String[] args) { InputReader reader = new InputReader(System.in); PrintWriter writer = new PrintWriter(System.out); String t = reader.next(); int[] need = new int[26]; for (char c: t.toCharArray()) { ++need[c-'a']; } int n = reader.nextInt(); int source = n+26; int target = n+27; Graph graph = new Graph(n+28); for (int i = 0; i < 26; ++i) if (need[i] > 0) graph.addEdge(n+i, target, need[i], 0); for (int i = 0; i < n; ++i) { String s = reader.next(); int[] has = new int[26]; for (char c: s.toCharArray()) { ++has[c-'a']; } for (int j = 0; j < 26; ++j) if (has[j] > 0) graph.addEdge(i, n+j, has[j], 0); graph.addEdge(source, i, reader.nextInt(), i+1); } MaxFlowMinCost mfmc = new MaxFlowMinCost(graph); writer.println(mfmc.find(t.length(), source, target)); writer.close(); } } class Config { public static final int INFINITY = (int) 1e9; } class Vertex extends AdjacencyListVertex<Edge> { public Vertex(int id) { super(id); } } class Edge extends CostedFlowableEdge<Vertex> { public Edge(Vertex to, int capacity, int cost) { super(to, capacity, cost); } } class Graph extends BaseGraph<Vertex, Edge> { public Graph(int n) { super(n, Vertex::new); } public void addEdge(int from, int to, int capacity, int cost) { Vertex f = getVertex(from); Vertex t = getVertex(to); Edge e1 = new Edge(t, capacity, cost); Edge e2 = new Edge(f, 0, -cost); e1.setReversed(e2); e2.setReversed(e1); f.addEdge(e1); t.addEdge(e2); } public void clear() { getVertices().stream() .map(AdjacencyListVertex::getState) .forEach(SearchState::clear); } public void updatePhi() { getVertices().stream() .map(AdjacencyListVertex::getState) .forEach(SearchState::updatePhi); } } interface IEdge<V extends IVertex> { public default boolean isAvailable() { return true; } public default int getWeight() { return 1; } } class DirectedEdge<V extends IVertex<? extends DirectedEdge>> implements IEdge<V> { public DirectedEdge(V to) { this.to = to; } public V getTo() { return to; } private V to; } class FlowableEdge<V extends IVertex<? extends FlowableEdge>> extends DirectedEdge<V> { public FlowableEdge(V to, int capacity) { super(to); this.capacity = capacity; } public void push(int flow) { this.flow += flow; reversed.flow -= flow; } public void setReversed(FlowableEdge<V> reversed) { this.reversed = reversed; } public int getResidualCapacity() { return capacity - flow; } public boolean isAvailable() { return flow < capacity; } int flow; int capacity; private FlowableEdge<V> reversed; } class CostedFlowableEdge<V extends IVertex<? extends CostedFlowableEdge>> extends FlowableEdge<V> { public CostedFlowableEdge(V to, int capacity, int cost) { super(to, capacity); this.cost = cost; } public int getCost() { return cost; } int cost; } interface IVertex<E extends IEdge> { } class AdjacencyListVertex<E extends DirectedEdge<? extends AdjacencyListVertex>> implements IVertex<E> { public AdjacencyListVertex(int id) { this.id = id; } public void addEdge(E edge) { edges.add(edge); } public List<E> getEdges() { return edges; } public SearchState<E> getState() { return state; } int id; private List<E> edges = new ArrayList<>(); private SearchState<E> state = new SearchState<>(); } enum StateColor { WHITE, GRAY, BLACK } class SearchState<E extends DirectedEdge<? extends AdjacencyListVertex>> { public boolean isOpened() { return color != StateColor.WHITE; } public boolean isClosed() { return color == StateColor.BLACK; } public void open(Vertex from, E by, Vertex to) { color = StateColor.GRAY; pathInfo.previous = from; pathInfo.by = by; if (edgesIter == null) edgesIter = (Iterator<E>) to.getEdges().iterator(); } public void close() { color = StateColor.BLACK; } public void init(Vertex source) { color = StateColor.GRAY; pathInfo.distance = 0; edgesIter = (Iterator<E>) source.getEdges().iterator(); } public void clear() { color = StateColor.WHITE; edgesIter = null; pathInfo.clear(); } public PathInfo<E> getPathInfo() { return pathInfo; } public void updatePhi() { if (pathInfo.distance != Config.INFINITY) phi += pathInfo.distance; } int phi; StateColor color; Iterator<E> edgesIter; PathInfo<E> pathInfo = new PathInfo<>(); } class PathInfo<E extends DirectedEdge<? extends AdjacencyListVertex>> { public void clear() { by = null; previous = null; distance = Config.INFINITY; } public void saveLayer() { layer = distance; } int layer; int distance; E by; AdjacencyListVertex previous; } class BaseGraph<V extends IVertex<? extends E>, E extends IEdge<? extends V>> { public BaseGraph(int n, IntFunction<V> vertexFactory) { this.n = n; vertices = range(0, n).mapToObj(vertexFactory).collect(toList()); } public int getN() { return n; } public V getVertex(int id) { return vertices.get(id); } public List<V> getVertices() { return vertices; } private int n; private List<V> vertices; } interface IOrder { public Vertex top(); public Vertex pop(); public void clear(); public boolean isEmpty(); public default void push(Vertex v) { } public default void remove(Vertex v) { } } class PriorityQueue implements IOrder { public PriorityQueue(Comparator<Vertex> comparator) { queue = new TreeSet<>(comparator); } @Override public Vertex top() { return queue.first(); } @Override public Vertex pop() { return queue.pollFirst(); } @Override public void push(Vertex v) { queue.add(v); } @Override public void remove(Vertex v) { queue.remove(v); } @Override public void clear() { queue.clear(); } @Override public boolean isEmpty() { return queue.isEmpty(); } private TreeSet<Vertex> queue; } class PathRestorer { public static List<Edge> get(AdjacencyListVertex<Edge> target) { if (target == null) { throw new IllegalArgumentException("target == null"); } if (!target.getState().isOpened()) { return null; } List<Edge> path = new ArrayList<>(); while (target.getState().getPathInfo().by != null) { path.add(target.getState().getPathInfo().by); target = target.getState().getPathInfo().previous; } reverse(path); return path; } } abstract class Search { public Search(Graph graph) { this.graph = graph; order = getOrder(); } public void run(Vertex source, Vertex target) { init(source); do { Vertex from = order.top(); if (from.getState().edgesIter.hasNext()) { Edge by = from.getState().edgesIter.next(); if (by.isAvailable() && isOptimal(from, by)) { go(from, by); } } else { close(order.pop()); } } while (!order.isEmpty()); } protected void init(Vertex source) { order.clear(); order.push(source); source.getState().init(source); } protected boolean isOptimal(Vertex from, Edge by) { return !by.getTo().getState().isOpened(); } protected void go(Vertex from, Edge by) { Vertex to = by.getTo(); if (to.getState().isOpened()) { order.remove(to); } open(from, by, to); update(from, by, to); order.push(to); } protected void open(Vertex from, Edge by, Vertex to) { to.getState().open(from, by, to); } protected void update(Vertex from, Edge by, Vertex to) { to.getState().getPathInfo().distance = from.getState().getPathInfo().distance + getWeight(from, by); } protected int getWeight(Vertex from, Edge by) { return by.getWeight(); } protected void close(Vertex v) { v.getState().close(); } protected abstract IOrder getOrder(); protected Graph graph; private IOrder order; } class DijkstraDense extends Search { public DijkstraDense(Graph graph) { super(graph); } @Override protected IOrder getOrder() { return new IOrder() { Vertex nearestUnused; public Vertex top() { if (nearestUnused != null && !nearestUnused.getState().isClosed()) { return nearestUnused; } return nearestUnused = graph.getVertices().stream() .filter(v -> v.getState().isOpened()) .filter(v -> !v.getState().isClosed()) .min(Comparator.comparing(v -> v.getState().getPathInfo().distance)) .orElse(null); } public Vertex pop() { return nearestUnused; } public void clear() { nearestUnused = null; } public boolean isEmpty() { return top() == null; } }; } @Override protected boolean isOptimal(Vertex from, Edge by) { return by.getTo().getState().getPathInfo().distance > from.getState().getPathInfo().distance+getWeight(from, by); } } class DijkstraSparse extends Search { public DijkstraSparse(Graph graph) { super(graph); } @Override protected boolean isOptimal(Vertex from, Edge by) { return by.getTo().getState().getPathInfo().distance > from.getState().getPathInfo().distance+getWeight(from, by); } @Override protected IOrder getOrder() { return new PriorityQueue((a, b) -> { int c = Integer.compare(a.getState().getPathInfo().distance, b.getState().getPathInfo().distance); return c != 0 ? c : a.id-b.id; }); } } class FordBellman { public void run(Graph graph, Vertex source) { int n = graph.getN(); graph.clear(); source.getState().getPathInfo().distance = 0; for (int i = 0; i < n-1; ++i) for (Vertex v: graph.getVertices()) { if (v.getState().getPathInfo().distance == Config.INFINITY) { continue; } for (Edge e: v.getEdges()) { if (e.isAvailable()) { e.getTo().getState().getPathInfo().distance = Math.min(e.getTo().getState().getPathInfo().distance, v.getState().getPathInfo().distance+e.getCost()); } } } } } class MaxFlowMinCost { public MaxFlowMinCost(Graph graph) { this.graph = graph; dijkstraSearcher = new DijkstraSparse(graph) { @Override protected int getWeight(Vertex from, Edge by) { return by.getCost() + from.getState().phi - by.getTo().getState().phi; } }; } public long find(int required, int source, int target) { return find(required, graph.getVertex(source), graph.getVertex(target)); } private long cost; public long find(int required, Vertex source, Vertex target) { // fordBellman.run(graph, source); // graph.updatePhi(); cost = 0; while (dijkstra(source, target)) { graph.updatePhi(); List<Edge> path = PathRestorer.get(target); long push = path.stream() .min(Comparator.comparing(e -> e.getResidualCapacity())) .get() .getResidualCapacity(); if (push == 0) { throw new RuntimeException("Zero residual capacity."); } required -= push; path.stream().forEach(e -> { e.push((int) push); cost += push*e.getCost(); }); } return required > 0 ? -1 : cost; } private boolean dijkstra(Vertex source, Vertex target) { graph.clear(); dijkstraSearcher.run(source, target); return target.getState().isOpened(); } private Graph graph; private FordBellman fordBellman = new FordBellman(); private Search dijkstraSearcher; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
1d86830c5fab57c2848b6cc57a2c8d31
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.*; import java.util.function.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.util.stream.IntStream.*; import static java.util.stream.Collectors.*; public class Main { public static void main(String[] args) { InputReader reader = new InputReader(System.in); PrintWriter writer = new PrintWriter(System.out); String t = reader.next(); int[] need = new int[26]; for (char c: t.toCharArray()) { ++need[c-'a']; } int n = reader.nextInt(); int source = n+26; int target = n+27; Graph graph = new Graph(n+28); for (int i = 0; i < 26; ++i) if (need[i] > 0) graph.addEdge(n+i, target, need[i], 0); for (int i = 0; i < n; ++i) { String s = reader.next(); int[] has = new int[26]; for (char c: s.toCharArray()) { ++has[c-'a']; } for (int j = 0; j < 26; ++j) if (has[j] > 0) graph.addEdge(i, n+j, has[j], 0); graph.addEdge(source, i, reader.nextInt(), i+1); } MaxFlowMinCost mfmc = new MaxFlowMinCost(graph); writer.println(mfmc.find(t.length(), source, target)); writer.close(); } } class Config { public static final int INFINITY = (int) 1e9; } class Vertex extends AdjacencyListVertex<Edge> { public Vertex(int id) { super(id); } } class Edge extends CostedFlowableEdge<Vertex> { public Edge(Vertex to, int capacity, int cost) { super(to, capacity, cost); } } class Graph extends BaseGraph<Vertex, Edge> { public Graph(int n) { super(n, Vertex::new); } public void addEdge(int from, int to, int capacity, int cost) { Vertex f = getVertex(from); Vertex t = getVertex(to); Edge e1 = new Edge(t, capacity, cost); Edge e2 = new Edge(f, 0, -cost); e1.setReversed(e2); e2.setReversed(e1); f.addEdge(e1); t.addEdge(e2); } public void clear() { getVertices().stream() .map(AdjacencyListVertex::getState) .forEach(SearchState::clear); } public void updatePhi() { getVertices().stream() .map(AdjacencyListVertex::getState) .forEach(SearchState::updatePhi); } } interface IEdge<V extends IVertex> { public default boolean isAvailable() { return true; } public default int getWeight() { return 1; } } class DirectedEdge<V extends IVertex<? extends DirectedEdge>> implements IEdge<V> { public DirectedEdge(V to) { this.to = to; } public V getTo() { return to; } private V to; } class FlowableEdge<V extends IVertex<? extends FlowableEdge>> extends DirectedEdge<V> { public FlowableEdge(V to, int capacity) { super(to); this.capacity = capacity; } public void push(int flow) { this.flow += flow; reversed.flow -= flow; } public void setReversed(FlowableEdge<V> reversed) { this.reversed = reversed; } public int getResidualCapacity() { return capacity - flow; } public boolean isAvailable() { return flow < capacity; } int flow; int capacity; private FlowableEdge<V> reversed; } class CostedFlowableEdge<V extends IVertex<? extends CostedFlowableEdge>> extends FlowableEdge<V> { public CostedFlowableEdge(V to, int capacity, int cost) { super(to, capacity); this.cost = cost; } public int getCost() { return cost; } int cost; } interface IVertex<E extends IEdge> { } class AdjacencyListVertex<E extends DirectedEdge<? extends AdjacencyListVertex>> implements IVertex<E> { public AdjacencyListVertex(int id) { this.id = id; } public void addEdge(E edge) { edges.add(edge); } public List<E> getEdges() { return edges; } public SearchState<E> getState() { return state; } int id; private List<E> edges = new ArrayList<>(); private SearchState<E> state = new SearchState<>(); } enum StateColor { WHITE, GRAY, BLACK } class SearchState<E extends DirectedEdge<? extends AdjacencyListVertex>> { public boolean isOpened() { return color != StateColor.WHITE; } public boolean isClosed() { return color == StateColor.BLACK; } public void open(Vertex from, E by, Vertex to) { color = StateColor.GRAY; pathInfo.previous = from; pathInfo.by = by; if (edgesIter == null) edgesIter = (Iterator<E>) to.getEdges().iterator(); } public void close() { color = StateColor.BLACK; } public void init(Vertex source) { color = StateColor.GRAY; pathInfo.distance = 0; edgesIter = (Iterator<E>) source.getEdges().iterator(); } public void clear() { color = StateColor.WHITE; edgesIter = null; pathInfo.clear(); } public PathInfo<E> getPathInfo() { return pathInfo; } public void updatePhi() { if (pathInfo.distance != Config.INFINITY) phi += pathInfo.distance; } int phi; StateColor color; Iterator<E> edgesIter; PathInfo<E> pathInfo = new PathInfo<>(); } class PathInfo<E extends DirectedEdge<? extends AdjacencyListVertex>> { public void clear() { by = null; previous = null; distance = Config.INFINITY; } public void saveLayer() { layer = distance; } int layer; int distance; E by; AdjacencyListVertex previous; } class BaseGraph<V extends IVertex<? extends E>, E extends IEdge<? extends V>> { public BaseGraph(int n, IntFunction<V> vertexFactory) { this.n = n; vertices = range(0, n).mapToObj(vertexFactory).collect(toList()); } public int getN() { return n; } public V getVertex(int id) { return vertices.get(id); } public List<V> getVertices() { return vertices; } private int n; private List<V> vertices; } interface IOrder { public Vertex top(); public Vertex pop(); public void clear(); public boolean isEmpty(); public default void push(Vertex v) { } public default void remove(Vertex v) { } } class PriorityQueue implements IOrder { public PriorityQueue(Comparator<Vertex> comparator) { queue = new TreeSet<>(comparator); } @Override public Vertex top() { return queue.first(); } @Override public Vertex pop() { return queue.pollFirst(); } @Override public void push(Vertex v) { queue.add(v); } @Override public void remove(Vertex v) { queue.remove(v); } @Override public void clear() { queue.clear(); } @Override public boolean isEmpty() { return queue.isEmpty(); } private TreeSet<Vertex> queue; } class PathRestorer { public static List<Edge> get(AdjacencyListVertex<Edge> target) { if (target == null) { throw new IllegalArgumentException("target == null"); } if (!target.getState().isOpened()) { return null; } List<Edge> path = new ArrayList<>(); while (target.getState().getPathInfo().by != null) { path.add(target.getState().getPathInfo().by); target = target.getState().getPathInfo().previous; } reverse(path); return path; } } abstract class Search { public Search(Graph graph) { this.graph = graph; order = getOrder(); } public void run(Vertex source, Vertex target) { init(source); do { Vertex from = order.top(); if (from.getState().edgesIter.hasNext()) { Edge by = from.getState().edgesIter.next(); if (by.isAvailable() && isOptimal(from, by)) { go(from, by); } } else { close(order.pop()); } } while (!order.isEmpty()); } protected void init(Vertex source) { order.clear(); order.push(source); source.getState().init(source); } protected boolean isOptimal(Vertex from, Edge by) { return !by.getTo().getState().isOpened(); } protected void go(Vertex from, Edge by) { Vertex to = by.getTo(); if (to.getState().isOpened()) { order.remove(to); } open(from, by, to); update(from, by, to); order.push(to); } protected void open(Vertex from, Edge by, Vertex to) { to.getState().open(from, by, to); } protected void update(Vertex from, Edge by, Vertex to) { to.getState().getPathInfo().distance = from.getState().getPathInfo().distance + getWeight(from, by); } protected int getWeight(Vertex from, Edge by) { return by.getWeight(); } protected void close(Vertex v) { v.getState().close(); } protected abstract IOrder getOrder(); protected Graph graph; private IOrder order; } class DijkstraDense extends Search { public DijkstraDense(Graph graph) { super(graph); } @Override protected IOrder getOrder() { return new IOrder() { Vertex nearestUnused; public Vertex top() { if (nearestUnused != null && !nearestUnused.getState().isClosed()) { return nearestUnused; } return nearestUnused = graph.getVertices().stream() .filter(v -> v.getState().isOpened()) .filter(v -> !v.getState().isClosed()) .min(Comparator.comparing(v -> v.getState().getPathInfo().distance)) .orElse(null); } public Vertex pop() { return nearestUnused; } public void clear() { nearestUnused = null; } public boolean isEmpty() { return top() == null; } }; } @Override protected boolean isOptimal(Vertex from, Edge by) { return by.getTo().getState().getPathInfo().distance > from.getState().getPathInfo().distance+getWeight(from, by); } } class DijkstraSparse extends Search { public DijkstraSparse(Graph graph) { super(graph); } @Override protected boolean isOptimal(Vertex from, Edge by) { return by.getTo().getState().getPathInfo().distance > from.getState().getPathInfo().distance+getWeight(from, by); } @Override protected IOrder getOrder() { return new PriorityQueue((a, b) -> { int c = Integer.compare(a.getState().getPathInfo().distance, b.getState().getPathInfo().distance); return c != 0 ? c : a.id-b.id; }); } } class FordBellman { public void run(Graph graph, Vertex source) { int n = graph.getN(); graph.clear(); source.getState().getPathInfo().distance = 0; for (int i = 0; i < n-1; ++i) for (Vertex v: graph.getVertices()) { if (v.getState().getPathInfo().distance == Config.INFINITY) { continue; } for (Edge e: v.getEdges()) { if (e.isAvailable()) { e.getTo().getState().getPathInfo().distance = Math.min(e.getTo().getState().getPathInfo().distance, v.getState().getPathInfo().distance+e.getCost()); } } } } } class MaxFlowMinCost { public MaxFlowMinCost(Graph graph) { this.graph = graph; dijkstraSearcher = new DijkstraDense(graph) { @Override protected int getWeight(Vertex from, Edge by) { return by.getCost() + from.getState().phi - by.getTo().getState().phi; } }; } public long find(int required, int source, int target) { return find(required, graph.getVertex(source), graph.getVertex(target)); } private long cost; public long find(int required, Vertex source, Vertex target) { // fordBellman.run(graph, source); // graph.updatePhi(); cost = 0; while (dijkstra(source, target)) { graph.updatePhi(); List<Edge> path = PathRestorer.get(target); long push = path.stream() .min(Comparator.comparing(e -> e.getResidualCapacity())) .get() .getResidualCapacity(); if (push == 0) { throw new RuntimeException("Zero residual capacity."); } required -= push; path.stream().forEach(e -> { e.push((int) push); cost += push*e.getCost(); }); } return required > 0 ? -1 : cost; } private boolean dijkstra(Vertex source, Vertex target) { graph.clear(); dijkstraSearcher.run(source, target); return target.getState().isOpened(); } private Graph graph; private FordBellman fordBellman = new FordBellman(); private Search dijkstraSearcher; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
b88378cd068ae88633de61e55c19867e
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.*; import java.util.function.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.util.stream.IntStream.*; import static java.util.stream.Collectors.*; public class Main { public static void main(String[] args) { InputReader reader = new InputReader(System.in); PrintWriter writer = new PrintWriter(System.out); String t = reader.next(); int[] need = new int[26]; for (char c: t.toCharArray()) { ++need[c-'a']; } int n = reader.nextInt(); int source = n+26; int target = n+27; Graph graph = new Graph(n+28); for (int i = 0; i < 26; ++i) if (need[i] > 0) graph.addEdge(n+i, target, need[i], 0); for (int i = 0; i < n; ++i) { String s = reader.next(); int[] has = new int[26]; for (char c: s.toCharArray()) { ++has[c-'a']; } for (int j = 0; j < 26; ++j) if (has[j] > 0) graph.addEdge(i, n+j, has[j], 0); graph.addEdge(source, i, reader.nextInt(), i+1); } MaxFlowMinCost mfmc = new MaxFlowMinCost(graph); writer.println(mfmc.find(t.length(), source, target)); writer.close(); } } class Config { public static final int INFINITY = (int) 1e9; } class Vertex extends AdjacencyListVertex<Edge> { public Vertex(int id) { super(id); } } class Edge extends CostedFlowableEdge<Vertex> { public Edge(Vertex to, int capacity, int cost) { super(to, capacity, cost); } } class Graph extends BaseGraph<Vertex, Edge> { public Graph(int n) { super(n, Vertex::new); } public void addEdge(int from, int to, int capacity, int cost) { Vertex f = getVertex(from); Vertex t = getVertex(to); Edge e1 = new Edge(t, capacity, cost); Edge e2 = new Edge(f, 0, -cost); e1.setReversed(e2); e2.setReversed(e1); f.addEdge(e1); t.addEdge(e2); } public void clear() { getVertices().stream() .map(AdjacencyListVertex::getState) .forEach(SearchState::clear); } public void updatePhi() { getVertices().stream() .map(AdjacencyListVertex::getState) .forEach(SearchState::updatePhi); } } interface IEdge<V extends IVertex> { public default boolean isAvailable() { return true; } public default int getWeight() { return 1; } } class DirectedEdge<V extends IVertex<? extends DirectedEdge>> implements IEdge<V> { public DirectedEdge(V to) { this.to = to; } public V getTo() { return to; } private V to; } class FlowableEdge<V extends IVertex<? extends FlowableEdge>> extends DirectedEdge<V> { public FlowableEdge(V to, int capacity) { super(to); this.capacity = capacity; } public void push(int flow) { this.flow += flow; reversed.flow -= flow; } public void setReversed(FlowableEdge<V> reversed) { this.reversed = reversed; } public int getResidualCapacity() { return capacity - flow; } public boolean isAvailable() { return flow < capacity; } int flow; int capacity; private FlowableEdge<V> reversed; } class CostedFlowableEdge<V extends IVertex<? extends CostedFlowableEdge>> extends FlowableEdge<V> { public CostedFlowableEdge(V to, int capacity, int cost) { super(to, capacity); this.cost = cost; } public int getCost() { return cost; } int cost; } interface IVertex<E extends IEdge> { } class AdjacencyListVertex<E extends DirectedEdge<? extends AdjacencyListVertex>> implements IVertex<E> { public AdjacencyListVertex(int id) { this.id = id; } public void addEdge(E edge) { edges.add(edge); } public List<E> getEdges() { return edges; } public SearchState<E> getState() { return state; } int id; private List<E> edges = new ArrayList<>(); private SearchState<E> state = new SearchState<>(); } enum StateColor { WHITE, GRAY, BLACK } class SearchState<E extends DirectedEdge<? extends AdjacencyListVertex>> { public boolean isOpened() { return color != StateColor.WHITE; } public boolean isClosed() { return color == StateColor.BLACK; } public void open(Vertex from, E by, Vertex to) { color = StateColor.GRAY; pathInfo.previous = from; pathInfo.by = by; if (edgesIter == null) edgesIter = (Iterator<E>) to.getEdges().iterator(); } public void close() { color = StateColor.BLACK; } public void init(Vertex source) { color = StateColor.GRAY; pathInfo.distance = 0; edgesIter = (Iterator<E>) source.getEdges().iterator(); } public void clear() { color = StateColor.WHITE; edgesIter = null; pathInfo.clear(); } public PathInfo<E> getPathInfo() { return pathInfo; } public void updatePhi() { if (pathInfo.distance != Config.INFINITY) phi += pathInfo.distance; } int phi; StateColor color; Iterator<E> edgesIter; PathInfo<E> pathInfo = new PathInfo<>(); } class PathInfo<E extends DirectedEdge<? extends AdjacencyListVertex>> { public void clear() { by = null; previous = null; distance = Config.INFINITY; } public void saveLayer() { layer = distance; } int layer; int distance; E by; AdjacencyListVertex previous; } class BaseGraph<V extends IVertex<? extends E>, E extends IEdge<? extends V>> { public BaseGraph(int n, IntFunction<V> vertexFactory) { this.n = n; vertices = range(0, n).mapToObj(vertexFactory).collect(toList()); } public int getN() { return n; } public V getVertex(int id) { return vertices.get(id); } public List<V> getVertices() { return vertices; } private int n; private List<V> vertices; } interface IOrder { public Vertex top(); public Vertex pop(); public void clear(); public boolean isEmpty(); public default void push(Vertex v) { } public default void remove(Vertex v) { } } class PriorityQueue implements IOrder { public PriorityQueue(Comparator<Vertex> comparator) { queue = new TreeSet<>(comparator); } @Override public Vertex top() { return queue.first(); } @Override public Vertex pop() { return queue.pollFirst(); } @Override public void push(Vertex v) { queue.add(v); } @Override public void remove(Vertex v) { queue.remove(v); } @Override public void clear() { queue.clear(); } @Override public boolean isEmpty() { return queue.isEmpty(); } private TreeSet<Vertex> queue; } class PathRestorer { public static List<Edge> get(AdjacencyListVertex<Edge> target) { if (target == null) { throw new IllegalArgumentException("target == null"); } if (!target.getState().isOpened()) { return null; } List<Edge> path = new ArrayList<>(); while (target.getState().getPathInfo().by != null) { path.add(target.getState().getPathInfo().by); target = target.getState().getPathInfo().previous; } reverse(path); return path; } } abstract class Search { public Search(Graph graph) { this.graph = graph; order = getOrder(); } public void run(Vertex source, Vertex target) { init(source); do { Vertex from = order.top(); if (from.getState().edgesIter.hasNext()) { Edge by = from.getState().edgesIter.next(); if (by.isAvailable() && isOptimal(from, by)) { go(from, by); } } else { close(order.pop()); } } while (!order.isEmpty()); } protected void init(Vertex source) { order.clear(); order.push(source); source.getState().init(source); } protected boolean isOptimal(Vertex from, Edge by) { return !by.getTo().getState().isOpened(); } protected void go(Vertex from, Edge by) { Vertex to = by.getTo(); if (to.getState().isOpened()) { order.remove(to); } open(from, by, to); update(from, by, to); order.push(to); } protected void open(Vertex from, Edge by, Vertex to) { to.getState().open(from, by, to); } protected void update(Vertex from, Edge by, Vertex to) { to.getState().getPathInfo().distance = from.getState().getPathInfo().distance + getWeight(from, by); } protected int getWeight(Vertex from, Edge by) { return by.getWeight(); } protected void close(Vertex v) { v.getState().close(); } protected abstract IOrder getOrder(); protected Graph graph; private IOrder order; } class DijkstraDense extends Search { public DijkstraDense(Graph graph) { super(graph); } @Override protected IOrder getOrder() { return new IOrder() { Vertex nearestUnused; public Vertex top() { if (nearestUnused != null && !nearestUnused.getState().isClosed()) { return nearestUnused; } return nearestUnused = graph.getVertices().stream() .filter(v -> v.getState().isOpened()) .filter(v -> !v.getState().isClosed()) .min(Comparator.comparing(v -> v.getState().getPathInfo().distance)) .orElse(null); } public Vertex pop() { return nearestUnused; } public void clear() { nearestUnused = null; } public boolean isEmpty() { return top() == null; } }; } @Override protected boolean isOptimal(Vertex from, Edge by) { return by.getTo().getState().getPathInfo().distance > from.getState().getPathInfo().distance+getWeight(from, by); } } class DijkstraSparse extends Search { public DijkstraSparse(Graph graph) { super(graph); } @Override protected boolean isOptimal(Vertex from, Edge by) { return by.getTo().getState().getPathInfo().distance > from.getState().getPathInfo().distance+getWeight(from, by); } @Override protected IOrder getOrder() { return new PriorityQueue((a, b) -> { int c = Integer.compare(a.getState().getPathInfo().distance, b.getState().getPathInfo().distance); return c != 0 ? c : a.id-b.id; }); } } class FordBellman { public void run(Graph graph, Vertex source) { int n = graph.getN(); graph.clear(); source.getState().getPathInfo().distance = 0; for (int i = 0; i < n-1; ++i) for (Vertex v: graph.getVertices()) { if (v.getState().getPathInfo().distance == Config.INFINITY) { continue; } for (Edge e: v.getEdges()) { e.getTo().getState().getPathInfo().distance = Math.min(e.getTo().getState().getPathInfo().distance, v.getState().getPathInfo().distance+e.getCost()); } } } } class MaxFlowMinCost { public MaxFlowMinCost(Graph graph) { this.graph = graph; dijkstraSearcher = new DijkstraDense(graph) { @Override protected int getWeight(Vertex from, Edge by) { return by.getCost() + from.getState().phi - by.getTo().getState().phi; } }; } public long find(int required, int source, int target) { return find(required, graph.getVertex(source), graph.getVertex(target)); } private long cost; public long find(int required, Vertex source, Vertex target) { fordBellman.run(graph, source); graph.updatePhi(); cost = 0; while (dijkstra(source, target)) { graph.updatePhi(); List<Edge> path = PathRestorer.get(target); long push = path.stream() .min(Comparator.comparing(e -> e.getResidualCapacity())) .get() .getResidualCapacity(); if (push == 0) { throw new RuntimeException("Zero residual capacity."); } required -= push; path.stream().forEach(e -> { e.push((int) push); cost += push*e.getCost(); }); } return required > 0 ? -1 : cost; } private boolean dijkstra(Vertex source, Vertex target) { graph.clear(); dijkstraSearcher.run(source, target); return target.getState().isOpened(); } private Graph graph; private FordBellman fordBellman = new FordBellman(); private Search dijkstraSearcher; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
f2cb556805b4b55ce82d60da5a4c4ceb
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.*; import java.util.function.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.util.stream.IntStream.*; import static java.util.stream.Collectors.*; public class Main { public static void main(String[] args) { InputReader reader = new InputReader(System.in); PrintWriter writer = new PrintWriter(System.out); String t = reader.next(); int[] need = new int[26]; for (char c: t.toCharArray()) { ++need[c-'a']; } int n = reader.nextInt(); int source = n+26; int target = n+27; Graph graph = new Graph(n+28); for (int i = 0; i < 26; ++i) if (need[i] > 0) graph.addEdge(n+i, target, need[i], 0); for (int i = 0; i < n; ++i) { String s = reader.next(); int[] has = new int[26]; for (char c: s.toCharArray()) { ++has[c-'a']; } for (int j = 0; j < 26; ++j) if (has[j] > 0) graph.addEdge(i, n+j, has[j], 0); graph.addEdge(source, i, reader.nextInt(), i+1); } MaxFlowMinCost mfmc = new MaxFlowMinCost(graph); writer.println(mfmc.find(t.length(), source, target)); writer.close(); } } class Config { public static final int INFINITY = (int) 1e9; } class Vertex extends AdjacencyListVertex<Edge> { public Vertex(int id) { super(id); } } class Edge extends CostedFlowableEdge<Vertex> { public Edge(Vertex to, int capacity, int cost) { super(to, capacity, cost); } } class Graph extends BaseGraph<Vertex, Edge> { public Graph(int n) { super(n, Vertex::new); } public void addEdge(int from, int to, int capacity, int cost) { Vertex f = getVertex(from); Vertex t = getVertex(to); Edge e1 = new Edge(t, capacity, cost); Edge e2 = new Edge(f, 0, -cost); e1.setReversed(e2); e2.setReversed(e1); f.addEdge(e1); t.addEdge(e2); } public void clear() { getVertices().stream() .map(AdjacencyListVertex::getState) .forEach(SearchState::clear); } public void updatePhi() { getVertices().stream() .map(AdjacencyListVertex::getState) .forEach(SearchState::updatePhi); } } interface IEdge<V extends IVertex> { public default boolean isAvailable() { return true; } public default int getWeight() { return 1; } } class DirectedEdge<V extends IVertex<? extends DirectedEdge>> implements IEdge<V> { public DirectedEdge(V to) { this.to = to; } public V getTo() { return to; } private V to; } class FlowableEdge<V extends IVertex<? extends FlowableEdge>> extends DirectedEdge<V> { public FlowableEdge(V to, int capacity) { super(to); this.capacity = capacity; } public void push(int flow) { this.flow += flow; reversed.flow -= flow; } public void setReversed(FlowableEdge<V> reversed) { this.reversed = reversed; } public int getResidualCapacity() { return capacity - flow; } public boolean isAvailable() { return flow < capacity; } int flow; int capacity; private FlowableEdge<V> reversed; } class CostedFlowableEdge<V extends IVertex<? extends CostedFlowableEdge>> extends FlowableEdge<V> { public CostedFlowableEdge(V to, int capacity, int cost) { super(to, capacity); this.cost = cost; } public int getCost() { return cost; } int cost; } interface IVertex<E extends IEdge> { } class AdjacencyListVertex<E extends DirectedEdge<? extends AdjacencyListVertex>> implements IVertex<E> { public AdjacencyListVertex(int id) { this.id = id; } public void addEdge(E edge) { edges.add(edge); } public List<E> getEdges() { return edges; } public SearchState<E> getState() { return state; } int id; private List<E> edges = new ArrayList<>(); private SearchState<E> state = new SearchState<>(); } enum StateColor { WHITE, GRAY, BLACK } class SearchState<E extends DirectedEdge<? extends AdjacencyListVertex>> { public boolean isOpened() { return color != StateColor.WHITE; } public boolean isClosed() { return color == StateColor.BLACK; } public void open(Vertex from, E by, Vertex to) { color = StateColor.GRAY; pathInfo.previous = from; pathInfo.by = by; if (edgesIter == null) edgesIter = (Iterator<E>) to.getEdges().iterator(); } public void close() { color = StateColor.BLACK; } public void init(Vertex source) { color = StateColor.GRAY; pathInfo.distance = 0; edgesIter = (Iterator<E>) source.getEdges().iterator(); } public void clear() { color = StateColor.WHITE; edgesIter = null; pathInfo.clear(); } public PathInfo<E> getPathInfo() { return pathInfo; } public void updatePhi() { if (pathInfo.distance != Config.INFINITY) phi += pathInfo.distance; } int phi; StateColor color; Iterator<E> edgesIter; PathInfo<E> pathInfo = new PathInfo<>(); } class PathInfo<E extends DirectedEdge<? extends AdjacencyListVertex>> { public void clear() { by = null; previous = null; distance = Config.INFINITY; } public void saveLayer() { layer = distance; } int layer; int distance; E by; AdjacencyListVertex previous; } class BaseGraph<V extends IVertex<? extends E>, E extends IEdge<? extends V>> { public BaseGraph(int n, IntFunction<V> vertexFactory) { this.n = n; vertices = range(0, n).mapToObj(vertexFactory).collect(toList()); } public int getN() { return n; } public V getVertex(int id) { return vertices.get(id); } public List<V> getVertices() { return vertices; } private int n; private List<V> vertices; } interface IOrder { public Vertex top(); public Vertex pop(); public void clear(); public boolean isEmpty(); public default void push(Vertex v) { } public default void remove(Vertex v) { } } class PriorityQueue implements IOrder { public PriorityQueue(Comparator<Vertex> comparator) { queue = new TreeSet<>(comparator); } @Override public Vertex top() { return queue.first(); } @Override public Vertex pop() { return queue.pollFirst(); } @Override public void push(Vertex v) { queue.add(v); } @Override public void remove(Vertex v) { queue.remove(v); } @Override public void clear() { queue.clear(); } @Override public boolean isEmpty() { return queue.isEmpty(); } private TreeSet<Vertex> queue; } class PathRestorer { public static List<Edge> get(AdjacencyListVertex<Edge> target) { if (target == null) { throw new IllegalArgumentException("target == null"); } if (!target.getState().isOpened()) { return null; } List<Edge> path = new ArrayList<>(); while (target.getState().getPathInfo().by != null) { path.add(target.getState().getPathInfo().by); target = target.getState().getPathInfo().previous; } reverse(path); return path; } } abstract class Search { public Search(Graph graph) { this.graph = graph; order = getOrder(); } public void run(Vertex source, Vertex target) { init(source); do { Vertex from = order.top(); if (from.getState().edgesIter.hasNext()) { Edge by = from.getState().edgesIter.next(); if (by.isAvailable() && isOptimal(from, by)) { go(from, by); } } else { close(order.pop()); } } while (!order.isEmpty()); } protected void init(Vertex source) { order.clear(); order.push(source); source.getState().init(source); } protected boolean isOptimal(Vertex from, Edge by) { return !by.getTo().getState().isOpened(); } protected void go(Vertex from, Edge by) { Vertex to = by.getTo(); if (to.getState().isOpened()) { order.remove(to); } open(from, by, to); update(from, by, to); order.push(to); } protected void open(Vertex from, Edge by, Vertex to) { to.getState().open(from, by, to); } protected void update(Vertex from, Edge by, Vertex to) { to.getState().getPathInfo().distance = from.getState().getPathInfo().distance + getWeight(from, by); } protected int getWeight(Vertex from, Edge by) { return by.getWeight(); } protected void close(Vertex v) { v.getState().close(); } protected abstract IOrder getOrder(); protected Graph graph; private IOrder order; } class DijkstraDense extends Search { public DijkstraDense(Graph graph) { super(graph); } @Override protected IOrder getOrder() { return new IOrder() { Vertex nearestUnused; public Vertex top() { if (nearestUnused != null && !nearestUnused.getState().isClosed()) { return nearestUnused; } return nearestUnused = graph.getVertices().stream() .filter(v -> v.getState().isOpened()) .filter(v -> !v.getState().isClosed()) .min(Comparator.comparing(v -> v.getState().getPathInfo().distance)) .orElse(null); } public Vertex pop() { return nearestUnused; } public void clear() { nearestUnused = null; } public boolean isEmpty() { return top() == null; } }; } } class DijkstraSparse extends Search { public DijkstraSparse(Graph graph) { super(graph); } @Override protected boolean isOptimal(Vertex from, Edge by) { return by.getTo().getState().getPathInfo().distance > from.getState().getPathInfo().distance+getWeight(from, by); } @Override protected int getWeight(Vertex from, Edge by) { return by.getWeight(); } @Override protected IOrder getOrder() { return new PriorityQueue((a, b) -> { int c = Integer.compare(a.getState().getPathInfo().distance, b.getState().getPathInfo().distance); return c != 0 ? c : a.id-b.id; }); } } class MaxFlowMinCost { public MaxFlowMinCost(Graph graph) { this.graph = graph; dijkstraSearcher = new DijkstraSparse(graph) { @Override protected int getWeight(Vertex from, Edge by) { return by.getCost() + from.getState().phi - by.getTo().getState().phi; } }; } public long find(int required, int source, int target) { return find(required, graph.getVertex(source), graph.getVertex(target)); } private long cost; public long find(int required, Vertex source, Vertex target) { cost = 0; while (dijkstra(source, target)) { graph.updatePhi(); List<Edge> path = PathRestorer.get(target); int push = path.stream() .min(Comparator.comparing(e -> e.getResidualCapacity())) .get() .getResidualCapacity(); if (push == 0) { throw new RuntimeException("Zero residual capacity."); } required -= push; path.stream().forEach(e -> { e.push(push); cost += push*e.getCost(); }); } return required > 0 ? -1 : cost; } private boolean dijkstra(Vertex source, Vertex target) { graph.clear(); dijkstraSearcher.run(source, target); return target.getState().isOpened(); } private Graph graph; private Search dijkstraSearcher; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
8166f73fda12c8a90f59c000250f1006
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.*; import java.util.function.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.util.stream.IntStream.*; import static java.util.stream.Collectors.*; public class Main { public static void main(String[] args) { InputReader reader = new InputReader(System.in); PrintWriter writer = new PrintWriter(System.out); String t = reader.next(); int[] need = new int[26]; for (char c: t.toCharArray()) { ++need[c-'a']; } int n = reader.nextInt(); int source = n+26; int target = n+27; Graph graph = new Graph(n+28); for (int i = 0; i < 26; ++i) if (need[i] > 0) graph.addEdge(n+i, target, need[i], 0); for (int i = 0; i < n; ++i) { String s = reader.next(); int[] has = new int[26]; for (char c: s.toCharArray()) { ++has[c-'a']; } for (int j = 0; j < 26; ++j) if (has[j] > 0) graph.addEdge(i, n+j, has[j], 0); graph.addEdge(source, i, reader.nextInt(), i+1); } MaxFlowMinCost mfmc = new MaxFlowMinCost(graph); writer.println(mfmc.find(t.length(), source, target)); writer.close(); } } class Config { public static final int INFINITY = (int) 1e9; } class Vertex extends AdjacencyListVertex<Edge> { public Vertex(int id) { super(id); } } class Edge extends CostedFlowableEdge<Vertex> { public Edge(Vertex to, int capacity, int cost) { super(to, capacity, cost); } } class Graph extends BaseGraph<Vertex, Edge> { public Graph(int n) { super(n, Vertex::new); } public void addEdge(int from, int to, int capacity, int cost) { Vertex f = getVertex(from); Vertex t = getVertex(to); Edge e1 = new Edge(t, capacity, cost); Edge e2 = new Edge(f, 0, -cost); e1.setReversed(e2); e2.setReversed(e1); f.addEdge(e1); t.addEdge(e2); } public void clear() { getVertices().stream() .map(AdjacencyListVertex::getState) .forEach(SearchState::clear); } public void updatePhi() { getVertices().stream() .map(AdjacencyListVertex::getState) .forEach(SearchState::updatePhi); } } interface IEdge<V extends IVertex> { public default boolean isAvailable() { return true; } public default int getWeight() { return 1; } } class DirectedEdge<V extends IVertex<? extends DirectedEdge>> implements IEdge<V> { public DirectedEdge(V to) { this.to = to; } public V getTo() { return to; } private V to; } class FlowableEdge<V extends IVertex<? extends FlowableEdge>> extends DirectedEdge<V> { public FlowableEdge(V to, int capacity) { super(to); this.capacity = capacity; } public void push(int flow) { this.flow += flow; reversed.flow -= flow; } public void setReversed(FlowableEdge<V> reversed) { this.reversed = reversed; } public int getResidualCapacity() { return capacity - flow; } public boolean isAvailable() { return flow < capacity; } int flow; int capacity; private FlowableEdge<V> reversed; } class CostedFlowableEdge<V extends IVertex<? extends CostedFlowableEdge>> extends FlowableEdge<V> { public CostedFlowableEdge(V to, int capacity, int cost) { super(to, capacity); this.cost = cost; } public int getCost() { return cost; } int cost; } interface IVertex<E extends IEdge> { } class AdjacencyListVertex<E extends DirectedEdge<? extends AdjacencyListVertex>> implements IVertex<E> { public AdjacencyListVertex(int id) { this.id = id; } public void addEdge(E edge) { edges.add(edge); } public List<E> getEdges() { return edges; } public SearchState<E> getState() { return state; } int id; private List<E> edges = new ArrayList<>(); private SearchState<E> state = new SearchState<>(); } enum StateColor { WHITE, GRAY, BLACK } class SearchState<E extends DirectedEdge<? extends AdjacencyListVertex>> { public boolean isOpened() { return color != StateColor.WHITE; } public boolean isClosed() { return color == StateColor.BLACK; } public void open(Vertex from, E by, Vertex to) { color = StateColor.GRAY; pathInfo.previous = from; pathInfo.by = by; if (edgesIter == null) edgesIter = (Iterator<E>) to.getEdges().iterator(); } public void close() { color = StateColor.BLACK; } public void init(Vertex source) { color = StateColor.GRAY; pathInfo.distance = 0; edgesIter = (Iterator<E>) source.getEdges().iterator(); } public void clear() { color = StateColor.WHITE; edgesIter = null; pathInfo.clear(); } public PathInfo<E> getPathInfo() { return pathInfo; } public void updatePhi() { if (pathInfo.distance != Config.INFINITY) phi += pathInfo.distance; } int phi; StateColor color; Iterator<E> edgesIter; PathInfo<E> pathInfo = new PathInfo<>(); } class PathInfo<E extends DirectedEdge<? extends AdjacencyListVertex>> { public void clear() { by = null; previous = null; distance = Config.INFINITY; } public void saveLayer() { layer = distance; } int layer; int distance; E by; AdjacencyListVertex previous; } class BaseGraph<V extends IVertex<? extends E>, E extends IEdge<? extends V>> { public BaseGraph(int n, IntFunction<V> vertexFactory) { this.n = n; vertices = range(0, n).mapToObj(vertexFactory).collect(toList()); } public int getN() { return n; } public V getVertex(int id) { return vertices.get(id); } public List<V> getVertices() { return vertices; } private int n; private List<V> vertices; } interface IOrder { public Vertex top(); public Vertex pop(); public void clear(); public boolean isEmpty(); public default void push(Vertex v) { } public default void remove(Vertex v) { } } class PriorityQueue implements IOrder { public PriorityQueue(Comparator<Vertex> comparator) { queue = new TreeSet<>(comparator); } @Override public Vertex top() { return queue.first(); } @Override public Vertex pop() { return queue.pollFirst(); } @Override public void push(Vertex v) { queue.add(v); } @Override public void remove(Vertex v) { queue.remove(v); } @Override public void clear() { queue.clear(); } @Override public boolean isEmpty() { return queue.isEmpty(); } private TreeSet<Vertex> queue; } class PathRestorer { public static List<Edge> get(AdjacencyListVertex<Edge> target) { if (target == null) { throw new IllegalArgumentException("target == null"); } if (!target.getState().isOpened()) { return null; } List<Edge> path = new ArrayList<>(); while (target.getState().getPathInfo().by != null) { path.add(target.getState().getPathInfo().by); target = target.getState().getPathInfo().previous; } reverse(path); return path; } } abstract class Search { public Search(Graph graph) { this.graph = graph; order = getOrder(); } public void run(Vertex source, Vertex target) { init(source); do { Vertex from = order.top(); if (from.getState().edgesIter.hasNext()) { Edge by = from.getState().edgesIter.next(); if (by.isAvailable() && isOptimal(from, by)) { go(from, by); } } else { close(order.pop()); } } while (!order.isEmpty()); } protected void init(Vertex source) { order.clear(); order.push(source); source.getState().init(source); } protected boolean isOptimal(Vertex from, Edge by) { return !by.getTo().getState().isOpened(); } protected void go(Vertex from, Edge by) { Vertex to = by.getTo(); if (to.getState().isOpened()) { order.remove(to); } open(from, by, to); update(from, by, to); order.push(to); } protected void open(Vertex from, Edge by, Vertex to) { to.getState().open(from, by, to); } protected void update(Vertex from, Edge by, Vertex to) { to.getState().getPathInfo().distance = from.getState().getPathInfo().distance + getWeight(from, by); } protected int getWeight(Vertex from, Edge by) { return by.getWeight(); } protected void close(Vertex v) { v.getState().close(); } protected abstract IOrder getOrder(); protected Graph graph; private IOrder order; } class DijkstraDense extends Search { public DijkstraDense(Graph graph) { super(graph); } @Override protected IOrder getOrder() { return new IOrder() { Vertex nearestUnused; public Vertex top() { if (nearestUnused != null && !nearestUnused.getState().isClosed()) { return nearestUnused; } return nearestUnused = graph.getVertices().stream() .filter(v -> v.getState().isOpened()) .filter(v -> !v.getState().isClosed()) .min(Comparator.comparing(v -> v.getState().getPathInfo().distance)) .orElse(null); } public Vertex pop() { return nearestUnused; } public void clear() { nearestUnused = null; } public boolean isEmpty() { return top() == null; } }; } } class DijkstraSparse extends Search { public DijkstraSparse(Graph graph) { super(graph); } @Override protected boolean isOptimal(Vertex from, Edge by) { return by.getTo().getState().getPathInfo().distance > from.getState().getPathInfo().distance+getWeight(from, by); } @Override protected int getWeight(Vertex from, Edge by) { return by.getWeight(); } @Override protected IOrder getOrder() { return new PriorityQueue((a, b) -> { int c = Integer.compare(a.getState().getPathInfo().distance, b.getState().getPathInfo().distance); return c != 0 ? c : a.id-b.id; }); } } class FordBellman { public void run(Graph graph, Vertex source) { int n = graph.getN(); graph.clear(); source.getState().getPathInfo().distance = 0; for (int i = 0; i < n-1; ++i) for (Vertex v: graph.getVertices()) { if (v.getState().getPathInfo().distance == Config.INFINITY) { continue; } for (Edge e: v.getEdges()) { e.getTo().getState().getPathInfo().distance = Math.min(e.getTo().getState().getPathInfo().distance, v.getState().getPathInfo().distance+e.getCost()); } } } } class MaxFlowMinCost { public MaxFlowMinCost(Graph graph) { this.graph = graph; dijkstraSearcher = new DijkstraSparse(graph) { @Override protected int getWeight(Vertex from, Edge by) { return by.getCost() + from.getState().phi - by.getTo().getState().phi; } }; } public long find(int required, int source, int target) { return find(required, graph.getVertex(source), graph.getVertex(target)); } private long cost; public long find(int required, Vertex source, Vertex target) { fordBellman.run(graph, source); graph.updatePhi(); cost = 0; while (dijkstra(source, target)) { graph.updatePhi(); List<Edge> path = PathRestorer.get(target); long push = path.stream() .min(Comparator.comparing(e -> e.getResidualCapacity())) .get() .getResidualCapacity(); if (push == 0) { throw new RuntimeException("Zero residual capacity."); } required -= push; path.stream().forEach(e -> { e.push((int) push); cost += push*e.getCost(); }); } return required > 0 ? -1 : cost; } private boolean dijkstra(Vertex source, Vertex target) { graph.clear(); dijkstraSearcher.run(source, target); return target.getState().isOpened(); } private Graph graph; private FordBellman fordBellman = new FordBellman(); private Search dijkstraSearcher; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
040f4f6f7c4dbc48719d16a8ebd0ee7f
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.*; import java.util.function.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.util.stream.IntStream.*; import static java.util.stream.Collectors.*; public class Main { public static void main(String[] args) { InputReader reader = new InputReader(System.in); PrintWriter writer = new PrintWriter(System.out); String t = reader.next(); int[] need = new int[26]; for (char c: t.toCharArray()) { ++need[c-'a']; } int n = reader.nextInt(); int source = n+26; int target = n+27; Graph graph = new Graph(n+28); for (int i = 0; i < 26; ++i) if (need[i] > 0) graph.addEdge(n+i, target, need[i], 0); for (int i = 0; i < n; ++i) { String s = reader.next(); int[] has = new int[26]; for (char c: s.toCharArray()) { ++has[c-'a']; } for (int j = 0; j < 26; ++j) if (has[j] > 0) graph.addEdge(i, n+j, has[j], 0); graph.addEdge(source, i, reader.nextInt(), i+1); } MaxFlowMinCost mfmc = new MaxFlowMinCost(graph); writer.println(mfmc.find(t.length(), source, target)); writer.close(); } } class Config { public static final int INFINITY = (int) 1e9; } class Vertex extends AdjacencyListVertex<Edge> { public Vertex(int id) { super(id); } } class Edge extends CostedFlowableEdge<Vertex> { public Edge(Vertex to, int capacity, int cost) { super(to, capacity, cost); } } class Graph extends BaseGraph<Vertex, Edge> { public Graph(int n) { super(n, Vertex::new); } public void addEdge(int from, int to, int capacity, int cost) { Vertex f = getVertex(from); Vertex t = getVertex(to); Edge e1 = new Edge(t, capacity, cost); Edge e2 = new Edge(f, 0, -cost); e1.setReversed(e2); e2.setReversed(e1); f.addEdge(e1); t.addEdge(e2); } public void clear() { getVertices().stream() .map(AdjacencyListVertex::getState) .forEach(SearchState::clear); } public void updatePhi() { getVertices().stream() .map(AdjacencyListVertex::getState) .forEach(SearchState::updatePhi); } } interface IEdge<V extends IVertex> { public default boolean isAvailable() { return true; } public default int getWeight() { return 1; } } class DirectedEdge<V extends IVertex<? extends DirectedEdge>> implements IEdge<V> { public DirectedEdge(V to) { this.to = to; } public V getTo() { return to; } private V to; } class FlowableEdge<V extends IVertex<? extends FlowableEdge>> extends DirectedEdge<V> { public FlowableEdge(V to, int capacity) { super(to); this.capacity = capacity; } public void push(int flow) { this.flow += flow; reversed.flow -= flow; } public void setReversed(FlowableEdge<V> reversed) { this.reversed = reversed; } public int getResidualCapacity() { return capacity - flow; } public boolean isAvailable() { return flow < capacity; } int flow; int capacity; private FlowableEdge<V> reversed; } class CostedFlowableEdge<V extends IVertex<? extends CostedFlowableEdge>> extends FlowableEdge<V> { public CostedFlowableEdge(V to, int capacity, int cost) { super(to, capacity); this.cost = cost; } public int getCost() { return cost; } int cost; } interface IVertex<E extends IEdge> { } class AdjacencyListVertex<E extends DirectedEdge<? extends AdjacencyListVertex>> implements IVertex<E> { public AdjacencyListVertex(int id) { this.id = id; } public void addEdge(E edge) { edges.add(edge); } public List<E> getEdges() { return edges; } public SearchState<E> getState() { return state; } int id; private List<E> edges = new ArrayList<>(); private SearchState<E> state = new SearchState<>(); } enum StateColor { WHITE, GRAY, BLACK } class SearchState<E extends DirectedEdge<? extends AdjacencyListVertex>> { public boolean isOpened() { return color != StateColor.WHITE; } public boolean isClosed() { return color == StateColor.BLACK; } public void open(Vertex from, E by, Vertex to) { color = StateColor.GRAY; pathInfo.previous = from; pathInfo.by = by; if (edgesIter == null) edgesIter = (Iterator<E>) to.getEdges().iterator(); } public void close() { color = StateColor.BLACK; } public void init(Vertex source) { color = StateColor.GRAY; pathInfo.distance = 0; edgesIter = (Iterator<E>) source.getEdges().iterator(); } public void clear() { color = StateColor.WHITE; edgesIter = null; pathInfo.clear(); } public PathInfo<E> getPathInfo() { return pathInfo; } public void updatePhi() { if (pathInfo.distance != Config.INFINITY) phi += pathInfo.distance; } int phi; StateColor color; Iterator<E> edgesIter; PathInfo<E> pathInfo = new PathInfo<>(); } class PathInfo<E extends DirectedEdge<? extends AdjacencyListVertex>> { public void clear() { by = null; previous = null; distance = Config.INFINITY; } public void saveLayer() { layer = distance; } int layer; int distance; E by; AdjacencyListVertex previous; } class BaseGraph<V extends IVertex<? extends E>, E extends IEdge<? extends V>> { public BaseGraph(int n, IntFunction<V> vertexFactory) { this.n = n; vertices = range(0, n).mapToObj(vertexFactory).collect(toList()); } public int getN() { return n; } public V getVertex(int id) { return vertices.get(id); } public List<V> getVertices() { return vertices; } private int n; private List<V> vertices; } interface IOrder { public Vertex top(); public Vertex pop(); public void clear(); public boolean isEmpty(); public default void push(Vertex v) { } public default void remove(Vertex v) { } } class PriorityQueue implements IOrder { public PriorityQueue(Comparator<Vertex> comparator) { queue = new TreeSet<>(comparator); } @Override public Vertex top() { return queue.first(); } @Override public Vertex pop() { return queue.pollFirst(); } @Override public void push(Vertex v) { queue.add(v); } @Override public void remove(Vertex v) { queue.remove(v); } @Override public void clear() { queue.clear(); } @Override public boolean isEmpty() { return queue.isEmpty(); } private TreeSet<Vertex> queue; } class PathRestorer { public static List<Edge> get(AdjacencyListVertex<Edge> target) { if (target == null) { throw new IllegalArgumentException("target == null"); } if (!target.getState().isOpened()) { return null; } List<Edge> path = new ArrayList<>(); while (target.getState().getPathInfo().by != null) { path.add(target.getState().getPathInfo().by); target = target.getState().getPathInfo().previous; } reverse(path); return path; } } abstract class Search { public Search(Graph graph) { this.graph = graph; order = getOrder(); } public void run(Vertex source, Vertex target) { init(source); do { Vertex from = order.top(); if (from.getState().edgesIter.hasNext()) { Edge by = from.getState().edgesIter.next(); if (by.isAvailable() && isOptimal(from, by)) { go(from, by); } } else { close(order.pop()); } } while (!order.isEmpty()); } protected void init(Vertex source) { order.clear(); order.push(source); source.getState().init(source); } protected boolean isOptimal(Vertex from, Edge by) { return !by.getTo().getState().isOpened(); } protected void go(Vertex from, Edge by) { Vertex to = by.getTo(); if (to.getState().isOpened()) { order.remove(to); } open(from, by, to); update(from, by, to); order.push(to); } protected void open(Vertex from, Edge by, Vertex to) { to.getState().open(from, by, to); } protected void update(Vertex from, Edge by, Vertex to) { to.getState().getPathInfo().distance = from.getState().getPathInfo().distance + getWeight(from, by); } protected int getWeight(Vertex from, Edge by) { return by.getWeight(); } protected void close(Vertex v) { v.getState().close(); } protected abstract IOrder getOrder(); protected Graph graph; private IOrder order; } class DijkstraDense extends Search { public DijkstraDense(Graph graph) { super(graph); } @Override protected IOrder getOrder() { return new IOrder() { Vertex nearestUnused; public Vertex top() { if (nearestUnused != null && !nearestUnused.getState().isClosed()) { return nearestUnused; } return nearestUnused = graph.getVertices().stream() .filter(v -> v.getState().isOpened()) .filter(v -> !v.getState().isClosed()) .min(Comparator.comparing(v -> v.getState().getPathInfo().distance)) .orElse(null); } public Vertex pop() { return nearestUnused; } public void clear() { nearestUnused = null; } public boolean isEmpty() { return top() == null; } }; } @Override protected boolean isOptimal(Vertex from, Edge by) { return by.getTo().getState().getPathInfo().distance > from.getState().getPathInfo().distance+getWeight(from, by); } } class DijkstraSparse extends Search { public DijkstraSparse(Graph graph) { super(graph); } @Override protected boolean isOptimal(Vertex from, Edge by) { return by.getTo().getState().getPathInfo().distance > from.getState().getPathInfo().distance+getWeight(from, by); } @Override protected IOrder getOrder() { return new PriorityQueue((a, b) -> { int c = Integer.compare(a.getState().getPathInfo().distance, b.getState().getPathInfo().distance); return c != 0 ? c : a.id-b.id; }); } } class FordBellman { public void run(Graph graph, Vertex source) { int n = graph.getN(); graph.clear(); source.getState().getPathInfo().distance = 0; for (int i = 0; i < n-1; ++i) for (Vertex v: graph.getVertices()) { if (v.getState().getPathInfo().distance == Config.INFINITY) { continue; } for (Edge e: v.getEdges()) { e.getTo().getState().getPathInfo().distance = Math.min(e.getTo().getState().getPathInfo().distance, v.getState().getPathInfo().distance+e.getCost()); } } } } class MaxFlowMinCost { public MaxFlowMinCost(Graph graph) { this.graph = graph; dijkstraSearcher = new DijkstraDense(graph) { @Override protected int getWeight(Vertex from, Edge by) { return by.getCost() + from.getState().phi - by.getTo().getState().phi; } }; } public long find(int required, int source, int target) { return find(required, graph.getVertex(source), graph.getVertex(target)); } private long cost; public long find(int required, Vertex source, Vertex target) { // fordBellman.run(graph, source); // graph.updatePhi(); cost = 0; while (dijkstra(source, target)) { graph.updatePhi(); List<Edge> path = PathRestorer.get(target); long push = path.stream() .min(Comparator.comparing(e -> e.getResidualCapacity())) .get() .getResidualCapacity(); if (push == 0) { throw new RuntimeException("Zero residual capacity."); } required -= push; path.stream().forEach(e -> { e.push((int) push); cost += push*e.getCost(); }); } return required > 0 ? -1 : cost; } private boolean dijkstra(Vertex source, Vertex target) { graph.clear(); dijkstraSearcher.run(source, target); return target.getState().isOpened(); } private Graph graph; private FordBellman fordBellman = new FordBellman(); private Search dijkstraSearcher; } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 1<<15); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
577e37b568d38cbdc578e439aad9e5a2
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Abood2D { static final int INF = (int)1e9; static int V, s, t; //s != t static ArrayList<Integer>[] adjList; static int[][] res; //instead of res, you can use c[][], f[][] so as not to destroy the graph static int[] p; //res (residual) = c (capacity) - f (flow) static String[] SS; static int[] xs, c; static int edmondsKarp() //O(min(VE^2, flow * E)) for adjList, O(V^3E) { int mf = 0; while(true) { Queue<Integer> q = new LinkedList<Integer>(); p = new int[V]; Arrays.fill(p, -1); q.add(s); p[s] = s; while(!q.isEmpty()) { int u = q.remove(); if(u == t) break; for (int i = 0; i < adjList[u].size(); i++) { int v = adjList[u].get(i); if(res[u][v] > 0 && p[v] == -1) { p[v] = u; q.add(v); } } } if(p[t] == -1) break; mf += augment(t, INF); } return mf; } static int augment(int v, int flow) { if(v == s) return flow; flow = augment(p[v], Math.min(flow, res[p[v]][v])); res[p[v]][v] -= flow; res[v][p[v]] += flow; return flow; } static void run() { res = new int[V][V]; for (int i = 1; i <= SS.length; i++) { String sI = SS[i - 1]; int[] cI = new int[26]; for (int j = 0; j < sI.length(); j++) cI[sI.charAt(j) - 'a']++; int x = xs[i - 1]; res[0][i] = x; for (int j = 0; j < 26; j++) res[i][SS.length + j + 1] = cI[j]; } for (int i = 0; i < 26; i++) res[SS.length + i + 1][V - 1] = c[i]; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); String S = sc.next(); int n = sc.nextInt(); SS = new String[n]; xs = new int[n]; for (int i = 0; i < n; i++) { SS[i] = sc.next(); xs[i] = sc.nextInt(); } c = new int[26]; for (int i = 0; i < S.length(); i++) c[S.charAt(i) - 'a']++; V = n + 26 + 2; adjList = new ArrayList[V]; res = new int[V][V]; for (int i = 0; i < V; i++) adjList[i] = new ArrayList<>(); for (int i = 1; i <= n; i++) { String sI = SS[i - 1]; int[] cI = new int[26]; for (int j = 0; j < sI.length(); j++) cI[sI.charAt(j) - 'a']++; int x = xs[i - 1]; adjList[0].add(i); adjList[i].add(0); res[0][i] = x; for (int j = 0; j < 26; j++) { adjList[i].add(n + j + 1); adjList[n + j + 1].add(i); res[i][n + j + 1] = cI[j]; } } for (int i = 0; i < 26; i++) { adjList[V - 1].add(n + i + 1); adjList[n + i + 1].add(V - 1); res[n + i + 1][V - 1] = c[i]; } s = 0; t = V - 1; int v = edmondsKarp(); if(v == S.length()) { int ans = 0; for (int i = 1; i <= n; i++) { ans += res[i][0] * i; } for (int i = n; i > 0; i--) { xs[i - 1] = res[i][0]; for (int j = xs[i - 1] - 1; j >= 0; j--) { xs[i - 1] = j; run(); v = edmondsKarp(); if(v == S.length()) { int t = 0; for (int k = 1; k <= n; k++) { t += res[k][0] * k; } ans = Math.min(t, ans); } else { xs[i - 1]++; break; } } } out.println(ans); } else out.println(-1); out.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 8
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
4e75d99dac7f3e126cc6f4141112e207
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; public class Solver { StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) throws NumberFormatException, IOException { Solver solver = new Solver(); solver.open(); long time = System.currentTimeMillis(); solver.solve(); if (!"true".equals(System.getProperty("ONLINE_JUDGE"))) { System.out.println("Spent time: " + (System.currentTimeMillis() - time)); System.out.println("Memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); } solver.close(); } public void open() throws IOException { if (!"true".equals(System.getProperty("ONLINE_JUDGE"))) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { // in = new BufferedReader(new FileReader(FNAME + ".in")); // out = new PrintWriter(new FileWriter(FNAME + ".out")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } public String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } class Edge { int cost; int weight; int already; int to; public Edge(int cost, int weight, int to) { super(); this.cost = cost; this.weight = weight; this.to = to; } @Override public String toString() { return "(" + to + "," + weight + ")"; } } List<List<Edge>> graph = new ArrayList<List<Edge>>(); public void solve() throws NumberFormatException, IOException { String t = nextToken(); ArrayList<Edge> start = new ArrayList<Edge>(); graph.add(start); for (char c = 'a'; c <= 'z'; c++) { graph.add(new ArrayList<Edge>()); int tmp = 0; for (int i = 0; i < t.length(); i++) { if (t.charAt(i) == c) tmp++; } if (tmp > 0) { start.add(new Edge(0, tmp, c - 'a' + 1)); } } int n = nextInt(); int finishInd = 1 + ('z' - 'a' + 1) + n; for (int i = 1; i <= n; i++) { String s = nextToken(); int a = nextInt(); ArrayList<Edge> next = new ArrayList<Edge>(); graph.add(next); for (char c = 'a'; c <= 'z'; c++) { int tmp = 0; for (int j = 0; j < s.length(); j++) { if (s.charAt(j) == c) tmp++; } if (tmp > 0) { next.add(new Edge(-i, 0, c - 'a' + 1)); graph.get(c - 'a' + 1).add(new Edge(i, tmp, i + ('z' - 'a' + 1))); } } next.add(new Edge(0, a, finishInd)); } ArrayList<Edge> finish = new ArrayList<Edge>(); graph.add(finish); int m = finishInd + 1; int result = 0; int maxFlow = 0; while (true) { Queue<Integer> queue = new LinkedList<Integer>(); int[] path = new int[m]; Arrays.fill(path, -1); int[] min = new int[m]; Arrays.fill(min, Integer.MAX_VALUE >> 2); min[0] = 0; queue.add(0); while (!queue.isEmpty()) { int next = queue.remove(); List<Edge> list = graph.get(next); for (Edge edge : list) { if (min[edge.to] > min[next] + edge.cost && edge.weight - edge.already > 0) { path[edge.to] = next; min[edge.to] = min[next] + edge.cost; queue.add(edge.to); } } } if (path[m - 1] == -1) break; Stack<Integer> p = new Stack<Integer>(); int v = m - 1; while (v != -1) { p.push(v); v = path[v]; } List<Integer> tmp = new ArrayList<Integer>(p.size()); while (!p.isEmpty()) { tmp.add(p.pop()); } int minP = Integer.MAX_VALUE; for (int i = 0; i < tmp.size() - 1; i++) { int from = tmp.get(i); int to = tmp.get(i + 1); Edge r = null; for (Edge edge : graph.get(from)) { if (edge.to == to) { r = edge; break; } } minP = Math.min(r.weight - r.already, minP); } for (int i = 0; i < tmp.size() - 1; i++) { int from = tmp.get(i); int to = tmp.get(i + 1); Edge r = null; for (Edge edge : graph.get(from)) { if (edge.to == to) { r = edge; break; } } Edge o = null; for (Edge edge : graph.get(to)) { if (edge.to == from) { o = edge; break; } } r.already += minP; if (o != null) o.already -= minP; if (to==m-1){ maxFlow+=minP; } result += r.cost * minP; } } if(maxFlow==t.length()){ out.println(result); }else{ out.println(-1); } } public void close() { out.flush(); out.close(); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
b3692a3de19ef716a9efa622bfa69650
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class BuildString { public static void main(String[] args) { InputReader r = new InputReader(System.in); String t = r.next(); int k = r.nextInt(); String[] arr = new String[k]; int[] size = new int[k]; for (int i = 0; i < k; i++) { arr[i] = r.next(); size[i] = r.nextInt(); } int[][] cap = new int[k + 26 + 2][k + 26 + 2]; int[][] cost = new int[k + 26 + 2][k + 26 + 2]; for (int i = 0; i < k; i++) { for (int j = 0; j < arr[i].length(); j++) { cap[i][arr[i].charAt(j) - 'a' + k]++; cost[i][k + arr[i].charAt(j) - 'a'] = i + 1; cost[k + arr[i].charAt(j) - 'a'][i] = -(i + 1); } cap[k + 26][i] = size[i]; } for (int i = 0; i < t.length(); i++) { cap[k + t.charAt(i) - 'a'][k + 26 + 1]++; } parent = new int[k + 26 + 2]; int[] res = mcmf(cap, cost, k + 26, k + 26 + 1); if (res[0] == t.length()) System.out.println(res[1]); else System.out.println(-1); } static int inf = 1 << 27; static int[] parent; public static int[] mcmf(int[][] cap, int[][] cost, int src, int sink) { int totCost = 0, flow = 0; while (bellmanford(cap, cost, src, sink) != inf) { int[] temp = repair(cap, cost, src, sink); int newCost = temp[1]; totCost += newCost; flow += temp[0]; } return new int[] { flow, totCost }; } private static int bellmanford(int[][] cap, int[][] cost, int src, int sink) { int n = cap.length; int[] dist = new int[n]; Arrays.fill(dist, inf); dist[src] = 0; Arrays.fill(parent, -1); for (int i = 0; i < n - 1; i++) { for (int u = 0; u < n; u++) { for (int v = 0; v < n; v++) { if (cap[u][v] <= 0) continue; if (dist[v] > dist[u] + cost[u][v]) { dist[v] = dist[u] + cost[u][v]; parent[v] = u; } } } } return dist[sink]; } private static int[] repair(int[][] cap, int[][] cost, int src, int sink) { int flow = Integer.MAX_VALUE, pathCost = 0, current = sink; while (parent[current] != -1) { int from = parent[current], to = current; flow = Math.min(flow, cap[from][to]); pathCost += cost[from][to]; current = parent[current]; } current = sink; while (parent[current] != -1) { int from = parent[current], to = current; cap[from][to] -= flow; cap[to][from] += flow; current = parent[current]; } return new int[] { flow, flow * pathCost }; } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return 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
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
6e06205cbffbb571ab9ce822d5d4db7e
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.util.*; //import java.io.*; public class E { int n; int sink, source; int [][]cap, cost, f; boolean debug = true; public void run() throws Exception{ //Scanner in = new Scanner(new File("input.txt")); Scanner in = new Scanner(System.in); String s = in.next(); int k = in.nextInt(); String a[] = new String[k]; int r[] = new int[k]; for(int i=0;i<k;i++){ a[i] = in.next(); r[i] = in.nextInt(); } n = 26 + k + 2; source = n - 2; sink = n - 1; cap = new int[n][n]; cost = new int[n][n]; for(int i=0;i<n;i++) Arrays.fill(cost[i], Integer.MAX_VALUE/2); for(int i=0;i<k;i++) cost[source][i] = 0; for(int i=k;i<n-2;i++) cost[i][sink] = 0; f = new int[n][n]; for(int i=0;i<k;i++){ cap[source][i] = r[i]; for(char j : a[i].toCharArray()){ cap[i][k+j-'a']++; if (cost[i][k+j-'a'] == Integer.MAX_VALUE/2){ cost[i][k+j-'a']=i+1; cost[k+j-'a'][i]=-(i+1); }else{ //cost[i][k+j-'a']+=i+1; //cost[k+j-'a'][i]-=i+1; } } } for(char i : s.toCharArray()){ cap[k+i-'a'][sink]++; } int ans = 0; int flow = 0; while(true){ int cur = source; int d[] = new int[n]; Arrays.fill(d, Integer.MAX_VALUE/2); d[cur] = 0; int prev[] = new int[n]; Arrays.fill(prev, -1); boolean used[] = new boolean[n]; used[cur] = true; while(true){ for(int i=0;i<n;i++){ if (cap[cur][i] - f[cur][i] > 0 && d[i] > d[cur] + cost[cur][i]){ d[i] = d[cur] + cost[cur][i]; prev[i] = cur; } } int min = Integer.MAX_VALUE/2; int index = -1; for(int i=0;i<n;i++){ if (!used[i] && d[i] < min){ min = d[i]; index = i; } } if (index == -1 || index == sink) break; used[index] = true; cur = index; } //System.out.println(d[sink]); if (d[sink] == Integer.MAX_VALUE/2) break; int addFlow = Integer.MAX_VALUE/2; cur = sink; while(prev[cur] != -1){ int p = prev[cur]; addFlow = Math.min(addFlow, cap[p][cur] - f[p][cur]); cur = p; } //System.out.println("flow is " + addFlow); //if (debug) return; cur = sink; while(prev[cur] != -1){ int p = prev[cur]; ans+=addFlow*cost[p][cur]; f[p][cur]+=addFlow; f[cur][p]-=addFlow; cur = p; } flow+=addFlow; } if (flow == s.length()){ System.out.println(ans); }else{ System.out.println(-1); } } public static void main(String[] args) throws Exception{ new E().run(); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
b60a3b89291d0843791a541594139ccf
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class E147 { BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; static final int INF = Integer.MAX_VALUE / 2 - 1; public void solve() throws IOException { char[] t = reader.readLine().toCharArray(); int N = nextInt(); char[][] s = new char[N][]; int[] a = new int[N]; for(int i = 0; i < N; i++){ String[] input = reader.readLine().split(" "); s[i] = input[0].toCharArray(); a[i] = Integer.parseInt(input[1]); } int size = N + 26 + 2; int src = N + 26; int dst = N + 27; int alp_start = N; int str_start = 0; int[][] cap = new int[size][size]; int[][] cost = new int[size][size]; // for(int i = 0; i < size; i++){ // Arrays.fill(cap[i], INF); // Arrays.fill(cost[i], INF); // } for(int i = 0; i < N; i++){ cap[src][ str_start+i ] = a[i]; cost[src][ str_start+i ] = i+1; int[] counter = new int[26]; for(int j = 0; j < s[i].length; j++) counter[ s[i][j]-'a' ]++; for(int c = 0; c < 26; c++){ cap[ str_start+i ][ alp_start+c ] = counter[c]; cost[ str_start+i ][ alp_start+c ] = 0; } } int[] counter = new int[26]; for(int j = 0; j < t.length; j++) counter[ t[j]-'a' ]++; for(int c = 0; c < 26; c++){ cap[ alp_start+c ][dst] = counter[c]; cost[ alp_start+c ][dst] = 0; } // out.println("Cap: "); // for(int i = 0; i < size; i++){ // for(int j = 0; j < size; j++){ // if( cap[i][j] == INF) // out.print("- "); // else // out.print( cap[i][j] + " "); // } // out.println(); // } // out.println("Cost: "); // for(int i = 0; i < size; i++){ // for(int j = 0; j < size; j++){ // if( cost[i][j] == INF) // out.print("- "); // else // out.print( cost[i][j] + " "); // } // out.println(); // } MinCostMaxFlow flow = new MinCostMaxFlow(); int result[] = flow.getMaxFlow(cap, cost, src, dst); if( result[0] == t.length ) out.println(result[1]); else out.println(-1); // out.println( result[0] + ", " + result[1] ); } /** * @param args */ public static void main(String[] args) { new E147().run(); } public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; out = new PrintWriter(System.out); solve(); reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } } //Min cost max flow algorithm using an adjacency matrix. If you //want just regular max flow, setting all edge costs to 1 gives //running time O(|E|^2 |V|). // //Running time: O(min(|V|^2 * totflow, |V|^3 * totcost)) // //INPUT: cap -- a matrix such that cap[i][j] is the capacity of // a directed edge from node i to node j // // cost -- a matrix such that cost[i][j] is the (positive) // cost of sending one unit of flow along a // directed edge from node i to node j // // source -- starting node // sink -- ending node // //OUTPUT: max flow and min cost; the matrix flow will contain // the actual flow values (note that unlike in the MaxFlow // code, you don't need to ignore negative flow values -- there // shouldn't be any) // //To use this, create a MinCostMaxFlow object, and call it like this: // //MinCostMaxFlow nf; //int maxflow = nf.getMaxFlow(cap,cost,source,sink); class MinCostMaxFlow { boolean found[]; int N, cap[][], flow[][], cost[][], dad[], dist[], pi[]; static final int INF = Integer.MAX_VALUE / 2 - 1; boolean search(int source, int sink) { Arrays.fill(found, false); Arrays.fill(dist, INF); dist[source] = 0; while (source != N) { int best = N; found[source] = true; for (int k = 0; k < N; k++) { if (found[k]) continue; if (flow[k][source] != 0) { int val = dist[source] + pi[source] - pi[k] - cost[k][source]; if (dist[k] > val) { dist[k] = val; dad[k] = source; } } if (flow[source][k] < cap[source][k]) { int val = dist[source] + pi[source] - pi[k] + cost[source][k]; if (dist[k] > val) { dist[k] = val; dad[k] = source; } } if (dist[k] < dist[best]) best = k; } source = best; } for (int k = 0; k < N; k++) pi[k] = Math.min(pi[k] + dist[k], INF); return found[sink]; } int[] getMaxFlow(int cap[][], int cost[][], int source, int sink) { this.cap = cap; this.cost = cost; N = cap.length; found = new boolean[N]; flow = new int[N][N]; dist = new int[N+1]; dad = new int[N]; pi = new int[N]; int totflow = 0, totcost = 0; while (search(source, sink)) { int amt = INF; for (int x = sink; x != source; x = dad[x]) amt = Math.min(amt, flow[x][dad[x]] != 0 ? flow[x][dad[x]] :cap[dad[x]][x] - flow[dad[x]][x]); for (int x = sink; x != source; x = dad[x]) { if (flow[x][dad[x]] != 0) { flow[x][dad[x]] -= amt; totcost -= amt * cost[x][dad[x]]; } else { flow[dad[x]][x] += amt; totcost += amt * cost[dad[x]][x]; } } totflow += amt; } return new int[]{ totflow, totcost }; } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
ab2237a74f8bb86c16ad965bf4905afb
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; public class E237 implements Runnable { final int INF = Integer.MAX_VALUE; int n, ans, total; int[] d, p; int[][] cap, flow, cost; ArrayList<Integer>[] g; private void Solution() throws IOException { String t = nextToken(); n = nextInt(); String[] s = new String[n]; int[] a = new int[n]; for (int i = 0; i < n; i++) { s[i] = nextToken(); a[i] = nextInt(); } cap = new int[n + 28][n + 28]; cost = new int[n + 28][n + 28]; g = new ArrayList[n + 28]; for (int i = 0; i < n + 28; i++) g[i] = new ArrayList<Integer>(0); for (int i = 1; i <= n; i++) { g[0].add(i); cost[0][i] = i; cap[0][i] = a[i - 1]; g[i].add(0); cost[i][0] = -i; } int[] cnt = new int[26]; for (int i = 0; i < n; i++) { for (int j = 0; j < s[i].length(); j++) cnt[s[i].charAt(j) - 'a']++; for (int j = 0; j < 26; j++) { g[i + 1].add(n + j + 1); cap[i + 1][n + j + 1] = cnt[j]; g[n + j + 1].add(i + 1); } Arrays.fill(cnt, 0); } for (int i = 0; i < t.length(); i++) cnt[t.charAt(i) - 'a']++; for (int i = 0; i < 26; i++) { g[n + i + 1].add(n + 27); cap[n + i + 1][n + 27] = cnt[i]; g[n + 27].add(n + i + 1); } work(); print(total == t.length() ? ans : -1); } void work() { d = new int[n + 28]; p = new int[n + 28]; flow = new int[n + 28][n + 28]; while (fb() != 0); } int fb() { Arrays.fill(d, INF); d[0] = 0; Arrays.fill(p, -1); for (int i = 0; i < n + 27; i++) for (int from = 0; from < n + 27; from++) for (int to : g[from]) if (flow[from][to] < cap[from][to] && d[from] != INF && d[from] + cost[from][to] < d[to]) { d[to] = d[from] + cost[from][to]; p[to] = from; } if (d[n + 27] == INF) return 0; int f = INF; for (int cur = n + 27; p[cur] != -1; cur = p[cur]) f = Math.min(f, cap[p[cur]][cur] - flow[p[cur]][cur]); for (int cur = n + 27; p[cur] != -1; cur = p[cur]) { flow[p[cur]][cur] += f; flow[cur][p[cur]] -= f; } ans += d[n + 27] * f; total += f; return f; } public static void main(String[] args) { new E237().run(); } BufferedReader in; PrintWriter out; StringTokenizer tokenizer; public void run() { try { long beginTime = System.nanoTime(); long beginMemory = totalMemory() - freeMemory(); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); Solution(); out.close(); long endTime = System.nanoTime(); long endMemory = totalMemory() - freeMemory(); double totalTime = (endTime - beginTime) * 1d / 1000000000; double totalMemory = (endMemory - beginMemory) * 1d / 1024 / 1024; System.err.println(); System.err.println(); System.err.println("Time wasted - " + totalTime + " s"); System.err.println("Memory used - " + totalMemory + " mb"); } catch (Exception e) { e.printStackTrace(); System.exit(261); } } void halt() { out.close(); System.exit(0); } long totalMemory() { return Runtime.getRuntime().totalMemory(); } long freeMemory() { return Runtime.getRuntime().freeMemory(); } void print(Object... obj) { for (int i = 0; i < obj.length; i++) { if (i != 0) out.print(" "); out.print(obj[i]); } } void println(Object... obj) { print(obj); out.println(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { return in.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
7b66c1d8b436d39eced695e968510593
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; public class E237 implements Runnable { final int INF = Integer.MAX_VALUE; Deque q; int n, ans, total; int[] id, d, p; int[][] cap, flow, cost; ArrayList<Integer>[] g; private void Solution() throws IOException { String t = nextToken(); n = nextInt(); String[] s = new String[n]; int[] a = new int[n]; for (int i = 0; i < n; i++) { s[i] = nextToken(); a[i] = nextInt(); } cap = new int[n + 28][n + 28]; cost = new int[n + 28][n + 28]; g = new ArrayList[n + 28]; for (int i = 0; i < n + 28; i++) g[i] = new ArrayList<Integer>(0); for (int i = 1; i <= n; i++) { g[0].add(i); cost[0][i] = i; cap[0][i] = a[i - 1]; g[i].add(0); cost[i][0] = -i; } int[] cnt = new int[26]; for (int i = 0; i < n; i++) { for (int j = 0; j < s[i].length(); j++) cnt[s[i].charAt(j) - 'a']++; for (int j = 0; j < 26; j++) { g[i + 1].add(n + j + 1); cap[i + 1][n + j + 1] = cnt[j]; g[n + j + 1].add(i + 1); } Arrays.fill(cnt, 0); } for (int i = 0; i < t.length(); i++) cnt[t.charAt(i) - 'a']++; for (int i = 0; i < 26; i++) { g[n + i + 1].add(n + 27); cap[n + i + 1][n + 27] = cnt[i]; g[n + 27].add(n + i + 1); } work(); print(total == t.length() ? ans : -1); } void work() { q = new Deque(n + 28); id = new int[n + 28]; d = new int[n + 28]; p = new int[n + 28]; flow = new int[n + 28][n + 28]; while (fb() != 0); } int fb() { Arrays.fill(id, 0); Arrays.fill(d, INF); d[0] = 0; Arrays.fill(p, -1); q.clear(); q.addLast(0); while (!q.isEmpty()) { int v = q.pollFirst(); id[v] = 1; for (int to : g[v]) { if (flow[v][to] < cap[v][to] && d[to] > d[v] + cost[v][to]) { d[to] = d[v] + cost[v][to]; if (id[to] == 0) q.addLast(to); else if (id[to] == 1) q.addFirst(to); id[to] = 1; p[to] = v; } } } if (d[n + 27] == INF) return 0; int f = INF; for (int cur = n + 27; p[cur] != -1; cur = p[cur]) f = Math.min(f, cap[p[cur]][cur] - flow[p[cur]][cur]); for (int cur = n + 27; p[cur] != -1; cur = p[cur]) { flow[p[cur]][cur] += f; flow[cur][p[cur]] -= f; } ans += d[n + 27] * f; total += f; return f; } class Deque { int n, begin, end; int[] q; Deque(int n) { this.n = n * 2; q = new int[n * 2]; end = 1; } void addFirst(int a) { q[begin] = a; begin--; if (begin == -1) begin = n - 1; } void addLast(int a) { q[end] = a; end++; if (end == n) end = 0; } int pollFirst() { begin++; if (begin == n) begin = 0; return q[begin]; } int pollLast() { end--; if (end == -1) end = n - 1; return q[end]; } int size() { int res = end - begin - 1; if (res < 0) res += n; return res; } boolean isEmpty() { return size() == 0; } void clear() { begin = 0; end = 1; } } public static void main(String[] args) { new E237().run(); } BufferedReader in; PrintWriter out; StringTokenizer tokenizer; public void run() { try { long beginTime = System.nanoTime(); long beginMemory = totalMemory() - freeMemory(); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); Solution(); out.close(); long endTime = System.nanoTime(); long endMemory = totalMemory() - freeMemory(); double totalTime = (endTime - beginTime) * 1d / 1000000000; double totalMemory = (endMemory - beginMemory) * 1d / 1024 / 1024; System.err.println(); System.err.println(); System.err.println("Time wasted - " + totalTime + " s"); System.err.println("Memory used - " + totalMemory + " mb"); } catch (Exception e) { e.printStackTrace(); System.exit(261); } } void halt() { out.close(); System.exit(0); } long totalMemory() { return Runtime.getRuntime().totalMemory(); } long freeMemory() { return Runtime.getRuntime().freeMemory(); } void print(Object... obj) { for (int i = 0; i < obj.length; i++) { if (i != 0) out.print(" "); out.print(obj[i]); } } void println(Object... obj) { print(obj); out.println(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { return in.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
821fd6c8810edce792e39b9f87ffe81b
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.*; import java.util.*; public class E237 implements Runnable { final int INF = Integer.MAX_VALUE; Deque q; int n, ans, total; int[] id, d, p; int[][] cap, flow, cost; ArrayList<Integer>[] g; private void Solution() throws IOException { String t = nextToken(); n = nextInt(); String[] s = new String[n]; int[] a = new int[n]; for (int i = 0; i < n; i++) { s[i] = nextToken(); a[i] = nextInt(); } cap = new int[n + 28][n + 28]; cost = new int[n + 28][n + 28]; g = new ArrayList[n + 28]; for (int i = 0; i < n + 28; i++) g[i] = new ArrayList<Integer>(0); for (int i = 1; i <= n; i++) { g[0].add(i); cost[0][i] = i; cap[0][i] = a[i - 1]; g[i].add(0); cost[i][0] = -i; } int[] cnt = new int[26]; for (int i = 0; i < n; i++) { for (int j = 0; j < s[i].length(); j++) cnt[s[i].charAt(j) - 'a']++; for (int j = 0; j < 26; j++) { g[i + 1].add(n + j + 1); cap[i + 1][n + j + 1] = cnt[j]; g[n + j + 1].add(i + 1); } Arrays.fill(cnt, 0); } for (int i = 0; i < t.length(); i++) cnt[t.charAt(i) - 'a']++; for (int i = 0; i < 26; i++) { g[n + i + 1].add(n + 27); cap[n + i + 1][n + 27] = cnt[i]; g[n + 27].add(n + i + 1); } work(); print(total == t.length() ? ans : -1); } void work() { q = new Deque(n + 28); id = new int[n + 28]; d = new int[n + 28]; p = new int[n + 28]; flow = new int[n + 28][n + 28]; while (fb() != 0); } int fb() { Arrays.fill(d, INF); d[0] = 0; Arrays.fill(p, -1); for (int i = 0; i < n + 27; i++) for (int from = 0; from < n + 27; from++) for (int to : g[from]) if (flow[from][to] < cap[from][to] && d[from] != INF && d[from] + cost[from][to] < d[to]) { d[to] = d[from] + cost[from][to]; p[to] = from; } Arrays.fill(id, 0); Arrays.fill(d, INF); d[0] = 0; Arrays.fill(p, -1); q.clear(); q.addLast(0); while (!q.isEmpty()) { int v = q.pollFirst(); id[v] = 1; for (int to : g[v]) { if (flow[v][to] < cap[v][to] && d[to] > d[v] + cost[v][to]) { d[to] = d[v] + cost[v][to]; if (id[to] == 0) q.addLast(to); else if (id[to] == 1) q.addFirst(to); id[to] = 1; p[to] = v; } } } if (d[n + 27] == INF) return 0; int f = INF; for (int cur = n + 27; p[cur] != -1; cur = p[cur]) f = Math.min(f, cap[p[cur]][cur] - flow[p[cur]][cur]); for (int cur = n + 27; p[cur] != -1; cur = p[cur]) { flow[p[cur]][cur] += f; flow[cur][p[cur]] -= f; } ans += d[n + 27] * f; total += f; return f; } class Deque { int n, begin, end; int[] q; Deque(int n) { this.n = n * 2; q = new int[n * 2]; end = 1; } void addFirst(int a) { q[begin] = a; begin--; if (begin == -1) begin = n - 1; } void addLast(int a) { q[end] = a; end++; if (end == n) end = 0; } int pollFirst() { begin++; if (begin == n) begin = 0; return q[begin]; } int pollLast() { end--; if (end == -1) end = n - 1; return q[end]; } int size() { int res = end - begin - 1; if (res < 0) res += n; return res; } boolean isEmpty() { return size() == 0; } void clear() { begin = 0; end = 1; } } public static void main(String[] args) { new E237().run(); } BufferedReader in; PrintWriter out; StringTokenizer tokenizer; public void run() { try { long beginTime = System.nanoTime(); long beginMemory = totalMemory() - freeMemory(); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); Solution(); out.close(); long endTime = System.nanoTime(); long endMemory = totalMemory() - freeMemory(); double totalTime = (endTime - beginTime) * 1d / 1000000000; double totalMemory = (endMemory - beginMemory) * 1d / 1024 / 1024; System.err.println(); System.err.println(); System.err.println("Time wasted - " + totalTime + " s"); System.err.println("Memory used - " + totalMemory + " mb"); } catch (Exception e) { e.printStackTrace(); System.exit(261); } } void halt() { out.close(); System.exit(0); } long totalMemory() { return Runtime.getRuntime().totalMemory(); } long freeMemory() { return Runtime.getRuntime().freeMemory(); } void print(Object... obj) { for (int i = 0; i < obj.length; i++) { if (i != 0) out.print(" "); out.print(obj[i]); } } void println(Object... obj) { print(obj); out.println(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { return in.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
7d8a1dd38f98ea01c931819178662a48
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { /** * @param args */ static char[] t; static char[][] s; static int[] a; static int[][] cap, cost; static int N, all, start, end, inf = 1 << 28; public static void main(String[] args) { InputReader r = new InputReader(System.in); t = r.next().toCharArray(); N = r.nextInt(); a = new int[N]; s = new char[N][]; for(int k = 0; k < N; k++){ s[k] = r.next().toCharArray(); a[k] = r.nextInt(); } all = 2 + N + 26; start = all - 2; end = all - 1; cap = new int[all][all]; cost = new int[all][all]; for(int k = 0; k < N; k++){ cap[start][k] = a[k]; cost[start][k] = k + 1; cost[k][start] = -(k + 1); } for(int k = 0; k < N; k++){ int[] c = new int[26]; for(char ch : s[k]) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[k][N + x] = c[x]; } int[] c = new int[26]; for(char ch : t) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[N + x][end] = c[x]; int[] ret = new int[2]; while(true){ int[] curr = get(); // System.out.println(Arrays.toString(curr)); if(curr[0] == 0)break; ret[0] += curr[0]; ret[1] += curr[1]; } if(ret[0] == t.length){ System.out.println(ret[1]); }else System.out.println(-1); } private static int[] get() { int[] D = new int[all], P = new int[all], F = new int[all]; Arrays.fill(D, inf); Arrays.fill(P, -1); F[start] = inf; D[start] = 0; for(int itr = 0; itr < all; itr++) for(int i = 0; i < all; i++)if(D[i] < inf) for(int j = 0; j < all; j++)if(cap[i][j] > 0){ if(D[i] + cost[i][j] < D[j]){ D[j] = D[i] + cost[i][j]; F[j] = Math.min(F[i], cap[i][j]); P[j] = i; }else if(D[i] + cost[i][j] == D[j] && Math.min(F[i], cap[i][j]) > F[j]){ F[j] = Math.min(F[i], cap[i][j]); P[j] = i; } } // System.out.println(Arrays.toString(D)); // System.out.println(Arrays.toString(F)); if(D[end] == inf)return new int[]{0, 0}; int[] ret = new int[2]; ret[0] = F[end]; int curr = end; while(curr != start){ // System.out.println(P[curr] + " -> " + curr + ": " + cost[P[curr]][curr] + ", " + F[end]); ret[1] += cost[P[curr]][curr] * F[end]; cap[P[curr]][curr] -= F[end]; cap[curr][P[curr]] += F[end]; curr = P[curr]; } return ret; } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
820cdb96785549227c5639d9acbcae53
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { /** * @param args */ static char[] t; static char[][] s; static int[] a; static int[][] cap, cost, flow; static int N, all, start, end, inf = 1 << 28; public static void main(String[] args) { InputReader r = new InputReader(System.in); t = r.next().toCharArray(); N = r.nextInt(); a = new int[N]; s = new char[N][]; for(int k = 0; k < N; k++){ s[k] = r.next().toCharArray(); a[k] = r.nextInt(); } all = 2 + N + 26; start = all - 2; end = all - 1; flow = new int[all][all]; cap = new int[all][all]; cost = new int[all][all]; for(int k = 0; k < N; k++){ cap[start][k] = a[k]; cost[start][k] = k + 1; cost[k][start] = -(k + 1); } for(int k = 0; k < N; k++){ int[] c = new int[26]; for(char ch : s[k]) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[k][N + x] = c[x]; } int[] c = new int[26]; for(char ch : t) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[N + x][end] = c[x]; int[] ret = new int[2]; while(true){ int[] curr = get(); // System.out.println(Arrays.toString(curr)); if(curr[0] == 0)break; ret[0] += curr[0]; ret[1] += curr[1]; } if(ret[0] == t.length){ System.out.println(ret[1]); }else System.out.println(-1); } private static int[] get() { int[] D = new int[all], P = new int[all], F = new int[all]; Arrays.fill(D, inf); Arrays.fill(P, -1); F[start] = inf; D[start] = 0; PriorityQueue<State> pq = new PriorityQueue<State>(); pq.add(new State(start, 0)); while(!pq.isEmpty()){ State st = pq.poll(); if(st.c != D[st.i])continue; for(int j = 0; j < all; j++){ int cf = Math.min(F[st.i], cap[st.i][j] - flow[st.i][j]); if(cf > 0 && D[st.i] + cost[st.i][j] < D[j]){ D[j] = D[st.i] + cost[st.i][j]; F[j] = cf; P[j] = st.i; pq.add(new State(j, D[j])); } } } if(F[end] == 0)return new int[]{0, 0}; int curr = end; while(curr != start){ // cap[P[curr]][curr] -= F[end]; // cap[curr][P[curr]] += F[end]; flow[P[curr]][curr] += F[end]; flow[curr][P[curr]] -= F[end]; curr = P[curr]; } return new int[]{F[end], F[end] * D[end]}; } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } static class State implements Comparable<State>{ int i, c; public State(int ii, int ci){ i = ii; c = ci; } @Override public int compareTo(State b) { return c - b.c; } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
d6cba54fc06ad3a49c8746cb82125eec
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { /** * @param args */ static char[] t; static char[][] s; static int[] a; static int[][] cap, cost; static int N, all, start, end, inf = 1 << 28; public static void main(String[] args) { InputReader r = new InputReader(System.in); t = r.next().toCharArray(); N = r.nextInt(); a = new int[N]; s = new char[N][]; for(int k = 0; k < N; k++){ s[k] = r.next().toCharArray(); a[k] = r.nextInt(); } all = 2 + N + 26; start = all - 2; end = all - 1; cap = new int[all][all]; cost = new int[all][all]; for(int k = 0; k < N; k++){ cap[start][k] = a[k]; cost[start][k] = k + 1; cost[k][start] = -(k + 1); } for(int k = 0; k < N; k++){ int[] c = new int[26]; for(char ch : s[k]) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[k][N + x] = c[x]; } int[] c = new int[26]; for(char ch : t) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[N + x][end] = c[x]; int[] ret = new int[2]; while(true){ int[] curr = get(); // System.out.println(Arrays.toString(curr)); if(curr[0] == 0)break; ret[0] += curr[0]; ret[1] += curr[1]; } if(ret[0] == t.length){ System.out.println(ret[1]); }else System.out.println(-1); } private static int[] get() { int[] D = new int[all], P = new int[all], F = new int[all]; Arrays.fill(D, inf); Arrays.fill(P, -1); F[start] = inf; D[start] = 0; boolean updated = true; while(updated){ updated = false; for(int i = 0; i < all; i++)if(D[i] < inf) for(int j = 0; j < all; j++)if(cap[i][j] > 0){ if(D[i] + cost[i][j] < D[j]){ D[j] = D[i] + cost[i][j]; F[j] = Math.min(F[i], cap[i][j]); P[j] = i; updated = true; } // }else if(D[i] + cost[i][j] == D[j] && Math.min(F[i], cap[i][j]) > F[j]){ // F[j] = Math.min(F[i], cap[i][j]); // P[j] = i; // } } } if(D[end] == inf)return new int[]{0, 0}; int[] ret = new int[2]; ret[0] = F[end]; int curr = end; while(curr != start){ ret[1] += cost[P[curr]][curr] * F[end]; cap[P[curr]][curr] -= F[end]; cap[curr][P[curr]] += F[end]; curr = P[curr]; } return ret; } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
488a206151e365e9c2409ef9b2506c4b
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { /** * @param args */ static char[] t; static char[][] s; static int[] a; static int[][] cap, cost; static int N, all, start, end, inf = 1 << 28; public static void main(String[] args) { InputReader r = new InputReader(System.in); t = r.next().toCharArray(); N = r.nextInt(); a = new int[N]; s = new char[N][]; for(int k = 0; k < N; k++){ s[k] = r.next().toCharArray(); a[k] = r.nextInt(); } all = 2 + N + 26; start = all - 2; end = all - 1; cap = new int[all][all]; cost = new int[all][all]; for(int k = 0; k < N; k++){ cap[start][k] = a[k]; cost[start][k] = k + 1; cost[k][start] = -(k + 1); } for(int k = 0; k < N; k++){ int[] c = new int[26]; for(char ch : s[k]) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[k][N + x] = c[x]; } int[] c = new int[26]; for(char ch : t) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[N + x][end] = c[x]; int[] ret = new int[2]; while(true){ int[] curr = get(); // System.out.println(Arrays.toString(curr)); if(curr[0] == 0)break; ret[0] += curr[0]; ret[1] += curr[1]; } if(ret[0] == t.length){ System.out.println(ret[1]); }else System.out.println(-1); } private static int[] get() { int[] D = new int[all], P = new int[all], F = new int[all]; Arrays.fill(D, inf); Arrays.fill(P, -1); F[start] = inf; D[start] = 0; boolean updated = true; PriorityQueue<State> pq = new PriorityQueue<State>(); pq.add(new State(start, 0)); while(!pq.isEmpty()){ State st = pq.poll(); if(st.c != D[st.i])continue; for(int j = 0; j < all; j++)if(cap[st.i][j] > 0){ if(D[st.i] + cost[st.i][j] < D[j]){ D[j] = D[st.i] + cost[st.i][j]; F[j] = Math.min(F[st.i], cap[st.i][j]); P[j] = st.i; pq.add(new State(j, D[j])); } } } // while(updated){ // updated = false; // for(int i = 0; i < all; i++)if(D[i] < inf) // for(int j = 0; j < all; j++)if(cap[i][j] > 0){ // if(D[i] + cost[i][j] < D[j]){ // D[j] = D[i] + cost[i][j]; // F[j] = Math.min(F[i], cap[i][j]); // P[j] = i; // // updated = true; // } // // }else if(D[i] + cost[i][j] == D[j] && Math.min(F[i], cap[i][j]) > F[j]){ // // F[j] = Math.min(F[i], cap[i][j]); // // P[j] = i; // // } // } // } if(D[end] == inf)return new int[]{0, 0}; int[] ret = new int[2]; ret[0] = F[end]; int curr = end; while(curr != start){ ret[1] += cost[P[curr]][curr] * F[end]; cap[P[curr]][curr] -= F[end]; cap[curr][P[curr]] += F[end]; curr = P[curr]; } return ret; } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } static class State implements Comparable<State>{ int i, c; public State(int ii, int ci){ i = ii; c = ci; } @Override public int compareTo(State b) { return c - b.c; } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
1c568fa0326e477b17b6af8738493337
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { /** * @param args */ static char[] t; static char[][] s; static int[] a; static int[][] cap, cost; static int N, all, start, end, inf = 1 << 28; public static void main(String[] args) { InputReader r = new InputReader(System.in); t = r.next().toCharArray(); N = r.nextInt(); a = new int[N]; s = new char[N][]; for(int k = 0; k < N; k++){ s[k] = r.next().toCharArray(); a[k] = r.nextInt(); } all = 2 + N + 26; start = all - 2; end = all - 1; cap = new int[all][all]; cost = new int[all][all]; for(int k = 0; k < N; k++){ cap[start][k] = a[k]; cost[start][k] = k + 1; cost[k][start] = -(k + 1); } for(int k = 0; k < N; k++){ int[] c = new int[26]; for(char ch : s[k]) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[k][N + x] = c[x]; } int[] c = new int[26]; for(char ch : t) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[N + x][end] = c[x]; int[] ret = new int[2]; while(true){ int[] curr = get(); // System.out.println(Arrays.toString(curr)); if(curr[0] == 0)break; ret[0] += curr[0]; ret[1] += curr[1]; } if(ret[0] == t.length){ System.out.println(ret[1]); }else System.out.println(-1); } private static int[] get() { int[] D = new int[all], P = new int[all], F = new int[all]; Arrays.fill(D, inf); Arrays.fill(P, -1); F[start] = inf; D[start] = 0; boolean updated = true; PriorityQueue<State> pq = new PriorityQueue<State>(); pq.add(new State(start, 0)); while(!pq.isEmpty()){ State st = pq.poll(); if(st.c != D[st.i])continue; for(int j = 0; j < all; j++)if(cap[st.i][j] > 0){ if(D[st.i] + cost[st.i][j] < D[j]){ D[j] = D[st.i] + cost[st.i][j]; F[j] = Math.min(F[st.i], cap[st.i][j]); P[j] = st.i; pq.add(new State(j, D[j])); } } } if(D[end] == inf)return new int[]{0, 0}; int curr = end; while(curr != start){ cap[P[curr]][curr] -= F[end]; cap[curr][P[curr]] += F[end]; curr = P[curr]; } return new int[]{F[end], F[end] * D[end]}; } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } static class State implements Comparable<State>{ int i, c; public State(int ii, int ci){ i = ii; c = ci; } @Override public int compareTo(State b) { return c - b.c; } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
da085ee40a46c3e29c921d8b78082df4
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { /** * @param args */ static char[] t; static char[][] s; static int[] a; static int[][] cap, cost; static int N, all, start, end, inf = 1 << 28; public static void main(String[] args) { InputReader r = new InputReader(System.in); t = r.next().toCharArray(); N = r.nextInt(); a = new int[N]; s = new char[N][]; for(int k = 0; k < N; k++){ s[k] = r.next().toCharArray(); a[k] = r.nextInt(); } all = 2 + N + 26; start = all - 2; end = all - 1; cap = new int[all][all]; cost = new int[all][all]; for(int k = 0; k < N; k++){ cap[start][k] = a[k]; cost[start][k] = k + 1; cost[k][start] = -(k + 1); } for(int k = 0; k < N; k++){ int[] c = new int[26]; for(char ch : s[k]) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[k][N + x] = c[x]; } int[] c = new int[26]; for(char ch : t) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[N + x][end] = c[x]; int[] ret = new int[2]; while(true){ int[] curr = get(); // System.out.println(Arrays.toString(curr)); if(curr[0] == 0)break; ret[0] += curr[0]; ret[1] += curr[1]; } if(ret[0] == t.length){ System.out.println(ret[1]); }else System.out.println(-1); } private static int[] get() { int[] D = new int[all], P = new int[all], F = new int[all]; Arrays.fill(D, inf); Arrays.fill(P, -1); F[start] = inf; D[start] = 0; for(int itr = 0; itr < all; itr++) for(int i = 0; i < all; i++)if(D[i] < inf) for(int j = 0; j < all; j++)if(cap[i][j] > 0){ if(D[i] + cost[i][j] < D[j]){ D[j] = D[i] + cost[i][j]; F[j] = Math.min(F[i], cap[i][j]); P[j] = i; } // }else if(D[i] + cost[i][j] == D[j] && Math.min(F[i], cap[i][j]) > F[j]){ // F[j] = Math.min(F[i], cap[i][j]); // P[j] = i; // } } if(D[end] == inf)return new int[]{0, 0}; int[] ret = new int[2]; ret[0] = F[end]; int curr = end; while(curr != start){ ret[1] += cost[P[curr]][curr] * F[end]; cap[P[curr]][curr] -= F[end]; cap[curr][P[curr]] += F[end]; curr = P[curr]; } return ret; } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
ee0422de68b1e671c4ef602d03198c66
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { /** * @param args */ static char[] t; static char[][] s; static int[] a; static int[][] cap, cost, flow; static int N, all, start, end, inf = 1 << 28; public static void main(String[] args) { InputReader r = new InputReader(System.in); t = r.next().toCharArray(); N = r.nextInt(); a = new int[N]; s = new char[N][]; for(int k = 0; k < N; k++){ s[k] = r.next().toCharArray(); a[k] = r.nextInt(); } all = 2 + N + 26; start = all - 2; end = all - 1; flow = new int[all][all]; cap = new int[all][all]; cost = new int[all][all]; for(int k = 0; k < N; k++){ cap[start][k] = a[k]; cost[start][k] = k + 1; cost[k][start] = (k + 1); } for(int k = 0; k < N; k++){ int[] c = new int[26]; for(char ch : s[k]) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[k][N + x] = c[x]; } int[] c = new int[26]; for(char ch : t) c[ch - 'a']++; for(int x = 0; x < 26; x++) cap[N + x][end] = c[x]; int[] ret = new int[2]; while(true){ int[] curr = get(); // System.out.println(Arrays.toString(curr)); if(curr[0] == 0)break; ret[0] += curr[0]; ret[1] += curr[1]; } if(ret[0] == t.length){ System.out.println(ret[1]); }else System.out.println(-1); } private static int[] get() { int[] D = new int[all], P = new int[all], F = new int[all]; Arrays.fill(D, inf); Arrays.fill(P, -1); F[start] = inf; D[start] = 0; PriorityQueue<State> pq = new PriorityQueue<State>(); pq.add(new State(start, 0)); while(!pq.isEmpty()){ State st = pq.poll(); if(st.c != D[st.i])continue; for(int j = 0; j < all; j++){ int currCost = flow[j][st.i] > 0 ? - cost[st.i][j] : cost[st.i][j]; int cf = Math.min(F[st.i], cap[st.i][j] - flow[st.i][j]); if(flow[j][st.i] > 0)cf = Math.min(cf, flow[j][st.i]); if(cf > 0 && D[st.i] + currCost < D[j]){ D[j] = D[st.i] + currCost; F[j] = cf; P[j] = st.i; pq.add(new State(j, D[j])); } } } if(F[end] == 0)return new int[]{0, 0}; int curr = end; while(curr != start){ flow[P[curr]][curr] += F[end]; flow[curr][P[curr]] -= F[end]; curr = P[curr]; } return new int[]{F[end], F[end] * D[end]}; } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } static class State implements Comparable<State>{ int i, c; public State(int ii, int ci){ i = ii; c = ci; } @Override public int compareTo(State b) { return c - b.c; } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
f1bc9ab80b792b8b3ced2a001e0ec40e
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; import java.util.Scanner; public class e { int maxn = 510, maxm = 10100, inf = 1 << 28; class MINCOST { class node { int be, ne, cap, cst; node(int be, int ne, int cap, int cst) { this.be = be; this.ne = ne; this.cap = cap; this.cst = cst; } } int E[] = new int[maxn], len, p[] = new int[maxn]; int queue[] = new int[maxn], d[] = new int[maxn]; node buf[] = new node[maxm * 2]; boolean vis[] = new boolean[maxn]; void init() { Arrays.fill(E, -1); len = 0; } void addcap(int a, int b, int cap, int cst) { buf[len] = new node(b, E[a], cap, cst); E[a] = len++; buf[len] = new node(a, E[b], 0, -cst); E[b] = len++; } boolean spfa(int s, int t) { Arrays.fill(d, inf); Arrays.fill(p, -1); Arrays.fill(vis, false); d[s] = 0; vis[s] = true; int head = 0, tail = 0, v, u; queue[(tail++) % maxn] = s; while (tail != head) { u = queue[(head++) % maxn]; vis[u] = false; for (int i = E[u]; i != -1; i = buf[i].ne) { v = buf[i].be; if (buf[i].cap > 0 && d[u] + buf[i].cst < d[v]) { d[v] = buf[i].cst + d[u]; p[v] = i; if (!vis[v]) { queue[(tail++) % maxn] = v; vis[v] = true; } } } } return d[t] != inf; } int solve(int s, int t,int m) { int mincost = 0,flow=0; while (spfa(s, t)) { int temp = inf; for (int i = p[t]; i != -1; i = p[buf[i ^ 1].be]) temp = Math.min(temp, buf[i].cap); flow+=temp; mincost += d[t] * temp; for (int i = p[t]; i != -1; i = p[buf[i ^ 1].be]) { buf[i].cap -= temp; buf[i ^ 1].cap += temp; } } if(flow<m) System.out.println(-1); else System.out.println(mincost); return mincost; } } MINCOST mst=new MINCOST(); int cnt[]=new int[30]; void run() throws IOException { Scanner scan=new Scanner(System.in); String t=scan.next(); int n=scan.nextInt(); mst.init(); for(int i=0;i<t.length();i++) cnt[t.charAt(i)-'a'+1]++; for(int i=1;i<=26;i++) mst.addcap(n+i, n+27, cnt[i], 0); for(int i=1;i<=n;i++) { String s=scan.next(); int k=scan.nextInt(); Arrays.fill(cnt, 0); for(int j=0;j<s.length();j++) cnt[s.charAt(j)-'a'+1]++; mst.addcap(0, i,k,0); for(int j=1;j<=26;j++) mst.addcap(i, n+j,cnt[j],i); } mst.solve(0, n+27,t.length()); } StreamTokenizer in = new StreamTokenizer(new BufferedReader( new InputStreamReader(System.in))); int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } String next() throws IOException { in.nextToken(); return in.sval; } PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { new e().run(); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
6275a9a0eaae838f91e995e9a76fa9ff
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; import java.util.Scanner; public class e { int maxn = 510, maxm = 10100, inf = 1 << 28; class MINCOST { class node { int be, ne, cap, cst; node(int be, int ne, int cap, int cst) { this.be = be; this.ne = ne; this.cap = cap; this.cst = cst; } } int E[] = new int[maxn], len, p[] = new int[maxn]; int queue[] = new int[maxn], d[] = new int[maxn]; node buf[] = new node[maxm * 2]; boolean vis[] = new boolean[maxn]; void init() { Arrays.fill(E, -1); len = 0; } void addcap(int a, int b, int cap, int cst) { // 单向边 buf[len] = new node(b, E[a], cap, cst); E[a] = len++; buf[len] = new node(a, E[b], 0, -cst); E[b] = len++; } boolean spfa(int s, int t) { Arrays.fill(d, inf); Arrays.fill(p, -1); Arrays.fill(vis, false); d[s] = 0; vis[s] = true; int head = 0, tail = 0, v, u; queue[(tail++) % maxn] = s; while (tail != head) { u = queue[(head++) % maxn]; vis[u] = false; for (int i = E[u]; i != -1; i = buf[i].ne) { v = buf[i].be; if (buf[i].cap > 0 && d[u] + buf[i].cst < d[v]) { d[v] = buf[i].cst + d[u]; p[v] = i; if (!vis[v]) { queue[(tail++) % maxn] = v; vis[v] = true; }// 入队 }// 松弛 }// 邻接边 }// while return d[t] != inf; } int solve(int s, int t,int m) { int mincost = 0,flow=0; while (spfa(s, t)) { int temp = inf; for (int i = p[t]; i != -1; i = p[buf[i ^ 1].be]) temp = Math.min(temp, buf[i].cap);// 路径上的最小流量 flow+=temp; mincost += d[t] * temp; for (int i = p[t]; i != -1; i = p[buf[i ^ 1].be]) { // 更新流量 buf[i].cap -= temp; buf[i ^ 1].cap += temp; } } if(flow<m) System.out.println(-1); else System.out.println(mincost); return mincost; } } MINCOST mst=new MINCOST(); int cnt[]=new int[30]; void run() throws IOException { Scanner scan=new Scanner(System.in); String t=scan.next(); int n=scan.nextInt(); mst.init(); for(int i=0;i<t.length();i++) cnt[t.charAt(i)-'a'+1]++; for(int i=1;i<=26;i++) mst.addcap(n+i, n+27, cnt[i], 0); for(int i=1;i<=n;i++) { String s=scan.next(); int k=scan.nextInt(); Arrays.fill(cnt, 0); for(int j=0;j<s.length();j++) cnt[s.charAt(j)-'a'+1]++; mst.addcap(0, i,k,0); for(int j=1;j<=26;j++) mst.addcap(i, n+j,cnt[j],i); } mst.solve(0, n+27,t.length()); } StreamTokenizer in = new StreamTokenizer(new BufferedReader( new InputStreamReader(System.in))); int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } String next() throws IOException { in.nextToken(); return in.sval; } PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { new e().run(); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
cf2fa804645aba30a91d0ab38926b98e
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.util.*; public class E { Scanner sc = new Scanner(System.in); void doIt() { int vnum = 0; Graph g = new Graph(20000); String line = sc.next(); int [] cnt = new int[256]; for(int i = 0; i < line.length(); i++) cnt[(int)line.charAt(i)]++; // 0をソース // 1をシンク // 2-27 第1層 a-z for(int i = 0; i < 26; i++) { g.addEdge(0, i+2, cnt['a' + i], 0); } vnum++; vnum++; vnum += 26; int n = sc.nextInt(); for(int i = 0; i < n; i++) { String s = sc.next(); int a = sc.nextInt(); int vnext = vnum + s.length(); for(int j = 0; j < s.length(); j++) { g.addEdge(2 + s.charAt(j) - 'a', vnum + j, 1, 0); g.addEdge(vnum + j, vnext, 1, i+1); // コストがi+1行目 } g.addEdge(vnext, 1, a, 0); // a個しか使えない vnum = vnext + 1; } g.V = vnum; int ans = g.minCostFlow(0, 1, line.length()); System.out.println(ans); } public static void main(String[] args) { new E().doIt(); } // from arihon class Graph { int V; List [] G; Graph (int v) { V = v; G = new List[V]; for(int i = 0; i < V; i++) { G[i] = new ArrayList<Edge>(); } } void addEdge(int from, int to, int cap, int cost) { G[from].add(new Edge(to, cap, cost, G[to].size())); G[to].add(new Edge(from, 0, - cost, G[from].size() - 1)); } int minCostFlow(int s, int t, int f) { final int INF = Integer.MAX_VALUE / 4; int res = 0; int h[] = new int[V]; int dist[] = new int[V]; int prevv[] = new int[V]; int preve[] = new int[V]; while(f > 0) { PriorityQueue <Data> que = new PriorityQueue<Data>(); Arrays.fill(dist, INF); dist[s] = 0; que.add(new Data(0, s)); while(que.isEmpty() == false) { Data p = que.poll(); int v = p.node; if(dist[v] < p.min_dist) continue; for(int i = 0; i < G[v].size(); i++) { Edge e = (Edge)G[v].get(i); if(e.cap > 0 && dist[e.to]> dist[v] + e.cost + h[v] - h[e.to] ){ dist [e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.add(new Data(dist[e.to], e.to)); } } } if(dist[t] >= INF) return -1; for(int v = 0; v < V; v++) h[v] += dist[v]; int d = f; for(int v = t; v != s; v = prevv[v]) { Edge e = (Edge)(G[prevv[v]].get(preve[v])); d = Math.min(d, e.cap); } f -= d; res += d * h[t]; for(int v = t; v != s; v = prevv[v]) { Edge e = (Edge)G[prevv[v]].get(preve[v]); e.cap -= d; Edge ne = (Edge)(G[v].get(e.rev)); ne.cap += d; } } return res; } } class Edge { int to, cap, cost, rev; Edge (int to, int cap, int cost, int rev) { this.to = to; this.cap = cap; this.cost = cost; this.rev = rev; } } class Data implements Comparable<Data>{ int min_dist, node; public Data(int min_dist, int node) { this.min_dist = min_dist; this.node = node; } @Override public int compareTo(Data o) { return this.min_dist - o.min_dist; } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
e1b958765e76e68a9da77c7c7297df01
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class MinCostMax { static class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String nextLine() { try { return br.readLine(); } catch (Exception e) { throw (new RuntimeException()); } } public String next() { while (!st.hasMoreTokens()) { String l = nextLine(); if (l == null) return null; st = new StringTokenizer(l); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for (int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public void sortIntArray(int[] array) { Integer[] vals = new Integer[array.length]; for (int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for (int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortLongArray(long[] array) { Long[] vals = new Long[array.length]; for (int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for (int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortDoubleArray(double[] array) { Double[] vals = new Double[array.length]; for (int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for (int i = 0; i < array.length; i++) array[i] = vals[i]; } } static final long INF = Long.MAX_VALUE / 4; static class MinCostMaxFlow { static class Pair { int first; int second; } int N; long[][] cap, flow, cost; boolean[] found; long[] dist, pi, width; Pair[] dad; MinCostMaxFlow(int N) { this.N = N; cap = new long[N][N]; flow = new long[N][N]; cost = new long[N][N]; dad = new Pair[N]; for(int i = 0; i < N; i++) dad[i] = new Pair(); found = new boolean[N]; dist = new long[N]; pi = new long[N]; width = new long[N]; } void AddEdge(int from, int to, long cap, long cost) { this.cap[from][to] = cap; this.cost[from][to] = cost; } void Relax(int s, int k, long cap, long cost, int dir) { long val = dist[s] + pi[s] - pi[k] + cost; if (cap != 0 && val < dist[k]) { dist[k] = val; dad[k].first = s; dad[k].second = dir; width[k] = Math.min(cap, width[s]); } } long Dijkstra(int s, int t) { Arrays.fill(found, false); Arrays.fill(dist, INF); Arrays.fill(width, 0); dist[s] = 0; width[s] = INF; while (s != -1) { int best = -1; found[s] = true; for (int k = 0; k < N; k++) { if (found[k]) continue; Relax(s, k, cap[s][k] - flow[s][k], cost[s][k], 1); Relax(s, k, flow[k][s], -cost[k][s], -1); if (best == -1 || dist[k] < dist[best]) best = k; } s = best; } for (int k = 0; k < N; k++) pi[k] = Math.min(pi[k] + dist[k], INF); return width[t]; } long[] GetMaxFlow(int s, int t) { long totflow = 0, totcost = 0; long amt; while ((amt = Dijkstra(s, t)) != 0) { totflow += amt; for (int x = t; x != s; x = dad[x].first) { if (dad[x].second == 1) { flow[dad[x].first][x] += amt; totcost += amt * cost[dad[x].first][x]; } else { flow[x][dad[x].first] -= amt; totcost -= amt * cost[x][dad[x].first]; } } } return new long[]{totflow, totcost}; } } public static void main(String[] args) { Scanner sc = new Scanner(); String objetivo = sc.next(); int n = sc.nextInt(); String[] strings = new String[n]; int[] limites = new int[n]; for(int i = 0; i < n; i++) { strings[i] = sc.next(); limites[i] = sc.nextInt(); } int actual = 0; int source = actual++; int sink = actual++; int[] nodos = new int[n]; for(int i = 0; i < nodos.length; i++) nodos[i] = actual++; int[] nodosLetras = new int[26]; for(int i = 0; i < nodosLetras.length; i++) nodosLetras[i] = actual++; MinCostMaxFlow grafo = new MinCostMaxFlow(actual); for(int i = 0; i < strings.length; i++) { grafo.AddEdge(source, nodos[i], limites[i], 0); for(int j = 0; j < 26; j++) { int cuenta = 0; for(char c : strings[i].toCharArray()) if(c == j + 'a') cuenta++; grafo.AddEdge(nodos[i], nodosLetras[j], cuenta, (i + 1)); } } for(int i = 0; i < strings.length; i++) { for(int j = 0; j < 26; j++) { int cuenta = 0; for(char c : objetivo.toCharArray()) if(c == j + 'a') cuenta++; grafo.AddEdge(nodosLetras[j], sink, cuenta, 0); } } long[] mFlow = grafo.GetMaxFlow(source, sink); if(mFlow[0] == objetivo.length()) System.out.println(mFlow[1]); else System.out.println(-1); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
0c747cf66b102af6576c7e06ed25e328
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { BufferedReader c=new BufferedReader(new InputStreamReader(System.in)); String s=c.readLine(); int N=Integer.parseInt(c.readLine()); int cap[][]=new int[N+26+2][N+26+2]; int cost[][]=new int[N+26+2][N+26+2]; int H[]=hist(s); for(int i=0;i<26;i++) cap[N+i+1][N+26+1]=H[i]; for(int i=0;i<N;i++) { String S[]=c.readLine().split(" "); H=hist(S[0]); for(int j=0;j<26;j++) { cap[1+i][N+j+1]=H[j]; cost[1+i][N+j+1]=i+1; } int max=Integer.parseInt(S[1]); cap[0][i+1]=max; } MinCostMaxFlow flow = new MinCostMaxFlow(); int A[]=flow.getMaxFlow(cap,cost,0,N+26+1); if(A[0]!=s.length()) System.out.println(-1); else System.out.println(A[1]); } public static int[] hist(String s) { int h[]=new int[26]; for(int i=0;i<s.length();i++) { h[s.charAt(i)-'a']++; } return h; } } //must declare new classes here class MinCostMaxFlow { boolean found[]; int N, cap[][], flow[][], cost[][], dad[], dist[], pi[]; static final int INF = Integer.MAX_VALUE / 2 - 1; boolean search(int source, int sink) { Arrays.fill(found, false); Arrays.fill(dist, INF); dist[source] = 0; while (source != N) { int best = N; found[source] = true; for (int k = 0; k < N; k++) { if (found[k]) continue; if (flow[k][source] != 0) { int val = dist[source] + pi[source] - pi[k] - cost[k][source]; if (dist[k] > val) { dist[k] = val; dad[k] = source; } } if (flow[source][k] < cap[source][k]) { int val = dist[source] + pi[source] - pi[k] + cost[source][k]; if (dist[k] > val) { dist[k] = val; dad[k] = source; } } if (dist[k] < dist[best]) best = k; } source = best; } for (int k = 0; k < N; k++) pi[k] = Math.min(pi[k] + dist[k], INF); return found[sink]; } int[] getMaxFlow(int cap[][], int cost[][], int source, int sink) { this.cap = cap; this.cost = cost; N = cap.length; found = new boolean[N]; flow = new int[N][N]; dist = new int[N+1]; dad = new int[N]; pi = new int[N]; int totflow = 0, totcost = 0; while (search(source, sink)) { int amt = INF; for (int x = sink; x != source; x = dad[x]) amt = Math.min(amt, flow[x][dad[x]] != 0 ? flow[x][dad[x]] : cap[dad[x]][x] - flow[dad[x]][x]); for (int x = sink; x != source; x = dad[x]) { if (flow[x][dad[x]] != 0) { flow[x][dad[x]] -= amt; totcost -= amt * cost[x][dad[x]]; } else { flow[dad[x]][x] += amt; totcost += amt * cost[dad[x]][x]; } } totflow += amt; } return new int[]{ totflow, totcost }; } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
a514bd365b26f01532dd9dfa8bfaa51d
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; public class ProblemE { public static class State implements Comparable { int dist; int now; public State(int _n, int _d) { now = _n; dist = _d; } public int compareTo(Object arg0) { State a = (State) arg0; return dist - a.dist; } } public static class Edge { int to; int cap; int rev; int cost; public Edge(int _to, int _cap, int _cost, int _rev) { to = _to; cap = _cap; rev = _rev; cost = _cost; } } public static int INF = 10000000; public static int V; public static int[] h; public static int[] dist; public static int[] prevv, preve; public static Map<Integer, List<Edge>> graph = new HashMap<Integer, List<Edge>>(); public static void init(int size) { for (int i = 0 ; i < size ; i++) { graph.put(i, new ArrayList<Edge>()); } dist = new int[size]; prevv = new int[size]; preve = new int[size]; h = new int[size]; V = size; } public static void edge(int from, int to, int cap, int cost) { graph.get(from).add(new Edge(to, cap, cost, graph.get(to).size())); graph.get(to).add(new Edge(from, 0, -cost, graph.get(from).size() - 1)); } public static int min_cost_flow(int s, int t, int f) { int res = 0; Arrays.fill(h, 0); while (f > 0) { Queue<State> q = new PriorityQueue<State>(10000); Arrays.fill(dist, INF); dist[s] = 0; q.add(new State(s, 0)); while (q.size() >= 1) { State stat = q.poll(); int v = stat.now; if (dist[v] < stat.dist) { continue; } for (int i = 0 ; i < graph.get(v).size() ; i++) { Edge e = graph.get(v).get(i); if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; q.add(new State(e.to, dist[e.to])); } } } if (dist[t] == INF) { return -1; } for (int v = 0 ; v < V ; v++) { h[v] += dist[v]; } int d = f; for (int v = t ; v != s ; v = prevv[v]) { d = Math.min(d, graph.get(prevv[v]).get(preve[v]).cap); } f -= d; res += d * h[t]; for (int v = t ; v != s ; v = prevv[v]) { Edge e = graph.get(prevv[v]).get(preve[v]); e.cap -= d; graph.get(v).get(e.rev).cap += d; } } return res; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int[] needs = new int[26]; int all = 0; for (char c : in.readLine().toCharArray()) { needs[c-'a']++; all++; } int n = Integer.valueOf(in.readLine()); int[][] have = new int[n][26]; int[] allowedUse = new int[n]; for (int i = 0 ; i < n ; i++) { String[] line = in.readLine().split(" "); for (char c : line[0].toCharArray()) { have[i][c-'a']++; } allowedUse[i] = Integer.valueOf(line[1]); } int SOURCE = n+26*n+26; int SINK = SOURCE+1; init(SINK+1); for (int i = 0 ; i < n ; i++) { edge(SOURCE, i, allowedUse[i], 0); } for (int i = 0 ; i < n ; i++) { for (int x = 0 ; x < 26 ; x++) { edge(i, n + i * 26 + x, allowedUse[i], 0); edge(n + i * 26 + x, SOURCE-1-x, have[i][x], i+1); } } for (int i = 0 ; i < 26 ; i++) { edge(SOURCE-1-i, SINK, needs[i], 0); } out.println(min_cost_flow(SOURCE, SINK, all)); out.flush(); } public static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
9952924f6cc5e3b810986af794b6ff6f
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
//package round147; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.TreeSet; public class E { InputStream is; PrintWriter out; String INPUT = ""; void solve() { char[] s = ns().toCharArray(); int n = ni(); char[][] fr = new char[n][]; int[] lim = new int[n]; for(int i = 0;i < n;i++){ fr[i] = ns().toCharArray(); lim[i] = ni(); } // 0,n-1 // n,n+25 // n+26 // n+27 int src = n+26, sink = n+27; int m = 2*(27*n+26); int[] from = new int[m]; int[] to = new int[m]; int[] cost = new int[m]; int[] cap = new int[m]; int p = 0; for(int i = 0;i < n;i++){ from[p] = src; to[p] = i; cost[p] = 0; cap[p] = lim[i]; p++; int[] ct = new int[26]; for(char c : fr[i]){ ct[c-'a']++; } for(int j = 0;j < 26;j++){ if(ct[j] > 0){ from[p] = i; to[p] = n+j; cost[p] = i+1; cap[p] = ct[j]; p++; } } } int[] ct = new int[26]; for(char c : s){ ct[c-'a']++; } for(int i = 0;i < 26;i++){ from[p] = n+i; to[p] = sink; cost[p] = 0; cap[p] = ct[i]; p++; } int[][][] caps = packWD(n+28, from, to, cap, p); int[][][] costs = packWD(n+28, from, to, cost, p); out.println(solveMinCostFlow(costs, caps, src, sink, s.length)); } public static int[][][] packWD(int n, int[] from, int[] to, int[] w, int sup) { int[][][] g = new int[n][][]; int[] p = new int[n]; for(int i = 0;i < sup;i++)p[from[i]]++; for(int i = 0;i < n;i++)g[i] = new int[p[i]][2]; for(int i = 0;i < sup;i++){ --p[from[i]]; g[from[i]][p[from[i]]][0] = to[i]; g[from[i]][p[from[i]]][1] = w[i]; } return g; } public static int solveMinCostFlow(int[][][] cost, int[][][] capacity, int src, int sink, int all) { int n = cost.length; int[][][] flow = new int[n][][]; for(int i = 0;i < n;i++) { flow[i] = new int[cost[i].length][2]; for(int j = 0;j < cost[i].length;j++){ flow[i][j][0] = cost[i][j][0]; } } // unweighted invgraph // 逆グラフのcurのi番目=nextのとき、順グラフでcurはnextの何番目にあるかを返す int[][][] ig = new int[n][][]; { int[] p = new int[n]; for(int i = 0;i < n;i++){ for(int j = 0;j < cost[i].length;j++)p[cost[i][j][0]]++; } for(int i = 0;i < n;i++)ig[i] = new int[p[i]][2]; for(int i = n-1;i >= 0;i--){ for(int j = 0;j < cost[i].length;j++){ int u = --p[cost[i][j][0]]; ig[cost[i][j][0]][u][0] = i; ig[cost[i][j][0]][u][1] = j; } } } int mincost = 0; int[] pot = new int[n]; // ポテンシャル final int[] d = new int[n]; TreeSet<Integer> q = new TreeSet<Integer>(new Comparator<Integer>(){ public int compare(Integer a, Integer b) { if(d[a] - d[b] != 0)return d[a] - d[b]; return a - b; } }); while(all > 0){ // src~sinkの最短路を探す int[] prev = new int[n]; int[] myind = new int[n]; Arrays.fill(prev, -1); Arrays.fill(d, Integer.MAX_VALUE / 2); d[src] = 0; q.clear(); q.add(src); while(!q.isEmpty()){ int cur = q.pollFirst(); if(cur == sink)break; for(int i = 0;i < cost[cur].length;i++) { int next = cost[cur][i][0]; if(capacity[cur][i][1] - flow[cur][i][1] > 0){ int nd = d[cur] + cost[cur][i][1] + pot[cur] - pot[next]; if(d[next] > nd){ q.remove(next); d[next] = nd; prev[next] = cur; myind[next] = i; q.add(next); } } } for(int i = 0;i < ig[cur].length;i++) { int next = ig[cur][i][0]; int cind = ig[cur][i][1]; if(flow[next][cind][1] > 0){ int nd = d[cur] - cost[next][cind][1] + pot[cur] - pot[next]; if(d[next] > nd){ q.remove(next); d[next] = nd; prev[next] = cur; myind[next] = -cind-1; q.add(next); } } } } if(prev[sink] == -1)break; int minflow = all; int sumcost = 0; for(int i = sink;i != src;i = prev[i]){ if(myind[i] >= 0){ minflow = Math.min(minflow, capacity[prev[i]][myind[i]][1] - flow[prev[i]][myind[i]][1]); sumcost += cost[prev[i]][myind[i]][1]; }else{ // cur->next // prev[i]->i // iが持ってる // ig[cur][j][0]=nextのときg[next][ig[cur][j][1]] = cur int ind = -myind[i]-1; // tr(prev[i], ind); minflow = Math.min(minflow, flow[i][ind][1]); sumcost -= cost[i][ind][1]; } } mincost += minflow * sumcost; for(int i = sink;i != src;i = prev[i]){ if(myind[i] >= 0){ flow[prev[i]][myind[i]][1] += minflow; }else{ int ind = -myind[i]-1; flow[i][ind][1] -= minflow; } } // tr(flow); all -= minflow; for(int i = 0;i < n;i++){ pot[i] += d[i]; } } if(all > 0)return -1; return mincost; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new E().run(); } public int ni() { try { int num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public long nl() { try { long num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public String ns() { try{ int b = 0; StringBuilder sb = new StringBuilder(); while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' ')); if(b == -1)return ""; sb.append((char)b); while(true){ b = is.read(); if(b == -1)return sb.toString(); if(b == '\r' || b == '\n' || b == ' ')return sb.toString(); sb.append((char)b); } } catch (IOException e) { } return ""; } public char[] ns(int n) { char[] buf = new char[n]; try{ int b = 0, p = 0; while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n')); if(b == -1)return null; buf[p++] = (char)b; while(p < n){ b = is.read(); if(b == -1 || b == ' ' || b == '\r' || b == '\n')break; buf[p++] = (char)b; } return Arrays.copyOf(buf, p); } catch (IOException e) { } return null; } double nd() { return Double.parseDouble(ns()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
1056c3e2c8d20fc2399b587f4aa29d9b
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import static java.lang.Math.*; import static java.util.Arrays.*; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { try { String packageName = new Main().getClass().getPackage().getName(); System.setIn(new FileInputStream("src/" + packageName + "/input.txt")); // System.setOut(new PrintStream(new FileOutputStream("src/" + packageName + "/result.txt"))); } catch (FileNotFoundException e) { } catch (NullPointerException e) { } new Main().run(); } void tr(Object... os) { System.err.println(deepToString(os)); } Scanner sc; void run() { sc = new Scanner(System.in); char[] t = sc.next().toCharArray(); int[] count = getCount(t); int n = sc.nextInt(); char[][] s = new char[n][]; int[] a = new int[n]; for (int i = 0; i < n; ++i) { s[i] = sc.next().toCharArray(); a[i] = sc.nextInt(); } V[] vs = new V[2 + n + 26]; for (int i = 0; i < vs.length; i++) vs[i] = new V(); for (int i = 0; i < vs.length; i++) vs[i].id = i; V start = vs[vs.length - 2]; V end = vs[vs.length - 1]; for (int i = 0; i < n; i++) { start.add(vs[i], a[i], 0); } for (int i = 0; i < 26; i++) { vs[n + i].add(end, count[i], 0); } for (int i = 0; i < n; i++) { count = getCount(s[i]); for (int j = 0; j < 26; j++) { vs[i].add(vs[n + j], count[j], i + 1); } } int ans = minCostMaxFlow(vs, start, end, t.length); System.out.println(ans); } int[] getCount(char[] s) { int res[] = new int[26]; for (int i = 0; i < s.length; i++) { res[ s[i] - 'a' ]++; } return res; } static final int INF = 1001001001; int minCostMaxFlow(V[] vs, V s, V t, int need) { int res = 0; while (need > 0) { for (V v : vs) v.min = INF; PriorityQueue<E> que = new PriorityQueue<E>(); s.min = 0; que.offer(new E(s, 0, 0)); while (!que.isEmpty()) { E crt = que.poll(); if (crt.cost == crt.to.min) { for (E e : crt.to.es) { int tmp = crt.cost + e.cost + crt.to.h - e.to.h; if (e.cap > 0 && e.to.min > tmp) { e.to.min = tmp; e.to.prev = e; que.offer(new E(e.to, 0, e.to.min)); } } } } if (t.min == INF) return -1; int d = need; for (E e = t.prev; e != null; e = e.rev.to.prev) { d = min (d, e.cap); } for (E e = t.prev; e != null; e = e.rev.to.prev) { res += d * e.cost; e.cap -= d; e.rev.cap += d; } need -= d; for (V v : vs) v.h += v.min; } return res; } class V { int id; ArrayList<E> es = new ArrayList<E>(); E prev; int min, h; void add (V to, int cap, int cost) { E e = new E(to, cap, cost), rev = new E(this, 0, -cost); e.rev= rev; rev.rev = e; es.add(e); to.es.add(rev); } } class E implements Comparable<E> { V to; E rev; int cap, cost; E (V to, int cap, int cost) { this.to = to; this.cap = cap; this.cost = cost; } public int compareTo(E o) { return cost - o.cost; } } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
957bc1b916ab4b4e7e0cb969ccdce206
train_002.jsonl
1351179000
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
256 megabytes
import static java.lang.Math.*; import java.io.*; import java.util.*; public class Template { BufferedReader in; PrintWriter out; StringTokenizer st; String next() { while (st==null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (Exception e) {} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } class Edge { int u, v, f, c, p; Edge r; public Edge(int u, int v, int f, int c, int p) { this.u=u; this.v=v; this.f=f; this.c=c; this.p=p; } } class Pair implements Comparable<Pair> { int w, v; public Pair(int w, int v) { this.w=w; this.v=v; } public int compareTo(Pair o) { if (w!=o.w) return w - o.w; else return v - o.v; } } class Graph { ArrayList<Edge>[] g; int n; public Graph(int n) { this.n=n; g = new ArrayList[n]; for (int i=0; i<n; i++) g[i] = new ArrayList<Edge>(); } void add(int u, int v, int c, int p) { Edge ef = new Edge(u, v, 0, c, p); Edge er = new Edge(v, u, 0, 0, -p); ef.r=er; er.r=ef; g[u].add(ef); g[v].add(er); } int minCostFlow(int s, int t, int flow) { int[] d = new int[n]; boolean[] u = new boolean[n]; d[s] = 0; u[s] = true; boolean changed = true; // Ford - Bellman while (changed) { changed = false; for (int i=0; i<n; i++) if (u[i]) for (Edge e : g[i]) if ((!u[e.v] || d[e.v] > d[e.u] + e.p) && (e.c > e.f)) { changed = true; u[e.v] = true; d[e.v] = d[e.u] + e.p; } } // System.err.println("ok"); // potentials int[] q = new int[n]; for (int i=0; i<n; i++) q[i] = d[i]; int curflow=0; int cost = 0; int[] f = new int[n]; while (u[t] && curflow < flow) { Arrays.fill(u, false); Arrays.fill(d, 0); Arrays.fill(f, 0); PriorityQueue<Pair> pq = new PriorityQueue<Pair>(); d[s] = 0; u[s] = true; f[s] = Integer.MAX_VALUE; Edge[] p = new Edge[n]; pq.add(new Pair(0, s)); while (!pq.isEmpty()) { Pair cur = pq.poll(); if (cur.w!=d[cur.v]) continue; for (Edge e : g[cur.v]) if (e.c > e.f) { int w = d[e.u] + e.p + q[e.u] - q[e.v]; if (!u[e.v] || d[e.v] > w) { pq.add(new Pair(w,e.v)); f[e.v] = Math.min(f[e.u], e.c - e.f); d[e.v] = w; p[e.v] = e; u[e.v] = true; } } } if (!u[t]) break; if (f[t] > flow - curflow) { f[t] = flow - curflow; } curflow+=f[t]; cost+=(q[t] + d[t])*f[t]; int x = t; while (x != s) { Edge e = p[x]; e.f += f[t]; e.r.f -= f[t]; x = e.u; } for (int i=0; i<n; i++) { q[i]+=d[i]; } } if (curflow < flow) return -1; return cost; } } public void run() throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); Long start = System.currentTimeMillis(); String t = next(); int[] ch = new int[26]; for (int i=0; i<t.length(); i++) ch[t.charAt(i) - 'a']++; //System.err.println(Arrays.toString(ch)); int n = nextInt(); Graph g = new Graph(26 + n + 2); for (int i=0; i<26; i++) g.add(n + 26, i, ch[i], 0); for (int j=0; j<n; j++) { String s = next(); int cap = nextInt(); ch = new int[26]; for (int i=0; i<s.length(); i++) ch[s.charAt(i) - 'a']++; //System.err.println(Arrays.toString(ch)); for (int i=0; i<26; i++) g.add(i, 26 + j, ch[i], j + 1); g.add(26 + j, n + 27, cap, 0); } int ans = g.minCostFlow(n + 26, n + 27, t.length()); out.println(ans); Long end = System.currentTimeMillis(); out.close(); } public static void main(String[] args) throws Exception { new Template().run(); } }
Java
["bbaze\n3\nbzb 2\naeb 3\nba 10", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1"]
2 seconds
["8", "18", "-1"]
NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Java 6
standard input
[ "flows", "graphs" ]
adc23c13988fc955f4589c88829ef0e7
The first line of the input contains string t — the string that you need to build. The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
2,000
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
standard output
PASSED
e1121ff1a3899d94687a32fd786f9829
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class rtain { public static void main(String[] args) throws IOException { InputReader input = new InputReader(System.in); int n=input.nextInt(); int delay=input.nextInt(); int count=0; int word1=0; for(int i=0;i<n;i++) { int word=input.nextInt(); if((word-word1)>delay) { count=1; }else { count++; } word1=word; } System.out.println(count); } static class InputReader { StringTokenizer tokenizer; BufferedReader reader; String token; String temp; public InputReader(InputStream stream) { tokenizer = null; reader = new BufferedReader(new InputStreamReader(stream)); } public InputReader(FileInputStream stream) { tokenizer = null; reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() throws IOException { return reader.readLine(); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { if (temp != null) { tokenizer = new StringTokenizer(temp); temp = null; } else { tokenizer = new StringTokenizer(reader.readLine()); } } catch (IOException e) { } } return tokenizer.nextToken(); } public double nextDouble() { return Double.parseDouble(next()); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
1d7da0a444595605973ff2857a042c81
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
import java.io.*; import java.util.*; public class A { FastScanner in; PrintWriter out; void solve() { //This is the main logic code int x = in.nextInt(); long y = in.nextInt(); int cnt = 1; int f = in.nextInt(); while(x-->1) { int f1 = in.nextInt(); if(f1-f>y)cnt=1; else cnt++; f=f1; } out.print(cnt); } int fact(int n) { if(n==1 || n==0)return 1; return n*fact(n-1); } public static void main(String[] args) { new A().runIO(); } void run() { try { in = new FastScanner(new File("A.in")); out = new PrintWriter(new File("A.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
fb77f621e26e1c62f8012089650518bd
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
import java.util.Scanner; public class CrazyComputer { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n= sc.nextInt(); int t= sc.nextInt(); int a[]=new int[n]; for (int i = 0; i < n; i++) { a[i]=sc.nextInt(); } int c=1; for (int i = 0; i < n-1; i++) { int r=a[i+1]-a[i]; if(r<=t){ c++; } else { c=1; } } System.out.println(c); } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
6c7c11954049800615e3ef988e165b28
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
import java.util.Scanner; public class Main{ private static int count = 1; public static void main(String[] args){ Scanner in = new Scanner(System.in); int num = in.nextInt(); int c = in.nextInt(); int[] arr = new int[num]; for(int i = 0; i < num; i++){ arr[i] = in.nextInt(); } for(int i = 1; i < num; i++){ if( arr[i] - arr[i-1] > c){ count = 1; }else{ count++; } } System.out.println(count); } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
3bb8c30f4aabe250ccb5795484518b50
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; /** * * @author scilab5 */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { FastReader console = new FastReader () ; int n = console.nextInt() ; int c = console.nextInt() ; int []x = new int [n+1] ; int count = 0 ; x[0]=0 ; for (int i=1 ; i<x.length ; i++){ x[i]=console.nextInt() ; } for (int i=1 ; i<x.length ; i++){ if (x[i]-x[i-1]<=c){ count ++ ; } else { count = 0 ; } } if (n==1){ System.out.println("1"); } else { if (count>0){ if (count==n) { System.out.println(count ); } else {System.out.println(count+1);} } else { System.out.println("1"); } } } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
e9f7477ef2d8ad4b1c592385a788a287
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
import java.util.Scanner; /** * * @author scilab5 */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner console = new Scanner (System.in) ; int n = console.nextInt() ; int c = console.nextInt() ; int []x = new int [n+1] ; int count = 0 ; x[0]=0 ; for (int i=1 ; i<x.length ; i++){ x[i]=console.nextInt() ; } for (int i=1 ; i<x.length ; i++){ if (x[i]-x[i-1]<=c){ count ++ ; } else { count = 0 ; } } if (n==1){ System.out.println("1"); } else { if (count>0){ if (count==n) { System.out.println(count ); } else {System.out.println(count+1);} } else { System.out.println("1"); } } } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
fa9dd30880a81b7438b2e6eadee1ba1e
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
import java.util.Scanner ; public class A716_CrazyComputer { public static void main(String[] args) { Scanner ss =new Scanner (System.in) ; int n = ss.nextInt() ; int c = ss.nextInt() ; int w = 0 ; long f = ss.nextLong() ; long tan = 0 ; for (int i = 1 ; i < n ; i ++ ) { tan = ss.nextLong() ; if (tan-f <= c ) w ++ ; else w= 0 ; f =(long) tan ; } System.out.println(w+1); } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
174b3f594597a9e83b2767f1d9d0085f
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
/** * @(#)CrazyComputer.java * * * @author * @version 1.00 2016/10/19 */ import java.util.*; public class CrazyComputer { public static void main(String[] args) { Scanner in = new Scanner(System.in); int x = in.nextInt(); int y = in.nextInt(); int total = 0; int prev = 0; for (int i=0; i<x; i++) { int curr = in.nextInt(); int value = curr-prev; if(value>y){ total=1; }else{ total++; } prev=curr; } System.out.println(total); } // public static int crazy(int a, int b, int current){ // int total = 0; // int previous = 0; // // for(int i = 0; i <x; i++){ // int value = current-previous; // // if (value > y){ // total = 1; // }else { // total++; // } // previous = current; // } // return(total); // } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
1e1996cbeb40fca4daf36c7bd3577f01
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
/** * @(#)CrazyComputer.java * * * @author * @version 1.00 2016/10/19 */ import java.util.*; public class CrazyComputer { public static void main(String[] args) { Scanner in = new Scanner(System.in); int first = in.nextInt(); int second = in.nextInt(); int total = 0; int a = 0; for (int i=0; i<first; i++) { int b = in.nextInt(); if(b-a>second){ total=1; }else{ total++; } a = b; } System.out.println(total); } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
6679ad0f21fcfb87b325d0ddcafda610
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
/** * @(#)CrazyComputer.java * * * @author * @version 1.00 2016/10/19 */ import java.util.*; public class CrazyComputer { public static void main(String[] args) { Scanner in = new Scanner(System.in); int x = in.nextInt(); int y = in.nextInt(); int total = 0; int prev = 0; for (int i=0; i<x; i++) { int curr = in.nextInt(); int value = curr-prev; if(value>y){ total=1; }else{ total++; } prev=curr; } System.out.println(total); } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
0ed1d59b429a48191dd4666cb021dba8
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int c = sc.nextInt(); int [] a = new int [n]; //int ans = 1; for(int i =0; i<n; i++){ a[i]=sc.nextInt(); } int ans = 1; for(int j =1; j<n; j++){ if(a[j]-a[j-1]>c){ ans =1; } else ans++; } System.out.println(ans); } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
f0140dfc11aea2508aad5aa4c6241a9e
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int c = sc.nextInt(); int a = sc.nextInt(); int ans = 1; for(int i =0; i<n-1; i++){ int b=sc.nextInt(); //int ans = 1; if(b-a<=c){ ans +=1; //a=b; } else ans=1; a=b; } System.out.println(ans); } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
d08fd120010f5072da725664a9e8c1ae
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
//package com.company; import java.util.Scanner; public class Crazy_Computer { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); long k = input.nextLong(); String[] s = new String[n]; for(int i=0;i<n;i++) s[i] = input.next(); if(n==1) System.out.println(1); else { StringBuilder sb = new StringBuilder(); sb.append("1"); for (int i = 1; i < n; i++) { if (Long.parseLong(s[i]) - Long.parseLong(s[i - 1]) <= k) sb.append("1"); else { sb = new StringBuilder(); sb.append("1"); } } System.out.println(sb.toString().length()); } } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
532d65345316b2db06cf29d1114da2ed
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
import java.util.*; public class Problem_716A { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int n=sc.nextInt(); int c=sc.nextInt(); int[]a=new int[n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); int w=1; for(int i=0;i<n-1;i++) { if(a[i+1]-a[i] <= c) w++; else w=1; } // if(n==1) // w=1; System.out.println(w); } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
277b99eed9a9e17fb8bf838bf8914fe1
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
/** * Created by mo on 9/23/16. */ import java.util.*; import java.io.*; public class Problem716A { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(), c = sc.nextInt(); int count = 0; int in[] = new int[n]; for (int i = 0; i < n; i++) in[i] = sc.nextInt(); for (int i = 0; i < n; i++){ if (i == 0) count++; else { if (in[i] - in[i-1] <= c) count++; else count = 1; } } System.out.println(count); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output
PASSED
aab1384b57167c1ad1fe6a40bf9b0645
train_002.jsonl
1474119900
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a &gt; c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; 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); Problem A = new Problem(); A.solve(in, out); out.close(); } static class Problem { public void solve(Scanner in, PrintWriter out) { int n, c; n = in.nextInt(); c = in.nextInt(); int x1 = 0; int count = 0; for (int i = 0; i < n; i++) { int x2 = in.nextInt(); if (x2 - x1 > c) { count = 0; } count++; x1 = x2; } out.println(count); } } static class Scanner { public BufferedReader reader; public StringTokenizer tokenizer; public Scanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"]
2 seconds
["3", "2"]
NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 &gt; 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.
Java 8
standard input
[ "implementation" ]
fb58bc3be4a7a78bdc001298d35c6b21
The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 &lt; t2 &lt; ... &lt; tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.
800
Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.
standard output