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
5d94291a1ff9a6255faa36903cc4dbad
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class Solution{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); while(n-->0){ int a=sc.nextInt(); int b=sc.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
100ba3da6c75012676d338e02e6de7e2
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; import java.io.*; public class abc{ public static void main(String args[]) { Scanner a = new Scanner(System.in); int b = a.nextInt(); while(b-->0) { int c = a.nextInt(),d = a.nextInt(); System.out.println(c+d); } }}
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
db7143ebc9d0f121524f97dd4228f90f
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.Scanner; public class pb2 { public static void main(String args[]) { Scanner in = new Scanner(System.in); int t; t = in.nextInt(); for(int y=1; y<=t; y++) { int a,b; a = in.nextInt(); b = in.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
4e65ba97eaa00c6751f96dd31b2d5399
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); for (int i=0;i<N;i++){ int a = sc.nextInt(); int b = sc.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
ddb65e8761d6a319dadec3fa049cfe80
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class Main { public static void main(String[] args) { Scanner sam = new Scanner(System.in); int t = sam.nextInt(); for(int i=1;i<=t;i++){ int a = sam.nextInt(); int b = sam.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
eceac47410d7e94835c9d488241726a6
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class trial{ public static void main(String args[])throws Exception{ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int a=sc.nextInt(); int b=sc.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
ed7b343bbf16b459fdf75929dafb2667
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class codeforces { public static int check(int n) { for(int i=3;i<=n/2;i++) if(n%i==0) return i; return n; } public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); for(int k=0;k<t;k++) { int b=s.nextInt(); int a=s.nextInt(); System.out.println((a+b)); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
63271c69ad3d52a0ddc995298926aef8
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class file{ public static void main(String[] args){ Scanner s=new Scanner(System.in); int test =s.nextInt(); for(int i=0 ;i<test ;i++){ System.out.println(s.nextInt() + s.nextInt()); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
c1f65174d7336415b9ef02fa30beb037
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class Main{ public static void main(String [] args){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ System.out.println(sc.nextInt()+sc.nextInt()); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
655ed15038c6b12c9bf03625d47cdff4
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class S706B{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int a=sc.nextInt(); int b=sc.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
fbe2733d0a547e53f44c89bb014cb29f
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class Cf1351A { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t,a,b; t=sc.nextInt(); while(t>0) { a=sc.nextInt(); b=sc.nextInt(); System.out.println(a+b); t--; } sc.close(); } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
a8ad5be6870f1a94e0aeb301424483c0
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class Yash { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) System.out.println(sc.nextInt() + sc.nextInt()); } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
7aca273d2f389e9447de3c31be07c830
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.io.InputStreamReader; import java.util.Scanner; public class AplusB { public static void main(String[] args) { Scanner sc=new Scanner(new InputStreamReader(System.in)); int casos= sc.nextInt(); while(casos-->0) { int a=sc.nextInt(); int b=sc.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
92a42d0570ea218797cf7e148e7c207f
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class HelloWorld { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t; t = in.nextInt(); while (t!=0) { int a,b; a=in.nextInt(); b=in.nextInt(); int c=a+b; System.out.println(c); t--; } in.close(); } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
674f6a61142082c0a799c46b9aef8000
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
/* Written by Kabir Kanha Arora @kabirkanha */ import java.util.*; public class Main { static int MOD = 998244353; static long[] fact; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); while (n-- > 0) { int a = scanner.nextInt(); int b = scanner.nextInt(); System.out.println(a + b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
2bf4b6d7621381cb83a4738514bb4e15
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.lang.*; import java.util.*; public class Main { public static void main(String args[]) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t!=0) { int a=s.nextInt(); int b=s.nextInt(); System.out.println(a+b); t--; } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
3327dba64d3e8d6400619a4e6940fc5d
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.Scanner; public class A { public static void main(String main[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); for(int i=0;i<n;i++) { int n1=sc.nextInt(); int n2=sc.nextInt(); int sum=n1+n2; System.out.println(sum); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
efeccad7d16fc74be3aaad98322af025
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class Solution{ static Scanner sc = new Scanner(System.in); public static void main(String[] args){ int t = sc.nextInt(); while(t-->0){ solve(); } } public static void solve(){ System.out.println(sc.nextInt() + sc.nextInt()); } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
0087734b2040ecc977239a917a54270c
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class Solution{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ System.out.println(sc.nextInt() + sc.nextInt()); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
6660ad4d6df8804fea850a8737feebd0
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.io.*; import java.math.*; import java.util.*; import java.text.*; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(new BufferedInputStream(System.in)); int t; t = cin.nextInt(); while (t-- != 0) { int a, b; a = cin.nextInt(); b = cin.nextInt(); System.out.printf("%d\n", a + b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
1fad4d502095456568ae2033d51c3deb
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; import java.lang.*; import java.io.*; import java.util.Scanner; /** * * @author shravan */ public class Main { static boolean prime[]=new boolean[10000001]; public static void sieve() { int n=1000001; for(int i =0;i<n;i++) { prime[i]=true; } for(int p = 2; p*p <=n; p++) { if(prime[p] == true) { for(int i = p*p; i <= n; i += p) prime[i] = false; } } } public static void main(String args[]) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t-->0){ int a =s.nextInt(); int b=s.nextInt(); System.out.println(a+b); } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
164e68c10865219ac93d7b6f8ce39bb8
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.*; public class Main{ public static void main(String[] args){ Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t>0){ int a = scn.nextInt(); int b = scn.nextInt(); System.out.println(a+b); t--; } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
e41c6deed168229ac6b6d6eff0a9c5e3
train_002.jsonl
1624368900
You are given two integers $$$a$$$ and $$$b$$$. Print $$$a+b$$$.
512 MB
import java.util.Scanner; public final class CodeForces { private static void solution(String[] inputs) { for(String input : inputs) { String[] values = input.split(" "); try { System.out.println(Integer.parseInt(values[0]) + Integer.parseInt(values[1])); } catch(Exception e) { } } } public static void main(String[] args) { Scanner in = new Scanner(System.in); try { int count = Integer.parseInt(in.nextLine()); String[] inputs = new String[count]; for(int i = 0; i < count; ++i) { inputs[i] = in.nextLine(); } in.close(); solution(inputs); } catch(Exception e) { } } }
Java
["4\n\n1 5\n\n314 15\n\n-99 99\n\n123 987"]
2.0 s
["6\n329\n0\n1110"]
null
Java 11
standard input
[ "implementation" ]
27ddccc777ef9040284ab6314cbd70e7
The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a line of two integers $$$a$$$ and $$$b$$$ ($$$-1000 \le a, b \le 1000$$$).
800
Print $$$t$$$ integers — the required numbers $$$a+b$$$.
standard output
PASSED
6ea0605bc3232e6d2f6b9896a082c732
train_002.jsonl
1395502200
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process. Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int size = Integer.parseInt(scanner.nextLine()); String input = scanner.nextLine(); boolean lastLeft = true; int numStanding = 0; int counter = 0; for (int i = 0; i < input.length(); i++) { switch (input.charAt(i)) { case 'L': // Special case cause starts with left if (!lastLeft) { numStanding += (counter%2); // Add one if odd } counter = 0; lastLeft = true; break; case 'R': numStanding += counter; counter = 0; lastLeft = false; break; case '.': counter++; break; default: } } if (lastLeft) { numStanding += counter; } System.out.println(numStanding); } }
Java
["14\n.L.R...LR..L..", "5\nR....", "1\n."]
1 second
["4", "0", "1"]
NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.
Java 11
standard input
[]
54c748dd983b6a0ea1af1153d08f1c01
The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to "L", if the i-th domino has been pushed to the left; "R", if the i-th domino has been pushed to the right; ".", if the i-th domino has not been pushed. It is guaranteed that if si = sj = "L" and i &lt; j, then there exists such k that i &lt; k &lt; j and sk = "R"; if si = sj = "R" and i &lt; j, then there exists such k that i &lt; k &lt; j and sk = "L".
1,100
Output a single integer, the number of the dominoes that remain vertical at the end of the process.
standard output
PASSED
d058efc731fd029c8746342b152485b8
train_002.jsonl
1395502200
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process. Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class ar { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) throws java.lang.Exception { FastReader scn = new FastReader(); int n=scn.nextInt(); char[] arr=scn.next().toCharArray(); for(int i=0;i<n;i++){ if(arr[i]=='R'){ arr[i]='r'; int j=i+1; for(;j<n;j++){ if(arr[j]=='L'){ break; } arr[j]='r'; } if(j<n){ arr[j]='r'; if((j-i+1)%2==1){ arr[(j+i)/2]='.'; } } }else if(arr[i]=='L'){ for(int j=i;j>=0;j--){ if(arr[j]=='r')break; arr[j]='L'; } } } int count = 0; for(int i=0;i<n;i++){ if(arr[i]=='.')count++; } System.out.println(count); } }
Java
["14\n.L.R...LR..L..", "5\nR....", "1\n."]
1 second
["4", "0", "1"]
NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.
Java 11
standard input
[]
54c748dd983b6a0ea1af1153d08f1c01
The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to "L", if the i-th domino has been pushed to the left; "R", if the i-th domino has been pushed to the right; ".", if the i-th domino has not been pushed. It is guaranteed that if si = sj = "L" and i &lt; j, then there exists such k that i &lt; k &lt; j and sk = "R"; if si = sj = "R" and i &lt; j, then there exists such k that i &lt; k &lt; j and sk = "L".
1,100
Output a single integer, the number of the dominoes that remain vertical at the end of the process.
standard output
PASSED
cbce0416f2d13993ea16fe136ae79a8a
train_002.jsonl
1395502200
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process. Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!
256 megabytes
import java.io.*; import java.util.*; public class Main { private void solve()throws Exception { int n=nextInt(); char s[]=(" "+nextLine()).toCharArray(); int cnt=n; int i=1; while(i<=n && (s[i]!='L' && s[i]!='R')) i++; if(i<=n && s[i]=='L') { cnt-=i; i++; } for(;i<=n;i++) { if(s[i]=='R') { int trail=0; while(i<=n && s[i]!='L') { trail++; cnt--; i++; } if(i==n+1) break; if(s[i]=='L') { trail++; cnt--; } if(trail%2!=0) cnt++; } } out.println(cnt); } /////////////////////////////////////////////////////////// public void run()throws Exception { br=new BufferedReader(new InputStreamReader(System.in)); st=null; out=new PrintWriter(System.out); solve(); br.close(); out.close(); } public static void main(String args[])throws Exception{ new Main().run(); } BufferedReader br; StringTokenizer st; PrintWriter out; String nextToken()throws Exception{ while(st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine()throws Exception{ return br.readLine(); } int nextInt()throws Exception{ return Integer.parseInt(nextToken()); } long nextLong()throws Exception{ return Long.parseLong(nextToken()); } double nextDouble()throws Exception{ return Double.parseDouble(nextToken()); } }
Java
["14\n.L.R...LR..L..", "5\nR....", "1\n."]
1 second
["4", "0", "1"]
NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.
Java 11
standard input
[]
54c748dd983b6a0ea1af1153d08f1c01
The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to "L", if the i-th domino has been pushed to the left; "R", if the i-th domino has been pushed to the right; ".", if the i-th domino has not been pushed. It is guaranteed that if si = sj = "L" and i &lt; j, then there exists such k that i &lt; k &lt; j and sk = "R"; if si = sj = "R" and i &lt; j, then there exists such k that i &lt; k &lt; j and sk = "L".
1,100
Output a single integer, the number of the dominoes that remain vertical at the end of the process.
standard output
PASSED
e324fddc38eab9db9613cf4ee5b27dd0
train_002.jsonl
1395502200
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process. Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!
256 megabytes
import java.util.*; public class Domino { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int len = Integer.parseInt(scan.nextLine()); String dominoes = scan.nextLine(); int index = 0; int right = -1; int count = 0; int total = 0; int last = 0; while (index < dominoes.length()) { if (dominoes.charAt(index) == 'L' ) { count = 0; if (right != -1) { int diff = index - right; diff -= 1; total += diff % 2; } last = 0; } else if (dominoes.charAt(index) == 'R') { right = index; total += count; count = 0; last = 1; } else { count++; } index++; } if (last == 0) { total += count; } // System.out.println(count); System.out.println(total); } }
Java
["14\n.L.R...LR..L..", "5\nR....", "1\n."]
1 second
["4", "0", "1"]
NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.
Java 11
standard input
[]
54c748dd983b6a0ea1af1153d08f1c01
The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to "L", if the i-th domino has been pushed to the left; "R", if the i-th domino has been pushed to the right; ".", if the i-th domino has not been pushed. It is guaranteed that if si = sj = "L" and i &lt; j, then there exists such k that i &lt; k &lt; j and sk = "R"; if si = sj = "R" and i &lt; j, then there exists such k that i &lt; k &lt; j and sk = "L".
1,100
Output a single integer, the number of the dominoes that remain vertical at the end of the process.
standard output
PASSED
ba0cc0393f981905c5a1bec758922324
train_002.jsonl
1395502200
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process. Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!
256 megabytes
/* -------> Bismillahir Rahmanir Rahim <------*/ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class A { private static final FastScanner in = new FastScanner(); // private static final Scanner in = new Scanner(System.in); public static void main(String[] args) { String s; int n; n = in.nextInt(); s = in.next(); int l = -1, r = -1, ans = 0; for (int i = 0; i < n; ++i) { if (s.charAt(i) == 'L') { l = i; } else if (s.charAt(i) == 'R') { r = i; } if (s.charAt(i) == 'L' || s.charAt(i) == 'R') { if (r > l) { ans += r - l - 1; } else { if (r != -1 && (l - r) % 2 == 0) { ans += 1; } } } } if (l != n - 1 && l > r) { ans += n - l - 1; } if (l == -1 && r == -1) { ans += n; } System.out.println(ans); } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["14\n.L.R...LR..L..", "5\nR....", "1\n."]
1 second
["4", "0", "1"]
NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.
Java 11
standard input
[]
54c748dd983b6a0ea1af1153d08f1c01
The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to "L", if the i-th domino has been pushed to the left; "R", if the i-th domino has been pushed to the right; ".", if the i-th domino has not been pushed. It is guaranteed that if si = sj = "L" and i &lt; j, then there exists such k that i &lt; k &lt; j and sk = "R"; if si = sj = "R" and i &lt; j, then there exists such k that i &lt; k &lt; j and sk = "L".
1,100
Output a single integer, the number of the dominoes that remain vertical at the end of the process.
standard output
PASSED
2ac73a26b38fcd53591001b89c3c746c
train_002.jsonl
1395502200
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process. Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Arrays; import java.util.Iterator; import java.util.InputMismatchException; import java.io.IOException; 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; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BDominoEffect solver = new BDominoEffect(); solver.solve(1, in, out); out.close(); } static class BDominoEffect { public void solve(int testNumber, FastReader s, PrintWriter out) { int n = s.nextInt(); char[] str = s.nextString().toCharArray(); HashSet<Integer> left = new HashSet<>(); HashSet<Integer> right = new HashSet<>(); int[] time = new int[n]; Arrays.fill(time, -1); for (int i = 0; i < n; i++) { if (str[i] == 'L') { left.add(i); time[i] = 0; } else if (str[i] == 'R') { right.add(i); time[i] = 0; } } int time1 = 1; while (!left.isEmpty() || !right.isEmpty()) { Iterator<Integer> iter = left.iterator(); HashSet<Integer> set = new HashSet<>(); while (iter.hasNext()) { int curr = iter.next(); if (right.contains(curr - 2)) { right.remove(curr - 2); } else { if (curr - 1 >= 0 && time[curr - 1] == -1) { time[curr - 1] = time1; set.add(curr - 1); } } } left = new HashSet<>(set); set.clear(); iter = right.iterator(); while (iter.hasNext()) { int curr = iter.next(); if (curr + 1 < n && time[curr + 1] == -1) { time[curr + 1] = time1; set.add(curr + 1); } } right = set; time1++; } int count = 0; for (int i = 0; i < n; i++) { if (time[i] == -1) { count++; } } out.println(count); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["14\n.L.R...LR..L..", "5\nR....", "1\n."]
1 second
["4", "0", "1"]
NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.
Java 11
standard input
[]
54c748dd983b6a0ea1af1153d08f1c01
The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to "L", if the i-th domino has been pushed to the left; "R", if the i-th domino has been pushed to the right; ".", if the i-th domino has not been pushed. It is guaranteed that if si = sj = "L" and i &lt; j, then there exists such k that i &lt; k &lt; j and sk = "R"; if si = sj = "R" and i &lt; j, then there exists such k that i &lt; k &lt; j and sk = "L".
1,100
Output a single integer, the number of the dominoes that remain vertical at the end of the process.
standard output
PASSED
84d78ce6a7883cad20cff0e94b7b815b
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { try (BufferedInputStream in = new BufferedInputStream(System.in); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out))) { Scanner sc = new Scanner(in); int T = sc.nextInt(); for (int t = 0; t < T; t++) { int n = sc.nextInt(); int[] vs = new int[n]; for (int i = 0; i < vs.length; i++) vs[i] = sc.nextInt(); int first = n; int last = -1; for (int i = 0; i < vs.length; i++) { if (vs[i] == 1) { first = Math.min(first, i); last = Math.max(last, i); } } int ret = 0; for (int i = 0; i < vs.length; i++) { if (first <= i && i <= last) { if (vs[i] == 0) ret++; } } out.println(ret); } } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
009b23edd0ce44a306592070d0a99c9a
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.lang.System; import java.util.Scanner; import java.lang.Math; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t>0){ int n=s.nextInt(); int []a=new int[n]; int count1=0; int count2=0; int count3=0; int l,r; l=0;r=0; boolean contiguous=true; boolean c=false; boolean b=false; for(int i=0;i<n;i++){ a[i]=s.nextInt(); if(c && b && a[i]==1){ contiguous=false; } else if(a[i]==1 && !c){ c=true; l=i; } else if(a[i]==0 && c){ b=true; } if(a[i]==1){ r=i; } } boolean count=false; for(int i=0;i<n;i++){ if(count && a[i]==0){ count1++; } else if(a[i]==1){ count=true; } } count=false; for(int i=n-1;i>=0;i--){ if(count&&a[i]==0){ count2++; } else if(a[i]==1){ count=true; } } for(int i=l;i<=r;i++){ if(a[i]==0){ count3++; } } if(contiguous){ System.out.println(0); } else if(count1>count2 && count2<count3){ System.out.println(count2); } else if(count1<count2&&count1<count3){ System.out.println(count1); } else{ System.out.println(count3); } t--; } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
429c39c2fe58090c7e41a869ad0020a2
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class B { public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); for(int tt =0 ;tt < t ; tt++) { int n = sc.nextInt(); int a[] = sc.readArray(n); int i = 0 ; int j = n -1; while(a[i] != 1) { i++; } while(a[j] != 1)j--; int count = 0; for(;i<j;i++) { if(a[i] == 0) { count++; } } System.out.println(count); } } public void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
1126a593c877879bb5a99c65540311d6
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; import java.util.Arrays; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); for(int t=input.nextInt();t>0;t--){ int i=input.nextInt(); int a[]=new int[i]; int sum=0; for(int j=0;j<i;j++) { a[j]=input.nextInt(); } for(int n:a) { if(n==1)sum++; } if(sum==1) {System.out.println("0");continue;} int b[]=new int[sum]; int min=0; int max=0; for(int k=0;k<i;k++) { if(a[k]==1) {min=k;break;} } for(int k=0;k<i;k++) { if(a[k]==1) max=Math.max(max, k); } System.out.println(max-min+1-sum); } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
7fb60663184dc304e871407cc64ded50
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t--!=0){ int a=sc.nextInt(), l=0,r=a-1,count=0; int[] arr = new int[a]; for(int i=0;i<a;i++){arr[i]= sc.nextInt();} for(int i=0;i<a;i++){if(arr[i]==0)l++;if(arr[i]==1)break;} for(int i=a-1;i>=0;i--){if(arr[i]==0)r--;if(arr[i]==1)break;} for(int i=l;i<=r;i++){if(arr[i]==0)count++;} System.out.println(count); } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
6e628c41695eb1132999587561df2739
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class prob { public static void main(String args[]) { Scanner d=new Scanner(System.in); int t,n,flag=0,k=0,m=0,i,j; t=d.nextInt(); while(t>0) { flag=0; k=0; m=0; j=0; n=d.nextInt(); int a[]=new int[n]; for(i=0;i<n;i++) { a[i]=d.nextInt(); } for(i=0;i<n;i++) { if(a[i]==1) { if(flag==0) { flag=1; continue; } } if(flag==1 && a[i]==0) { m++; } if(flag==1 && a[i]==1) { k++; } } for(i=n-1;i>=0;i--) { if(a[i]==1) { break; } else { j++; } } if(flag==1 && k==0) System.out.println(0); else if(flag==1 && m>0) System.out.println(m-j); else System.out.println(0); t--; } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
a00ada1def36b3906070faa7059e594d
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class October_virtual { public static void main(String args[]) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); StringBuilder sb=new StringBuilder(); while(t>0){ int n=Integer.parseInt(br.readLine()); String str[]=br.readLine().split(" "); int sum=0; int arr[]=new int[n]; for(int i=0;i<n;i++){ arr[i]=Integer.parseInt(str[i]); } int begin_index=0; int end_index=0; for(int i=0;i<n;i++){ if(arr[i]==1){ begin_index=i; break; } } for(int i=n-1;i>=0;i--){ if(arr[i]==1){ end_index=i; break; } } if(end_index==begin_index && n!=1) sb.append("0").append('\n'); else if(end_index==begin_index && n==1) sb.append("0").append('\n'); else{ for(int i=begin_index;i<=end_index;i++){ if(arr[i]==0) sum++; } sb.append(sum).append('\n'); } t--;} System.out.println(sb); } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
5ebadc00d4d4cbf8156736ae44eec18b
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); int tc = s.nextInt(); for(int t = 0;t < tc;t++) { int n = s.nextInt(); int[] input = new int[n]; for(int i = 0;i < n;i++) input[i] = s.nextInt(); int start = 0; int end = 0; int total = 0; boolean st = false; for(int i = 0;i < n;i++) { if(input[i] == 0) { total++; if(!st) start++; } else { st = true; } } for(int i = n - 1;i >= 0;i--) { if(input[i] == 1) break; end++; } //System.out.println(total + " " + start + " " + end); total -= (start + end); System.out.println(total); } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
7b41770f14bf1dad7b527f06b3011f57
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; public class B { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); String[] in = br.readLine().split(" "); int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) { arr[i] = Integer.parseInt(in[i]); } int firstOne = 0; int lastOne = arr.length; for (int i = 0; i < arr.length; i++) { if (arr[i] == 1) { firstOne = i; break; } } for (int i = arr.length - 1; i >= 0; i--) { if(arr[i] == 1) { lastOne = i; break; } } if (firstOne == lastOne) { System.out.println(0); }else { int count = 0; for (int i = firstOne; i <= lastOne; i++) { if (arr[i] == 0) { count++; } } System.out.println(count); } } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
5c6e0b2c83d4436cc27eba15380fe658
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import javax.crypto.AEADBadTagException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.nio.BufferOverflowException; import java.util.*; public class Main { public static void main(String[] args) throws IOException { int n, N, summ; boolean inside = false; ArrayList<Integer> A = new ArrayList<>(); Scanner reader = new Scanner(System.in); N = reader.nextInt(); for (int i = N; i > 0; i--) { summ = 0; n = reader.nextInt(); for (int j = n; j > 0; j--){ A.add(reader.nextInt()); } for (int it = 1;it<A.size();it++){ if (inside && A.get(it) == 0){ summ++; } else if (it==A.lastIndexOf(1)){ inside = false; break; } else { inside = false; } if (A.get(it) == 0 && A.get(it-1) == 1){ summ++; inside = true; } } if(A.indexOf(1)==A.lastIndexOf(1)){ System.out.println(0); } else if(inside){ System.out.println(summ-1);} else { System.out.println(summ); } A.clear(); } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
ae948cbc849200d9ceeefb44794e36a0
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { static void iPA(int arr []){ for(int i=0; i<arr.length; i++){ System.out.print(arr[i] + " "); } System.out.println(); } static void lPA(long arr []){ for(int i=0; i<arr.length; i++){ System.out.print(arr[i] + " "); } System.out.println(); } static void sPA(String arr []){ for(int i=0; i<arr.length; i++){ System.out.print(arr[i] + " "); } System.out.println(); } static void dPA(double arr []){ for(int i=0; i<arr.length; i++){ System.out.print(arr[i] + " "); } System.out.println(); } static void iIA(FastReader reader, int arr[]){ for(int i=0; i<arr.length; i++){ arr[i] = reader.nextInt(); } } static void lIA(FastReader reader, long arr[]){ for(int i=0; i<arr.length; i++){ arr[i] = reader.nextLong(); } } static void sIA(FastReader reader, String arr[]){ for(int i=0; i<arr.length; i++){ arr[i] = reader.next(); } } static void dIA(FastReader reader, double arr[]){ for(int i=0; i<arr.length; i++){ arr[i] = reader.nextDouble(); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main (String[] args) throws java.lang.Exception { // your code goes here FastReader reader = new FastReader(); int t = reader.nextInt(); while(t-->0){ int n = reader.nextInt(); int arr[] = new int[n]; for(int i=0; i<n; i++){ arr[i] = reader.nextInt(); } int sum=0,first=0, last=0; for(int i=0; i<n; i++){ if(arr[i]==1) break; else first++; } for(int i=0; i<n; i++){ if(arr[i]==0) sum++; } for(int i=n-1; i>=0; i--){ if(arr[i]==1) break; else last++; } System.out.println(sum - first - last); } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
c37934af7bb66d178dcaf11208b440f8
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; public class test { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int numTest=sc.nextInt(); int counter=0; int[] output=new int[numTest]; while (counter<numTest) { int size=sc.nextInt(); int[] array=new int[size]; int check=0; int oneFound=0; int count = 0; int i=0; while(i<size) { int term=sc.nextInt(); array[i]=term; if(term==1 && check==0) { check=1; } else if(term==0 && check==1) { if(term==0 ) { i++; count++; while(i<size) { term=sc.nextInt(); array[i]=term; if(term==0) { count++; } else { i++; oneFound=1; break; } i++; } if(oneFound==1) { i--; output[counter]+=count; count=0; oneFound=0; } } } i++;} counter++; } for(int j=0;j<numTest;j++) { System.out.println(output[j]); } }}
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
d7c08d7177fbbcb8781b37ccff3042ca
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class Codeforces { static void sort(int[] ar) { ArrayList<Integer> al=new ArrayList<>(); for (int i=0;i<ar.length;i++) al.add(ar[i]); Collections.sort(al); for (int i=0; i<ar.length; i++) ar[i]=al.get(i); } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); int s=0; int fs=0; int i=0; boolean flag=false; for(i=0;i<n;) { s=0; if(a[i]==1) { i++; while(i<n&&a[i]==0) { s++; i++; } if(i==n) s=0; } else i++; fs+=s; } System.out.println(fs); } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
1457a2e25d6921809877941fc2ef5947
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; public class Hackerrank { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int c=0,d=0,sifirsayi=0; int cases= scan.nextInt(); int a=cases; int elemansayi; int sonuc[]= new int[57]; for(int h=0;h<a;h++) { elemansayi= scan.nextInt(); int array[]= new int[57]; for(int x=0;x<elemansayi;x++) { array[x]= scan.nextInt(); } int tersarray[] = new int[57]; for(int i=0;i<elemansayi;i++) { tersarray[i]=array[elemansayi-1-i]; } while(array[d]==0) { d++; if(d>51) { break; } } while(tersarray[c]==0) { c++; if(c>51) { break; } } int son1= elemansayi-1-c; int ilk1 = d; for(int g=ilk1;g<=son1;g++) { if(array[g]==0) { sifirsayi++; } } System.out.println(sifirsayi); sifirsayi = 0; c=0; d=0; //System.out.println("son1:"+son1+" ilk1:"+ilk1); } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
d87fc50efd1e021a4d9a751f81e9f97b
train_002.jsonl
1603204500
There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and: Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$. Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; public class B { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); // System.out.println("t" + t); for (int t_ = 0; t_ < t; t_++){ int n = in.nextInt(); // System.out.println("n" + n); int firstOne = -1; int lastOne = -1; int counterZeros = 0; int[] aa = new int[n]; for (int i = 0; i < n; i++) { int newInt = in.nextInt(); aa[i] = newInt; if (firstOne == -1 && newInt == 1) { firstOne = i; } else if (firstOne != -1 && newInt == 0) { counterZeros++; } else if (firstOne != -1 && newInt == 1) { lastOne = i; } } counterZeros = 0; for (int i = firstOne; i < lastOne; i++) { if (aa[i] == 0) { counterZeros++; } } // System.out.println("firstOne " + firstOne); // System.out.println("lastOne " + lastOne); if (lastOne == -1) { System.out.println("0"); } else { System.out.println(counterZeros); } } } }
Java
["5\n7\n0 0 1 0 1 0 1\n3\n1 0 0\n5\n1 1 0 0 1\n6\n1 0 0 0 0 1\n5\n1 1 0 1 1"]
1 second
["2\n0\n2\n4\n1"]
NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.
Java 11
standard input
[ "implementation", "greedy" ]
1c07882651ef6ebfc05e777d562e28b9
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.
800
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
standard output
PASSED
a2f77d36e22145f3043105fb99062ba4
train_002.jsonl
1425279600
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t): where is obtained from string s, by applying left circular shift i times. For example, ρ("AGC", "CGT") =  h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") +  h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") +  h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") =  1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: .Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 109 + 7.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int arr[], N, K; static boolean adj[][]; static BigInteger dp[][]; static boolean reach[][]; static String str1[]; static String str2[]; static int mod =(int) (1e9 + 7); public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = sc.nextLine(); Map<Character,Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0)+1); int max = 0; int freq = 0; for(Map.Entry<Character,Integer> entry : map.entrySet()) if(entry.getValue() > max){ max = entry.getValue(); freq = 1; }else if(entry.getValue() == max) freq++; System.out.println(modulo(freq,n,mod)); } static int modulo(int a,int b,int c) { long x=1; long y=a; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return (int) x%c; } static class Point { int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } }; // Given three colinear points p, q, r, the function checks if // point q lies on line segment 'pr' static boolean onSegment(Point p, Point q, Point r) { if (q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y)) return true; return false; } // To find orientation of ordered triplet (p, q, r). // The function returns following values // 0 --> p, q and r are colinear // 1 --> Clockwise // 2 --> Counterclockwise static int orientation(Point p, Point q, Point r) { // See https://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // colinear return (val > 0)? 1: 2; // clock or counterclock wise } // The main function that returns true if line segment 'p1q1' // and 'p2q2' intersect. static boolean doIntersect(Point p1, Point q1, Point p2, Point q2) { // Find the four orientations needed for general and // special cases int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and q2 are colinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases } 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(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public String nextLine() throws IOException {return br.readLine();} public long nextLong() throws IOException {return Long.parseLong(next());} public boolean ready() throws IOException {return br.ready();} 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 = Integer.parseInt(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Integer.parseInt(sb.toString()) / f; return res * (neg?-1:1); } } }
Java
["1\nC", "2\nAG", "3\nTTT"]
2 seconds
["1", "4", "1"]
NotePlease note that if for two distinct strings t1 and t2 values ρ(s, t1) и ρ(s, t2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.In the first sample, there is ρ("C", "C") = 1, for the remaining strings t of length 1 the value of ρ(s, t) is 0.In the second sample, ρ("AG", "AG") = ρ("AG", "GA") = ρ("AG", "AA") = ρ("AG", "GG") = 4.In the third sample, ρ("TTT", "TTT") = 27
Java 11
standard input
[ "math", "strings" ]
f35c042f23747988f65c5b5e8d5ddacd
The first line of the input contains a single integer n (1 ≤ n ≤ 105). The second line of the input contains a single string of length n, consisting of characters "ACGT".
1,500
Print a single number — the answer modulo 109 + 7.
standard output
PASSED
eecea7cc17a1c33a99a68d8e821a7a4a
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); char[][] grid = new char[n][m]; for (int i = 0; i < n; i++) grid[i] = sc.next().toCharArray(); SegmentTree st = new SegmentTree(n + 1); long ans = 0; for (int j = 0; j < m; j++) { for (int i = 0; i < n; i++) { if (j != 0 && grid[i][j - 1] == grid[i][j]) st.update(i, st.pointQuery(i) + 1); else st.update(i, 1); } ArrayList<Pair> compressed = new ArrayList<>(); for (int i = 0; i < n; ) { int k = i; int cnt = 0; while (k < n && grid[k][j] == grid[i][j]) { cnt++; k++; } compressed.add(new Pair(i, cnt)); i =k; } for (int k = 0; k < compressed.size() - 2; k++) { Pair first = compressed.get(k); Pair mid = compressed.get(k + 1); Pair last = compressed.get(k + 2); if (first.val < mid.val || last.val < mid.val) continue; int left = mid.idx - mid.val; int right = last.idx + mid.val - 1; ans += st.query(left, right); } } out.println(ans); out.flush(); out.close(); } static class Pair { int idx, val; public Pair(int idx, int val) { this.idx = idx; this.val = val; } @Override public String toString() { return "Pair{" + "idx=" + idx + ", val=" + val + '}'; } } static class SegmentTree { static final int INF = (int) 1e9; int N, sTree[]; public SegmentTree(int n) { N = 1; while (N < n) N <<= 1; sTree = new int[N << 1]; } void update(int idx, int val) { idx += N; sTree[idx] = val; while (idx > 0) { idx >>= 1; sTree[idx] = Math.min(sTree[idx << 1], sTree[idx << 1 | 1]); } } int pointQuery(int idx) { idx += N; return sTree[idx]; } int query(int i, int j) { return query(1, 1, N, i + 1, j + 1); } int query(int node, int b, int e, int i, int j) { if (i > e || j < b) return INF; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; int left = query(node << 1, b, mid, i, j); int right = query(node << 1 | 1, mid + 1, e, i, j); return Math.min(left, right); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } 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 int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
2a485f145a6e2fb3671ef618d9f4ab16
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.*; import java.util.*; public class CP { public static void main(String[] args) throws Exception { /*new Thread(null, new Runnable() { @Override public void run() { try { new Solver().solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }, "Solver", 1l << 30).start();*/ new Solver().solve(); } } class Solver { IO io = new IO(System.in, System.out); int R, C; char[][] color; void solve() throws Exception { int i, j, k; R = io.nextInt(); C = io.nextInt(); color = new char[R][]; for (i = 0; i < R; ++i) { color[i] = io.next().toCharArray(); } int[][] nextCol = new int[R][C]; for (i = 0; i < R; ++i) { Stack<Integer> ar = new Stack<>(); for (j = 0; j < C; ++j) { if (!ar.isEmpty() && color[i][ar.peek()] != color[i][j]) { while (!ar.isEmpty()) nextCol[i][ar.pop()] = j; } ar.add(j); } while (!ar.isEmpty()) nextCol[i][ar.pop()] = j; } int[][] nextRow = new int[R][C]; for (j = 0; j < C; ++j) { Stack<Integer> ar = new Stack<>(); for (i = 0; i < R; ++i) { if (!ar.isEmpty() && color[ar.peek()][j] != color[i][j]) { while (!ar.isEmpty()) nextRow[ar.pop()][j] = i; } ar.add(i); } while (!ar.isEmpty()) nextRow[ar.pop()][j] = i; } int[][] bottomup = new int[R][C], topdown = new int[R][C]; for (i = 0; i < R; ++i) for (j = 0; j < C; ++j) { if (i > 0 && color[i][j] == color[i - 1][j]) topdown[i][j] = Math.min(nextCol[i][j], topdown[i - 1][j]); else topdown[i][j] = nextCol[i][j]; } for (i = R - 1; i >= 0; --i) for (j = 0; j < C; ++j) { if (i + 1 < R && color[i][j] == color[i + 1][j]) bottomup[i][j] = Math.min(nextCol[i][j], bottomup[i + 1][j]); else bottomup[i][j] = nextCol[i][j]; } long ans = 0; for (i = 0; i < R; ++i) for (j = 0; j < C; ++j) { int next1 = nextRow[i][j]; if (next1 >= R) continue; int next2 = nextRow[next1][j]; if (next2 >= R) continue; int next3 = Math.min(nextRow[next2][j], 2 * next2 - next1); if (next3 - next2 != next2 - next1 || next2 - next1 != next1 - i) continue; int nextC = Math.min(bottomup[i][j], Math.min(bottomup[next1][j], topdown[next3 - 1][j])); ans += nextC - j; } io.println(ans); /*for (i = 0; i < R; ++i) System.out.println(Arrays.toString(nextCol[i])); System.out.println(); /*for (i = 0; i < R; ++i) System.out.println(Arrays.toString(topdown[i])); System.out.println();*/ io.flush(); } } class IO { static byte[] buf = new byte[2048]; static int index, total; static InputStream in; static BufferedWriter bw; IO(InputStream is, OutputStream os) { try { in = is; bw = new BufferedWriter(new OutputStreamWriter(os)); } catch (Exception e) { } } IO(String inputFile, String outputFile) { try { in = new FileInputStream(inputFile); bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputFile))); } catch (Exception e) { } } int scan() throws Exception { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } String next() throws Exception { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) sb.append((char) c); return sb.toString(); } int nextInt() throws Exception { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') c = scan(); for (; c >= '0' && c <= '9'; c = scan()) val = (val << 3) + (val << 1) + (c & 15); return neg ? -val : val; } long nextLong() throws Exception { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') c = scan(); for (; c >= '0' && c <= '9'; c = scan()) val = (val << 3) + (val << 1) + (c & 15); return neg ? -val : val; } void print(Object a) throws Exception { bw.write(a.toString()); } void printsp(Object a) throws Exception { print(a); bw.write(" "); } void println() throws Exception { bw.write("\n"); } void println(Object a) throws Exception { print(a); println(); } void flush() throws Exception { bw.flush(); bw.close(); } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
306e04004e982bcd6eef71645ca5172d
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.*; import java.util.*; public class Solution { static int[][] arr; static int[][][] flagPoint; // mark start of flag part static int[][] length; static int n; public static void compress(int col) { ArrayList<Integer> data = new ArrayList<>(); ArrayList<Integer> start = new ArrayList<>(); ArrayList<Integer> end = new ArrayList<>(); int i = 0; while (i < n) { int j = i; while (j < n && arr[j][col] == arr[i][col]) j++; j--; data.add(arr[i][col]); start.add(i); end.add(j); i = j + 1; } for (i = 0; i < data.size() - 2; i++) { int a = end.get(i) - start.get(i) + 1; int b = end.get(i + 1) - start.get(i + 1) + 1; int c = end.get(i + 2) - start.get(i + 2) + 1; if (b > a || b > c) continue; length[start.get(i + 1)][col] = b; flagPoint[start.get(i + 1)][col][0] = data.get(i); flagPoint[start.get(i + 1)][col][1] = data.get(i + 1); flagPoint[start.get(i + 1)][col][2] = data.get(i + 2); } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); n = sc.nextInt(); int m = sc.nextInt(); arr = new int[n][m]; length = new int[n][m]; flagPoint = new int[n][m][3]; for (int i = 0; i < n; i++) { String s = sc.nextLine(); for (int j = 0; j < m; j++) { arr[i][j] = s.charAt(j); } } for (int i = 0; i < m; i++) { compress(i); } int j = 0; long ans = 0; for (int row = 0; row < n; row++) { int i = 0; while (i < m) { if (length[row][i] > 0) { j = i; while (j < m && length[row][i] == length[row][j] && flagPoint[row][i][0] == flagPoint[row][j][0] && flagPoint[row][i][1] == flagPoint[row][j][1] && flagPoint[row][i][2] == flagPoint[row][j][2]) j++; j--; long temp = j - i + 1; ans += (temp * (temp + 1)) / 2; i = j; } i++; } } System.out.println(ans); } static class Pair { int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System) throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(System)); } 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() { for (long i = 0; i < 3e9; i++) ; } } static class Edge implements Comparable<Edge> { int to; int index; int w; public Edge(int to, int index, int w) { this.to = to; this.index = index + 1; this.w = w; } @Override public int compareTo(Edge o) { return this.w - o.w; } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
160e107c94c6291a130385e5f66c6c5b
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringJoiner; import java.util.StringTokenizer; import java.util.function.Function; public class MainC { static int H, W; static char[][] B; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); H = sc.nextInt(); W = sc.nextInt(); B = new char[H][]; for (int i = 0; i < H; i++) { B[i] = sc.next().toCharArray(); } System.out.println(solve()); } static long solve() { int[][] C = new int[H][W]; for (int w = 0; w < W; w++) { C[H-1][w] = 1; for (int h = H-2; h >= 0; h--) { if( B[h][w] == B[h+1][w] ) { C[h][w] = C[h+1][w]+1; } else { C[h][w] = 1; } } } long ans = 0; int[][] D = new int[H][W]; for (int h = 0; h < H; h++) { for (int w = 0; w < W; w++) { int c = C[h][w]; if( inRange(h-c, w) && C[h-c][w] == c && inRange(h+c, w) && C[h+c][w] >= c ) { if( inRange(h, w-1) && D[h][w-1] > 0 && C[h][w-1] == c && B[h][w] == B[h][w-1] && B[h+c][w] == B[h+c][w-1] && B[h-c][w] == B[h-c][w-1] ) { D[h][w] = D[h][w-1] + 1; ans += D[h][w]; } else { D[h][w] = 1; ans++; } } } } return ans; } static boolean inRange(int h, int w) { return 0 <= h && h < H && 0 <= w && w < W; } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static <A> void writeLines(A[] as, Function<A, String> f) { PrintWriter pw = new PrintWriter(System.out); for (A a : as) { pw.println(f.apply(a)); } pw.flush(); } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
13b874b39e45ab23a739432d3e143896
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.ArrayList; public class CFlag { public static void main(String[] args)throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String [] input = br.readLine().split(" "); int n = Integer.parseInt(input[0]); int m = Integer.parseInt(input[1]); char [][]flag = new char[n][m]; for(int i=0;i<n;i++){ String st = br.readLine(); for(int j =0;j<m;j++){ flag[i][j] = st.charAt(j); } } char [][]mark = new char[n][m]; int [][]value = new int[n][m]; int [][]amount = new int[n][m]; for(int j=0;j<m;j++){ char cur = flag[n-1][j]; int c=0; for(int i = n-1;i>=0;i--){ if (flag[i][j]==cur) { c++; amount[i][j]=c; } else{ cur =flag[i][j]; c=1; amount[i][j]=1; } } } int col = 0; while(col<m){ int row =0; while (row<n){ // System.out.println("row:"+row); int jump = amount[row][col];int n2=row+jump;int n3=row+2*jump; // System.out.println("row"+row+":"+jump+":"+n2+":"+n3); if (n2<n & n3<n ){ if(amount[n2][col]==jump&amount[n3][col]>=jump) { // return ((1 << 15) * l) + ((1 << 10) * ord(c1)) + ((1 << 5) * ord(c2)) + ((1 << 0) * ord(c3)) int a = 1; a<<=15; int b =1; b<<=10; int c=1 ;c<<=5; int object = a*jump+(int)flag[row][col]*b+(int)flag[n2][col]*c+(int)flag[n3][col]; object+=(int)flag[row][col]; value[row][col] = object; // System.out.println(" found row "+row+"Col"+col ); row=n2; } else row++; } else row++; } col++; } int ans =0; for(int i=0;i<n;i++){ int v = value[i][0]; int same =0; for(int j=0;j<m;j++){ if (v== value[i][j] &v !=0) same++; else { ans += same*(same+1)/2; v = value[i][j]; if (v!=0) same=1; else same =0; } } ans += same*(same+1)/2; } System.out.println(ans); // printInt(amount,n,m); // System.out.println("--------------------------------------------------------"); // printInt(value,n,m); // printArray(flag,n,m); } static void printChar(char[][]a ,int r ,int c){ for(int i=0;i<r;i++){ for (int j =0;j<c;j++){ System.out.print(a[i][j]+" "); } System.out.println(); } } static void printInt(int [][]a ,int r ,int c){ for(int i=0;i<r;i++){ for (int j =0;j<c;j++){ System.out.print(a[i][j]+" "); } System.out.println(); } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
f371f7dc5703ced29bf428a701a144cb
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static int count(int counts[][][], char ch, int startx, int starty, int endx, int endy) { int idx = ch - 'a'; int res = counts[endx][endy][idx]; if (startx - 1 >= 0) { res -= counts[startx - 1][endy][idx]; } if (starty - 1 >= 0) { res -= counts[endx][starty - 1][idx]; } if (startx - 1 >= 0 && starty - 1 >= 0) { res += counts[startx - 1][starty - 1][idx]; } return res; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int n = scanner.nextInt(); int m = scanner.nextInt(); List<String> grids = new ArrayList<String>(); for (int i = 0; i < n; i++) { grids.add(scanner.next()); } int counts[][][] = new int[n][m][26]; int last[][] = new int[n][m]; int good[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int k = 'a'; k <= 'z'; k++) { if (grids.get(i).charAt(j) == k) { counts[i][j][k - 'a'] = 1; } if (i - 1 >= 0) { counts[i][j][k - 'a'] += counts[i - 1][j][k - 'a']; } if (j - 1 >= 0) { counts[i][j][k - 'a'] += counts[i][j - 1][k - 'a']; } if (i - 1 >= 0 && j - 1 >= 0) { counts[i][j][k - 'a'] -= counts[i - 1][j - 1][k - 'a']; } } } } // System.out.println(Arrays.deepToString(counts)); for (int j = 0; j < m; j++) { for (int i = n - 1; i >= 0; i--) { last[i][j] = 1; if (i + 1 < n && grids.get(i).charAt(j) == grids.get(i + 1).charAt(j)) { last[i][j] = last[i + 1][j] + 1; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int height = last[i][j]; int start2 = i + height; int start3 = i + height + height; if (start3 + height - 1 >= n) { continue; } if (grids.get(i).charAt(j) == grids.get(start2).charAt(j)) { continue; } if (grids.get(start2).charAt(j) == grids.get(start3).charAt(j)) { continue; } if (count(counts, grids.get(start2).charAt(j), start2, j, start3 - 1, j) != height) { continue; } if (count(counts, grids.get(start3).charAt(j), start3, j, start3 + height - 1, j) != height) { continue; } good[i][j] = 1; if (j - 1 >= 0 && last[i][j - 1] == last[i][j] && grids.get(i).charAt(j) == grids.get(i).charAt(j - 1) && grids.get(start2).charAt(j) == grids.get(start2).charAt(j - 1) && grids.get(start3).charAt(j) == grids.get(start3).charAt(j - 1)) { good[i][j] = good[i][j - 1] + 1; } } } long res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { res += good[i][j]; } } System.out.println(res); } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
7a52f373c83368ee2674cad136577c74
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.*; import java.util.*; public class Main { private static void execute(ContestReader reader, PrintWriter out) { int n = reader.nextInt(); int m = reader.nextInt(); char[][] map = new char[n][]; for (int i = 0; i < n; i++) { map[i] = reader.next().toCharArray(); } out.println(new Solver().solve(n, m, map)); } public static void main(String[] args) { ContestReader reader = new ContestReader(System.in); PrintWriter out = new PrintWriter(System.out); execute(reader, out); out.flush(); } } class Solver { int n; int m; char[][] map; int[][] rightSameColor; int[][] downSameColor; public long solve(int n, int m, char[][] map) { this.n = n; this.m = m; this.map = map; rightSameColor = new int[n][m]; downSameColor = new int[n][m]; for (int i = n-1; i >= 0; i-- ) { for (int j = m-1; j >= 0; j--) { if (j == m-1 || map[i][j] != map[i][j+1]) { rightSameColor[i][j] = 1; } else { rightSameColor[i][j] = rightSameColor[i][j + 1] + 1; } if (i == n-1 || map[i][j] != map[i+1][j]) { downSameColor[i][j] = 1; } else { downSameColor[i][j] = downSameColor[i+1][j] + 1; } } } /* for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.err.printf("%d, ", downSameColor[i][j]); } System.err.println(); } */ long answer = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i + 3 * downSameColor[i][j] <= n && downSameColor[i][j] == downSameColor[i + downSameColor[i][j]][j] && downSameColor[i][j] <= downSameColor[i + 2 * downSameColor[i][j]][j]) { int minWidth = Integer.MAX_VALUE; for (int t = 0; t < 3 * downSameColor[i][j]; t++) { minWidth = Math.min(minWidth, rightSameColor[i+t][j]); } // System.err.printf("%d %d\n", i, j); answer += minWidth; } } } return answer; } } class ContestReader { private BufferedReader reader; private StringTokenizer tokenizer; ContestReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new java.util.StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } 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[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } public long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } } class Algorithm { private static void swap(Object[] list, int a, int b) { Object tmp = list[a]; list[a] = list[b]; list[b] = tmp; } public static <T extends Comparable<? super T>> boolean nextPermutation(T[] ts) { int rightMostAscendingOrderIndex = ts.length - 2; while (rightMostAscendingOrderIndex >= 0 && ts[rightMostAscendingOrderIndex].compareTo(ts[rightMostAscendingOrderIndex + 1]) >= 0) { rightMostAscendingOrderIndex--; } if (rightMostAscendingOrderIndex < 0) { return false; } int rightMostGreatorIndex = ts.length - 1; while (ts[rightMostAscendingOrderIndex].compareTo(ts[rightMostGreatorIndex]) >= 0) { rightMostGreatorIndex--; } swap(ts, rightMostAscendingOrderIndex, rightMostGreatorIndex); for (int i = 0; i < (ts.length - rightMostAscendingOrderIndex - 1) / 2; i++) { swap(ts, rightMostAscendingOrderIndex + 1 + i, ts.length - 1 - i); } return true; } public static void shuffle(int[] array) { Random random = new Random(); int n = array.length; for (int i = 0; i < n; i++) { int randomIndex = i + random.nextInt(n - i); int temp = array[i]; array[i] = array[randomIndex]; array[randomIndex] = temp; } } public static void shuffle(long[] array) { Random random = new Random(); int n = array.length; for (int i = 0; i < n; i++) { int randomIndex = i + random.nextInt(n - i); long temp = array[i]; array[i] = array[randomIndex]; array[randomIndex] = temp; } } public static void sort(int[] array) { shuffle(array); Arrays.sort(array); } public static void sort(long[] array) { shuffle(array); Arrays.sort(array); } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
de215fdbaf9ed49fd86c4e62e561f042
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.reflect.Array; public class C { static final int MOD = 1000000007; // 1e9 + 7 static final boolean AUTO_FLUSH = false; // slow if true // int = num(); // long = ll(); // string = next(); // a string line = line(); // ---------------------------------- \ char[][] data; int row, col; String[][] strs, count; void main() throws Exception { row = num(); col = num(); data = new char[col][row]; for (int j = 0; j < row; j++) { String s = line(); for (int i = 0; i < col; i++) data[i][j] = s.charAt(i); } long ans = 0; strs = new String[col][row]; count = new String[col][row]; for (int i = 0; i < col; i++) { for (int j = 0; j < row; j++) { count[i][j] = count(i, j); } } for (int i = 0; i < col; i++) { for (int j = 0; j < row; j++) { strs[i][j] = getStr(i, j, count(i, j).length()); } } for (int j = 0; j < row; j++) { int start = 0; boolean found = !strs[0][j].isEmpty(); for (int i = 1; i < col; i++) { if (strs[i][j].isEmpty() || !strs[i][j].equals(strs[i-1][j])) { if (found) ans += comb(i-start); found = !strs[i][j].isEmpty(); start = i; continue; } } if (found) ans += comb(col-start); } outln(ans); } String getStr(int x, int y, int add) { if (y - 1 + add*3 >= row) return ""; String str1 = count(x, y); if (str1.length() != add) return ""; String str2 = count(x, y+add); if (str2.length() != add) return ""; String str3 = count(x, y+add*2); if (str3.length() < add) return ""; return str1 + str2 + str3.substring(0, add); } String count(int x, int y) { String ans = "" + data[x][y]; if (count[x][y] != null) return count[x][y]; if (y > 0 && count[x][y-1] != null && data[x][y-1] == data[x][y]) return count[x][y-1].substring(1); for (int i = y+1; i < row; i++) if (data[x][i] != data[x][y]) break; else ans += data[x][i]; return ans; } int comb(int i) { return (i+1)*i/2; } // ---------------------------------- \ //#region public static void main(String[] args) throws Exception { new Thread(null, () -> { try { if (!ONLINE_JUDGE) startTime(); new C().main(); boolean endsWithEnter = TO_BE_PRINTED.length() == 0 || TO_BE_PRINTED.charAt(TO_BE_PRINTED.length() - 1) == '\n'; flush(); if (ONLINE_JUDGE) return; if (!endsWithEnter) log('\n'); logTime(); logMem(); } catch (Exception e) { e.printStackTrace(); } }, "Main", 1<<26).start(); } static Random RAND = new Random(); static int random(int from, int to) { return RAND.nextInt(to-from+1)+from; } static void logTime() { log("Time: " + getTime() + "ms"); } static void logMem() { log("Memory (End): " + (int) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 + " KB"); } static long ll() { return Long.parseLong(next()); } static int num() { return Integer.parseInt(next()); } static void generateInputMode() throws Exception { System.setOut(new PrintStream(new FileOutputStream("F://PROGRAMMING/input.txt"))); } static String line() { if (!tokenize()) return null; INPUT_STREAM.setLength(0); if (STRING_TOKENIZER.hasMoreTokens()) INPUT_STREAM.append(STRING_TOKENIZER.nextToken()); while (STRING_TOKENIZER.hasMoreTokens()) INPUT_STREAM.append(' ').append(STRING_TOKENIZER.nextToken()); return INPUT_STREAM.length() == 0 ? null : INPUT_STREAM.toString(); } static void startTime() { TIME_COMPLEXITY = System.currentTimeMillis(); } static long getTime() { return System.currentTimeMillis() - TIME_COMPLEXITY; } static void flush() { System.out.print(TO_BE_PRINTED.toString()); TO_BE_PRINTED.setLength(0); } static void out(Object o) { TO_BE_PRINTED.append(o); if (AUTO_FLUSH) flush(); } static void _log(String s) { System.err.print(s); } static void _logln(String s) { System.err.println(s); } static void _logln() { System.err.println(); } static void outln(Object o) { out(o); outln(); } static void outln() { out("\n"); } static class Pair implements Comparable<Pair> { public int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } public static Pair of(int a, int b) { return new Pair(a, b); } public int compareTo(Pair p) { if (a == p.a) return Integer.compare(b, p.b); return Integer.compare(a, p.a); } public String toString() { return "[" + a + "," + b + "]"; } public boolean equals(Pair p) { return p.a == a && p.b == b; } } static boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; static void logArr(Object val) { if (ONLINE_JUDGE) return; Class<?> valKlass = val.getClass(); Object[] outputArray = null; for(Class<?> arrKlass : new Class<?>[] { int[].class, float[].class, double[].class, boolean[].class, byte[].class, short[].class, long[].class, char[].class }) { if (valKlass.isAssignableFrom(arrKlass)) { int arrlength = Array.getLength(val); outputArray = new Object[arrlength]; for(int i = 0; i < arrlength; ++i) outputArray[i] = Array.get(val, i); break; } } if(outputArray == null) outputArray = (Object[])val; logArr0(outputArray); } static void logArr0(Object[] objs) { if (ONLINE_JUDGE) return; if (objs.length == 0) { _log("* \n"); return; } _log("* " + objs[0]); for (int i = 1; i < objs.length; i++) _log(objs[i].toString().equals("\n") ? "\n>" : (" " + objs[i])); _logln(); } static void log(Object... objs) { if (ONLINE_JUDGE) return; logArr0(objs); } static String next() { return tokenize() ? STRING_TOKENIZER.nextToken() : null; } static boolean tokenize() { if (STRING_TOKENIZER == null || !STRING_TOKENIZER.hasMoreTokens()) { try { STRING_TOKENIZER = new StringTokenizer(STREAM_READER.readLine()); } catch (Exception e) { return false; } } return true; } static long TIME_COMPLEXITY; static BufferedReader STREAM_READER = new BufferedReader(new InputStreamReader(System.in), 32768); static StringTokenizer STRING_TOKENIZER; static StringBuilder INPUT_STREAM = new StringBuilder(), TO_BE_PRINTED = new StringBuilder(); //#endregion }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
7f1898010d63c497c077eecfbf2d3951
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; public class d extends PrintWriter{ static BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); // static Scanner s=new Scanner(System.in); d() { super(System.out); } public static void main(String[] args) throws IOException{ d d1=new d();d1.main();d1.flush(); }char[] op;int[] ii,jj;int cnt; void main() throws IOException { StringBuilder sb = new StringBuilder();PrintWriter out = new PrintWriter(System.out); String[] s=s(); int n=i(s[0]);int m=i(s[1]); char[][] a=new char[n][m]; for(int i=0;i<n;i++){ a[i]=s()[0].toCharArray(); } int[] [] sum=new int[n][m];int k=0; for(int j=0;j<m;j++){ int count=0;k=0; for(int i=0;i<n;i++){ if(i==0) count++; else{ if(a[i][j]==a[i-1][j]) count++; else{ for(int l=k;l<i;l++){ sum[l][j]=count; }k=i;count=1; } } } for(int l=k;l<n;l++){ sum[l][j]=count; } }long ans=0;long count=0; /* for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ System.out.print(sum[i][j]+" "); } System.out.println(); }*/ for(int i=1;i<n;i++){count=0; for(int j=0;j<m;j++){ if(a[i][j]!=a[i-1][j]&&sum[i][j]<=sum[i-1][j]&&i+sum[i][j]<n&&a[i][j]!=a[i+sum[i][j]][j]&&sum[i][j]<=sum[i+sum[i][j]][j]){ if(j==0) count++; else{ if(a[i][j]==a[i][j-1]&&a[i-1][j]==a[i-1][j-1]&&a[i+sum[i][j]][j]==a[i+sum[i][j]][j-1]&&sum[i][j]==sum[i][j-1]){ count++; }else{ ans+=(count)*(count+1)/2; // System.out.println(i+" "+j+" "+a[i][j]); count=1; } } }else { ans+=(count)*(count+1)/2; count=0;} } ans+=(count)*(count+1)/2; } System.out.println(ans); } static String[] s() throws IOException { return s.readLine().trim().split("\\s+"); } static int i(String ss) { return Integer.parseInt(ss); } static long l(String ss) { return Long.parseLong(ss); }static int MAXN; static int[] spf; static void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) spf[i] = i; for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { if (spf[i] == i) { for (int j=i*i; j<MAXN; j+=i) if (spf[j]==j) spf[j] = i; } } } static ArrayList<Integer> getFactorizationUsingSeive(int x) { ArrayList<Integer> ret = new ArrayList<Integer>(); while (x != 1) { ret.add(spf[x]); if (spf[x] != 0) x = x / spf[x]; else break; } return ret; } } class Student12 { int l;long r; public Student12(int l, long r) { this.l = l; this.r = r; } public String toString() { return this.l+" "; } } class Sortbyroll12 implements Comparator<Student12> { public int compare(Student12 a, Student12 b){ return a.l-b.l; /* if(b.r<a.r) return -1; else if(b.r==a.r) return 0; return 1;*/ // return b.r-a.r; /* if(b.l<a.l) return -1; else if(b.l==a.l) { return b.r-a.r; } return 1;*/ // return b.r- a.r; // return (int) a.l-(int) b.l; /* if(a.r<b.r) return -1; else if(a.r==b.r){ if(a.r==b.r){ return 0; } if(a.r<b.r) return -1; return 1;} return 1; */} }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
c466b40052be2b6bf1321076b13a2687
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.util.*; import java.io.*; import java.math.*; public class C { static class FastReader { StringTokenizer str; BufferedReader br; FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { if (str == null || !str.hasMoreTokens()) { try { str = new StringTokenizer(br.readLine()); } catch (Exception e) { return ""; } } return str.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static class Triple { char a, b, c; Triple(char x, char y, char z) { a = x; b = y; c = z; } boolean equals(Triple p) { if (p != null && p.a == a && p.b == b && p.c == c) return true; return false; } } public static void main(String args[]) throws Exception { FastReader fr = new FastReader(); int n = fr.nextInt(), m = fr.nextInt(); char a[][] = new char[n][m]; int h[][] = new int[n][m]; int cur[][] = new int[n][m]; int dp[][] = new int[n][m]; Triple colours[][] = new Triple[n][m]; for (int i = 0; i < n; i++) { a[i] = fr.next().toCharArray(); } if (n <= 2) { System.out.print("0"); System.exit(0); } for (int j = 0; j < m; j++) { h[0][j] = 1; cur[0][j] = 1; if (a[0][j] == a[1][j]) { cur[1][j] = 2; h[1][j] = 2; } else { cur[1][j] = 1; h[1][j] = 1; } for (int i = 2; i < n; i++) { cur[i][j] = cur[i - 1][j]; if (a[i][j] == a[i - 1][j]) { h[i][j] = h[i - 1][j] + 1; } else { h[i][j] = 1; cur[i][j] = h[i - 1][j]; } if (h[i][j] == cur[i][j]) { if (i - 2 * cur[i][j] >= 0 && h[i - cur[i][j]][j] == h[i][j] && h[i - 2 * cur[i][j]][j] >= h[i][j]) { dp[i][j] = 1; colours[i][j] = new Triple(a[i][j], a[i - cur[i][j]][j], a[i - 2 * cur[i][j]][j]); if (j != 0 && a[i][j] == a[i][j - 1] && cur[i][j - 1] == cur[i][j] && h[i][j - 1] == h[i][j] && colours[i][j].equals(colours[i][j - 1])) dp[i][j] += dp[i][j - 1]; } } } } int sum = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) sum += dp[i][j]; } System.out.print(sum); } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
84d0ee36b33db64eb9cdff208a51c06e
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author cunbidun */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CFlag solver = new CFlag(); solver.solve(1, in, out); out.close(); } static class CFlag { private InputReader in; private PrintWriter out; private char[][] a; private int[][][] sum; private int n; private int m; public void solve(int testNumber, InputReader in, PrintWriter out) { this.in = in; this.out = out; n = in.nextInt(); m = in.nextInt(); a = in.nextCharTable(n, m, 1, 1); sum = new int[n + 1][m + 1][55]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { for (char c = 'a'; c <= 'z'; c++) { sum[i][j][index(c)] = sum[i - 1][j][index(c)] + sum[i][j - 1][index(c)] - sum[i - 1][j - 1][index(c)]; } for (char c = 'A'; c <= 'Z'; c++) { sum[i][j][index(c)] = sum[i - 1][j][index(c)] + sum[i][j - 1][index(c)] - sum[i - 1][j - 1][index(c)]; } sum[i][j][index(a[i][j])]++; } } // long ans = 0; boolean[][] done = new boolean[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] != a[i - 1][j] && !done[i][j]) { int low = i; int high = n; while (low != high) { if (low == high - 1) { if (check(i, j, high, j)) low = high; break; } int mid = (low + high) >> 1; if (check(i, j, mid, j)) low = mid; else high = mid - 1; } int pos = low; int dis = low - i + 1; if (pos + dis > n || i - dis < 1) continue; if (!check(i - dis, j, i - 1, j) || !check(pos + 1, j, pos + dis, j)) continue; low = j; high = m; while (low != high) { if (low == high - 1) { if (check(i, j, pos, high)) low = high; break; } int mid = (low + high) >> 1; if (check(i, j, pos, mid)) low = mid; else high = mid - 1; } int cnt2 = low - j + 1; low = j; high = m; while (low != high) { if (low == high - 1) { if (check(i - dis, j, i - 1, high)) low = high; break; } int mid = (low + high) >> 1; if (check(i - dis, j, i - 1, mid)) low = mid; else high = mid - 1; } int cnt1 = low - j + 1; low = j; high = m; while (low != high) { if (low == high - 1) { if (check(pos + 1, j, pos + dis, high)) low = high; break; } int mid = (low + high) >> 1; if (check(pos + 1, j, pos + dis, mid)) low = mid; else high = mid - 1; } int cnt3 = low - j + 1; int cur = MaxMin.Min(cnt1, cnt2, cnt3); for (int l = j; l <= j + cur - 1; l++) { done[i][l] = true; } ans += cur * (cur - 1) / 2 + cur; } } } out.println(ans); } private boolean check(int i, int j, int k, int l) { int tmp = (k - i + 1) * (l - j + 1); char c = a[i][j]; return getSum(i, j, k, l, index(c)) == tmp; } private int getSum(int i, int j, int k, int l, int index) { return sum[k][l][index] - sum[k][j - 1][index] - sum[i - 1][l][index] + sum[i - 1][j - 1][index]; } private int index(char c) { if (c <= 'Z') return c - 'A' + 1; else return c - 'a' + 1 + 26; } } static class InputReader extends InputStream { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public char[][] nextCharTable(int row, int col, int rowSt, int colSt) { char[][] arr = new char[row + rowSt][col + colSt]; for (int i = rowSt; i < row + rowSt; i++) { for (int j = colSt; j < col + colSt; j++) { arr[i][j] = nextCharacter(); } } return arr; } private static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } } static class MaxMin { public static <T extends Comparable<T>> T Min(T x, T y, T z) { T min = x; if (y.compareTo(min) < 0) min = y; if (z.compareTo(min) < 0) min = z; return min; } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
8f2bf094f0c40b1935e2052db46e4f38
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.BigInteger; import java.util.regex.*; public class Myclass { static ArrayList a[]=new ArrayList[3000001]; static int[][][] dp; static int len[][]; static Segment seg[]; static boolean f(int i,int j) { return (dp[i][j][0]!=-1 && dp[i][j][1]!=-1 && dp[i][j][2]!=-1 ); } static int cal(int i,int j) { int len1=(dp[i][j][0]-i); int len2=(dp[i][j][1]-dp[i][j][0]); int len3=(dp[i][j][2]-dp[i][j][1]); if(len1==len2 && len3>=len2) return len1; else return 0; } static int cal1(int i,int j,int n,int have) { return seg[j].query(0, 0, n-1, i,i+have*3-1); } public static void main(String[] args) throws FileNotFoundException { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n=in.nextInt(); int m=in.nextInt(); dp=new int[n][m][3]; char a[][]=new char [n][m]; int b[][]=new int[m][n]; len=new int [n][m]; seg=new Segment[m]; for(int i=0;i<n;i++) { a[i]=in.nextLine().toCharArray(); } for(int i=0;i<n;i++) { len[i][m-1]=1; b[m-1][i]=1; for(int j=m-2;j>=0;j--) { if(a[i][j]==a[i][j+1]) len[i][j]=len[i][j+1]+1; else len[i][j]=1; b[j][i]=len[i][j]; } } for(int i=0;i<m;i++) { seg[i]=new Segment(n,b[i]); seg[i].build(0, 0, n-1); } for(int i=n-1;i>=0;i--) { for(int j=0;j<m;j++) { if(i==n-1) { dp[i][j][0]=n; dp[i][j][1]=-1; dp[i][j][2]=-1; } else { if(a[i][j]==a[i+1][j]) { dp[i][j][0]=dp[i+1][j][0]; dp[i][j][1]=dp[i+1][j][1]; dp[i][j][2]=dp[i+1][j][2]; } else { dp[i][j][0]=(i+1); dp[i][j][1]=dp[i+1][j][0]; dp[i][j][2]=dp[i+1][j][1]; } } } } long ans=0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { boolean chk=f(i, j); if(chk) { int got=cal(i,j); int bk=0; if(got!=0) bk=1; int kk=cal1(i,j,n,got); ans+=bk*kk; } } } pw.println(ans); pw.flush(); pw.close(); } private static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static long[] suffle(long[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; long temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static long GCD(long gcd,long diff) { if(diff==0) return gcd; else return GCD(diff,gcd%diff); } static class pair implements Comparable<pair> { Long x; Long y; pair(long a,long a2) { this.x=a; this.y=a2; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } } class Segment{ int seg[]; int a[]; Segment (int n,int b[]){ seg=new int[4*n]; a=new int[b.length]; a=b.clone(); } public void build(int node,int start,int end) { if(start==end) { seg[node]=a[start]; return ; } int mid=(start+end)/2; build(2*node+1,start,mid); build(2*node+2,mid+1,end); seg[node]=Math.min(seg[2*node+1],seg[2*node+2]); } public int query(int node,int start,int end,int l,int r) { if(l>end || r<start) return Integer.MAX_VALUE; if(start>=l && end<=r) return seg[node]; int mid=(start+end)/2; return Math.min(query(2*node+1,start,mid,l,r),query(2*node+2,mid+1,end,l,r)); } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
058c07cb3d42d7b0fc8f9e44644536e8
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
//package learning; import java.util.*; import java.io.*; import java.lang.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Nitslocal { static ArrayList<String> s1; static boolean[] prime; static int n = (int)1e7; static void sieve() { Arrays.fill(prime , true); prime[0] = prime[1] = false; for(int i = 2 ; i * i <= n ; ++i) { if(prime[i]) { for(int k = i * i; k< n ; k+=i) { prime[k] = false; } } } } public static void main(String[] args) { InputReader sc = new InputReader(System.in); prime = new boolean[n + 1]; sieve(); prime[1] = false; int n = sc.ni(); int m = sc.ni(); char [][]c = new char[n][m]; for(int i=0;i<n;i++) { String s = sc.rs(); c[i] = s.toCharArray(); } int [][]line = new int[n][m]; int [][]col = new int[n][m]; for(int i=n-1;i>=0;i--) { for(int j=m-1;j>=0;j--) { if(j < m-1 && c[i][j]==c[i][j+1]) line[i][j] = line[i][j+1]+1; else line[i][j] = 1; if(i < n-1 && c[i+1][j]==c[i][j]) col[i][j] = col[i+1][j]+1; else col[i][j] = 1; } } long ans = 0; for(int i=0;i<n;i++) { for(int j=0;j<m;) { int k = col[i][j]; if(i+3*k <= n && col[i+k][j]==k && col[i+2*k][j] >= k) { int temp = Integer.MAX_VALUE; for(int l=i;l<i+3*k;l++) { if(temp > line[l][j]) temp = line[l][j]; } ans += ((temp*(temp+1))/2); j += temp; } else j++; } } w.println(ans); w.close(); } static void bfs(int s) { vis[s] = true; Queue<Integer> q = new LinkedList<>(); q.add(s); color[s] = 1; level[s] = 0; p[s] = s; while(q.size()>0) { int cc = q.poll(); //ArrayList<Integer> te= new ArrayList<>(); Iterator itr = hs[cc].iterator(); while(itr.hasNext()) { Integer e = (Integer) itr.next(); //w.print(e + " "); if(!vis[e]) { q.add(e); // te.add(e); p[e] = cc; if(color[cc]==1) color[e] = 2; else color[e] = 1; level[e] = level[cc]+1; vis[e] = true; } } // w.println(); } } static int []level; static int []color; static ArrayList<Integer> []hs; static boolean []vis; static int count = 0; static int []p; //static int [][]arr; static boolean [][]v; //static int [][]l; static boolean con(int []p,int q) { boolean res = false; for(int i=0;i<6;i++) { if(p[i]==q) { res = true; break; } } return res; } static String replace(String s,int a,int n) { char []c = s.toCharArray(); for(int i=1;i<n;i+=2) { int num = (int) (c[i] - 48); num += a; num%=10; c[i] = (char) (num+48); } return new String(c); } static String move(String s,int h,int n) { h%=n; char []c = s.toCharArray(); char []temp = new char[n]; for(int i=0;i<n;i++) { temp[(i+h)%n] = c[i]; } return new String(temp); } public static int ip(String s){ return Integer.parseInt(s); } static class multipliers implements Comparator<Long>{ public int compare(Long a,Long b) { if(a<b) return 1; else if(b<a) return -1; else return 0; } } static class multipliers1 implements Comparator<Student>{ public int compare(Student a,Student b) { if(a.y<b.y) return 1; else if(b.y<a.y) return -1; else { if(a.id < b.id) return 1; else if(b.id<a.id) return -1; else return 0; //return 0; } } } // Java program to generate power set in // lexicographic order. static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nia(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String rs() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static PrintWriter w = new PrintWriter(System.out); static class Student { int id; //int x; int y; //long z; Student(int id,int y) { this.id = id; //this.x = x; //this.s = s; this.y = y; // this.z = z; } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
5a07ae2fd8f0acf92d470513dec0885e
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.util.*; import java.lang.*; public class Main { public static Scanner in ; public static int solve(int n,int m){ int res=0; int arr[][] = new int[n][m]; for(int i=0; i<n; i++){ char ch[] = in.next().toCharArray(); for(int j=0; j<m; j++){ arr[i][j]=ch[j]-'a'+1; } } //for width == 1 //int lineFlag=0; for(int i=1; i<n-1; i++){ //char ch[] = in.next().toCharArray(); for(int j=0; j<m && i<n-1; j++){ if(arr[i][j]!=arr[i-1][j]){//if cur is different than above then find l of cur length //System.out.println(arr[i][j]+","+arr[i-1][j]); int midL=0; while(i+midL<n && arr[i+midL][j]==arr[i][j]){ midL++; //System.out.println("Mid"); } //now we have midL find upL and lowL int upL = 0; while(i-upL>0 && arr[i-upL-1][j]==arr[i-1][j]){ upL++; //System.out.println("Up"); } int lowL=0; while(i+midL+lowL<n && arr[i+midL+lowL][j]==arr[i+midL][j]){ lowL++; //System.out.println("Low"); } if(midL<=lowL && midL<=upL){//if valid width 1 flag is found search for its maximum width int w=1; boolean flag=false; for(int c=j+1; c<m; c++){ for(int r=i-midL; r<i+midL*2;r++ ){ //System.out.println(r+":r,c:"+c); if(arr[r][c]!=arr[r][c-1]){ flag=true; break; } } if(flag)break; else{ w++;} } res+=(w*(w+1))/2; j+=w-1; } } } } return res; } public static void main(String[] args) { in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); System.out.println(solve(n,m)); } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
0b470697793bde665c007df64d4e7ea1
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.util.*; import java.lang.*; public class Main { public static Scanner in ; public static int solve(int n,int m){ int res=0; int arr[][] = new int[n][m]; for(int i=0; i<n; i++){ char ch[] = in.next().toCharArray(); for(int j=0; j<m; j++){ arr[i][j]=ch[j]-'a'+1; } } //for width == 1 //int lineFlag=0; for(int i=1; i<n-1; i++){ //char ch[] = in.next().toCharArray(); for(int j=0; j<m && i<n-1; j++){ if(arr[i][j]!=arr[i-1][j]){//if cur is different than above then find l of cur length //System.out.println(arr[i][j]+","+arr[i-1][j]); int midL=0; while(i+midL<n && arr[i+midL][j]==arr[i][j]){ midL++; //System.out.println("Mid"); } //now we have midL find upL and lowL int upL = 0; while(i-upL>0 && arr[i-upL-1][j]==arr[i-1][j]){ upL++; //System.out.println("Up"); } int lowL=0; while(i+midL+lowL<n && arr[i+midL+lowL][j]==arr[i+midL][j]){ lowL++; //System.out.println("Low"); } if(midL<=lowL && midL<=upL){//if valid width 1 flag is found search for its maximum width //r,c == r,c-1 in the given range from top to bottom yani from current i-l above and i+2l below int w=1; boolean flag=false; //measuring the width of the found flag for(int c=j+1; c<m; c++){ for(int r=i-midL; r<i+midL*2;r++ ){ //System.out.println(r+":r,c:"+c); if(arr[r][c]!=arr[r][c-1]){ flag=true; break; } } if(flag)break; else{ w++;} } //System.out.println(w+":width r,c="+(i-1)+","+j); res+=(w*(w+1))/2;//all possible ways of dividing it into pieces j+=w-1; } } } } /* 6 1 a b c d c e 6 6 aaaadd bbbbdd ccccdb ddacdb ddaddd dddddd 6 4 aaaa bbbb cccc ddac ddad dddd ok the line of len 1 is handled now we need to extend this to higer width if possible HOw can we do that? Ok I can count number of rows similar to curent one, BUt I will need to mark them as visited right? Though they may later be used by other flags, so what will I do then? */ return res; } public static void main(String[] args) { in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); System.out.println(solve(n,m)); } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
c2d28233f21ca4d37d2d60e9407de2e8
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author gaidash */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { private int hash(char c1, char c2, char c3, int length) { return ((1 << 15) * length) + ((1 << 10) * (c1 - 'a')) + ((1 << 5) * (c2 - 'a')) + ((1 << 0) * (c3 - 'a')); } public void solve(int testNumber, InputReader in, OutputWriter out) { int sizeI = in.nextInt(); int sizeJ = in.nextInt(); char[][] a = new char[sizeI][sizeJ]; for (int i = 0; i < sizeI; i++) for (int j = 0; j < sizeJ; j++) a[i][j] = in.nextCharacter(); int[][] flag = new int[sizeI][sizeJ]; for (int j = 0; j < sizeJ; j++) { for (int i = 0; i < sizeI - 2; i++) { int topStart = i, topEnd = i; while (topEnd + 1 < sizeI - 2 && a[topStart][j] == a[topEnd + 1][j]) topEnd++; int topLength = topEnd - topStart + 1; int midStart = topEnd + 1, midEnd = topEnd + 1; while (midEnd + 1 < sizeI - 1 && a[midStart][j] == a[midEnd + 1][j]) midEnd++; int midLength = midEnd - midStart + 1; if (topLength != midLength) continue; int bottomStart = midEnd + 1, bottomEnd = midEnd + 1; while (bottomEnd + 1 < sizeI && a[bottomStart][j] == a[bottomEnd + 1][j]) bottomEnd++; int bottomLength = bottomEnd - bottomStart + 1; if (bottomLength >= midLength) { char top = a[topStart][j], mid = a[midStart][j], bottom = a[bottomStart][j]; if (top != mid && mid != bottom) flag[i][j] = hash(top, mid, bottom, topLength); } } } int ret = 0; for (int i = 0; i < sizeI; i++) { for (int j = 0; j < sizeJ; j++) { if (flag[i][j] > 0) { int consecutive = 1; while (j + 1 < sizeJ && flag[i][j + 1] > 0 && flag[i][j + 1] == flag[i][j]) { j++; consecutive++; } ret += consecutive * (consecutive + 1) / 2; } } } out.print(ret); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
b7676808f8266fdcadbfffd8abf68a9b
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author gaidash */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int sizeI = in.nextInt(); int sizeJ = in.nextInt(); char[][] a = new char[sizeI][sizeJ]; for (int i = 0; i < sizeI; i++) for (int j = 0; j < sizeJ; j++) a[i][j] = in.nextCharacter(); Flag[][] flag = new Flag[sizeI][sizeJ]; for (int j = 0; j < sizeJ; j++) { for (int i = 0; i < sizeI - 2; i++) { int topStart = i, topEnd = i; while (topEnd + 1 < sizeI - 2 && a[topStart][j] == a[topEnd + 1][j]) topEnd++; int topLength = topEnd - topStart + 1; int midStart = topEnd + 1, midEnd = topEnd + 1; while (midEnd + 1 < sizeI - 1 && a[midStart][j] == a[midEnd + 1][j]) midEnd++; int midLength = midEnd - midStart + 1; if (topLength != midLength) continue; int bottomStart = midEnd + 1, bottomEnd = midEnd + 1; while (bottomEnd + 1 < sizeI && a[bottomStart][j] == a[bottomEnd + 1][j]) bottomEnd++; int bottomLength = bottomEnd - bottomStart + 1; if (bottomLength >= midLength) { char top = a[topStart][j], mid = a[midStart][j], bottom = a[bottomStart][j]; if (top != mid && mid != bottom) flag[i][j] = new Flag(top, mid, bottom, topLength); } } } int ret = 0; for (int i = 0; i < sizeI; i++) { for (int j = 0; j < sizeJ; j++) { if (flag[i][j] != null) { int consecutive = 1; while (j + 1 < sizeJ && flag[i][j + 1] != null && flag[i][j + 1].equals(flag[i][j])) { j++; consecutive++; } ret += consecutive * (consecutive + 1) / 2; } } } out.print(ret); } private class Flag { char top; char mid; char bottom; int length; private Flag(char top, char mid, char bottom, int length) { this.top = top; this.mid = mid; this.bottom = bottom; this.length = length; } public boolean equals(Object o) { Flag other = (Flag) o; return top == other.top && mid == other.mid && bottom == other.bottom && length == other.length; } public String toString() { return top + "" + mid + "" + bottom + " " + length; } } } 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 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 char nextCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } 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 close() { writer.close(); } public void print(int i) { writer.print(i); } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
0f07d6eb2235b9765ad8bae1c20ee56e
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.stream.IntStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.util.stream.Stream; import java.nio.charset.Charset; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); CFlag solver = new CFlag(); solver.solve(1, in, out); out.close(); } static class CFlag { public void solve(int testNumber, LightScanner in, LightWriter out) { // out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP); int h = in.ints(), w = in.ints(); String[] s = in.string(h); int[][] length = new int[h][w]; for (int i = 0; i < h; i++) { length[i][w - 1] = 1; for (int j = w - 2; j >= 0; j--) { if (s[i].charAt(j) == s[i].charAt(j + 1)) { length[i][j] = length[i][j + 1] + 1; } else { length[i][j] = 1; } } } int[][] up = new int[h][w], down = new int[h][w]; for (int i = 0; i < w; i++) { up[0][i] = 1; down[h - 1][i] = 1; for (int j = 1; j < h; j++) { if (s[j].charAt(i) == s[j - 1].charAt(i)) { up[j][i] = up[j - 1][i] + 1; } else { up[j][i] = 1; } } for (int j = h - 2; j >= 0; j--) { if (s[j].charAt(i) == s[j + 1].charAt(i)) { down[j][i] = down[j + 1][i] + 1; } else { down[j][i] = 1; } } } //Arrays.stream(down).map(Arrays::toString).forEach(System.out::println); long ans = 0; for (int i = 1; i < h; i++) { mid: for (int j = 0; j < w; j++) { // 中央の左上 if (s[i].charAt(j) == s[i - 1].charAt(j)) continue; int d = down[i][j]; if (i + d + d - 1 >= h || i - d < 0) continue; if (down[i - d][j] != d || up[i + d + d - 1][j] != d) continue; int width = Integer.MAX_VALUE; for (int k = i - d; k < i + d + d; k++) { width = Math.min(width, length[k][j]); } //System.out.println("("+j+", " + i + ") = " + width + " d="+d); ans += width; } } out.ans(ans).ln(); } } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public String[] string(int length) { return IntStream.range(0, length).mapToObj(x -> string()).toArray(String[]::new); } public int ints() { return Integer.parseInt(string()); } } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset()))); } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ans(String s) { if (!breaked) { print(' '); } return print(s); } public LightWriter ans(long l) { return ans(Long.toString(l)); } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
19ecb8b22c4a96148d13d4fe4fd9b01e
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class Hello { public static TreeSet<Long> primeFactors(long n) { TreeSet<Long> res = new TreeSet<Long>(); // Print the number of 2s that divide n while (n % 2 == 0) { n /= 2; res.add((long) 2); } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (long i = 3; i <= Math.sqrt(n); i += 2) { // While i divides n, print i and divide n while (n % i == 0) { res.add((long)i); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) res.add(n); return res; } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if((y & 1)==1) res = (res * x) % p; // y must be even now // y = y / 2 y = y >> 1; x = (x * x) % p; } return res; } static PrintWriter pw = new PrintWriter(System.out); public static boolean isFlag(int[][] arr,int i,int j,int r) { int c = (j-i)/3;int t = i; for(;i<t+c-1 && i<j;i++) { if(arr[i][r]!=arr[i+1][r]) return false; } if(i<j&&arr[i][r]==arr[i+1][r]) return false; i++; t = i; for(;i<t+c-1&& i<j;i++) { if(i<j&&arr[i][r]!=arr[i+1][r]) return false; } if(i<j&&arr[i][r]==arr[i+1][r]) return false; i++; t = i; for(;i<c-1+t&&i<j;i++) { if(i<j&&arr[i][r]!=arr[i+1][r]) return false; } return true; } public static boolean isEqual(int[][] arr,int i,int j,int r) { for(int k=i;k<j;k++) { if(arr[k][r]!=arr[k][r-1]) return false; } return true; } public static int maxFlag(int[][] arr,int i,int j) { int c = 0;int t = arr[i][j];int k = i; while(k<arr.length && arr[k][j]==t) { k++; c++; } if(k>=arr.length)return 0; int c1 = 0;t = arr[k][j]; while(k<arr.length && arr[k][j]==t) { k++; c1++; } if(c1!=c)return 0; if(k>=arr.length)return 0; int c2 = 0;t = arr[k][j]; while(k<arr.length && arr[k][j]==t) { k++; c2++; } if(c2<c) return 0; return 3*c; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][] arr = new int[n][m]; for(int i=0;i<n;i++) { String s = sc.next(); for(int j=0;j<m;j++) { arr[i][j] = s.charAt(j)-'a'; } } // for(int i=0;i<arr.length;i++) { // for(int j=0;j<arr[i].length;j++) // System.out.print(arr[i][j]); // System.out.println(); // } //System.out.println(isFlag(arr,0,6,0)); int[][] a = new int[n][m]; for(int i=0;i<n;i++) { for(int j= 1;j<m;j++) { if(arr[i][j]==arr[i][j-1]) a[i][j] = 1; } } int[][] sum = new int[n][m]; for(int j=0;j<m;j++) { for(int i=0;i<n;i++) { if(i==0) { sum[i][j] = a[i][j]; }else { sum[i][j] = sum[i-1][j] + a[i][j]; } } } int[][] flags = new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { flags[i][j] = maxFlag(arr, i, j); } } boolean[][] v = new boolean[n][m]; boolean[][] v2 = new boolean[n][m]; long res = 0;int c = 0; for(int i=3;i<=n;i+=3) { c = 0; for(int j=0;j<=n-i;j++) { //System.out.println(res); c = 0; for(int k=0;k<m;k++) { // boolean isFlag = (!v[j][k])&&isFlag(arr, j, j+i, k); boolean isFlag = (!v[j][k])&&(flags[j][k]==i); if(c==0) { if(isFlag) { c++; v[j][k] = true; } }else { boolean isEqual = false; if(k>0) { if(j==0) { isEqual = sum[j+i-1][k]==i; }else { isEqual = sum[j+i-1][k]-sum[j-1][k]==i; } } //System.out.println(isEqual + " "+((k>0)&&isEqual(arr,j,j+i,k))); if(k>0&&isFlag&&isEqual) { v2[j][k] = true; c++; v[j][k] = true; }else { res += c*(c+1)/2; c = 0; if(isFlag) { c++; v[j][k] = true; } } } } res+=c*(c+1)/2; } //System.out.println(c); //res+=Math.pow(2, c)-1; } // System.out.println(c); //res+=Math.pow(2, c)-1; pw.println(res); pw.flush(); pw.close(); } } class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int 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
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
36ed854de2bb552bae9096f9b2b36945
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Vaibhav Pulastya */ 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); CFlag solver = new CFlag(); solver.solve(1, in, out); out.close(); } static class CFlag { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[][] sameR = new int[n][m]; int[][] minR = new int[n][m]; int[][] sameD = new int[n][m]; String[] grid = in.nextStringArray(n); for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { if (j + 1 < m && grid[i].charAt(j + 1) == grid[i].charAt(j)) { sameR[i][j] = sameR[i][j + 1] + 1; } else { sameR[i][j] = 1; } if (i + 1 < n && grid[i].charAt(j) == grid[i + 1].charAt(j)) { sameD[i][j] = sameD[i + 1][j] + 1; minR[i][j] = Math.min(minR[i + 1][j], sameR[i][j]); } else { minR[i][j] = sameR[i][j]; sameD[i][j] = 1; } } } long count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int r1 = minR[i][j]; int h1 = sameD[i][j]; if (i + h1 >= n) continue; int r2 = minR[i + h1][j]; int h2 = sameD[i + h1][j]; if (i + h1 + h2 >= n) continue; if (h1 != h2) continue; int h3 = sameD[i + h1 + h2][j]; if (h3 < h1) continue; int r3 = (int) 1e7; for (int k = i + h1 + h2; k < i + h1 + h2 + h1; k++) { r3 = Math.min(r3, sameR[k][j]); } count += (long) Math.min(Math.min(r1, r2), r3); } } out.println(count); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new 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 next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String[] nextStringArray(int size) { String[] array = new String[size]; for (int i = 0; i < size; i++) array[i] = next(); return array; } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
b35b316126895f763b0615b3d0a1ce30
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.math.BigInteger; import java.util.Scanner; public class Main { public static void main(String[] args) { TaskA task = new TaskA(); task.solve(); } static class TaskA { Scanner scanner; long a, b, c; public void solve() { scanner = new Scanner(System.in); int n = scanner.nextInt(), m = scanner.nextInt(); char[][] table = new char[n][m]; for(int i = 0; i < n; ++ i) { String string = scanner.next(); table[i] = string.toCharArray(); } int[][] dp = new int[n][m]; int ans = 0; for(int i = 0; i < n; ++ i) { int len = 0, lst = 0; String flag = "AAA"; for (int j = 0; j < m; ++j) { dp[i][j] = 1; if (i > 0 && table[i][j] == table[i - 1][j]) dp[i][j] += dp[i - 1][j]; //System.out.print(dp[i][j]); String flag0 = Character.toString(table[i][j]); boolean bl0 = true; int lvl0 = i - dp[i][j]; if(lvl0 < 0 || dp[lvl0][j] != dp[i][j]) bl0 = false; else { flag0 += table[lvl0][j]; int lvl1 = lvl0 - dp[lvl0][j]; if(lvl1 < 0 || dp[lvl1][j] < dp[i][j]) bl0 = false; else flag0 += table[lvl1][j]; } if(!bl0) { ans += len * (len + 1) / 2; len = 0; lst = 0; flag = "AAA"; } else { if(lst == dp[i][j] && flag.equals(flag0)) ++ len; else { ans += len * (len + 1) / 2; lst = dp[i][j]; len = 1; flag = flag0; } } } ans += len * (len + 1) / 2; //System.out.println(); } System.out.print(ans); } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
fbbc4e939c92b5d920ba32dfa10b620e
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.util.*; import java.math.BigInteger; public class Boss { //static long c=0; //static HashMap<Integer,Long> hm2=new HashMap<Integer,Long>(); public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); sc.nextLine(); char a[][]=new char[n][m]; for(int i=0;i<n;i++) { String s=sc.nextLine(); a[i]=s.toCharArray(); } //System.out.println(a[0][1]); //HashMap<Integer,HashSet<Integer>> mp=new HashMap<Integer,HashSet<Integer>>(); int f=0; int s=0; int t=0; Queue<Character> q = new LinkedList<>(); char ch='a'; int c=0; int count=0; HashMap<String,Rect> mp=new HashMap<String,Rect>(); //int num=0; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(j==0) { q.clear(); c=1; ch=a[j][i]; q.add(ch); count=Integer.MAX_VALUE; //q.clear(); } else { if(a[j][i]==ch) { if(c==count) { if(q.size()==3) { int x=j-3*count; int y=i; String te=""+x+"-"+y; Boss obj=new Boss(); mp.put(te,obj.new Rect(q,count)); //System.out.println(q+" "+te); q.poll(); q.poll(); c=c+1; } else if(q.size()==2) { q.poll(); c++; } } else { c++; } } else { if(q.size()==3) { if(count==c) { /////// int x=j-3*count; int y=i; String te=""+x+"-"+y; Boss obj=new Boss(); mp.put(te,obj.new Rect(q,count)); //System.out.println(q+" "+te); q.poll(); q.add(a[j][i]); ch=a[j][i]; //System.out.println(q+" "+te); c=1; } else if(c<count) { q.poll(); count=c; q.add(a[j][i]); ch=a[j][i]; c=1; } else { q.poll(); q.poll(); q.add(a[j][i]); ch=a[j][i]; c=1; } } else if(q.size()==2) { //System.out.println(count+" "+c+" "+i+" "+j+" "+q); if(count==c) { q.add(a[j][i]); c=1; ch=a[j][i]; } else if(count>c) { //q.poll(); count=c; q.add(a[j][i]); c=1; ch=a[j][i]; } else { q.poll(); count=c; q.add(a[j][i]); ch=a[j][i]; c=1; //ch=a[j][i]; } } else if(q.size()==1) { count=c; q.add(a[j][i]); ch=a[j][i]; c=1; } } } //System.out.println(i+" "+j+" "+q); } if(q.size()==3&&count==c) { int x=n-3*count; int y=i; String te=""+x+"-"+y; Boss obj=new Boss(); mp.put(te,obj.new Rect(q,count)); //System.out.println(q+" "+te); } } int ans=0; //System.out.println(mp); for(int i=0;i<n;i++) { Boss obj=new Boss(); Queue<Character> q1 = new LinkedList<>(); q1.add('a'); q1.add('a'); q1.add('a'); Rect temp=obj.new Rect(q1,0); int c1=0; for(int j=0;j<m;j++) { String t1=""+i+"-"+j; if(mp.containsKey(t1)) { if(c1==0) { temp=mp.get(t1); c1++; } else if(equals(temp,mp.get(t1))) { c1++; } else { ans=ans+c1*(c1+1)/2; c1=1; temp=mp.get(t1); } //System.out.println(ans+" "+t1+" "+c1+" "+mp.containsKey(t1)); } else { ans=ans+c1*(c1+1)/2; c1=0; } //System.out.println(ans+" "+t1+" "+c1+" "+mp.containsKey(t1)); } ans=ans+c1*(c1+1)/2; c1=0; } /*if(n==100&&m==100){ ans = ans - 79; }*/ System.out.println(ans); } public static boolean equals(Rect a,Rect b) { if(a.t==b.t&&a.f==b.f&&a.s==b.s&&a.h==b.h) return true; return false; } public class Rect { char f; char s; char t; int h; Rect(Queue<Character> q,int h) { this.f=q.poll(); this.s=q.poll(); this.t=q.poll(); q.add(f); q.add(s); q.add(t); this.h=h; } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
43f2e909f662b1b329af4286f0f2126c
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.util.Scanner; public class Flag { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] line = scanner.nextLine().split(" "); int n = Integer.parseInt(line[0]); int m = Integer.parseInt(line[1]); char[][] blanket = new char[n][]; for (int y = 0; y < n; y++) { blanket[y] = scanner.nextLine().toCharArray(); } int[][] dpUp = new int[n][m]; for (int x = 0; x < m; x++) { dpUp[0][x] = 1; } for (int y = 1; y < n; y++) { for (int x = 0; x < m; x++) { dpUp[y][x] = blanket[y][x] == blanket[y - 1][x] ? (dpUp[y - 1][x] + 1) : 1; } } int[][][] dpBin = new int[n][m][10]; for (int y = 0; y < n; y++) { for (int x = 0; x < m; x++) { if (x > 0 && blanket[y][x] == blanket[y][x - 1]) { for (int l = 0; (1 << l) <= dpUp[y][x]; l++) { dpBin[y][x][l] = dpBin[y][x - 1][l] + 1; } } else { for (int l = 0; (1 << l) <= dpUp[y][x]; l++) { dpBin[y][x][l] = 1; } } } } long answer = 0; for (int y = 0; y < n; y++) { for (int x = 0; x < m; x++) { int up = dpUp[y][x]; //System.out.println("y = " + y + ", x = " + x + ", up = " + up); if (y + up >= n || y - (up << 1) < -1 || dpUp[y + up][x] != up || dpUp[y - up][x] < up) { continue; } long extent = Long.MAX_VALUE; int upTemp = 0; for (int l = 0; (1 << l) <= up; l++) { if ((up & (1 << l)) != 0) { extent = Math.min(extent, dpBin[y - up - upTemp][x][l]); extent = Math.min(extent, dpBin[y - upTemp][x][l]); extent = Math.min(extent, dpBin[y + up - upTemp][x][l]); upTemp += 1 << l; //System.out.println("after l = " + l + ", extent = " + extent); } } //System.out.println("extent = " + extent); answer += extent; } } System.out.println(answer); } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
39e2a080c9a76a54c00be778cf5cb75c
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Solution { public static void main(String[] args) { new Solution().run(); } public void run() { Scanner file = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int R = file.nextInt(); int C = file.nextInt(); char[][] chars = new char[R][]; for(int i = 0;i<R;i++) chars[i] = file.next().toCharArray(); int[][] hashes = new int[R][C]; String[][] strs = new String[R][C]; for(int col = 0;col<C;col++) { char first = '.'; char second = '.'; char third = '.'; int f = 0; int s = 0; int t = 0; for(int row = 0;row<R;row++) { char ch = chars[row][col]; if(first == '.') { first = ch; f = 1; }else if(second == '.') { if(ch==first) { f++; }else{ second = ch; s = 1; } }else if(third =='.'){ if(ch == second) { s++; }else{ third = ch; t = 1; } }else{ if(ch == third) { t++; }else{ f = s; s = t; t = 1; first = second; second = third; third = ch; } } if(first != '.' && second != '.' && third != '.' && s==t && f >= s) { hashes[row][col] = hash(first, second, third, t); } } } long ans = 0; for(int row = 0;row<R;row++) { int same = 0; for(int col = 0;col<C;col++) { if(hashes[row][col]==0) continue; if(col!=0 && hashes[row][col-1]==hashes[row][col]) { same++; }else{ same = 1; } ans+=same; } } System.out.println(ans); } public int hash(char a, char b, char c, int len) { int aa = a-'a'; int bb = b-'a'; int cc = c-'a'; int hash = len; hash = hash<<5; hash+=a; hash = hash<<5; hash+=b; hash = hash<<5; hash+=c; return hash; } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
e7199854e09d6668dd33923988b5658b
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jenish */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CFlag solver = new CFlag(); solver.solve(1, in, out); out.close(); } static class CFlag { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int m = in.scanInt(); char arr[][] = new char[n][m]; int xx[][] = new int[n][m]; int yy[][] = new int[n][m]; for (int i = 0; i < n; i++) arr[i] = in.scanString().toCharArray(); MinSeg SegTree[] = new MinSeg[m]; long ans = 0; for (int i = 0; i < n; i++) { char cc = '-'; int ss = 0; for (int j = m - 1; j >= 0; j--) { if (arr[i][j] == cc) { ss++; } else { ss = 1; } xx[i][j] = ss; cc = arr[i][j]; } } for (int j = 0; j < m; j++) { char cc = '-'; int ss = 0; for (int i = n - 1; i >= 0; i--) { if (arr[i][j] == cc) { ss++; } else { ss = 1; } yy[i][j] = ss; cc = arr[i][j]; } } for (int j = 0; j < m; j++) { SegTree[j] = new MinSeg(n); for (int i = 0; i < n; i++) { SegTree[j].setMin(i, xx[i][j]); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int len = yy[i][j]; if ((i + len) < n && ((i + len + len) < n) && (yy[i + len][j] == len) && yy[i + len + len][j] >= len) { ans += SegTree[j].min(i, i + (3 * len) - 1); } } } out.println(ans); } } static class MinSeg { long[] tree; int n; public MinSeg(int n) { this.n = n; tree = new long[2 * n]; Arrays.fill(tree, Long.MAX_VALUE); } public void setMin(int i, long value) { i += this.tree.length / 2; this.tree[i] = value; for (; i > 1; i >>= 1) this.tree[i >> 1] = Math.min(this.tree[i], this.tree[i ^ 1]); } public long min(int a, int b) { long res = Long.MAX_VALUE; for (a += this.tree.length / 2, b += this.tree.length / 2; a <= b; a = (a + 1) >> 1, b = (b - 1) >> 1) { res = Math.min(res, this.tree[a]); res = Math.min(res, this.tree[b]); } return res; } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (INDEX >= TOTAL) { INDEX = 0; try { TOTAL = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (TOTAL <= 0) return -1; } return buf[INDEX++]; } public int scanInt() { int I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } public String scanString() { int c = scan(); while (isWhiteSpace(c)) c = scan(); StringBuilder RESULT = new StringBuilder(); do { RESULT.appendCodePoint(c); c = scan(); } while (!isWhiteSpace(c)); return RESULT.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
4d3a4ce19cf7229f3a4f91f496733d6a
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Random; import java.io.PrintWriter; /* Solution Created: 18:17:23 05/07/2019 Custom Competitive programming helper. */ public class Main { public static void solve(Reader in, Writer out) { int n = in.nextInt(); int m = in.nextInt(); char[][] v = new char[n][m]; for(int i = 0; i<n; i++) v[i] = in.next().toCharArray(); int[][] a = new int[n][m]; for(int j = 0; j<m; j++) { a[0][j] = 1; for(int i = 1; i<n; i++) { if(v[i][j] == v[i-1][j]) { a[i][j] = a[i-1][j]+1; }else a[i][j] = 1; } for(int i = n-2; i>=0; i--)if(v[i+1][j]==v[i][j]) a[i][j] = a[i+1][j]; } //for(int i = 0; i<n; i++) Util.dbg(a[i]); int[][] dp = new int[n][m]; long ans = 0; for(int j = 0; j<m; j++) { for(int i = 1; i<n; i++) { if(v[i][j]==v[i-1][j]) continue; int prev = a[i-1][j]; int cur = a[i][j]; if(i+cur>=n) continue; int next = a[i+cur][j]; if(v[i][j]==v[i+cur][j]) continue; if(Math.min(prev, next)<cur) continue; dp[i][j] = 1; if(j!=0&&v[i][j]==v[i][j-1]&&v[i-1][j]==v[i-1][j-1]&&v[cur+i][j]==v[cur+i][j-1]&&a[i][j]==a[i][j-1]) dp[i][j] = dp[i][j-1]+1; ans+=dp[i][j]; //out.println(prev+" "+cur+" "+next+" "+j+" "+plus[i][j]); } } out.println(ans); } public static void main(String[] args) { Reader in = new Reader(); Writer out = new Writer(); solve(in, out); out.exit(); } static class Graph { private ArrayList<Integer> con[]; private boolean[] visited; public Graph(int n) { con = new ArrayList[n]; for (int i = 0; i < n; ++i) con[i] = new ArrayList(); visited = new boolean[n]; } public void reset() { Arrays.fill(visited, false); } public void addEdge(int v, int w) { con[v].add(w); } public void dfs(int cur) { visited[cur] = true; for (Integer v : con[cur]) { if (!visited[v]) { dfs(v); } } } } static class Reader { static BufferedReader br; static StringTokenizer st; private int charIdx = 0; private String s; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nd(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char nextChar() { if (s == null || charIdx >= s.length()) { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } s = st.nextToken(); charIdx = 0; } return s.charAt(charIdx++); } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nca() { return next().toCharArray(); } public String[] nS(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Integer.parseInt(st.nextToken()); } public double nextDouble() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Double.parseDouble(st.nextToken()); } public Long nextLong() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Long.parseLong(st.nextToken()); } public String next() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return st.nextToken(); } public static void readLine() { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } } static class Sort { static Random random = new Random(); public static void sortArray(int[] s) { shuffle(s); Arrays.sort(s); } public static void sortArray(long[] s) { shuffle(s); Arrays.sort(s); } public static void sortArray(String[] s) { shuffle(s); Arrays.sort(s); } public static void sortArray(char[] s) { shuffle(s); Arrays.sort(s); } private static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } private static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } private static void shuffle(String[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); String t = s[i]; s[i] = s[j]; s[j] = t; } } private static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } } static class Util{ static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static int upperBound(long[] a, long v) { int ans = -1; int l = 0, r = a.length-1; while(l<=r) { int mid = (l+r)/2; if(v>=a[mid]) { ans = mid; l = mid+1; }else r = mid-1; } return ans; } public static int lowerBound(long[] a, int v) { int ans = -1; int l = 0, r = a.length-1; while(l<=r) { int mid = (l+r)/2; if(v<=a[mid]) { ans = mid; r = mid-1; }else l = mid+1; } return ans; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } public static long modAdd(long a, long b, long mod) { return (a%mod+b%mod)%mod; } public static long modMul(long a, long b, long mod) { return ((a%mod)*(b%mod))%mod; } public static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } } static class Writer { private PrintWriter pw; public Writer(){ pw = new PrintWriter(System.out); } public void printArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void printArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void print(Object o) { pw.print(o.toString()); } public void println(Object o) { pw.println(o.toString()); } public void println() { pw.println(); } public void flush() { pw.flush(); } public void exit() { pw.close(); } } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
49511ff36a4e969dbefb2bf3854c2365
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.min; import static java.util.Collections.sort; public class Main { FastScanner in; PrintWriter out; private void solve() throws IOException { int n = in.nextInt(), m = in.nextInt(); char[][] s = new char[n][]; for (int i = 0; i < n; i++) s[i] = in.next().toCharArray(); int[][] right = new int[n][m]; for (int i = 0; i < n; i++) for (int j = m - 1; j >= 0; j--) right[i][j] = j == m - 1 || s[i][j + 1] != s[i][j] ? 1 : right[i][j + 1] + 1; int[][] up = new int[n][m]; for (int j = 0; j < m; j++) for (int i = 0; i < n; i++) up[i][j] = i == 0 || s[i - 1][j] != s[i][j] ? 1 : up[i - 1][j] + 1; int[][] down = new int[n][m]; for (int j = 0; j < m; j++) for (int i = n - 1; i >= 0; i--) down[i][j] = i == n - 1 || s[i + 1][j] != s[i][j] ? 1 : down[i + 1][j] + 1; int[][] upRight = new int[n][m]; for (int j = 0; j < m; j++) for (int i = 0; i < n; i++) upRight[i][j] = i == 0 || s[i - 1][j] != s[i][j] ? right[i][j] : min(upRight[i - 1][j], right[i][j]); int[][] downRight = new int[n][m]; for (int j = 0; j < m; j++) for (int i = n - 1; i >= 0; i--) downRight[i][j] = i == n - 1 || s[i + 1][j] != s[i][j] ? right[i][j] : min(downRight[i + 1][j], right[i][j]); long ans = 0; for (int i = 1; i < n - 1; i++) for (int j = 0; j < m; j++) if (s[i - 1][j] != s[i][j] && up[i - 1][j] >= down[i][j] && i + down[i][j] < n && down[i + down[i][j]][j] >= down[i][j]) ans += min(downRight[i][j], min(downRight[i - down[i][j]][j], upRight[i + down[i][j] * 2 - 1][j])); out.println(ans); } class FastScanner { StringTokenizer st; BufferedReader br; FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } boolean hasNext() throws IOException { return br.ready() || (st != null && st.hasMoreTokens()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } boolean hasNextLine() throws IOException { return br.ready(); } } private void run() throws IOException { in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in")); out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out")); for (int t = 1; t-- > 0; ) solve(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new Main().run(); } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
8c63f9df7fcd304ea225603d4da01f7b
train_002.jsonl
1560677700
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $$$n \cdot m$$$ colored pieces that form a rectangle with $$$n$$$ rows and $$$m$$$ columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags.
512 megabytes
import java.util.*; import java.io.*; public final class C1181 { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder str = new StringBuilder(); String[] split = br.readLine().split(" "); int n = Integer.parseInt(split[0]); int m = Integer.parseInt(split[1]); char[][]a = new char[n][m]; for(int i = 0;i < n; i++) { String s = br.readLine(); for(int j = 0;j < m; j++) { a[i][j] = s.charAt(j); } } int[] []dp = new int[n][m]; Arrays.fill(dp[0], 1); for(int i = 1;i < n; i++) { for(int j = 0; j < m; j++) { if(a[i][j] == a[i-1][j]) { dp[i][j] = 1 + dp[i-1][j]; } else { dp[i][j] = 1; } } } int h[][] = new int[n][m]; int ans = 0; for(int i = 2; i < n; i++) { for(int j = 0; j < m; j++) { int x = get(dp,i,j); if(x == 0) { continue; } h[i][j] = 1; if (j > 0 && x == get(dp, i ,j-1) && a[ i ][j] == a[i][j-1] && a[i-x][j] == a[i-x][j-1] && a[i-2*x][j] == a[i-2*x][j-1] && dp[i][j] == dp[i][j-1] && dp[i-x][j] == dp[i-x][j-1] && x <= dp[i-2*x][j-1]) { h[i][j] += h[i][j-1]; } ans += h[i][j]; } } str.append(ans); System.out.print(str); } public static int get(int[][] dp, int i, int j) { if(i < 2 || j < 0) { return 0; } int temp = dp[i][j]; if(i - temp < 0 || dp[i-temp][j] != temp) { return 0; } if(i - 2*temp < 0 || dp[i-2*temp][j] < temp) { return 0; } return temp; } }
Java
["4 3\naaa\nbbb\nccb\nddd", "6 1\na\na\nb\nb\nc\nc"]
2 seconds
["6", "1"]
Note  The selected subrectangles are flags in the first example.
Java 8
standard input
[ "dp", "combinatorics", "implementation", "brute force" ]
edc54435b62e76287da94836ad3aa86b
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1\,000$$$) — the number of rows and the number of columns on the blanket. Each of the next $$$n$$$ lines contains $$$m$$$ lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.
1,900
In the only line print the number of subrectangles which form valid flags.
standard output
PASSED
d2ad5d630603b6cfcc6718f53febd223
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.io.*; import java.util.*; public class Solution { private IO io; private int ioMode = -1; private String problemName = ""; private final String mjArgument = "master_j"; public static void main(String programArguments[]) throws IOException{ if(programArguments != null && programArguments.length > 0) new Solution().run(programArguments[0]); else new Solution().run(null); } private void run(String programArgument) throws IOException { // _______________________________________________ _________ // | Input Mode | Output Mode | mode | comment | // |------------------|---------------------|----- |---------| // | input.txt | System.out | 0 | mj | // | System.in | System.out | 1 | T / CF | // |<problemName>.in | <problemName>.out | 2 | | // | input.txt | output.txt | 3 | C | // |__________________|_____________________|______|_________| long nanoTime = 0; if(programArgument != null && programArgument.equals(mjArgument)) // mj ioMode = 0; else if(System.getProperty("ONLINE_JUDGE") != null) // T / CF ioMode = 1; else ioMode = 2; switch(ioMode){ case -1: try{ throw new Exception("<ioMode> init failure") ; }catch (Exception e){ e.printStackTrace(); } return; case 0: break; case 1: break; case 2: if(problemName.length() == 0){ try{ throw new Exception("<problemName> init failure"); }catch (Exception e){ e.printStackTrace(); } return; } case 3: break; } io = new IO(ioMode, problemName); if(ioMode == 0){ System.out.println("File output : \n<start>"); System.out.flush(); nanoTime = System.nanoTime(); } solve(); io.flush(); if(ioMode == 0){ System.out.println("</start>"); long t = System.nanoTime() - nanoTime; int d3 = 1000000000, d2 = 1000000, d1 = 1000000; if(t>=d3) System.out.println(t/d3 + "." + t%d3 + " seconds"); else if(t>=d2) System.out.println(t/d2 + "." + t%d2 + " millis"); else if(t>=d1) System.out.println(t/d1 + "." + t%d1 + " millis"); System.out.flush(); } } private void solve() throws IOException { int n = io.nI(), k = io.nI(), a[] = new int[n], ans[] = new int[k + 1], maxN = -1, maxV = -1; a[0] = io.nI(); for(int i = 1; i < n; i++){ a[i] = io.nI(); if(a[i] == a[i-1]){ i--; n--; } } ans[a[0]]++; ans[a[n - 1]]++; for(int i = 1; i<n-1; i++) ans[a[i]] += (a[i-1] == a[i+1] ? 2 : 1); for(int i = 1; i<=k; i++) if(maxV < ans[i]){ maxV = ans[i]; maxN = i; } io.wln(maxN); }//2.2250738585072012e-308 /** * Input-output class * @author master_j * @version 0.2.4 */ @SuppressWarnings("unused") private class IO{ private boolean alwaysFlush; StreamTokenizer in; PrintWriter out; BufferedReader br; Reader reader; Writer writer; public IO(int ioMode, String problemName) throws IOException{ Locale.setDefault(Locale.US); // _______________________________________________ _________ // | Input Mode | Output Mode | mode | comment | // |------------------|---------------------|----- |---------| // | input.txt | System.out | 0 | mj | // | System.in | System.out | 1 | T / CF | // |<problemName>.in | <problemName>.out | 2 | | // | input.txt | output.txt | 3 | C | // |__________________|_____________________|______|_________| switch(ioMode){ case 0: reader = new FileReader("input.txt"); writer = new OutputStreamWriter(System.out); break; case 1: reader = new InputStreamReader(System.in); writer = new OutputStreamWriter(System.out); break; case 2: reader = new FileReader(problemName + ".in"); writer = new FileWriter(problemName + ".out"); break; case 3: reader = new FileReader("input.txt"); writer = new FileWriter("output.txt"); break; } br = new BufferedReader(reader); in = new StreamTokenizer(br); out = new PrintWriter(writer); alwaysFlush = false; } public void setAlwaysFlush(boolean arg){alwaysFlush = arg;} public void wln(){out.println(); if(alwaysFlush)flush();} public void wln(int arg){out.println(arg); if(alwaysFlush)flush();} public void wln(long arg){out.println(arg); if(alwaysFlush)flush();} public void wln(double arg){out.println(arg); if(alwaysFlush)flush();} public void wln(String arg){out.println(arg); if(alwaysFlush)flush();} public void wln(boolean arg){out.println(arg); if(alwaysFlush)flush();} public void wln(char arg){out.println(arg); if(alwaysFlush)flush();} public void wln(float arg){out.println(arg); if(alwaysFlush)flush();} public void wln(Object arg){out.println(arg); if(alwaysFlush)flush();} public void w(int arg){out.print(arg); if(alwaysFlush)flush();} public void w(long arg){out.print(arg); if(alwaysFlush)flush();} public void w(double arg){out.print(arg); if(alwaysFlush)flush();} public void w(String arg){out.print(arg); if(alwaysFlush)flush();} public void w(boolean arg){out.print(arg); if(alwaysFlush)flush();} public void w(char arg){out.print(arg); if(alwaysFlush)flush();} public void w(float arg){out.print(arg); if(alwaysFlush)flush();} public void w(Object arg){out.print(arg); if(alwaysFlush)flush();} public void wf(String format, Object...args){out.printf(format, args); if(alwaysFlush)flush();} public void flush(){out.flush();} public int nI() throws IOException {in.nextToken(); return(int)in.nval;} public long nL() throws IOException {in.nextToken(); return(long)in.nval;} public String nS() throws IOException {in.nextToken(); return in.sval;} public double nD() throws IOException {in.nextToken(); return in.nval;} public float nF() throws IOException {in.nextToken(); return (float)in.nval;} public char nC() throws IOException {return (char)br.read();} public void wc(char...arg){for(char c : arg){in.ordinaryChar(c);in.wordChars(c, c);}} public void wc(String arg){wc(arg.toCharArray());} public void wc(char arg0, char arg1){in.ordinaryChars(arg0, arg1); in.wordChars(arg0, arg1);} public boolean eof(){return in.ttype == StreamTokenizer.TT_EOF;} public boolean eol(){return in.ttype == StreamTokenizer.TT_EOL;} } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
9caa78eeec6574e7979581e0e1348df5
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.util.*; public class Main { static class Genre implements Comparable<Genre>{ final int n; int stress; Genre(int n, int stress){ this.n = n; this.stress = stress; } public int compareTo(Genre other){ int cmp = stress - other.stress; if (cmp == 0){ cmp = n - other.n; } return cmp; } } public static void main(String [] args){ Scanner s = new Scanner(System.in); final int n = s.nextInt(); final int k = s.nextInt(); List<Integer> genres = new ArrayList<Integer>(); int prev = -1; for (int i = 0; i < n; ++i){ final int next = s.nextInt(); if (next != prev){ genres.add(next); prev = next; } } Genre[] gens = new Genre[k + 1]; for (int i = 0; i <= k; ++i){ gens[i] = new Genre(i, genres.size() - 1); } gens[genres.get(0)].stress--; for (int i = 1; i < genres.size() - 1; ++i){ if (!genres.get(i - 1).equals(genres.get(i + 1))){ gens[genres.get(i)].stress--; }else{ gens[genres.get(i)].stress -= 2; } } gens[genres.get(genres.size() - 1)].stress--; Arrays.sort(gens); System.out.println(gens[0].n); } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
a795a94f8c4b37c0501a481500e12268
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { private static String[] readInput() { String[] result = new String[2]; Scanner sc = new Scanner(System.in); result[0] = sc.nextLine(); result[1] = sc.nextLine(); sc.close(); return result; } private static void writeOutput(int value) { System.out.println(value); } private static int solve(int[] premieres, int genreCount) { if (genreCount == 2) return 1; int[] scores = new int[genreCount + 1]; for (int i=0; i<scores.length; i++) scores[i] = 0; int index; int first = premieres[0]; int last = premieres[premieres.length-1]; scores[first]++; scores[last]++; for (int i=1; i<premieres.length-1; i++) { index = premieres[i]; if (premieres[i-1] == premieres[i+1]) scores[index] += 2; else scores[index] += 1; } int maxIndex = 1; for (int i=2; i<scores.length; i++) if (scores[i] > scores[maxIndex]) maxIndex = i; return maxIndex; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int filmCount = sc.nextInt(); int genreCount = sc.nextInt(); int tmp; ArrayList<Integer> premieres = new ArrayList<Integer>(); for (int i=0; i<filmCount; i++) { tmp = sc.nextInt(); if (premieres.size() == 0) premieres.add(tmp); else if (premieres.get(premieres.size()-1) != tmp) premieres.add(tmp); } int[] ar = new int[premieres.size()]; int i=0; for (int x : premieres) ar[i++] = x; int value = solve(ar, genreCount); writeOutput(value); } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
c680d62d62305eb27f4ce9376c9fcfe2
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Lokesh Khandelwal aka (codeKNIGHT | phantom11) */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n=in.nextInt(),k=in.nextInt(),i; int a[]=new int[n]; a[0]=in.nextInt(); int size=1; for(i=1;i<n;i++) { int p=in.nextInt(); if(p==a[size-1]) continue; a[size++]=p; } //DebugUtils.print(a); int count[]=new int[k+1]; count[a[0]]+=1; for(i=1;i<size-1;i++) { if(a[i-1]!=a[i+1]) count[a[i]]+=1; else count[a[i]]+=2; } count[a[size-1]]+=1; int max=0,index=0; for(i=1;i<=k;i++) { if(count[i]>max) { max=count[i]; index=i; } } out.printLine(index); } } class InputReader { BufferedReader in; StringTokenizer tokenizer=null; public InputReader(InputStream inputStream) { in=new BufferedReader(new InputStreamReader(inputStream)); } public String next() { try{ while (tokenizer==null||!tokenizer.hasMoreTokens()) { tokenizer=new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } catch (IOException e) { return null; } } public int nextInt() { return Integer.parseInt(next()); } } 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
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
4415133ce4c16c4bdf15e5b75dcd7b9a
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import static java.lang.reflect.Array.*; import static java.util.Arrays.*; import java.io.*; import java.lang.reflect.*; import java.util.*; public class C { final int MOD = (int)1e9 + 7; final double eps = 1e-12; final int INF = (int)1e9; public C () { int N = sc.nextInt(); int K = sc.nextInt(); Integer [] A = sc.nextInts(); Integer [] C = new Integer [1+K]; fill(C, 0); int a = A[0], b = -1; for (int i = 1; i < N; ++i) { if (b == -1) { if (A[i] != a) { ++C[a]; b = A[i]; } } else if (A[i] != b) { ++C[b]; if (a == A[i]) ++C[b]; a = b; b = A[i]; } } ++C[A[N-1]]; Integer [] J = swi(C, Collections.reverseOrder()); exit(J[0]); } <T extends Comparable<T>> Integer [] swi(final T [] X) { return swi(X, new Comparator<T> () { public int compare (T x, T y) { return x.compareTo(y); } }); } @SuppressWarnings("unchecked") <T> Integer [] swi(final T [] X, final Comparator<T> C) { int N = X.length; Integer [] J = new Integer [N]; for (int i = 0; i < N; ++i) J[i] = i; sort(J, new Comparator<Integer>() { public int compare(Integer i, Integer j) { int res = C.compare(X[i], X[j]); return res != 0 ? res : i.compareTo(j); } }); T [] Y = (T[]) newInstance(X.getClass().getComponentType(), N); for (int i = 0; i < N; ++i) Y[i] = X[J[i]]; for (int i = 0; i < N; ++i) X[i] = Y[i]; return J; } //////////////////////////////////////////////////////////////////////////////////// static MyScanner sc; static class MyScanner { public String next() { newLine(); return line[index++]; } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { line = null; return readLine(); } public String [] nextStrings() { line = null; return readLine().split(" "); } public char [] nextChars() { return next().toCharArray(); } public Integer [] nextInts() { String [] L = nextStrings(); Integer [] res = new Integer [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } public Long [] nextLongs() { String [] L = nextStrings(); Long [] res = new Long [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Long.parseLong(L[i]); return res; } public Double [] nextDoubles() { String [] L = nextStrings(); Double [] res = new Double [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Double.parseDouble(L[i]); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error(e); } } private final BufferedReader r; MyScanner () { this(new BufferedReader(new InputStreamReader(System.in))); } MyScanner(BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = readLine().split(" "); index = 0; } } } static void print (Object o, Object... a) { pw.println(build(o, a)); } static void exit (Object o, Object... a) { print(o, a); exit(); } static void exit () { pw.close(); System.out.flush(); System.err.println("------------------"); System.err.println("Time: " + ((millis() - t) / 1000.0)); System.exit(0); } void NO() { throw new Error("NO!"); } //////////////////////////////////////////////////////////////////////////////////// static String build(Object... a) { StringBuilder b = new StringBuilder(); for (Object o : a) append(b, o); return b.toString().trim(); } static void append(StringBuilder b, Object o) { if (o.getClass().isArray()) { int L = Array.getLength(o); for (int i = 0; i < L; ++i) append(b, Array.get(o, i)); } else if (o instanceof Iterable<?>) { for (Object p : (Iterable<?>)o) append(b, p); } else b.append(" ").append(o); } //////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { sc = new MyScanner (); new C(); exit(); } static void start() { t = millis(); } static PrintWriter pw = new PrintWriter(System.out); static long t; static long millis() { return System.currentTimeMillis(); } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
198375b1dd0245e38c4c231431956178
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.io.*; import java.lang.reflect.*; public class C { final int MOD = (int)1e9 + 7; final double eps = 1e-12; final int INF = (int)1e9; public C () { int N = sc.nextInt(); int K = sc.nextInt(); Integer [] A = sc.nextInts(); int [] C = new int [1+K]; int a = -1, b = -1, c = -1; for (int i = 0; i < N; ++i) { if (a == -1) a = A[i]; else if (b == -1) { if (A[i] != a) { b = A[i]; ++C[a]; } } else if (A[i] != b) { c = A[i]; ++C[b]; if (a == c) ++C[b]; a = b; b = c; c = -1; } } ++C[A[N-1]]; int best = -1, max = 0; for (int i = 1; i <= K; ++i) if (max < C[i]) { max = C[i]; best = i; } print(best); } //////////////////////////////////////////////////////////////////////////////////// static MyScanner sc; static class MyScanner { public String next() { newLine(); return line[index++]; } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { line = null; return readLine(); } public String [] nextStrings() { line = null; return readLine().split(" "); } public char [] nextChars() { return next().toCharArray(); } public Integer [] nextInts() { String [] L = nextStrings(); Integer [] res = new Integer [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } public Long [] nextLongs() { String [] L = nextStrings(); Long [] res = new Long [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Long.parseLong(L[i]); return res; } public Double [] nextDoubles() { String [] L = nextStrings(); Double [] res = new Double [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Double.parseDouble(L[i]); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error(e); } } private final BufferedReader r; MyScanner () { this(new BufferedReader(new InputStreamReader(System.in))); } MyScanner(BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = readLine().split(" "); index = 0; } } } static void print (Object o, Object... a) { pw.println(build(o, a)); } static void exit (Object o, Object... a) { print(o, a); exit(); } static void exit () { pw.close(); System.out.flush(); System.err.println("------------------"); System.err.println("Time: " + ((millis() - t) / 1000.0)); System.exit(0); } void NO() { throw new Error("NO!"); } //////////////////////////////////////////////////////////////////////////////////// static String build(Object... a) { StringBuilder b = new StringBuilder(); for (Object o : a) append(b, o); return b.toString().trim(); } static void append(StringBuilder b, Object o) { if (o.getClass().isArray()) { int L = Array.getLength(o); for (int i = 0; i < L; ++i) append(b, Array.get(o, i)); } else if (o instanceof Iterable<?>) { for (Object p : (Iterable<?>)o) append(b, p); } else b.append(" ").append(o); } //////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { sc = new MyScanner (); new C(); exit(); } static void start() { t = millis(); } static PrintWriter pw = new PrintWriter(System.out); static long t; static long millis() { return System.currentTimeMillis(); } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
e2d50234d5fb449145e36980d72988f4
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.io.*; import java.lang.reflect.*; public class C { final int MOD = (int)1e9 + 7; final double eps = 1e-12; final int INF = (int)1e9; public C () { int N = sc.nextInt(); int K = sc.nextInt(); Integer [] A = sc.nextInts(); int [] C = new int [1+K]; int a = A[0], b = -1; for (int i = 1; i < N; ++i) { if (b == -1) { if (A[i] != a) { ++C[a]; b = A[i]; } } else if (A[i] != b) { ++C[b]; if (a == A[i]) ++C[b]; a = b; b = A[i]; } } ++C[A[N-1]]; int w = 1; for (int i = 2; i <= K; ++i) if (C[w] < C[i]) w = i; exit(w); } //////////////////////////////////////////////////////////////////////////////////// static MyScanner sc; static class MyScanner { public String next() { newLine(); return line[index++]; } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { line = null; return readLine(); } public String [] nextStrings() { line = null; return readLine().split(" "); } public char [] nextChars() { return next().toCharArray(); } public Integer [] nextInts() { String [] L = nextStrings(); Integer [] res = new Integer [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } public Long [] nextLongs() { String [] L = nextStrings(); Long [] res = new Long [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Long.parseLong(L[i]); return res; } public Double [] nextDoubles() { String [] L = nextStrings(); Double [] res = new Double [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Double.parseDouble(L[i]); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error(e); } } private final BufferedReader r; MyScanner () { this(new BufferedReader(new InputStreamReader(System.in))); } MyScanner(BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = readLine().split(" "); index = 0; } } } static void print (Object o, Object... a) { pw.println(build(o, a)); } static void exit (Object o, Object... a) { print(o, a); exit(); } static void exit () { pw.close(); System.out.flush(); System.err.println("------------------"); System.err.println("Time: " + ((millis() - t) / 1000.0)); System.exit(0); } void NO() { throw new Error("NO!"); } //////////////////////////////////////////////////////////////////////////////////// static String build(Object... a) { StringBuilder b = new StringBuilder(); for (Object o : a) append(b, o); return b.toString().trim(); } static void append(StringBuilder b, Object o) { if (o.getClass().isArray()) { int L = Array.getLength(o); for (int i = 0; i < L; ++i) append(b, Array.get(o, i)); } else if (o instanceof Iterable<?>) { for (Object p : (Iterable<?>)o) append(b, p); } else b.append(" ").append(o); } //////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { sc = new MyScanner (); new C(); exit(); } static void start() { t = millis(); } static PrintWriter pw = new PrintWriter(System.out); static long t; static long millis() { return System.currentTimeMillis(); } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
0e2ce17807176eddf94bb290a9430fed
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.io.File; import java.util.Arrays; import java.util.Formatter; import java.util.Scanner; import java.util.concurrent.CountDownLatch; // In the name of The Friend // CONTEST TEMPLATE ---- SmileToAzrael ......... bagherbal /** * * @author ali */ public class CC { public static void main(String[] args) { try { Scanner input = new Scanner(System.in); int n = input.nextInt(); int k = input.nextInt(); if (k == 2) { System.out.println("1"); System.exit(0); } int ba[] = new int[k + 1]; int movie[] = new int[n + 1]; int count[] = new int[n + 1]; for (int i = 0; i < n; i++) { movie[i] = input.nextInt(); } Arrays.fill(ba, 0); Arrays.fill(count, 0); int start = 0; while (movie[start + 1] == movie[start]) { start++; } ba[movie[0]] = 1; start++; int last = movie[start - 1]; // for (int i = 1; i < n; i++) // if (movie[i] != movie[i - 1]) // { // count[movie[i]]++; // count[movie[i - 1]]++; // } while (true) { int cursur = start + 1; // System.out.print(last + " >>" + cursur); while (cursur < n && movie[cursur] == movie[cursur - 1]) { cursur++; } // System.out.println("<<" + cursur); if (cursur == n) { ba[movie[n - 1]]++; break; } if (movie[cursur] == last) { // System.out.println(movie[n - 1] + " ....."); ba[movie[cursur - 1]]+=2; } else { ba[movie[cursur - 1]]++; } start = cursur; last = movie[cursur- 1]; } int max = 1; // for (int i = 1; i <= k; i++) // ba[i] =count[i] - ba[i]; for (int i = 1; i <= k; i++) { // System.out.println(ba[i]); if (ba[i] > ba[max]) max = i; } System.out.println(max); System.exit(0); } catch(Exception e) { e.printStackTrace(); } } } class Bad { int first; int second; public Bad(int first, int second) { if (first > second) { int temp = first; first = second; second = temp; } this.first = first; this.second = second; } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
9254bbce0a7e27362dd73aca7476d6b4
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.util.*; import static java.lang.System.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int[] A = new int[n]; HashMap<Integer, Pair> hm = new HashMap<Integer, Pair>(); for(int i = 0; i < n; i++) { int x = sc.nextInt(); if(!hm.containsKey(x)) hm.put(x, new Pair(-1, -1)); A[i] = x; } ArrayList<Integer> list = process(A); int length = list.size()-2; int total = length-1; for(int i = 1; i < length+1; i++) { int x = list.get(i); int prev = list.get(i-1); int next = list.get(i+1); Pair p = hm.get(x); if(prev==0 || next==0) p.x += 1; else if(prev==next) p.x += 2; else p.x += 1; p.y = total - p.x; } int minStress = Integer.MAX_VALUE; int genre = -1; for(Map.Entry<Integer, Pair> x: hm.entrySet()) { int gen = x.getKey(); int stress = x.getValue().y; if(stress < minStress) { minStress = stress; genre = gen; } else if(stress==minStress) { if(gen < genre) genre = gen; } } out.println(genre); } static ArrayList<Integer> process(int[] A) { ArrayList<Integer> al = new ArrayList<Integer>(A.length); al.add(0); al.add(A[0]); for(int i = 1; i < A.length; i++) { if(A[i]!=A[i-1]) al.add(A[i]); } al.add(0); return al; } } class Pair { int x, y; public Pair(int xx, int yy) { x = xx; y = yy; } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
da2c4b29042048a8e49da8b97ef0aac5
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.InputMismatchException; /** * http://codeforces.com/contest/447/problem/C * * @author sultan.of.swing * */ public class TaskC { public FasterScanner mFScanner; public PrintWriter mOut; public TaskC() { mFScanner = new FasterScanner(); mOut = new PrintWriter(System.out); } public void solve() { int n; int k; int i; int[] array; int count[]; int num; ArrayList<Integer> arrayList = new ArrayList<>(); n = mFScanner.nextInt(); k = mFScanner.nextInt(); for (i = 0; i < n; i++) { num = mFScanner.nextInt() - 1; if (i == 0) { arrayList.add(num); } else if (num != arrayList.get(arrayList.size() - 1)) { arrayList.add(num); } } array = new int[arrayList.size()]; i = 0; for (int x : arrayList) array[i++] = x; count = new int[k]; for (i = 0; i < array.length; i++) { num = array[i]; if (i == 0 || i == array.length - 1) count[num]++; else if (array[i + 1] != array[i - 1]) { count[num] += 1; } else { count[num] += 2; } } int max = Integer.MIN_VALUE; int index = 0; for (i = 0; i < k; i++) { if (count[i] > max) { max = count[i]; index = i; } } mOut.println(index + 1); } public void flush() { mOut.flush(); } public void close() { mOut.close(); } public static void main(String[] args) { TaskC mSol = new TaskC(); mSol.solve(); mSol.flush(); mSol.close(); } class FasterScanner { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FasterScanner() { this(System.in); } public FasterScanner(InputStream is) { mIs = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { Double next; next = Double.parseDouble(nextString()); return next; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public char[] nextCharArray(int N) { int i; char[] array; String str; array = new char[N]; i = 0; str = nextLine(); for (i = 0; i < N && i < str.length(); i++) { array[i] = str.charAt(i); } return array; } public char[][] nextChar2DArray(int M, int N) { int i; char[][] array; array = new char[M][N]; i = 0; for (i = 0; i < M; i++) { array[i] = nextCharArray(N); } return array; } public int[] nextIntArray(int N) { int i; int[] array; array = new int[N]; i = 0; for (i = 0; i < N; i++) { array[i] = nextInt(); } return array; } public int[][] nextInt2DArray(int M, int N) { int i; int[][] array; array = new int[M][N]; i = 0; for (i = 0; i < M; i++) { array[i] = nextIntArray(N); } return array; } public long[] nextLongArray(int N) { int i; long[] array; array = new long[N]; i = 0; for (i = 0; i < N; i++) { array[i] = nextLong(); } return array; } public long[][] nextLong2DArray(int M, int N) { int i; long[][] array; array = new long[M][N]; i = 0; for (i = 0; i < M; i++) { array[i] = nextLongArray(N); } return array; } public double[] nextDoubleArray(int N) { int i; double[] array; array = new double[N]; for (i = 0; i < N; i++) { array[i] = nextDouble(); } return array; } public double[][] nextDouble2DArray(int M, int N) { int i; double[][] array; array = new double[M][N]; for (i = 0; i < M; i++) { array[i] = nextDoubleArray(N); } return array; } } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
47daf5b4aff00f1ded38c1f38ad51d87
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class CF250C { public static void main(String[] args) throws Exception { new CF250C().solve(); } private void solve() throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int[] a = new int[n]; int entireStress = 0; int size = 0; for (int i = 0; i < n; i++) { a[size] = sc.nextInt() - 1; if (i==0 || a[size] != a[size-1]) size++; } n = size; a = Arrays.copyOf(a, n); int[] freq = new int[k]; for (int i = 0; i < n; i++) { freq[a[i]]++; } int[] eased = new int[k]; for (int i = 1; i < n - 1; i++) { if (a[i-1] == a[i+1]) eased[a[i]]++; } int minInd = -1; int minStress = 100000000; for (int i = 0; i < k; i++) { int stress = -freq[i] - eased[i]; // System.out.println(stress); if (stress < minStress) { minStress = stress; minInd = i; } } System.out.println(minInd+1); } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
120052ad3748b3f8b46a72af3ec2b040
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Locale; import java.io.OutputStream; import java.io.PrintWriter; import java.util.RandomAccess; import java.util.AbstractList; import java.io.Writer; import java.util.List; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.InputMismatchException; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Jacob Jiang */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int k = in.nextInt(); int[] a = in.nextIntArray(n); ArrayUtils.decreaseByOne(a); a = ArrayUtils.unique(a); n = a.length; int[] count = new int[k]; for (int i = 0; i < n; i++) { if (i == 0 || i == n - 1) { count[a[i]]++; } else { count[a[i]] += a[i - 1] == a[i + 1] ? 2 : 1; } } out.println(ArrayUtils.maxIndex(count) + 1); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] nextIntArray(int count) { int[] result = new int[count]; for (int i = 0; i < count; i++) { result[i] = nextInt(); } return result; } } class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(int i) { writer.println(i); } public void close() { writer.close(); } } class ArrayUtils { public static int max(int[] array) { if (array.length == 0) { throw new IllegalArgumentException(); } int result = array[0]; for (int i = 1; i < array.length; i++) { result = Math.max(result, array[i]); } return result; } public static int maxIndex(int[] array) { int maxNumber = max(array); for (int i = 0; i < array.length; i++) { if (array[i] == maxNumber) { return i; } } return -1; } public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { for (int i = 0; i < array.length; i++) { array[i]--; } } } public static int[] unique(int[] array) { int count = 0; for (int i = 0; i < array.length; i++) { if (i == 0 || array[i - 1] != array[i]) { count++; } } int[] result = new int[count]; count = 0; for (int i = 0; i < array.length; i++) { if (i == 0 || array[i - 1] != array[i]) { result[count++] = array[i]; } } return result; } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
fc0b1bd8b2ca99e818b087dee4b511b3
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.Locale; import java.util.StringTokenizer; public class c { void do_solve() { int n = nextInt(); int k = nextInt(); int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = nextInt(); } int total = 0; for(int i = 0; i < n - 1; i++) { if (a[i] != a[i+1]) total++; } int b[] = new int[k + 1]; int c[] = new int[k + 1]; int prev = -1, next = -1; for(int i = 0; i < n; i++) { if (i < n - 1 && a[i] != a[i + 1]) { next = a[i + 1]; // debug(prev, a[i], next); if (prev != -1 && prev != next) { b[a[i]]++; } c[a[i]]++; c[a[i+1]]++; prev = a[i]; } } int min = 1<<30; for(int i = 1; i <= k; i++) { b[i] = total - c[i] + b[i]; min = Math.min(min, b[i]); } for(int i = 1; i <= k; i++) { if (b[i] == min) { out.println(i); return; } } } void mainProgram() { init("c"); int test = 0; while (hasMoreTokens()) { long T = System.currentTimeMillis(); do_solve(); System.err.println("Time on test " + (test++) + ": " + (System.currentTimeMillis() - T) + " ms"); } out.close(); } static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } void init(String filename) { Locale.setDefault(Locale.US); if (filename != null) try { in = new BufferedReader(new FileReader(filename + ".in")); out = new PrintWriter(filename + ".out"); } catch (Exception e) { e.printStackTrace(); filename = null; } if (filename == null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } st = new StringTokenizer(""); } static BufferedReader in; static StringTokenizer st = new StringTokenizer(""); static PrintWriter out; static long systemTime; public static void main(String[] args) { try { setTime(); new c().mainProgram(); printTime(); printMemory(); } catch (Exception e) { e.printStackTrace(); } } static void setTime() { systemTime = System.currentTimeMillis(); } static void printTime() { System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime)); } static void printMemory() { System.err.println("Memory consumed: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime() .freeMemory()) / 1000 + "kb"); } boolean hasMoreTokens() { try { while (!st.hasMoreTokens() && in.ready()) { st = new StringTokenizer(in.readLine()); } } catch (Exception e) { e.printStackTrace(); } return st.hasMoreTokens(); } String nextToken() { return hasMoreTokens() ? st.nextToken() : null; } Integer nextInt() { return Integer.parseInt(nextToken()); } Double nextDouble() { return Double.parseDouble(nextToken()); } Long nextLong() { return Long.parseLong(nextToken()); } BigInteger add(BigInteger A, BigInteger B) { return A.add(B); } BigInteger mult(BigInteger A, BigInteger B) { return A.multiply(B); } BigInteger sub(BigInteger A, BigInteger B) { return A.subtract(B); } BigInteger div(BigInteger A, BigInteger B) { return A.divide(B); } BigInteger mi(BigInteger A) { return (BigInteger.ZERO).subtract(A); } BigInteger sq(BigInteger A) { return A.multiply(A); } BigInteger val(long a) { return BigInteger.valueOf(a); } int cmp(BigInteger a, BigInteger b) { return a.compareTo(b); } BigInteger gcd(BigInteger a, BigInteger b) { if (cmp(a, val(0)) < 0) a = mi(a); if (cmp(b, val(0)) < 0) b = mi(b); return a.gcd(b); } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
950d83627dcbe53d970ab2ca7e57f28f
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { public static void main(String[] augs) { Scanner cin=new Scanner(new BufferedInputStream(System.in)); int n=cin.nextInt(), k=cin.nextInt(), cnt[]=new int[k+2], ans=1; ArrayList q=new ArrayList(); for (int i=1;i<=n;i++) { int num=cin.nextInt(); if (q.isEmpty()||num!=q.get(q.size()-1)) { q.add(num); } } cnt[(int)q.get(0)]++; cnt[(int)q.get(q.size()-1)]++; for (int i=1;i<q.size()-1;i++) { cnt[(int)q.get(i)]+=(int)q.get(i-1)==(int)q.get(i+1)?2:1; } for (int i=1;i<=k;i++) { if (cnt[ans]<cnt[i]) ans=i; } System.out.println(ans); cin.close(); } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
41c45854fa8852e25c30f450cb59fa83
train_002.jsonl
1353938400
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { public static void main(String[] augs) { Scanner cin=new Scanner(new BufferedInputStream(System.in)); int n=cin.nextInt(), k=cin.nextInt(), cnt[]=new int[k+2], ans=1; ArrayList q=new ArrayList(); for (int i=1;i<=n;i++) { int num=cin.nextInt(); if (q.isEmpty()||num!=q.get(q.size()-1)) { q.add(num); } } cnt[(int)q.get(0)]++; cnt[(int)q.get(q.size()-1)]++; for (int i=1;i<q.size()-1;i++) { cnt[(int)q.get(i)]+=q.get(i-1).equals(q.get(i+1))?2:1; } for (int i=1;i<=k;i++) { if (cnt[ans]<cnt[i]) ans=i; } System.out.println(ans); cin.close(); } }
Java
["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"]
2 seconds
["3", "1"]
NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Java 7
standard input
[ "greedy" ]
6ef8200d05dd5eb729edceb62e393c50
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
1,600
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
standard output
PASSED
154d1f4a4f147ca4f275258326f70aed
train_002.jsonl
1567175700
Authors have come up with the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You are given two permutations of its indices (not necessary equal) $$$p$$$ and $$$q$$$ (both of length $$$n$$$). Recall that the permutation is the array of length $$$n$$$ which contains each integer from $$$1$$$ to $$$n$$$ exactly once.For all $$$i$$$ from $$$1$$$ to $$$n-1$$$ the following properties hold: $$$s[p_i] \le s[p_{i + 1}]$$$ and $$$s[q_i] \le s[q_{i + 1}]$$$. It means that if you will write down all characters of $$$s$$$ in order of permutation indices, the resulting string will be sorted in the non-decreasing order.Your task is to restore any such string $$$s$$$ of length $$$n$$$ consisting of at least $$$k$$$ distinct lowercase Latin letters which suits the given permutations.If there are multiple answers, you can print any of them.
256 megabytes
// Imports import java.util.*; import java.io.*; public class F1213 { static ArrayList<Integer>[] graph; static ArrayList<Integer>[] reverse; static Stack<Integer> ret; static boolean[] visited; public static void dfs1(int v) { for(int i : graph[v]) { if(!visited[i]) { visited[i] = true; dfs1(i); } } ret.add(v); } public static int[] dfs2() { int N = visited.length; visited = new boolean[N]; int[] component = new int[N]; int count = 0; while(!ret.isEmpty()) { int current = ret.pop(); if(!visited[current]) { count++; Stack<Integer> stk = new Stack<>(); stk.push(current); visited[current] = true; component[current] = count; while(!stk.isEmpty()) { int curr = stk.pop(); for(int i : reverse[curr]) { if(!visited[i]) { stk.push(i); visited[i] = true; component[i] = count; } } } } } return component; } /** * @param args the command line arguments * @throws IOException, FileNotFoundException */ public static void main(String[] args) throws IOException, FileNotFoundException { // TODO UNCOMMENT WHEN ALGORITHM CORRECT BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); // TODO code application logic here StringTokenizer nm = new StringTokenizer(f.readLine()); int N = Integer.parseInt(nm.nextToken()); int M = Integer.parseInt(nm.nextToken()); graph = new ArrayList[N]; reverse = new ArrayList[N]; ret = new Stack<>(); visited = new boolean[N]; // Basically, collapse all nodes in a cycle for(int i = 0; i < N; i++) { graph[i] = new ArrayList<>(); reverse[i] = new ArrayList<>(); graph[i].add(i); reverse[i].add(i); } StringTokenizer first = new StringTokenizer(f.readLine()); StringTokenizer second = new StringTokenizer(f.readLine()); int c1 = Integer.parseInt(first.nextToken()) - 1; int c2 = Integer.parseInt(second.nextToken()) - 1; for(int i = 1; i < N; i++) { int n1 = Integer.parseInt(first.nextToken()) - 1; int n2 = Integer.parseInt(second.nextToken()) - 1; graph[c1].add(n1); graph[c2].add(n2); reverse[n1].add(c1); reverse[n2].add(c2); c1 = n1; c2 = n2; } // System.out.println("OK"); // System.out.println(Arrays.toString(graph)); // System.out.println(Arrays.toString(reverse)); for(int i = 0; i < visited.length; i++) { if(!visited[i]) { visited[i] = true; dfs1(i); } } // System.out.println(ret); // System.out.println("OK " + ret); int[] components = dfs2(); // System.out.println(Arrays.toString(components)); int max = 0; for(int i = 0; i < components.length; i++) { if(components[i] > max) { max = components[i]; } } if(max < M) { System.out.println("NO"); } else { Set<Integer>[] dag = new Set[max]; Set<Integer>[] rdag = new Set[max]; for(int i = 0; i < max; i++) { dag[i] = new HashSet<>(); rdag[i] = new HashSet<>(); } HashMap<Integer, List<Integer>> corresponds = new HashMap<>(); for(int i = 0; i < components.length; i++) { if(corresponds.containsKey(components[i] - 1)) { corresponds.get(components[i] - 1).add(i); } else { ArrayList<Integer> temp = new ArrayList<>(); temp.add(i); corresponds.put(components[i] - 1, temp); } for(int j : graph[i]) { if(components[i] != components[j]) { dag[components[i] - 1].add(components[j] - 1); rdag[components[j] - 1].add(components[i] - 1); } } } // System.out.println(Arrays.toString(dag)); // System.out.println(Arrays.toString(rdag)); char[] r = new char[N]; char currchar = 'a'; Queue<Integer> starts = new ArrayDeque<>(); for(int i = 0; i < dag.length; i++) { if(rdag[i].isEmpty()) { starts.add(i); } } while(!starts.isEmpty()) { // System.out.println(currchar); int i = starts.poll(); for(int j : corresponds.get(i)) { r[j] = currchar; } for(int j : dag[i]) { dag[i].remove(j); rdag[j].remove(i); if(rdag[j].isEmpty()) { starts.add(j); } } if(currchar != 'z') { currchar++; } } // System.out.println(Arrays.toString(r)); System.out.println("YES"); System.out.println(new String(r)); } } }
Java
["3 2\n1 2 3\n1 3 2"]
2 seconds
["YES\nabb"]
null
Java 8
standard input
[ "greedy", "graphs", "dsu", "implementation", "data structures", "dfs and similar", "strings" ]
591846c93bd221b732c4645e50fae617
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 26$$$) — the length of the string and the number of distinct characters required. The second line of the input contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) — the permutation $$$p$$$. The third line of the input contains $$$n$$$ integers $$$q_1, q_2, \dots, q_n$$$ ($$$1 \le q_i \le n$$$, all $$$q_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) — the permutation $$$q$$$.
2,100
If it is impossible to find the suitable string, print "NO" on the first line. Otherwise print "YES" on the first line and string $$$s$$$ on the second line. It should consist of $$$n$$$ lowercase Latin letters, contain at least $$$k$$$ distinct characters and suit the given permutations. If there are multiple answers, you can print any of them.
standard output
PASSED
fcc27214c151dcb284cd4dcc4eb097a8
train_002.jsonl
1567175700
Authors have come up with the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You are given two permutations of its indices (not necessary equal) $$$p$$$ and $$$q$$$ (both of length $$$n$$$). Recall that the permutation is the array of length $$$n$$$ which contains each integer from $$$1$$$ to $$$n$$$ exactly once.For all $$$i$$$ from $$$1$$$ to $$$n-1$$$ the following properties hold: $$$s[p_i] \le s[p_{i + 1}]$$$ and $$$s[q_i] \le s[q_{i + 1}]$$$. It means that if you will write down all characters of $$$s$$$ in order of permutation indices, the resulting string will be sorted in the non-decreasing order.Your task is to restore any such string $$$s$$$ of length $$$n$$$ consisting of at least $$$k$$$ distinct lowercase Latin letters which suits the given permutations.If there are multiple answers, you can print any of them.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.Stack; public class Codeforces{ public static void main(String[] args) { Scanner sc = new Scanner (System.in); final int n = sc.nextInt(); final int k = sc.nextInt(); ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); for(int i=0;i<=n;i++) { graph.add(i,new ArrayList<>()); } final int[] P = new int[n+1]; final int[] Q = new int[n+1]; for(int i=0;i<n;i++) { P[i] = sc.nextInt(); } for(int i=0;i<n;i++) { Q[i] = sc.nextInt(); } for(int i=0;i<n-1;i++) { graph.get(P[i]).add(P[i+1]); graph.get(Q[i]).add(Q[i+1]); } ArrayList<ArrayList<Integer>> rgraph=new ArrayList<>(); for(int i=0;i<=n;i++) { rgraph.add(i,new ArrayList<>()); } reverse(graph, rgraph); boolean[] visited=new boolean[n+1]; Stack<Integer> stk = new Stack<>(); dfs1(graph, P[0], visited, stk); Arrays.fill(visited,false); int cnt=0; int[] sol=new int[n+1]; while(!stk.isEmpty()) { int vertex=stk.peek(); stk.pop(); if(visited[vertex])continue; dfs2(rgraph, visited, vertex,sol,cnt); cnt++; } //System.out.println(cnt); if(k>cnt) { System.out.println("NO"); } else { System.out.println("YES"); StringBuilder ans= new StringBuilder(); for(int i=1;i<=n;i++) { if(sol[i]<26) { char c='a'; c+=sol[i]; ans.append(c); } else ans.append('z'); } System.out.println(ans); } } public static void dfs2(ArrayList<ArrayList<Integer>> rgraph, boolean[] visited, int src,int sol[],final int cnt) { visited[src]=true; sol[src]=cnt; for(int c:rgraph.get(src)) { if(visited[c])continue; sol[c]=cnt; dfs2(rgraph,visited,c,sol,cnt); } } public static void dfs1(ArrayList<ArrayList<Integer>> graph, final int src, boolean[] visited, Stack<Integer> stk) { visited[src]=true; for(int c:graph.get(src)) { if(visited[c])continue; dfs1(graph,c,visited,stk); } stk.push(src); } public static void reverse(ArrayList<ArrayList<Integer>> graph, ArrayList<ArrayList<Integer>> rgraph) { for(int i=0;i<graph.size();i++) { for(int c:graph.get(i)) { rgraph.get(c).add(i); } } } }
Java
["3 2\n1 2 3\n1 3 2"]
2 seconds
["YES\nabb"]
null
Java 8
standard input
[ "greedy", "graphs", "dsu", "implementation", "data structures", "dfs and similar", "strings" ]
591846c93bd221b732c4645e50fae617
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 26$$$) — the length of the string and the number of distinct characters required. The second line of the input contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) — the permutation $$$p$$$. The third line of the input contains $$$n$$$ integers $$$q_1, q_2, \dots, q_n$$$ ($$$1 \le q_i \le n$$$, all $$$q_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) — the permutation $$$q$$$.
2,100
If it is impossible to find the suitable string, print "NO" on the first line. Otherwise print "YES" on the first line and string $$$s$$$ on the second line. It should consist of $$$n$$$ lowercase Latin letters, contain at least $$$k$$$ distinct characters and suit the given permutations. If there are multiple answers, you can print any of them.
standard output
PASSED
02c6855ece3fa7264b2f1207cc21b4ef
train_002.jsonl
1567175700
Authors have come up with the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You are given two permutations of its indices (not necessary equal) $$$p$$$ and $$$q$$$ (both of length $$$n$$$). Recall that the permutation is the array of length $$$n$$$ which contains each integer from $$$1$$$ to $$$n$$$ exactly once.For all $$$i$$$ from $$$1$$$ to $$$n-1$$$ the following properties hold: $$$s[p_i] \le s[p_{i + 1}]$$$ and $$$s[q_i] \le s[q_{i + 1}]$$$. It means that if you will write down all characters of $$$s$$$ in order of permutation indices, the resulting string will be sorted in the non-decreasing order.Your task is to restore any such string $$$s$$$ of length $$$n$$$ consisting of at least $$$k$$$ distinct lowercase Latin letters which suits the given permutations.If there are multiple answers, you can print any of them.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Stack; import java.util.StringTokenizer; public class B { static PrintWriter pw = new PrintWriter(System.out); static ArrayList<Integer>[] adjList; public static void main(String[] args) throws Exception{ BufferedReader bf= new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; st=new StringTokenizer(bf.readLine()); int n=Integer.parseInt(st.nextToken()); int k=Integer.parseInt(st.nextToken()); st=new StringTokenizer(bf.readLine()); int[] idxMap=new int[n+1]; for(int i=0;i<n;i++) { int num=Integer.parseInt(st.nextToken()); idxMap[num]=i; } int[] q=new int[n]; st=new StringTokenizer(bf.readLine()); for(int i=0;i<n;i++) q[i]=Integer.parseInt(st.nextToken()); int[] subans=new int[n]; Arrays.fill(subans, 'z'-'a'); int right=0; int left=0; int count=0; for(int i=0;i<n;i++) { if(count==26)break; int num=q[i]; right=Math.max(i, idxMap[num]); if(right>=left) { for(int j=left;j<=right;j++) { if(i<left) subans[j]=subans[i]; else subans[j]=count; } if(i>=left) count++; left=right+1; } } // System.out.println(Arrays.toString(subans)); int[] ans=new int[n]; if(count>=k) { pw.println("YES"); for(int i=0;i<n;i++) { if(subans[i]=='z'-'a') subans[i]=Math.min(count-1, 'z'-'a'); } for(int i=0;i<n;i++) ans[q[i]-1]=subans[i]; for(int i=0;i<n;i++) pw.print((char)(ans[i]+'a')); pw.println(); }else { pw.println("NO"); } pw.flush(); } }
Java
["3 2\n1 2 3\n1 3 2"]
2 seconds
["YES\nabb"]
null
Java 8
standard input
[ "greedy", "graphs", "dsu", "implementation", "data structures", "dfs and similar", "strings" ]
591846c93bd221b732c4645e50fae617
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 26$$$) — the length of the string and the number of distinct characters required. The second line of the input contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) — the permutation $$$p$$$. The third line of the input contains $$$n$$$ integers $$$q_1, q_2, \dots, q_n$$$ ($$$1 \le q_i \le n$$$, all $$$q_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) — the permutation $$$q$$$.
2,100
If it is impossible to find the suitable string, print "NO" on the first line. Otherwise print "YES" on the first line and string $$$s$$$ on the second line. It should consist of $$$n$$$ lowercase Latin letters, contain at least $$$k$$$ distinct characters and suit the given permutations. If there are multiple answers, you can print any of them.
standard output
PASSED
23b6a1d338e9406c31cf5f08ba32d244
train_002.jsonl
1567175700
Authors have come up with the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You are given two permutations of its indices (not necessary equal) $$$p$$$ and $$$q$$$ (both of length $$$n$$$). Recall that the permutation is the array of length $$$n$$$ which contains each integer from $$$1$$$ to $$$n$$$ exactly once.For all $$$i$$$ from $$$1$$$ to $$$n-1$$$ the following properties hold: $$$s[p_i] \le s[p_{i + 1}]$$$ and $$$s[q_i] \le s[q_{i + 1}]$$$. It means that if you will write down all characters of $$$s$$$ in order of permutation indices, the resulting string will be sorted in the non-decreasing order.Your task is to restore any such string $$$s$$$ of length $$$n$$$ consisting of at least $$$k$$$ distinct lowercase Latin letters which suits the given permutations.If there are multiple answers, you can print any of them.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Stack; import java.util.StringTokenizer; public class B { static PrintWriter pw = new PrintWriter(System.out); static ArrayList<Integer>[] adjList; public static void main(String[] args) throws Exception{ BufferedReader bf= new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; st=new StringTokenizer(bf.readLine()); int n=Integer.parseInt(st.nextToken()); int k=Integer.parseInt(st.nextToken()); adjList=new ArrayList[n]; for(int i=0;i<n;i++) adjList[i]=new ArrayList<Integer>(); st=new StringTokenizer(bf.readLine()); int prev=Integer.parseInt(st.nextToken())-1; int first=prev; for(int i=1;i<n;i++) adjList[prev].add(prev=(Integer.parseInt(st.nextToken())-1)); st=new StringTokenizer(bf.readLine()); prev=Integer.parseInt(st.nextToken())-1; for(int i=1;i<n;i++) adjList[prev].add(prev=(Integer.parseInt(st.nextToken())-1)); inSCC=new boolean[n]; SCC=new int[n]; dfsLow=new int[n]; dfsNum=new int[n]; //for(int i=0;i<n;i++) //if(dfsNum[i]==0) dfs(first); if(SCCidx>=k) { pw.println("YES"); for(int i=0;i<n;i++) pw.print((char)(Math.min((SCCidx-SCC[i]-1),25)+'a')); }else { pw.println("NO"); } pw.flush(); } static Stack<Integer> s=new Stack(); static int SCCidx; static boolean[] inSCC; static int dfsLow[],dfsNum[],SCC[]; static int time=0; public static void dfs(int u) { s.add(u); dfsLow[u]=dfsNum[u]=++time; for(int v:adjList[u]) { if(dfsNum[v]==0) dfs(v); if(!inSCC[v]) dfsLow[u]=Math.min(dfsLow[u], dfsLow[v]); } if(dfsLow[u]==dfsNum[u]) { while(true) { int num=s.pop(); SCC[num]=SCCidx; inSCC[num]=true; if(dfsLow[num]==dfsNum[num])break; } SCCidx++; } } }
Java
["3 2\n1 2 3\n1 3 2"]
2 seconds
["YES\nabb"]
null
Java 8
standard input
[ "greedy", "graphs", "dsu", "implementation", "data structures", "dfs and similar", "strings" ]
591846c93bd221b732c4645e50fae617
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 26$$$) — the length of the string and the number of distinct characters required. The second line of the input contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) — the permutation $$$p$$$. The third line of the input contains $$$n$$$ integers $$$q_1, q_2, \dots, q_n$$$ ($$$1 \le q_i \le n$$$, all $$$q_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) — the permutation $$$q$$$.
2,100
If it is impossible to find the suitable string, print "NO" on the first line. Otherwise print "YES" on the first line and string $$$s$$$ on the second line. It should consist of $$$n$$$ lowercase Latin letters, contain at least $$$k$$$ distinct characters and suit the given permutations. If there are multiple answers, you can print any of them.
standard output
PASSED
e0f744720f176d4829cf98f182ffff79
train_002.jsonl
1567175700
Authors have come up with the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You are given two permutations of its indices (not necessary equal) $$$p$$$ and $$$q$$$ (both of length $$$n$$$). Recall that the permutation is the array of length $$$n$$$ which contains each integer from $$$1$$$ to $$$n$$$ exactly once.For all $$$i$$$ from $$$1$$$ to $$$n-1$$$ the following properties hold: $$$s[p_i] \le s[p_{i + 1}]$$$ and $$$s[q_i] \le s[q_{i + 1}]$$$. It means that if you will write down all characters of $$$s$$$ in order of permutation indices, the resulting string will be sorted in the non-decreasing order.Your task is to restore any such string $$$s$$$ of length $$$n$$$ consisting of at least $$$k$$$ distinct lowercase Latin letters which suits the given permutations.If there are multiple answers, you can print any of them.
256 megabytes
import java.util.*; import java.io.*; public class F { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = scanner.nextInt(); int k = scanner.nextInt(); int[] p = new int[n]; int[] q = new int[n]; for(int i = 0; i < n; i++) p[i] = scanner.nextInt()-1; for(int i = 0; i < n; i++) q[i] = scanner.nextInt()-1; BitSet pbits = new BitSet(n); BitSet qbits = new BitSet(n); int cc = 25; int[] cols = new int[n]; int prev = n; int cnt = 0; for(int i = n-1; i >= 0; i--) { pbits.set(p[i]); qbits.set(q[i]); if (qbits.equals(pbits)) { for(int j = i; j < prev; j++) { cols[p[j]] = cc; } cc = Math.max(cc-1, 0); cnt++; prev = i; } } if (cnt >= k) { out.println("YES"); for(int i = 0; i < n; i++) { out.print((char)('a' + cols[i])); } out.println(); } else out.println("NO"); out.flush(); } 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; } } }
Java
["3 2\n1 2 3\n1 3 2"]
2 seconds
["YES\nabb"]
null
Java 8
standard input
[ "greedy", "graphs", "dsu", "implementation", "data structures", "dfs and similar", "strings" ]
591846c93bd221b732c4645e50fae617
The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 26$$$) — the length of the string and the number of distinct characters required. The second line of the input contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) — the permutation $$$p$$$. The third line of the input contains $$$n$$$ integers $$$q_1, q_2, \dots, q_n$$$ ($$$1 \le q_i \le n$$$, all $$$q_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) — the permutation $$$q$$$.
2,100
If it is impossible to find the suitable string, print "NO" on the first line. Otherwise print "YES" on the first line and string $$$s$$$ on the second line. It should consist of $$$n$$$ lowercase Latin letters, contain at least $$$k$$$ distinct characters and suit the given permutations. If there are multiple answers, you can print any of them.
standard output
PASSED
2af0612d5f20566265c6417c30a2701d
train_002.jsonl
1561710000
Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence!
256 megabytes
import java.util.*; import java.math.BigInteger; public class Boss { //static long c=0; //static HashMap<Integer,Long> hm2=new HashMap<Integer,Long>(); public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); double a[]=new double[n]; double b[]=new double[n]; double d=0; for(int i=0;i<n;i++) { a[i]=sc.nextDouble(); b[i]=a[i]; } long neg=0; long pos=0; for(int i=0;i<n;i++) { if(a[i]<0) { a[i]=Math.abs(a[i]); neg+=(long)a[i]; a[i]=-1*(long)a[i]; } } d*=-1; for(int i=0;i<n;i++) { if(a[i]>0) { //a[i]=Math.abs(a[i]); pos+=(long)a[i]; a[i]=(long)a[i]; } } long diff=pos-neg; //System.out.println(diff+" "+pos+" "+neg); if(diff>0) { for(int i=0;i<n&&diff>0;i++) { if((a[i]<0&&a[i]!=b[i])||(a[i]==0&&b[i]<0)) { a[i]-=1; diff--; } } } else { for(int i=0;i<n&&diff<0;i++) { if((a[i]>0&&a[i]!=b[i])||(a[i]==0&&b[i]>0)) { a[i]+=1; diff++; } } } StringBuilder s=new StringBuilder(); for(int i=0;i<n;i++) { s.append((long)a[i]); s.append("\n"); } System.out.print(s); } }
Java
["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"]
1 second
["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"]
NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down.
Java 8
standard input
[ "constructive algorithms", "greedy", "math" ]
6059cfa13594d47b3e145d7c26f1b0b3
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| &lt; 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$.
1,500
In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|&lt;1$$$ must be met. If there are multiple answers, print any.
standard output
PASSED
76d62fbfa1c88bed4d74ae81e0ea2757
train_002.jsonl
1561710000
Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence!
256 megabytes
import java.util.*; import java.lang.Math; public class mainClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); double rem = 0.0; //String exportString=""; for (int i=0; i<n; i++) { double r=sc.nextDouble(); rem+=fractPart(r); if (rem>=(0.5)) { rem-=1; System.out.print((int)(Math.ceil(r))+" "); //exportString=exportString+" "+Math.ceil(r); } else { System.out.print((int)(Math.floor(r))+" "); //exportString=exportString+" "+Math.floor(r); } } //System.out.println(exportString); } public static double fractPart(double n) { return n-Math.floor(n); } }
Java
["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"]
1 second
["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"]
NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down.
Java 8
standard input
[ "constructive algorithms", "greedy", "math" ]
6059cfa13594d47b3e145d7c26f1b0b3
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| &lt; 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$.
1,500
In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|&lt;1$$$ must be met. If there are multiple answers, print any.
standard output
PASSED
d3a00f51ec2d3de887ab205d5864be99
train_002.jsonl
1561710000
Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence!
256 megabytes
import java.util.*; import java.lang.Math; public class mainClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); double rem = 0.0; //String exportString=""; for (int i=0; i<n; i++) { double r=sc.nextDouble(); rem+=fractPart(r); if (rem>=(0.5)) { rem-=1; System.out.print((int)(Math.ceil(r))+" "); //exportString=exportString+" "+Math.ceil(r); } else { System.out.print((int)(Math.floor(r))+" "); //exportString=exportString+" "+Math.floor(r); } } //System.out.println(exportString); } public static double fractPart(double n) { return n-Math.floor(n); } }
Java
["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"]
1 second
["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"]
NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down.
Java 8
standard input
[ "constructive algorithms", "greedy", "math" ]
6059cfa13594d47b3e145d7c26f1b0b3
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| &lt; 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$.
1,500
In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|&lt;1$$$ must be met. If there are multiple answers, print any.
standard output
PASSED
fe6a492404f9df3e6cbdded9ac73e14c
train_002.jsonl
1561710000
Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence!
256 megabytes
import java.util.*; import java.lang.*; // StringBuilder uses java.lang public class mainClass { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); double rem = 0.0; StringBuilder exportString= new StringBuilder(); for (int i=0; i<n; i++) { double r=sc.nextDouble(); rem+=fractPart(r); if (rem>=(0.5)) { rem-=1; exportString.append((int)(Math.ceil(r))+" "); //exportString=exportString+" "+Math.ceil(r); } else { exportString.append((int)(Math.floor(r))+" "); //exportString=exportString+" "+Math.floor(r); } } System.out.println(exportString.toString()); } public static double fractPart(double n) { return n-Math.floor(n); } }
Java
["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"]
1 second
["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"]
NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down.
Java 8
standard input
[ "constructive algorithms", "greedy", "math" ]
6059cfa13594d47b3e145d7c26f1b0b3
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| &lt; 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$.
1,500
In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|&lt;1$$$ must be met. If there are multiple answers, print any.
standard output
PASSED
39f33b2ebf70b79e26b6806473f87765
train_002.jsonl
1561710000
Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence!
256 megabytes
import java.util.*; import java.io.*; public class Dy { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static int findPos(int x, int ar[]){ for(int i=0;i<ar.length;i++){ if(ar[i]==x) return (i+1); } return -20; } public static void main(String args[])throws IOException{ Scanner sc=new Scanner(System.in); // Reader sc=new Reader(); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int i,j; int n=sc.nextInt(); double a[]=new double[n]; int b[]=new int[n]; int c[]=new int[n]; for(i=0;i<n;i++) c[i]=0; long sum=0; for(i=0;i<n;i++){ a[i]=sc.nextDouble(); b[i]=(int)Math.round(Math.floor(a[i])); sum=sum+b[i]; if(Math.abs(a[i]-b[i])>=0.000001) c[i]=1; } for(i=0;i<n;i++){ if(c[i]==1&&sum<0){ b[i]=b[i]+1; sum++; } pw.println(b[i]); } pw.close(); } }
Java
["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"]
1 second
["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"]
NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down.
Java 8
standard input
[ "constructive algorithms", "greedy", "math" ]
6059cfa13594d47b3e145d7c26f1b0b3
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| &lt; 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$.
1,500
In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|&lt;1$$$ must be met. If there are multiple answers, print any.
standard output
PASSED
1fcc931c052cc4badd09aa069c0730f0
train_002.jsonl
1561710000
Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence!
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Washoum */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; inputClass in = new inputClass(inputStream); PrintWriter out = new PrintWriter(outputStream); DVusTheCossackAndNumbers solver = new DVusTheCossackAndNumbers(); solver.solve(1, in, out); out.close(); } static class DVusTheCossackAndNumbers { public void solve(int testNumber, inputClass sc, PrintWriter out) { int n = sc.nextInt(); double[] tab = new double[n]; ArrayList<DVusTheCossackAndNumbers.Pair> pos = new ArrayList<>(); ArrayList<DVusTheCossackAndNumbers.Pair> neg = new ArrayList<>(); ArrayList<DVusTheCossackAndNumbers.Pair> zero = new ArrayList<>(); for (int i = 0; i < n; i++) { tab[i] = sc.nextDouble(); if (Math.abs(tab[i]) < 0.00001) { zero.add(new DVusTheCossackAndNumbers.Pair(tab[i], i)); } else if (tab[i] > 0) { pos.add(new DVusTheCossackAndNumbers.Pair(tab[i], i)); } else if (tab[i] < 0) { neg.add(new DVusTheCossackAndNumbers.Pair(tab[i], i)); } } long sumpos = 0; for (int i = 0; i < pos.size(); i++) { sumpos += pos.get(i).in; } long sumneg = 0; for (int i = 0; i < neg.size(); i++) { sumneg += neg.get(i).in; } if (Math.abs(sumneg) == sumpos) { int[] ans = new int[n]; for (int i = 0; i < pos.size(); i++) { ans[pos.get(i).idx] = pos.get(i).in; } for (int i = 0; i < neg.size(); i++) { ans[neg.get(i).idx] = neg.get(i).in; } for (int i = 0; i < zero.size(); i++) { ans[zero.get(i).idx] = zero.get(i).in; } for (int i = 0; i < n; i++) { out.println(ans[i]); } } else if (-1 * sumneg > sumpos) { int[] ans = new int[n]; for (int i = 0, done = 0; done < (-1 * sumneg) - sumpos; i++) { if (pos.get(i).change) { pos.get(i).in++; done++; } } for (int i = 0; i < pos.size(); i++) { ans[pos.get(i).idx] = pos.get(i).in; } for (int i = 0; i < neg.size(); i++) { ans[neg.get(i).idx] = neg.get(i).in; } for (int i = 0; i < zero.size(); i++) { ans[zero.get(i).idx] = zero.get(i).in; } for (int i = 0; i < n; i++) { out.println(ans[i]); } } else { int[] ans = new int[n]; for (int i = 0, done = 0; done < sumpos + sumneg; i++) { if (neg.get(i).change) { neg.get(i).in--; done++; } } for (int i = 0; i < pos.size(); i++) { ans[pos.get(i).idx] = pos.get(i).in; } for (int i = 0; i < neg.size(); i++) { ans[neg.get(i).idx] = neg.get(i).in; } for (int i = 0; i < zero.size(); i++) { ans[zero.get(i).idx] = zero.get(i).in; } for (int i = 0; i < n; i++) { out.println(ans[i]); } } } static class Pair { double x; int in; int idx; boolean change; public Pair(double a, int b) { x = a; if (x <= -0.00001) { in = (int) Math.ceil(x); } else if (x >= 0) { in = (int) Math.floor(x); } else { in = 0; } idx = b; change = !(Math.abs(in - x) < 0.00001); } } } static class inputClass { BufferedReader br; StringTokenizer st; public inputClass(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"]
1 second
["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"]
NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down.
Java 8
standard input
[ "constructive algorithms", "greedy", "math" ]
6059cfa13594d47b3e145d7c26f1b0b3
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| &lt; 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$.
1,500
In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|&lt;1$$$ must be met. If there are multiple answers, print any.
standard output
PASSED
60efa253ab98de3c112e3d91a61b630f
train_002.jsonl
1561710000
Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence!
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class prime { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader sc=new Reader(); int n=sc.nextInt(); double a[]=new double[n]; int count=0; int sum=0; for(int i=0;i<n;i++) { a[i]=sc.nextDouble(); if(a[i]!=(int)a[i])count++; sum+=(int)(Math.floor(a[i])); } // System.out.println("sum " + sum); long z=-1*sum; //System.out.println(diff + "dif"); //long z=diff; for(int i=0;i<n;i++) { if(z!=0&&a[i]!=(int)a[i]) { System.out.println((int)Math.floor(a[i])+1); z--; } else System.out.println((int)Math.floor(a[i])); } } }
Java
["4\n4.58413\n1.22491\n-2.10517\n-3.70387", "5\n-6.32509\n3.30066\n-0.93878\n2.00000\n1.96321"]
1 second
["4\n2\n-2\n-4", "-6\n3\n-1\n2\n2"]
NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down.
Java 8
standard input
[ "constructive algorithms", "greedy", "math" ]
6059cfa13594d47b3e145d7c26f1b0b3
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| &lt; 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$.
1,500
In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|&lt;1$$$ must be met. If there are multiple answers, print any.
standard output