exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
βŒ€
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
sequencelengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
βŒ€
difficulty
int64
-1
3.5k
βŒ€
prob_desc_output_spec
stringlengths
17
1.47k
βŒ€
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
3daffe5809221b1ceddbe65a9a11ce7c
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; import java.io.PrintWriter; public class a { public static void main(String[] args) { FastScanner fs = new FastScanner (); int T = fs.nextInt(); for (int tt=0; tt<T; tt++) { long a = fs.nextInt(); long b = fs.nextInt(); long c = fs.nextInt(); System.out.println(a+b+c-1); } } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } boolean hasNext() { String next=null; try { next = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (next==null) { return false; } st=new StringTokenizer(next); return true; } 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
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
8b6f8ca69f4e1bc8deda247c4f6ff017
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Tanzim Ibn Patowary */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { for (int test = 0; test < testNumber; test++) { int t = in.nextInt(); while (t-- != 0) { long a = in.nextInt(); long b = in.nextInt(); long c = in.nextInt(); out.println((a + b + c) - 1); } } } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
40d91818fb73ecbfca6ac94573fe0585
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++){ System.out.println(Math.max(sc.nextInt(),Math.max(sc.nextInt(),sc.nextInt()))); } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
acea32f3961674ab14474bcaa762f489
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class A { public static void main (String[] args) throws java.lang.Exception { FastReader in = new FastReader(); int t = in.nextInt(); while(t-->0) { int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); long ans = a+b+c-1; System.out.println(a+(long)b+c-1); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try{ st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
bbd11971518845814777583f462ae0b2
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class A { public static void main (String[] args) throws java.lang.Exception { FastReader in = new FastReader(); int t = in.nextInt(); while(t-->0) { int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); long ans = a+(long)b+c-1; System.out.println(ans); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try{ st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
792c853cdf827d881056f2ab61a067b8
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.util.*; public class Solution{ public static void main(String[] agrs){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int z=0;z<t;z++){ double a = sc.nextDouble(); double b = sc.nextDouble(); double c = sc.nextDouble(); double x; if(a<c){ x = a; a = c; c = x; } if(b<c){ x = b; b = c; c = x; } double m = Math.sqrt(a*a+b*b); double d = m - c; d = Math.ceil(d); System.out.println((int)d); } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
ce4ed1c1ac5e63b383b1b499f68d94c7
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; public class code1{ 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[]){ FastReader sc=new FastReader(); int t=sc.nextInt(); while(t-->0){ long a=sc.nextLong(); long b=sc.nextLong(); long c=sc.nextLong(); System.out.println(a+b+c-1); } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
2fecf849f93d31a74f96abe3ee4d626a
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
//package codeforce; import javafx.scene.transform.Scale; import java.util.Scanner; public class ograzhdenie { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { long a = sc.nextLong(), b = sc.nextLong(), c = sc.nextLong(); System.out.println(a + b + c - 1); } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
9cdc88c545ac88797d33f0fc0481f953
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
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 Main { public 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 scn = new FastReader(); int i, j, t, n; t = scn.nextInt(); while (t-- > 0) { int a[]=new int[3]; for (i=0;i<3;i++){ a[i]=scn.nextInt(); } Arrays.sort(a); System.out.println(a[2]); } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
54d431e088bb5351e9aeb19b6adb6c11
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author ujjwal abhishek */ public class A { public static void solve() { int t=sc.nextInt(); while (t-->0) { long a=sc.nextLong(),b=sc.nextLong(),c=sc.nextLong(); out.println(a+b+c-1); } } public static void main(String[] args) { new Thread(null, null, "Thread", 1 << 27) { public void run() { try { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(System.in); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } .start(); } public static PrintWriter out; public static FastReader sc; public static class FastReader { private InputStream stream; private byte[] buf = new byte[4096]; private int curChar, snumChars; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) { throw new InputMismatchException(); } if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException E) { throw new InputMismatchException(); } } if (snumChars <= 0) { return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int number = 0; do { number *= 10; number += c - '0'; c = read(); } while (!isSpaceChar(c)); return number * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } long sgn = 1; if (c == '-') { sgn = -1; c = read(); } long number = 0; do { number *= 10L; number += (long) (c - '0'); c = read(); } while (!isSpaceChar(c)); return number * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextLong(); } return arr; } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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; } public boolean isEndofLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
35d633a69b481a7718867ca2976ccf01
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author ujjwal abhishek */ public class A { public static void solve() { int t=sc.nextInt(); while (t-->0) { int[] a=sc.nextIntArray(3); Arrays.sort(a); out.println(a[2]+a[1]-1); } } public static void main(String[] args) { new Thread(null, null, "Thread", 1 << 27) { public void run() { try { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(System.in); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } .start(); } public static PrintWriter out; public static FastReader sc; public static class FastReader { private InputStream stream; private byte[] buf = new byte[4096]; private int curChar, snumChars; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) { throw new InputMismatchException(); } if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException E) { throw new InputMismatchException(); } } if (snumChars <= 0) { return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int number = 0; do { number *= 10; number += c - '0'; c = read(); } while (!isSpaceChar(c)); return number * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } long sgn = 1; if (c == '-') { sgn = -1; c = read(); } long number = 0; do { number *= 10L; number += (long) (c - '0'); c = read(); } while (!isSpaceChar(c)); return number * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = this.nextLong(); } return arr; } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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; } public boolean isEndofLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
d0fe1dc21f97b15c469e2802ccb3b474
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); for (int i = 0; i < n; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int c = scanner.nextInt(); System.out.println(a + (long) b + c - 1); } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
ae2a5d0cf429bd42fb650aeeca104f5f
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
//JAI BAJRANGBALI import java.util.*; import java.io.*; import java.math.BigInteger; //class Main //AtCoder //class Solution // Codechef public class Solution //Codeforces { public final static int d = 256; static int MOD = 1000000007; static final float EPSILON = (float)0.01; static final double PI = Math.PI; private static BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); private static BufferedWriter out = new BufferedWriter (new OutputStreamWriter (System.out)); static class Graph { int V; LinkedList<Integer>[] adjListArray; Graph(int V) { this.V = V; adjListArray = new LinkedList[V]; for(int i = 0; i < V ; i++){ adjListArray[i] = new LinkedList<Integer>(); } } void addEdge( int src, int dest) { adjListArray[src].add(dest); adjListArray[dest].add(src); } void DFSUtil(int v, boolean[] visited) { visited[v] = true; for (int x : adjListArray[v]) { if(!visited[x]) DFSUtil(x,visited); } } int connectedComponents() { boolean[] visited = new boolean[V]; int cnt = 0; for(int v = 0; v < V; ++v) { if(!visited[v] && adjListArray[v].size() != 0) { DFSUtil(v,visited); cnt++; } } return cnt; } } static class SegmentTree{ int arr[] , st[]; int maxSize , N; SegmentTree(int arr[] , int N){ this.arr = arr; this.N = N; int x = (int) (Math.ceil(Math.log(N) / Math.log(2))); this.maxSize = 2 * (int) Math.pow(2, x) - 1; this.st = new int[maxSize]; constructST(0 , N-1 , 0); } void constructST(int start , int end , int ind) { constructSTUtil(start , end , ind); } int constructSTUtil(int start , int end , int ind) { if(start == end){ st[ind] = arr[start]; return st[ind]; } else{ int mid = start + (end - start)/2; st[ind] = constructSTUtil(start , mid , (2*ind) + 1) ^ constructSTUtil(mid+1 , end , (2*ind) + 2); return st[ind]; } } int findXorInRange(int start , int end , int qstart , int qend , int index) { if(qstart <= start && qend >= end) { return st[index]; } else if(qstart > end || qend < start || end < start){ return 0; } else{ int mid = start + (end - start)/2; return findXorInRange(start , mid , qstart , qend , (2*index) + 1) ^ findXorInRange(mid+1 , end , qstart , qend , (2*index) + 2); } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Cell{ int X , Y , dis; Cell(int x , int y , int di){ X = x; Y = y; dis = di; } } static boolean isValid(int x , int y , int N , int M){ return ((x >= 0 && x < N) &&(y >= 0 && y < M)); } static int searchRabinKarp(String pat, String txt) { int M = pat.length(); int N = txt.length(); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1 , cnt = 0; int q = 3355439; for (i = 0; i < M-1; i++) h = (h*d)%q; for (i = 0; i < M; i++) { p = (d*p + pat.charAt(i))%q; t = (d*t + txt.charAt(i))%q; } for (i = 0; i <= N - M; i++) { if ( p == t ) { for (j = 0; j < M; j++) { if (txt.charAt(i+j) != pat.charAt(j)) break; } if (j == M) {//System.out.println("Pattern found at index " + i); cnt++; } } if ( i < N-M ) { t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%q; if (t < 0) t = (t + q); } } return cnt; } static long gcd(long bigger , long smaller) { if (smaller == 0) return bigger; return gcd(smaller, bigger % smaller); } static long lcm(long a, long b) { return (a*b)/gcd(a, b); } static long sumOfArray(long arr[]) { long sum = 0; for(int i = 0 ; i < arr.length ; i++) sum += arr[i]; return sum; } static boolean isPrime(long n) { if(n == 2) return true; else if(n == 1) return false; else if (n%2==0) return false; for(long i=3;i<=Math.sqrt(n);i+=2) { if(n%i==0) return false; } return true; } static long modularExpo(long x, long y, long p) { long res = 1; x = x % p; if (x == 0) return 0; while (y > 0) { if((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long countDigit(long n) { return (long)Math.floor(Math.log10(n) + 1); } static long sumOfDigits(long n) { long sum; for (sum = 0; n > 0; sum += n % 10,n /= 10); return sum; } static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) { if (str.charAt(i) != str.charAt(j)) return false; i++; j--; } return true; } static void sop(Object o){System.out.print(o);} static void sopln(Object o){System.out.println(o);} static class Int implements Comparator<Int>{ int pos ,op , val; Int(int a ,int o,int c){ pos=a; op=o; val=c; } @Override public int compare(Int anInt, Int t1) { return anInt.val-t1.val; } } public static void main(String args[]) { try{ Scanner scN = new Scanner(System.in); FastReader sc=new FastReader(); int T = sc.nextInt(); while(T-- > 0) { try { long A =sc.nextLong(); long B=sc.nextLong(); long C=sc.nextLong(); long max=Math.max(A,Math.max(B,C)); long min=Math.min(A,Math.min(B,C)); long second = A+B+C-max-min; double d = Math.sqrt(Double.valueOf(min*min)+Double.valueOf(second*second)); long dd = (long)(Math.floor(d)) + max - 1; System.out.println(dd); //System.out.println(Math.max(A,Math.max(B,C))-1); }catch(Exception e){ sop("HEHE"); } //sopln(N+" "+str); } try{ out.flush(); }catch(Exception e){ System.out.print(e); }; } catch(Exception e){ System.out.print(e); } } public static void solve(String str,int N) { long ans=0; sopln(ans); } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
92f269b74c48f2919d013031441c15e1
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
//package codeforces.div2; import java.util.Scanner; public class Fence { static public void print(long a, long b, long c) { long x = (a + b + c) - 1; System.out.println(x); } public static void main(String []args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); while ( n > 0) { long a = sc.nextLong(); long b = sc.nextLong(); long c = sc.nextLong(); print(a, b, c); n--; } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
2531c5ba70e60a7b7558a444fae6f649
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String args[]) { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t, n, i, j; String s; t = sc.nextInt(); while(t-->0) { int arr[] = sc.readArray(3); Arrays.sort(arr); out.println(arr[0]+arr[2]); } out.close(); } /* FASTREADER */ 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; } /*DEFINED BY ME */ int[] readArray(int n) { int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
c1c05164e2b60ef712fea706ff71d1a9
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Codeforces { public static boolean isPowerOfTwo (int x) { return x!=0 && ((x&(x-1)) == 0); } public static int binsearch(long[] a,long x){ int l = 0; int r = a.length; while (l <= r){ int mid = l + (r-l)/2; if (a[mid]==x) return 1; else if (a[mid] < x) l = mid+1; else r = mid-1; } return 0; } public static int upperbound(long arr[],long key){ int start=0;int end=arr.length-1; int idx=-1; int mid; while(start<=end){ int i=(start+end)/2; if(arr[i]<key){ start=i+1; } else if(arr[i]>key){ end=i-1; } else{ idx=i; start=i+1; } } return idx; } public static int lowerbound(long arr[],long key){ int start=0;int end=arr.length-1; int idx=-1; int mid; while(start<=end){ int i=(start+end)/2; if(arr[i]<key){ start=i+1; } else if(arr[i]>key){ end=i-1; } else{ idx=i; end=i-1; } } return idx; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ long[] x = new long[3]; for (int i=0;i<3;i++) x[i] = sc.nextLong(); Arrays.sort(x); long ans = x[2] + x[1] + x[0] - 1; System.out.println(ans); } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
ae4aff7b0b3469a3f6386dc653ee6245
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(); MyWriter out = new MyWriter(System.out); int tries = in.nextInt(); for (int i = 0; i < tries; i++) { long a = in.nextLong(); long b = in.nextLong(); long c = in.nextLong(); long sum = a+b+c; System.out.println(sum-1); } } static class MyWriter { BufferedOutputStream out; final int bufSize = 1 << 16; int n; byte b[] = new byte[bufSize]; MyWriter(OutputStream out) { this.out = new BufferedOutputStream(out, bufSize); this.n = 0; } byte c[] = new byte[20]; void print(int x) throws IOException { int cn = 0; if (n + 20 >= bufSize) flush(); if (x < 0) { b[n++] = (byte) ('-'); x = -x; } while (cn == 0 || x != 0) { c[cn++] = (byte) (x % 10 + '0'); x /= 10; } while (cn-- > 0) b[n++] = c[cn]; } void print(char x) throws IOException { if (n == bufSize) flush(); b[n++] = (byte) x; } void print(String s) throws IOException { for (int i = 0; i < s.length(); i++) print(s.charAt(i)); } void println(String s) throws IOException { print(s); println(); } static final String newLine = System.getProperty("line.separator"); void println() throws IOException { print(newLine); } void flush() throws IOException { out.write(b, 0, n); n = 0; } void close() throws IOException { flush(); out.close(); } } static class MyReader { BufferedInputStream in; final int bufSize = 1 << 16; final byte b[] = new byte[bufSize]; MyReader(InputStream in) { this.in = new BufferedInputStream(in, bufSize); } int nextInt() throws IOException { int c; while ((c = nextChar()) <= 32) ; int x = 0, sign = 1; if (c == '-') { sign = -1; c = nextChar(); } while (c >= '0') { x = x * 10 + (c - '0'); c = nextChar(); } return x * sign; } StringBuilder _buf = new StringBuilder(); String nextWord() throws IOException { int c; _buf.setLength(0); while ((c = nextChar()) <= 32 && c != -1) ; if (c == -1) return null; while (c > 32) { _buf.append((char) c); c = nextChar(); } return _buf.toString(); } int bn = bufSize, k = bufSize; int nextChar() throws IOException { if (bn == k) { k = in.read(b, 0, bufSize); bn = 0; } return bn >= k ? -1 : b[bn++]; } int nextNotSpace() throws IOException { int ch; while ((ch = nextChar()) <= 32 && ch != -1) ; return ch; } } static final Random random = new Random(); // static void ruffleSort(int[] a) { // int n = a.length;//shuffle, then sort // for (int i = 0; i < n; i++) { // int oi = random.nextInt(n), temp = a[oi]; // a[oi] = a[i]; // a[i] = temp; // } // Arrays.sort(a); // } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
9610b21591a8ae6da6c10234d1d74bba
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.util.*; public class mysol { public static void main(String[] args){ Scanner scn=new Scanner(System.in); int t=scn.nextInt(); long ans=0; while(t-->0){ long a=scn.nextLong(); long b=scn.nextLong(); long c=scn.nextLong(); ans=Math.max(a,Math.max(b,c)); System.out.println(ans); } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
fa83402f91bdde4c2be6e6d0c5750dc1
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Task{ // ..............code begins here.............. static long mod=(long)1e9+7; static void solve() throws IOException { long[] x=long_arr(); long s=(x[0]+x[1]+x[2]); out.write((s-1)+"\n"); } public static void main(String[] args) throws IOException{ assign(); int t=int_v(read()); while(t--!=0){solve();} out.flush(); } // taking inputs static BufferedReader s1; static BufferedWriter out; static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;} static int int_v (String s1){return Integer.parseInt(s1);} static long long_v(String s1){return Long.parseLong(s1);} static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;} static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;} static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));} static String setpreciosion(double d,int k){BigDecimal d1 = new BigDecimal(Double.toString(d));return d1.setScale(k,RoundingMode.HALF_UP).toString();}//UP DOWN HALF_UP static int gcd(int a,int b){if(b==0){return a;}return gcd(b,a%b);} static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res%m;} static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;} static long ModInv(long a,long m){return Modpow(a,m-2,m);} static long nck(int n,int r,long m){if(r>n){return 0l;}return Modmul(f[n],ModInv(Modmul(f[n-r],f[r],m),m),m);} static long[] f; }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
6086f2d6a7d88232d56cdf9046cd2cf6
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for (int i = 0; i < n; i++) { long a = sc.nextInt(); long b = sc.nextInt(); long c = sc.nextInt(); long ans = a+b+c-1; System.out.println(ans); } sc.close(); } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
35a0c15ffdc00df5d2d9e4784eee8182
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.util.*; public class ClassA { static Scanner scanner =new Scanner(System.in); static long a,b,c,testCases; public static void main(String[] args) { testCases=scanner.nextInt(); for(int i=0;i<testCases;i++){ a=scanner.nextLong(); b=scanner.nextLong(); c=scanner.nextLong(); // int answer=(int) Math.sqrt( Math.abs(Math.pow(a, 2)+Math.pow(b, 2)-Math.pow(c, 2)) ); long answer=(a+b+c)-1; System.out.println(answer); } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
3b246ebe3e6c3a1b5fd094461ebcf155
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.util.*; import java.io.*; public class D { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() throws Exception { 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 Exception{ FastReader scan =new FastReader(); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int t = scan.nextInt(); while(t-- > 0) { int a = scan.nextInt(); int b = scan.nextInt(); int c = scan.nextInt(); int ans = (int) Math.sqrt(Math.pow(b,2)+Math.pow((c-a),2)); out.println(ans); } out.flush(); } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
b836e81c917dbd8de841d607d0e40b8a
train_000.jsonl
1601827500
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.
256 megabytes
import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class atc3 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ long a=sc.nextLong(); long b=sc.nextLong(); long c=sc.nextLong(); int max=(int)Math.max(a,(int)Math.max(b,c)); System.out.println(max); } } }
Java
["2\n1 2 3\n12 34 56"]
1 second
["4\n42"]
NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.
Java 8
standard input
[ "geometry", "math" ]
40d679f53417ba058144c745e7a2c76d
The first line contains a single integer $$$t$$$Β β€” the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$Β β€” the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).
800
For each test case print a single integer $$$d$$$Β β€” the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.
standard output
PASSED
7a411b9ba1f25d0cf8e97277f6930a84
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
//package a2oj_ladder_C; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.Queue; import java.util.TreeMap; import java.util.TreeSet; @SuppressWarnings("unused") public class Hometask154A { InputStream is; PrintWriter out; String INPUT = ""; int mod = (int)(Math.pow(10,9)+7); void solve() { char ch[] = ns().toCharArray(); int k = ni(); int len = ch.length; boolean a[][] = new boolean[26][26]; for(int i = 0 ; i<k ; i++) { String s = ns(); a[s.charAt(0)-'a'][s.charAt(1)-'a'] = true; a[s.charAt(1)-'a'][s.charAt(0)-'a'] = true; } StringBuilder st = new StringBuilder(); ArrayList<Integer> al = new ArrayList<>(); for(int i = 0 ; i<len ; ) { int j = i+1; int ct = 1; while(j<len && ch[j] == ch[j-1]) { j++; ct++; } st.append(ch[i]); i = j; al.add(ct); } len = st.toString().length(); ch = st.toString().toCharArray(); //System.out.println(len); long rem = 0; for(int i = 0 ; i<len ; ) { if(i+1<len && (a[ch[i]-'a'][ch[i+1]-'a'] || a[ch[i+1]-'a'][ch[i]-'a'])) { char x = ch[i]; char y = ch[i+1]; int x1 = al.get(i); int y1 = al.get(i+1); int ct = 0; int j = i+2; //System.out.println(j); while(j<len) { if((j-i)%2 == 0 && ch[j] == x) { x1 += al.get(j); } else if((j-i-1)%2 == 0 && ch[j] == y) { y1 += al.get(j); } else break; j++; } i = j; rem += Math.min(x1 , y1); } else i++; } out.println(rem); } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Hometask154A().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int[][] na(int n , int m) { int[][] a = new int[n][m]; for(int i = 0;i < n;i++) for(int j = 0 ; j<m ; j++) a[i][j] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } void display2D(int a[][]) { for(int i[] : a) { for(int j : i) { out.print(j+" "); } out.println(); } } int[][] creategraph(int n , int m) { int g[][] = new int[n+1][]; int from[] = new int[m]; int to[] = new int[m]; int ct[] = new int[n+1]; for(int i = 0 ; i<m; i++) { from[i] = ni(); to[i] = ni(); ct[from[i]]++; ct[to[i]]++; } int parent[] = new int[n+1]; for(int i = 0 ; i<n+1 ; i++) g[i] = new int[ct[i]]; for(int i = 0 ; i<m ; i++) { g[from[i]][--ct[from[i]]] = to[i]; g[to[i]][--ct[to[i]]] = from[i]; } return g; } static long __gcd(long a, long b) { if(b == 0) { return a; } else { return __gcd(b, a % b); } } // To compute x^y under modulo m 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 % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Function to find modular // inverse of a under modulo m // Assumption: m is prime static long modInverse(long a, int m) { if (__gcd(a, m) != 1) { //System.out.print("Inverse doesn't exist"); return -1; } else { // If a and m are relatively prime, then // modulo inverse is a^(m-2) mode m // System.out.println("Modular multiplicative inverse is " // +power(a, m - 2, m)); return power(a, m - 2, m); } } static long nCrModPFermat(int n, int r, int p , long fac[]) { // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r long t = (fac[n]* modInverse(fac[r], p))%p; return ( (t* modInverse(fac[n-r], p))% p); } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
c51079bdceac154ef271fc0f93820588
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); String b; while ((b = br.readLine()) != null) { String[] r = br.readLine().split(" "); int n = Integer.parseInt(r[0]); int cont = 0; int x = 0; int y = 0; for (int i = 0; i < n; i++) { String l = br.readLine(); x = 0; y = 0; for (int j = 0; j < b.length(); j++) { if (b.charAt(j) == l.charAt(0)) { x++; } else if (b.charAt(j) == l.charAt(1)) { y++; } else { cont += Math.min(x, y); y = 0; x = 0; } } cont += Math.min(x, y); } pw.write(cont + "\n"); pw.flush(); } pw.close(); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
ad87ed164787a51f38c4458a4b204142
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
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.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { String s = in.next(); int k = in.nextInt(); long ans = 0; for (int i = 0; i < k; i++) { String pat = in.next(); char a = pat.charAt(0); char b = pat.charAt(1); int aCount = 0; int bCount = 0; for (int j = 0; j < s.length(); j++) { if (s.charAt(j) == a) { aCount++; } else if (s.charAt(j) == b) { bCount++; } else { ans += Math.min(aCount, bCount); aCount = 0; bCount = 0; } } ans += Math.min(aCount, bCount); } out.println(ans); } } static class InputReader { private StringTokenizer tokenizer; private BufferedReader reader; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private void fillTokenizer() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } } public String next() { fillTokenizer(); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
e89dc583cc2a91033569ce0f39df89e4
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; public class R109_D1_A { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); String input = reader.readLine(); int noOfPairs = Integer.parseInt(reader.readLine()); HashMap<Character, Character> map = new HashMap<>(); for (int i = 1; i <= noOfPairs; ++i) { char[] pair = reader.readLine().toCharArray(); map.put(pair[0], pair[1]); map.put(pair[1], pair[0]); } long result = 0l; int i = 0, j; int currCharCnt = 0; int checkCharCnt = 0; for (; i <= input.length() - 1;) { char currCharPair; if (map.containsKey(input.charAt(i))) { currCharPair = map.get(input.charAt(i)); j = i + 1; if (j > input.length() - 1) { result = result + Math.min(currCharCnt, checkCharCnt); break; } ++currCharCnt; } else { ++i; continue; } for (; j <= input.length() - 1;) { if (input.charAt(j) == currCharPair) { ++checkCharCnt; ++j; } else if (input.charAt(j) == input.charAt(i)) { ++currCharCnt; ++j; } else { result = result + Math.min(currCharCnt, checkCharCnt); currCharCnt = 0; checkCharCnt = 0; break; } } i = j; } result = result + Math.min(currCharCnt, checkCharCnt); writer.println(result); writer.flush(); reader.close(); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
131540dbeebe3a40b31ab271f7c63223
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.*; public class practice { public static void main(String[] args) { Scanner scn=new Scanner(System.in); String s=scn.next(),p; int k=scn.nextInt(),x=0,y=0,ans=0; char a,b; for(int i=0;i<k;i++){ p=scn.next(); for(int j=0;j<s.length();j++){ if(s.charAt(j)==p.charAt(0)){ x++; } else if(s.charAt(j)==p.charAt(1)){ y++; } else{ ans+=Math.min(x,y); x=0;y=0; } } ans+=Math.min(x,y); x=0;y=0; } System.out.println(ans); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
99d66afe8a7d77d20e991f81907e593e
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.*; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine(), " :"); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Template().run(); // new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } int INF = 1000 * 1000; void solve() throws IOException { char[] s = readString().toCharArray(); int n = s.length; int k = readInt(); int[] banned = new int[27]; Arrays.fill(banned, -1); for (int i = 0; i < k; i++) { char[] x = readString().toCharArray(); banned[x[0] - 'a' + 1] = x[1] - 'a' + 1; banned[x[1] - 'a' + 1] = x[0] - 'a' + 1; } int[][] dp = new int[27][n + 1]; for (int[] ddp : dp) { Arrays.fill(ddp, INF); } dp[0][0] = 0; for (int i = 0; i < n; i++) { int cur = s[i] - 'a' + 1; for (int prevLast = 0; prevLast < 27; prevLast++) { if (dp[prevLast][i] == INF) continue; if (banned[cur] != prevLast) { dp[cur][i + 1] = Math.min(dp[cur][i + 1], dp[prevLast][i]); } dp[prevLast][i + 1] = Math.min(dp[prevLast][i + 1], dp[prevLast][i] + 1); } } int min = INF; for (int i = 0; i < 27; i++) { min = Math.min(min, dp[i][n]); } out.println(min); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
bb111f29b8055c0b491934ff85176639
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class A154 { private static long mod = 1000000007; public static void main(String[] args) { InputReader in=new InputReader(System.in); PrintWriter pw=new PrintWriter(System.out); String s=" "; s+=in.nextLine(); int m=in.nextInt(); int count=0; for(int i=0;i<m;i++) { String cs=in.nextLine(); char c1=cs.charAt(0); char c2=cs.charAt(1); int n1=0,n2=0; for(int j=0;j<s.length();j++) { if(s.charAt(j)==c1) { n1++; } else if(s.charAt(j)==c2) { n2++; } else { count+=Math.min(n1,n2); n1=0; n2=0; } } count+=Math.min(n1,n2); n1=0; n2=0; } pw.println(count); pw.flush(); pw.close(); } 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 int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int 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 ArrayList<Integer> primeFactorization(int n) { ArrayList<Integer> a =new ArrayList<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 int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } 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); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
30d6062acc2380e5955fb3041d37bc5b
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 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.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { String s = in.next(); int forbidden = in.readInt(); HashMap<Character, Character> hm = new HashMap<>(); for (int i = 0; i < forbidden; i++) { char a = in.readCharacter(); char b = in.readCharacter(); hm.put(a, b); hm.put(b, a); } ArrayList<ArrayList<Character>> al = new ArrayList<>(); al.add(new ArrayList<>()); for (char c : s.toCharArray()) { ArrayList<Character> temp = al.get(al.size() - 1); if (temp != null && (temp.isEmpty() || temp.get(temp.size() - 1) == c || (hm.containsKey(temp.get(temp.size() - 1)) && hm.get(temp.get(temp.size() - 1)) == c))) { temp.add(c); } else { temp = new ArrayList<>(); temp.add(c); al.add(temp); } } int res = 0; for (ArrayList<Character> l : al) { res += solve(l); } out.printLine(res); } private int solve(ArrayList<Character> l) { if (l == null || l.size() == 0) return 0; char first = l.get(0); int count = 0; for (char c : l) if (c == first) count++; return Math.min(count, l.size() - count); } } 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 readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
808e3f03c5833c6fb91cd04bd4d3faa2
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true); TaskB solver = new TaskB(); solver.solve(1, in, out); out.flush(); out.close(); } } class Pair { int first; int second; Pair(int first, int second) { this.first = first; this.second = second; } } class TaskB { int INF = (int) 1e9 + 7; int MAX_N = (int) 1e5 + 5; long mod = (long) 1e8; ArrayList<Integer> edges[]; ArrayList<Integer> rev_edges[]; boolean visited[]; ArrayList<Integer> topSort; int color[]; public void solve(int testNumber, InputReader in, PrintWriter pw) { char arr[] = in.next().toCharArray(); int t = arr.length; int k = in.nextInt(); boolean forbidden[][] = new boolean[27][27]; for (int i = 0; i < k; i++) { char pair[] = in.next().toCharArray(); forbidden[pair[0] - 'a'][pair[1] - 'a'] = true; forbidden[pair[1] - 'a'][pair[0] - 'a'] = true; } int dp[][] = new int[t][27]; for (int x[] : dp) { Arrays.fill(x, INF); } dp[0][arr[0] - 'a'] = 0; dp[0][26] = 1; for (int i = 1; i < t; i++) { for (int j = 0; j < 27; j++) { if (!forbidden[j][arr[i] - 'a']) { dp[i][arr[i] - 'a'] = Math.min(dp[i][arr[i] - 'a'], dp[i - 1][j]); } dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + 1); } } int ans = INF; for (int i = 0; i < 26; i++) { ans = Math.min(dp[t - 1][i], ans); } pw.println(ans); } int[] shrink(int a[]) { int n = a.length; long b[] = new long[n]; for (int i = 0; i < n; i++) { b[i] = ((long) (a[i] << 32)) | i; } Arrays.sort(b); int ret[] = new int[n]; int p = 0; for (int i = 0; i < n; i++) { if (i > 0 && (b[i] ^ b[i - 1]) >> 32 != 0) { p++; } ret[(int) b[i]] = p; } return ret; } int sum(int ft[], int i) { int sum = 0; for (int j = i; j >= 1; j -= (j & -j)) { sum += ft[j]; // System.out.println(sum); } return sum; } void add(int ft[], int i, int x) { for (int j = i; j < ft.length; j += (j & -j)) { // System.out.println(j); ft[j] += x; } } boolean isValid(int i, int j, char arr[][]) { if (i >= arr[0].length || j >= arr[0].length) { return false; } if (arr[i][j] == '*') { return false; } return true; } long pow(long m, long k) { long prod = 1; for (int i = 0; i < k; i++) { prod = (prod * m) % INF; } return prod % INF; } // int sum(int k) { // int sum=0; // for(int i=k;i>=1;i) { // sum+=ft[k]; // } // } long fib(int N) { long fib[] = new long[N + 1]; fib[0] = 1; fib[1] = 1; for (int i = 2; i <= N; i++) { fib[i] = (fib[i - 1] + fib[i - 2]) % mod; } return fib[N] % mod; } long sum(int i, int j, long arr[]) { long sum = 0; for (int k = i; k <= j; k++) { sum += arr[k]; } return sum; } boolean FirstRow_Col(Pair pair) { return pair.first == 0 || pair.second == 0; } int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } public int getInt(int num) { int ret = -1; switch (num) { case 0: ret = 6; break; case 1: ret = 2; break; case 2: ret = 5; break; case 3: ret = 5; break; case 4: ret = 4; break; case 5: ret = 5; break; case 6: ret = 6; break; case 7: ret = 3; break; case 8: ret = 7; break; case 9: ret = 6; break; } return ret; } public int isPow(long num) { int count = 0; while (num > 0) { num /= 2; count++; } return count; } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
7cb40baece52de1c5c817069886f3a88
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true); TaskB solver = new TaskB(); solver.solve(1, in, out); out.flush(); out.close(); } } class Pair { int first; int second; Pair(int first, int second) { this.first = first; this.second = second; } } class TaskB { int INF = (int) 1e9 + 7; int MAX_N = (int) 1e5 + 5; long mod = (long) 1e8; ArrayList<Integer> edges[]; ArrayList<Integer> rev_edges[]; boolean visited[]; ArrayList<Integer> topSort; int color[]; public void solve(int testNumber, InputReader in, PrintWriter pw) { char arr[] = in.next().toCharArray(); int n = arr.length; int k = in.nextInt(); boolean forbidden[][] = new boolean[27][27]; for (int i = 0; i < k; i++) { char pair[] = in.next().toCharArray(); forbidden[pair[0] - 'a'][pair[1] - 'a'] = true; forbidden[pair[1] - 'a'][pair[0] - 'a'] = true; } int dp[][] = new int[n][27]; for (int x[] : dp) { Arrays.fill(x, INF); } dp[0][arr[0] - 'a'] = 0; dp[0][26] = 1; for (int i = 1; i < n; i++) { for (int j = 0; j < 27; j++) { if (!forbidden[j][arr[i] - 'a']) { dp[i][arr[i] - 'a'] = Math.min(dp[i][arr[i] - 'a'], dp[i - 1][j]); } dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + 1); } } int ans = INF; for (int i = 0; i < 26; i++) { ans = Math.min(dp[n - 1][i], ans); } pw.println(ans); } int[] shrink(int a[]) { int n = a.length; long b[] = new long[n]; for (int i = 0; i < n; i++) { b[i] = ((long) (a[i] << 32)) | i; } Arrays.sort(b); int ret[] = new int[n]; int p = 0; for (int i = 0; i < n; i++) { if (i > 0 && (b[i] ^ b[i - 1]) >> 32 != 0) { p++; } ret[(int) b[i]] = p; } return ret; } int sum(int ft[], int i) { int sum = 0; for (int j = i; j >= 1; j -= (j & -j)) { sum += ft[j]; // System.out.println(sum); } return sum; } void add(int ft[], int i, int x) { for (int j = i; j < ft.length; j += (j & -j)) { // System.out.println(j); ft[j] += x; } } boolean isValid(int i, int j, char arr[][]) { if (i >= arr[0].length || j >= arr[0].length) { return false; } if (arr[i][j] == '*') { return false; } return true; } long pow(long m, long k) { long prod = 1; for (int i = 0; i < k; i++) { prod = (prod * m) % INF; } return prod % INF; } // int sum(int k) { // int sum=0; // for(int i=k;i>=1;i) { // sum+=ft[k]; // } // } long fib(int N) { long fib[] = new long[N + 1]; fib[0] = 1; fib[1] = 1; for (int i = 2; i <= N; i++) { fib[i] = (fib[i - 1] + fib[i - 2]) % mod; } return fib[N] % mod; } long sum(int i, int j, long arr[]) { long sum = 0; for (int k = i; k <= j; k++) { sum += arr[k]; } return sum; } boolean FirstRow_Col(Pair pair) { return pair.first == 0 || pair.second == 0; } int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } public int getInt(int num) { int ret = -1; switch (num) { case 0: ret = 6; break; case 1: ret = 2; break; case 2: ret = 5; break; case 3: ret = 5; break; case 4: ret = 4; break; case 5: ret = 5; break; case 6: ret = 6; break; case 7: ret = 3; break; case 8: ret = 7; break; case 9: ret = 6; break; } return ret; } public int isPow(long num) { int count = 0; while (num > 0) { num /= 2; count++; } return count; } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
d04f3d222f31db6a09e1d373c2421337
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true); TaskB solver = new TaskB(); solver.solve(1, in, out); out.flush(); out.close(); } } class Pair { int first; int second; Pair(int first, int second) { this.first = first; this.second = second; } } class TaskB { int INF = (int) 1e9 + 7; int MAX_N = (int) 1e5 + 5; long mod = (long) 1e8; ArrayList<Integer> edges[]; ArrayList<Integer> rev_edges[]; boolean visited[]; ArrayList<Integer> topSort; int color[]; public void solve(int testNumber, InputReader in, PrintWriter pw) { char arr[] = in.next().toCharArray(); int t = arr.length; int k = in.nextInt(); boolean forbidden[][] = new boolean[26][26]; for (int i = 0; i < k; i++) { char pair[] = in.next().toCharArray(); forbidden[pair[0] - 'a'][pair[1] - 'a'] = true; forbidden[pair[1] - 'a'][pair[0] - 'a'] = true; } int dp[][] = new int[t + 1][27]; for (int i = 0; i <= t; i++) { for (int j = 0; j < 26; j++) { if (i == 0) { dp[i][j] = 0; } else { dp[i][j] = INF; } } } // dp[0][26] = 1; for (int i = 0; i < t; i++) { for (int j = 0; j < 26; j++) { if (!forbidden[j][arr[i] - 'a']) { dp[i + 1][arr[i] - 'a'] = Math.min(dp[i + 1][arr[i] - 'a'], dp[i][j]); } dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j] + 1); } // pw.println(dp[i][26]); } int ans = INF; for (int i = 0; i < 26; i++) { ans = Math.min(dp[t][i], ans); } pw.println(ans); } int[] shrink(int a[]) { int n = a.length; long b[] = new long[n]; for (int i = 0; i < n; i++) { b[i] = ((long) (a[i] << 32)) | i; } Arrays.sort(b); int ret[] = new int[n]; int p = 0; for (int i = 0; i < n; i++) { if (i > 0 && (b[i] ^ b[i - 1]) >> 32 != 0) { p++; } ret[(int) b[i]] = p; } return ret; } int sum(int ft[], int i) { int sum = 0; for (int j = i; j >= 1; j -= (j & -j)) { sum += ft[j]; // System.out.println(sum); } return sum; } void add(int ft[], int i, int x) { for (int j = i; j < ft.length; j += (j & -j)) { // System.out.println(j); ft[j] += x; } } boolean isValid(int i, int j, char arr[][]) { if (i >= arr[0].length || j >= arr[0].length) { return false; } if (arr[i][j] == '*') { return false; } return true; } long pow(long m, long k) { long prod = 1; for (int i = 0; i < k; i++) { prod = (prod * m) % INF; } return prod % INF; } // int sum(int k) { // int sum=0; // for(int i=k;i>=1;i) { // sum+=ft[k]; // } // } long fib(int N) { long fib[] = new long[N + 1]; fib[0] = 1; fib[1] = 1; for (int i = 2; i <= N; i++) { fib[i] = (fib[i - 1] + fib[i - 2]) % mod; } return fib[N] % mod; } long sum(int i, int j, long arr[]) { long sum = 0; for (int k = i; k <= j; k++) { sum += arr[k]; } return sum; } boolean FirstRow_Col(Pair pair) { return pair.first == 0 || pair.second == 0; } int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } public int getInt(int num) { int ret = -1; switch (num) { case 0: ret = 6; break; case 1: ret = 2; break; case 2: ret = 5; break; case 3: ret = 5; break; case 4: ret = 4; break; case 5: ret = 5; break; case 6: ret = 6; break; case 7: ret = 3; break; case 8: ret = 7; break; case 9: ret = 6; break; } return ret; } public int isPow(long num) { int count = 0; while (num > 0) { num /= 2; count++; } return count; } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
604193df86876f379d09b29864b47c9b
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true); TaskB solver = new TaskB(); solver.solve(1, in, out); out.flush(); out.close(); } } class Pair { int first; int second; Pair(int first, int second) { this.first = first; this.second = second; } } class TaskB { int INF = (int) 1e9 + 7; int MAX_N = (int) 1e5 + 5; long mod = (long) 1e8; ArrayList<Integer> edges[]; ArrayList<Integer> rev_edges[]; boolean visited[]; ArrayList<Integer> topSort; int color[]; public void solve(int testNumber, InputReader in, PrintWriter pw) { char arr[] = in.next().toCharArray(); int t = arr.length; int k = in.nextInt(); boolean forbidden[][] = new boolean[26][26]; for (int i = 0; i < k; i++) { char pair[] = in.next().toCharArray(); forbidden[pair[0] - 'a'][pair[1] - 'a'] = true; forbidden[pair[1] - 'a'][pair[0] - 'a'] = true; } int dp[][] = new int[t + 1][27]; for (int i = 0; i <= t; i++) { for (int j = 0; j < 26; j++) { if (i == 0) { dp[i][j] = 0; } else { dp[i][j] = INF; } } } // dp[0][26] = 1; for (int i = 0; i < t; i++) { for (int j = 0; j < 26; j++) { if (dp[i][j] < INF) { if (!forbidden[j][arr[i] - 'a']) { dp[i + 1][arr[i] - 'a'] = Math.min(dp[i + 1][arr[i] - 'a'], dp[i][j]); } dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j] + 1); } } // pw.println(dp[i][26]); } int ans = INF; for (int i = 0; i < 26; i++) { ans = Math.min(dp[t][i], ans); } pw.println(ans); } int[] shrink(int a[]) { int n = a.length; long b[] = new long[n]; for (int i = 0; i < n; i++) { b[i] = ((long) (a[i] << 32)) | i; } Arrays.sort(b); int ret[] = new int[n]; int p = 0; for (int i = 0; i < n; i++) { if (i > 0 && (b[i] ^ b[i - 1]) >> 32 != 0) { p++; } ret[(int) b[i]] = p; } return ret; } int sum(int ft[], int i) { int sum = 0; for (int j = i; j >= 1; j -= (j & -j)) { sum += ft[j]; // System.out.println(sum); } return sum; } void add(int ft[], int i, int x) { for (int j = i; j < ft.length; j += (j & -j)) { // System.out.println(j); ft[j] += x; } } boolean isValid(int i, int j, char arr[][]) { if (i >= arr[0].length || j >= arr[0].length) { return false; } if (arr[i][j] == '*') { return false; } return true; } long pow(long m, long k) { long prod = 1; for (int i = 0; i < k; i++) { prod = (prod * m) % INF; } return prod % INF; } // int sum(int k) { // int sum=0; // for(int i=k;i>=1;i) { // sum+=ft[k]; // } // } long fib(int N) { long fib[] = new long[N + 1]; fib[0] = 1; fib[1] = 1; for (int i = 2; i <= N; i++) { fib[i] = (fib[i - 1] + fib[i - 2]) % mod; } return fib[N] % mod; } long sum(int i, int j, long arr[]) { long sum = 0; for (int k = i; k <= j; k++) { sum += arr[k]; } return sum; } boolean FirstRow_Col(Pair pair) { return pair.first == 0 || pair.second == 0; } int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } public int getInt(int num) { int ret = -1; switch (num) { case 0: ret = 6; break; case 1: ret = 2; break; case 2: ret = 5; break; case 3: ret = 5; break; case 4: ret = 4; break; case 5: ret = 5; break; case 6: ret = 6; break; case 7: ret = 3; break; case 8: ret = 7; break; case 9: ret = 6; break; } return ret; } public int isPow(long num) { int count = 0; while (num > 0) { num /= 2; count++; } return count; } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
651c9aa97efeb490024c6203faa5c1f6
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
/* * * @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya) * Dhirubhai Ambani Institute of Information And Communication Technology * */ import java.util.*; import java.io.*; import java.lang.*; public class Code162 { 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 int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int 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 ArrayList<Integer> primeFactorization(int n) { ArrayList<Integer> a =new ArrayList<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 int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } 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); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); char[] s = in.nextLine().toCharArray(); int k = in.nextInt(); char[][] fb = new char[k][2]; int ans = 0; for(int i=0;i<k;i++) fb[i] = in.nextLine().toCharArray(); for(int i=0;i<k;i++) { int c1 = 0; int c2 = 0; for(int j=0;j<s.length;j++) { if(s[j]==fb[i][0]) c1++; else if(s[j]==fb[i][1]) c2++; else { ans+=Math.min(c2, c1); c1=0; c2=0; } } ans+=Math.min(c1, c2); } pw.println(ans); pw.flush(); pw.close(); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
78230c0ccc296804167fe78b3122a57b
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String str = sc.next(); int n = sc.nextInt(); int ans=0; int len=0; int aa=0; int bb=0; for(int j=1;j<=n;j++){ String s = sc.next(); char a = s.charAt(0); char b = s.charAt(1); len=0;aa=0;bb=0; for(int i=0;i<str.length();i++){ if(str.charAt(i)==a || str.charAt(i)==b){ len++; if(str.charAt(i)==a) aa++; else bb++; } else{ if(len==2 && aa!=0 && bb!=0) ans++; else if(len>2){ if(aa>bb) ans+=bb; else ans+=aa; } len=0; aa=0; bb=0; } } if(len>2){ if(aa>bb) ans+=bb; else ans+=aa; } } System.out.println(ans); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
b55be5202cf35ddaff326159d621bc5a
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import static java.lang.Integer.min; public class Hometask implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); public void solve() { x = in.next().toCharArray(); forbidden = new int[27]; for (int i = 0; i <= 26; i++) { forbidden[i] = -1; } int k = in.ni(); for (int i = 0; i < k; i++) { char[] pair = in.next().toCharArray(); int u = pair[0] - 'a' + 1, v = pair[1] - 'a' + 1; forbidden[u] = v; forbidden[v] = u; } dp = new Integer[x.length][27]; out.println(recurse(0, 0)); } private char[] x; private int[] forbidden = new int[27]; private Integer[][] dp; private int recurse(int idx, int last) { if (idx == x.length) return 0; if (dp[idx][last] != null) return dp[idx][last]; int ans = 1 + recurse(idx + 1, last); int u = x[idx] - 'a' + 1; if (forbidden[u] == last) { ans = min(ans, 1 + recurse(idx + 1, last)); } else { ans = min(ans, recurse(idx + 1, u)); } return dp[idx][last] = ans; } @Override public void close() throws IOException { in.close(); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (Hometask instance = new Hometask()) { instance.solve(); } } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
9d0dba7e112f69389d9b049014075904
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.*; import java.io.*; public class Hometask { /************************ SOLUTION STARTS HERE ************************/ private static void solve() { char str[] = nextLine().toCharArray(); int k = nextInt(); char map[] = new char[26]; while(k-->0) { String pair = nextLine(); map[pair.charAt(0) - 'a'] = pair.charAt(1); map[pair.charAt(1) - 'a'] = pair.charAt(0); } int cnt = 0; char curr = str[0]; int f1 = 1 , f2 = 0; for(int i = 1; i < str.length; i++) { if(str[i] == curr) f1++; else if(str[i] == map[curr - 'a']) f2++; else { // System.out.println("f1 = " + f1 + " f2 = " + f2); cnt += Math.min(f1, f2); f1 = 0; f2 = 0; curr = str[i]; f1++; } } // System.out.println("f1 = " + f1 + " f2 = " + f2); cnt += Math.min(f1, f2); println(cnt); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE **********************/ public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); st = null; solve(); reader.close(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer st; static String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} static String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} static int nextInt() {return Integer.parseInt(next());} static long nextLong() {return Long.parseLong(next());} static double nextDouble(){return Double.parseDouble(next());} static char nextChar() {return next().charAt(0);} static int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} static long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} static int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} static long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} static void print(Object o) { writer.print(o); } static void println(Object o){ writer.println(o);} /************************ TEMPLATE ENDS HERE ************************/ }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
0cc74b6c0043350228aad97b952b29dd
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.awt.*; import java.io.*; import java.math.BigInteger; import java.util.*; public class Abc { static char[] s; static int k; static Set<String> set; static int dp[][]; public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); s=sc.next().toCharArray(); k=sc.nextInt(); set=new HashSet<>(); dp=new int[s.length][60]; for (int i=0;i<k;i++){ String x=sc.next(); set.add(x); set.add(x.charAt(1)+""+x.charAt(0)+""); } for (int arr[]:dp) { Arrays.fill(arr, -1); } System.out.println(dp(0,(char) (s[0]+28))); } static int dp(int i,char prev){ if (i>=s.length)return 0; if (dp[i][prev-'a']!=-1)return dp[i][prev-'a']; if (set.contains(s[i]+""+prev+"")){ return dp[i][prev-'a']=dp(i+1,prev)+1; } return dp[i][prev-'a']=Math.min(dp(i+1,s[i]),1+dp(i+1,prev)); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
6412f0d52bbd321dc5e86e496fbfb4ab
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Closeable; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public class A implements Closeable { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); A() throws IOException { // reader = new BufferedReader(new FileReader("input.txt")); // writer = new PrintWriter(new FileWriter("output.txt")); } StringTokenizer stringTokenizer; String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } private int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } int product(int a, int b) { return (int) (1l * a * b % MOD); } int pow(int x, int k) { int result = 1; while (k > 0) { if (k % 2 == 1) { result = product(result, x); } x = product(x, x); k /= 2; } return result; } int inv(int x) { return pow(x, MOD - 2); } void solve() throws IOException { final char[] s = next().toCharArray(); int k = nextInt(); final char[] hate = new char[26]; for(int i = 0; i < k; i++) { char[] h = next().toCharArray(); for(int j = 0; j < 2; j++) { hate[h[j] - 'a'] = h[1 - j]; } } class Utils { int bestRemoval(int k, char prev) { if(k == s.length) { return 0; } int answer = 1 + bestRemoval(k + 1, prev); if(prev != hate[s[k] - 'a']) { answer = Math.min(answer, bestRemoval(k + 1, s[k])); } return answer; } } class CachedUtils extends Utils { Integer[][] cache = new Integer[s.length + 1][26]; @Override int bestRemoval(int k, char prev) { Integer best = cache[k][prev - 'a']; if(best == null) { best = super.bestRemoval(k, prev); cache[k][prev - 'a'] = best; } return best; } } Utils utils = new CachedUtils(); int best = s.length; for(char prev = 'a'; prev <= 'z'; prev++) { best = Math.min(best, utils.bestRemoval(0, prev)); } writer.println(best); } public static void main(String[] args) throws IOException { try (A a = new A()) { a.solve(); } } @Override public void close() throws IOException { reader.close(); writer.close(); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
ee89a55b67d6e9e5fbde0d41157905c1
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** What do you think? What do you think? 1st on Billboard, what do you think of it Next is a Grammy, what do you think of it However you think, I’m sorry, but shit, I have no fcking interest ******************************* I'm standing on top of my Monopoly board That means I'm on top of my game and it don't stop til my hip don't hop anymore https://www.a2oj.com/Ladder16.html ******************************* 300iq as writer = Sad! */ import java.util.*; import java.io.*; import java.math.*; public class x154A { public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); char[] arr = infile.readLine().toCharArray(); int N = arr.length; HashSet<String> set = new HashSet<String>(); int K = Integer.parseInt(infile.readLine()); int res = 0; for(int k=0; k < K; k++) { String input = infile.readLine(); int a = 0; int b = 0; for(int i=0; i < N; i++) { if(arr[i] == input.charAt(0)) a++; else if(arr[i] == input.charAt(1)) b++; else { res += Math.min(a,b); a = b = 0; } } res += Math.min(a,b); } System.out.println(res); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
1f3d84a0c9d9ff37767603382299061b
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.*; import java.util.*; public final class hometask { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static char[] a; static int[][] dp; static int[] b; static int n; static int solve(int idx,int last) { if(idx>=n) { return 0; } if(dp[idx][last]!=-1) { return dp[idx][last]; } else { int val=1+solve(idx+1,last); if(b[a[idx]-'a'+1]!=last) { val=Math.min(val,solve(idx+1,a[idx]-'a'+1)); } dp[idx][last]=val;return dp[idx][last]; } } public static void main(String args[]) throws Exception { a=sc.next().toCharArray();n=a.length;b=new int[27];int k=sc.nextInt();dp=new int[n][27];Arrays.fill(b,-1); while(k>0) { char[] arr=sc.next().toCharArray();b[arr[0]-'a'+1]=arr[1]-'a'+1;b[arr[1]-'a'+1]=arr[0]-'a'+1; k--; } for(int i=0;i<n;i++) { for(int j=0;j<27;j++) { dp[i][j]=-1; } } out.println(solve(0,0));out.close(); } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
71d04a20a2acba7a81e60da90d4380bb
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { private static char [] pair = new char[128]; private static char [] C,S; private static int [] cnt; private static void compress(){ int m = 0; char lst = 0; for (int i = 0;i < S.length;i++){ if (lst != S[i]) m++; lst = S[i]; } C = new char[m]; cnt = new int[m]; m = 0; for (int i = 0;i < S.length;) { int j = i; while (j < S.length && S[i] == S[j]) j++; C[m] = S[i]; cnt[m] = j - i; m++; i = j; } } public static void main(String[] args) throws Exception{ IO io = new IO(null,null); S = io.getNext().toCharArray(); int k = io.getNextInt(); for(int i = 0;i < k;i++) { char [] p = io.getNext().toCharArray(); char a = p[0],b = p[1]; pair[a] = b; pair[b] = a; } compress(); int ans = 0; for (int i = 0;i < C.length;) { int c1 = 0,c2 = 0,j = i; while (j < C.length && (C[j] == C[i] || C[j] == pair[C[i]])) { if (C[j] == C[i]) c1 += cnt[j]; else c2 += cnt[j]; j++; } // System.err.println(c1 + " " + c2); ans += Math.min(c1,c2); i = j; } io.println(ans); io.close(); } } class IO{ private BufferedReader br; private StringTokenizer st; private PrintWriter writer; private String inputFile,outputFile; public boolean hasMore() throws IOException{ if(st != null && st.hasMoreTokens()) return true; if(br != null && br.ready()) return true; return false; } public String getNext() throws FileNotFoundException, IOException{ while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String getNextLine() throws FileNotFoundException, IOException{ return br.readLine().trim(); } public int getNextInt() throws FileNotFoundException, IOException{ return Integer.parseInt(getNext()); } public long getNextLong() throws FileNotFoundException, IOException{ return Long.parseLong(getNext()); } public void print(double x,int num_digits) throws IOException{ writer.printf("%." + num_digits + "f" ,x); } public void println(double x,int num_digits) throws IOException{ writer.printf("%." + num_digits + "f\n" ,x); } public void print(Object o) throws IOException{ writer.print(o.toString()); } public void println(Object o) throws IOException{ writer.println(o.toString()); } public IO(String x,String y) throws FileNotFoundException, IOException{ inputFile = x; outputFile = y; if(x != null) br = new BufferedReader(new FileReader(inputFile)); else br = new BufferedReader(new InputStreamReader(System.in)); if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile))); else writer = new PrintWriter(new OutputStreamWriter(System.out)); } protected void close() throws IOException{ br.close(); writer.close(); } public void outputArr(Object [] A) throws IOException{ int L = A.length; for (int i = 0;i < L;i++) { if(i > 0) writer.print(" "); writer.print(A[i]); } writer.print("\n"); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
9efa6b868a95ef1fc6082e2f2cd40ca8
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; /** * * @author fz */ public class Rnd154A { Scanner in = new Scanner(System.in); private Rnd154A() throws IOException { //in.nextLine(); String s = in.next(); int n = in.nextInt(); in.nextLine(); String[] ps = new String[n]; String[] rev = new String[n]; for(int i = 0; i < n; i++) { ps[i] = in.next(); StringBuffer sb = new StringBuffer(ps[i]); sb = sb.reverse(); rev[i] = sb.toString(); } int res = 0; int i = 0; while(i < s.length()) { boolean flag = false; int jtp = -1; for(int j = 0; j < n; j++) { if(s.charAt(i) == ps[j].charAt(0) || s.charAt(i) == ps[j].charAt(1)) { flag = true; jtp = j; break; } } if(flag == false) { i++; } else { int j = i; int v1 = 0; int v2 = 0; while(j < s.length()) { if(s.charAt(j) == ps[jtp].charAt(0)) { v1++; j++; } else if(s.charAt(j) == ps[jtp].charAt(1)) { v2++; j++; } else break; } res += Math.min(v1, v2); i = j; } } out(res); } private int[] ns(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) { res[i] = in.nextInt(); } return res; } private int[][] getMat(int m, int n) {//m rows and n cols int[][] res = new int[m][n]; for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) res[i][j] = in.nextInt(); return res; } private static void out(Object x) { System.out.println(x); } public static void main(String[] args) throws IOException { new Rnd154A(); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
0f171dc1465a6fce0d6a95c436c89e9e
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.Arrays; import java.io.OutputStream; 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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { String S = in.next(); int K = in.nextInt(), N = S.length(); int[] pair = new int[26]; Arrays.fill(pair, -1); while (K -- > 0) { String p = in.next(); pair[p.charAt(0) - 'a'] = p.charAt(1) - 'a'; pair[p.charAt(1) - 'a'] = p.charAt(0) - 'a'; } int[] dp = new int[N + 1]; int ans = 0x3f3f3f3f; int[] last = new int[26]; for (int i = 1; i <= N; ++i) { int c = S.charAt(i - 1) - 'a'; dp[i] = 0x3f3f3f3f; for (int j = 0; j < 26; ++j) { if (j == pair[c]) continue; dp[i] = Math.min(dp[i], dp[last[j]] + i - last[j] - 1); } last[c] = i; ans = Math.min(ans, dp[i] + N - i); } out.println(ans); } } 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() { return Integer.parseInt(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
64d48d01cabebdf4a3358a87c2323722
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.StringTokenizer; /** * 154A * * @author artyom */ public class Hometask implements Runnable { private static final int MAX = 'z' + 1; private BufferedReader in; private PrintStream out; private StringTokenizer tok; private void solve() throws IOException { char[] phrase = (nextToken() + ".").toCharArray(); boolean[][] forbidden = new boolean[MAX][MAX]; for (int i = 0, k = nextInt(); i < k; i++) { char[] pair = nextToken().toCharArray(); forbidden[pair[0]][pair[1]] = forbidden[pair[1]][pair[0]] = true; } int removed = 0; for (int count1 = 1, count2 = 0, prev1 = phrase[0], prev2 = -1, i = 1, n = phrase.length; i < n; i++) { if (phrase[i] == prev1 || phrase[i] == prev2) { if (phrase[i] == prev1) { count1++; } else { count2++; } } else { if (prev2 != -1) { removed += Math.min(count1, count2); prev1 = phrase[i]; count1 = 1; prev2 = -1; count2 = 0; } else if (forbidden[prev1][phrase[i]]) { prev2 = phrase[i]; count2 = 1; } else { prev1 = phrase[i]; count1 = 1; } } } out.println(removed); } //-------------------------------------------------------------- public static void main(String[] args) { new Hometask().run(); } @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = System.out; tok = null; solve(); in.close(); } catch (IOException e) { System.exit(0); } } private String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
34ed64f61a93639f9fe06b0641b036d0
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){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 l(){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 i(){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 d() throws IOException {return Double.parseDouble(s()) ;} 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 int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;} } // |----| /\ | | ----- | // | / / \ | | | | // |--/ /----\ |----| | | // | \ / \ | | | | // | \ / \ | | ----- ------- static String s; static int mark[][]; static int cache[][]; public static int dp(int pos,int prev) { if(pos==s.length())return 0; if(cache[pos][prev]!=-1)return cache[pos][prev]; if(mark[prev][s.charAt(pos)-97]==1) return cache[pos][prev]=1+dp(pos+1,prev); else return cache[pos][prev]=Math.min(1+dp(pos+1,prev),dp(pos+1,s.charAt(pos)-97)); } public static void main(String[] args)throws IOException { PrintWriter out= new PrintWriter(System.out); Reader sc=new Reader(); s=sc.s(); int k=sc.i(); mark=new int[27][27]; cache=new int[s.length()][27]; for(int i=0;i<s.length();i++)Arrays.fill(cache[i],-1); while(k-->0) { String s=sc.s(); mark[s.charAt(0)-97][s.charAt(1)-97]=1; mark[s.charAt(1)-97][s.charAt(0)-97]=1; } int min=s.length(); for(int i=0;i<s.length();i++) min=Math.min(min,i+dp(i+1,s.charAt(i)-97)); out.println(min); out.flush(); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
6d76a96ad727609497e4125ebab9827d
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package CP; import java.io.*; import java.util.*; public class A154 { public static void main(String args[])throws IOException { Scanner sc=new Scanner(System.in); String s=sc.next(); int pair=sc.nextInt(); int n=s.length(); HashSet<String> set=new HashSet<>(); for(int i=0;i<pair;i++) { set.add(sc.next()); } int i=1,res=0; while(i<n) { String str=""+s.charAt(i)+s.charAt(i-1); String rev=""+s.charAt(i-1)+s.charAt(i); if(set.contains(str) || set.contains(rev)) { char ch1=s.charAt(i),ch2=s.charAt(i-1); int m1=0,m2=0,j=i-1; while(j<n) { char ch=s.charAt(j); if(ch!=ch1 && ch!=ch2) break; if(ch==ch1) m1++; else m2++; j++; } j=i-2; i+=m1+m2; while(j>=0) { char ch=s.charAt(j); if(ch!=ch1 && ch!=ch2) break; if(ch==ch1) m1++; else m2++; j--; } res+=Math.min(m1,m2); //System.out.println(i+" "+m1+" "+m2+" "+j); } else { i++; } } System.out.println(res); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
b58a6d41bc7d71cbe3bb45f6776e18e9
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.*; public class practice { public static void main(String[] args) { Scanner scn=new Scanner(System.in); String s=scn.next(),p; int k=scn.nextInt(),x=0,y=0,ans=0; char a,b; for(int i=0;i<k;i++){ p=scn.next(); for(int j=0;j<s.length();j++){ if(s.charAt(j)==p.charAt(0)){ x++; } else if(s.charAt(j)==p.charAt(1)){ y++; } else{ ans+=Math.min(x,y); x=0;y=0; } } ans+=Math.min(x,y); x=0;y=0; } System.out.println(ans); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
1f67c493a21898897f9f482eacaf90f3
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
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.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Nafiur Rahman Khadem Shafin */ public class Main { public static void main (String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader (inputStream); PrintWriter out = new PrintWriter (outputStream); TaskA solver = new TaskA (); solver.solve (1, in, out); out.close (); } static class TaskA { public void solve (int testNumber, InputReader in, PrintWriter out) { /* the weak point of the problem is a letter can't be in more than one pair. Let's try thinking case by case. * abbbbbba ==> remove 2 a, ababa ==> remove 2 b, ababbbba ==> remove 3 a, */ char[] str = in.next ().toCharArray (); int k = in.nextInt (), n = str.length, res = 0; char[][] frbdn = new char[k+5][5]; int[] cnt = new int[2+5]; for (int i = 0; i<k; i++) { frbdn[i] = in.next ().toCharArray ();//let's try avoiding genjam by only calculating for one pair at once for (char aStr : str) { if (aStr == frbdn[i][0]) { cnt[0]++; } else if (aStr == frbdn[i][1]) { cnt[1]++; } else { if (cnt[0]>0 && cnt[1]>0) res += Math.min (cnt[0], cnt[1]); // System.out.println (cnt[0]+" "+cnt[1]+" "+res); cnt[0] = cnt[1] = 0; } } if (cnt[0]>0 && cnt[1]>0) res += Math.min (cnt[0], cnt[1]); // System.out.println (cnt[0]+" "+cnt[1]+" "+res); cnt[0] = cnt[1] = 0; } out.println (res); } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader (InputStream stream) { reader = new BufferedReader (new InputStreamReader (stream)); tokenizer = null; } public String next () { while (tokenizer == null || !tokenizer.hasMoreTokens ()) { try { String str; if ((str = reader.readLine ()) != null) tokenizer = new StringTokenizer (str); else return null;//to detect eof } catch (IOException e) { throw new RuntimeException (e); } } return tokenizer.nextToken (); } public int nextInt () { return Integer.parseInt (next ()); } } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
95e5a643d5658c13e394061af9181c65
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.Scanner; public class Hometask { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); int k = sc.nextInt(); int[] pair = new int[26]; for(int i = 0; i < 26; i++) { pair[i] = -1; } for(int i = 0; i < k; i++) { String s2 = sc.next(); int a = s2.charAt(0) - 'a'; int b = s2.charAt(1) - 'a'; pair[a] = b; pair[b] = a; } int a = -1; int b = -1; int as = 0; int bs = 0; int r = 0; for(int i = 0; i < s.length(); i++) { int cur = s.charAt(i) - 'a'; if(cur == a || cur == b) { if(cur == a)as++; else if(cur == b)bs++; } else { r += Math.min(as, bs); a = cur; b = pair[a]; as = 1; bs = 0; } } r += Math.min(as, bs); System.out.println(r); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
2dc67aea106b2ea739d9f19f44080f59
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class PracticeProblem { /* * This FastReader code is taken from GeeksForGeeks.com * https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/ * * The article was written by Rishabh Mahrsee */ public 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 FastReader in = new FastReader(); public static PrintWriter out = new PrintWriter(System.out); public static final int MOD = (int)1e9 + 7; public static void main(String[] args) { char[] str = in.nextLine().toCharArray(); int k = in.nextInt(); Map<Character, Integer> mapping = new HashMap<>(); // Maps the character to it's forbiddenPairs index char[][] forbiddenPairs = new char[k][2]; for (int i = 0; i < k; i++) { String line = in.nextLine(); mapping.put(line.charAt(0), i); mapping.put(line.charAt(1), i); forbiddenPairs[i][0] = line.charAt(0); forbiddenPairs[i][1] = line.charAt(1); } long answer = 0; for (int i = 0; i < str.length; i++) { int curPair = -1; if (mapping.containsKey(str[i])) curPair = mapping.get(str[i]); else continue; int aCount = 0; int bCount = 0; while (i < str.length && mapping.containsKey(str[i]) && mapping.get(str[i]) == curPair) { if (str[i] == forbiddenPairs[curPair][0]) aCount++; else bCount++; i++; } i--; answer += min(aCount, bCount); } out.println(answer); out.close(); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 8
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
b1783ddc058bcfac90c0a8460d694001
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.HashMap; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { HashMap<Character,Character> map = new HashMap<Character, Character>(); int []a = new int[26]; String s = in.next(); int len = s.length(); int n = in.nextInt(); for(int i=0;i<len;i++) a[s.charAt(i)-'a']++; for(int i=0;i<n;i++){ String ss = in.next(); map.put(ss.charAt(0),ss.charAt(1)); map.put(ss.charAt(1),ss.charAt(0)); } int ans = 0; for(int i=0;i<s.length();){ if(!map.containsKey(s.charAt(i))){ i++; continue; } char x = s.charAt(i); char y = map.get(s.charAt(i)); int cnt1=0,cnt2 = 0; while (i<s.length() && (s.charAt(i)==x || s.charAt(i)==y)){ if(s.charAt(i)==x) cnt1++; else cnt2++; i++; } ans+= Math.min(cnt1,cnt2); } out.println(ans); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
79f75e8f34acdac84002c7e27ec893f9
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.*; public class C { static String s; static boolean[][] adj = new boolean[31][31]; static int[][] dp; static int n; public static void main(String[] args) { Scanner in = new Scanner(System.in); s = in.next(); int k = in.nextInt(); String t; int a, b; for (int i = 0; i < k; i++) { t = in.next(); a = t.charAt(0) - 'a'; b = t.charAt(1) - 'a'; adj[a][b] = adj[b][a] = true; } dp = new int[(n = s.length()) + 10][26 + 10]; for (int i = 0; i < dp.length; i++) Arrays.fill(dp[i], -1); System.out.println(solve(0, 30)); } public static int solve(int at, int last) { if (at == n) return 0; if (dp[at][last] != -1) return dp[at][last]; int min = 100005; if (adj[s.charAt(at) - 'a'][last]) { min = Math.min(min, 1 + solve(at + 1, last)); } else { min = Math.min(min, 1 + solve(at + 1, last)); min = Math.min(min, solve(at + 1, s.charAt(at) - 'a')); } return dp[at][last] = min; } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
d962b7067f91b6d17ddfa631ed7b2195
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.Scanner; public class ProblemA { private void solve() { Scanner in = new Scanner(new BufferedInputStream(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); char[] s = in.next().toCharArray(); int k = in.nextInt(); char[][] f = new char[2*k][2]; for (int i = 0; i < k; i++) { char[] t = in.next().toCharArray(); f[i][0] = f[i + k][1] = t[0]; f[i][1] = f[i + k][0] = t[1]; } int result = 0; int b = 0; //int e = 1; //boolean[] cut = new boolean[s.length]; while (b < s.length) { int j = -1; for (int i = 0; i < f.length; i++) { if (f[i][0] == s[b]) { j = i; break; } } if (j > -1) { int[] t = new int[2]; while (b < s.length) { if (s[b] == f[j][0]) { t[0]++; } else if (s[b] == f[j][1]) { t[1]++; } else { b--; break; } b++; } result += Math.min(t[0], t[1]); } b++; } out.println(result); out.flush(); out.close(); } public static void main(String[] args) { ProblemA solver = new ProblemA(); solver.solve(); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
10447fff86ac53dd619636c2667f9f5f
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class Hometask { private static final char SIMIL_NULL = (char)0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String theString = sc.next(); char[] theStringChar = theString.toCharArray(); System.err.println(theStringChar.length); int k = sc.nextInt(); int[] forbidden = new int[256]; HashSet<Character> charsSet = new HashSet<Character>(); charsSet.add(SIMIL_NULL); for (int i = 0; i < k; i++) { String couple = sc.next(); char c1 = couple.charAt(0); char c2 = couple.charAt(1); charsSet.add(c1); charsSet.add(c2); forbidden[(int)c1] = c2; forbidden[(int)c2] = c1; } int[][] dp = new int[256][theStringChar.length+1]; for(int[] a : dp) { Arrays.fill(a, -1); } for(Character c : charsSet) { for (int i = theStringChar.length-1; i >= 0; i--) { solve(i, c, forbidden, theStringChar, dp); } } System.out.println(solve(0, SIMIL_NULL, forbidden, theStringChar, dp)); } private static int solve(int pos, char prev, int[] forbidden, char[] theStringChar, int[][] dp) { if(pos == theStringChar.length) return 0; int cached = dp[(int)prev][pos]; if(cached != -1) return cached; int res = solve(pos+1, prev, forbidden, theStringChar, dp)+1; // delete first char current = theStringChar[pos]; if(canCoexist(prev, current, forbidden)) { int rec = solve(pos+1, current, forbidden, theStringChar, dp); res = Math.min(res, rec); } dp[(int)prev][pos] = res; return res; } private static boolean canCoexist(Character a, Character b, int[] forbidden) { if(a == SIMIL_NULL || b == SIMIL_NULL) return true; return forbidden[(int)a] != (int)b; } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
fef86cff7df2c86222db90c580d7de04
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.*; public class A { private static final Scanner sc = new Scanner(System.in); public static void main(String[] args) { final char[] cs = sc.next().toCharArray(); final int n = sc.nextInt(); char[][] pat = new char[n][]; for(int i = 0; i < n; i++) { pat[i] = sc.next().toCharArray(); } int res = 0; for(int i = 0; i + 1 < cs.length; i++) { for(int j = 0; j < n; j++) { if(cs[i] == pat[j][0] && cs[i+1] == pat[j][1] || cs[i] == pat[j][1] && cs[i+1] == pat[j][0]) { int r = i + 1, p1 = 1, p2 = 1; for(int k = i + 2; k < cs.length; k++) { if(cs[k] == cs[i+1]) { p2++; } else if(cs[k] == cs[i]) { p1++; } else { break; } r = k; } for(int k = i - 1; k >= 0; k--) { if(cs[k] == cs[i+1]) { p2++; } else if(cs[k] == cs[i]) { p1++; } else { break; } } res += Math.min(p2, p1); i = r; } } } System.out.println(res); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
c8f3b5c892da37f67403baece73a959f
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import static java.lang.Math.min; import static java.util.Arrays.deepToString; import java.io.*; import java.math.*; import java.util.*; public class A { static int solve(String ws, char[][] ch) { int ans = 0; char[] w = ws.toCharArray(); for (char[] c : ch) { int pos = 0; while (pos < w.length) { if (w[pos] == c[0] || w[pos] == c[1]) { int cnt0 = 0, cnt1 = 0; while (pos < w.length && (w[pos] == c[0] || w[pos] == c[1])) { if (w[pos] == c[0]) cnt0++; else cnt1++; pos++; } ans += min(cnt0, cnt1); } else { pos++; } } } return ans; } public static void main(String[] args) throws Exception { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); String w = next(); int k = nextInt(); char[][] ch = new char[k][]; for (int i = 0; i < k; i++) { ch[i] = next().toCharArray(); } setTime(); int ans = solve(w, ch); writer.println(ans); printTime(); printMemory(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer tok = new StringTokenizer(""); static long systemTime; static void debug(Object... o) { System.err.println(deepToString(o)); } 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"); } static String next() { while (!tok.hasMoreTokens()) { String w = null; try { w = reader.readLine(); } catch (Exception e) { e.printStackTrace(); } if (w == null) return null; tok = new StringTokenizer(w); } return tok.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static BigInteger nextBigInteger() { return new BigInteger(next()); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
fcb12603a60fea58b221585c9a4de6b9
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.*; public class A { char [] F = new char[256]; public A () throws IOException { String input = r.readLine(); int K = Integer.parseInt(r.readLine()); for (int i = 0; i < K; ++i) { char [] f = r.readLine().toCharArray(); F[f[0]] = f[1]; F[f[1]] = f[0]; } solve(input); } public void solve (String S) { start(); char [] C = S.toCharArray(); int N = C.length; int cnt = 0; for (int p = 0; p < N; ) { char A = C[p], B = F[C[p]]; int q; for (q = p; q < N && (C[q] == A || C[q] == B); ++q); int ca = 0, cb = 0; for (int i = p; i < q; ++i) { if (C[i] == A) ++ ca; if (C[i] == B) ++ cb; } cnt += Math.min(ca, cb); p = q; } print (cnt); } //////////////////////////////////////////////////////////////////////////////////// static BufferedReader r; static long t; static void print2 (Object o) { System.out.println(o); } static void print (Object o) { print2(o); //print2((millis() - t) / 1000.0); System.exit(0); } static void run () throws IOException { r = new BufferedReader(new InputStreamReader(System.in)); new A(); } public static void main(String[] args) throws IOException { run(); } static long millis() { return System.currentTimeMillis(); } static void start() { t = millis(); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
6b39019d56e4e9692ef8f2b008ce2fbd
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C109P3 { private static BufferedReader in; private static PrintWriter out; private static StringTokenizer input; public static void main(String[] args) throws IOException { //------------------------------------------------------------------------- //Initializing... new C109P3(); //------------------------------------------------------------------------- //put your code here... :) char [] x = nextString().toCharArray(); word = new int[x.length]; for (int i = 0; i < x.length; i++) { word[i] = x[i] - 'a' +1; } prob =new boolean [30][30]; int n = nextInt(); while(n-->0){ x = nextString().toCharArray(); prob[x[0] - 'a' +1][x[1] - 'a' +1] = prob[x[1] - 'a' +1][x[0] - 'a' +1] = true; } memo = new int[30][word.length+1]; for (int i = 0; i < memo.length; i++) { Arrays.fill(memo[i], -1); } writeln(""+(word.length - play(0,0))); //------------------------------------------------------------------------- //closing up end(); //-------------------------------------------------------------------------- } static int [] word; static boolean [][] prob; static int memo[][]; static int play (int p, int i){ if(i == word.length)return 0; if(memo[p][i]!=-1)return memo[p][i]; if (prob[p][word[i]]) return memo[p][i] =play(p,i+1); return memo[p][i]= Math.max(play(p,i+1), play(word[i],i+1)+1); } public C109P3() throws IOException { //Input Output for Console to be used for trying the test samples of the problem in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); //------------------------------------------------------------------------- //Initalize Stringtokenizer input input = new StringTokenizer(in.readLine()); } private static int nextInt() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Integer.parseInt(input.nextToken()); } private static long nextLong() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Long.parseLong(input.nextToken()); } private static double nextDouble() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Double.parseDouble(input.nextToken()); } private static String nextString() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return input.nextToken(); } private static void write(String output){ out.write(output); out.flush(); } private static void writeln(String output){ out.write(output+"\n"); out.flush(); } private static void end() throws IOException{ in.close(); out.close(); System.exit(0); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
2e963c617f7390ca4c7a2b75d1c7d478
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class C109P3 { private static BufferedReader in; private static PrintWriter out; private static StringTokenizer input; public static void main(String[] args) throws IOException { //------------------------------------------------------------------------- //Initializing... new C109P3(); //------------------------------------------------------------------------- //put your code here... :) char[] s = nextString().toCharArray(); int k = nextInt(); int c = 0; while(k-->0){ char [] l = nextString().toCharArray(); for (int i = 0; i < s.length; i++) { if(s[i]!=l[0]&&s[i]!=l[1])continue; int o1=0;int o2=0; while(i+o1+o2<s.length){ if(s[i+o1+o2]==l[0])o1++; else if(s[i+o1+o2]==l[1])o2++; else break; } c+=Math.min(o1, o2); i+=o1+o2; } } writeln(""+c); //------------------------------------------------------------------------- //closing up end(); //-------------------------------------------------------------------------- } static boolean [][] adj; public static int error(String s,int ss){ for (int i = ss; i < s.length()-1; i++) { if(adj[s.charAt(i)-'a'][s.charAt(i+1)-'a'])return i; } return -1; } public static int rights(String s,int i){ int c = 0; for (int j = i; j < s.length(); j++) { if(s.charAt(i)==s.charAt(j))c++; } return c; } public static int lefts(String s,int i){ int c = 0; for (int j = i; j >= 0; j--) { if(s.charAt(i)==s.charAt(j))c++; } return c; } public C109P3() throws IOException { //Input Output for Console to be used for trying the test samples of the problem in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); //------------------------------------------------------------------------- //Initalize Stringtokenizer input input = new StringTokenizer(in.readLine()); } private static int nextInt() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Integer.parseInt(input.nextToken()); } private static long nextLong() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Long.parseLong(input.nextToken()); } private static double nextDouble() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Double.parseDouble(input.nextToken()); } private static String nextString() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return input.nextToken(); } private static void write(String output){ out.write(output); out.flush(); } private static void writeln(String output){ out.write(output+"\n"); out.flush(); } private static void end() throws IOException{ in.close(); out.close(); System.exit(0); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
fe50d06006fc074df623b8b411178d28
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.*; public class c154A { private final Scanner sc; private static final boolean debug = true; static void debug(Object ... objects) { if(debug) System.err.println(Arrays.toString(objects)); } c154A() { sc = new Scanner(System.in); } public static void main(String [] args) { (new c154A()).solve(); } boolean [][] forbidden; void solve() { String s = sc.next(); int n= sc.nextInt(); forbidden = new boolean[26][26]; for(int i=0;i<n;i++) { String fnPair = sc.next(); int x = fnPair.charAt(0) - 'a', y = fnPair.charAt(1) - 'a'; forbidden[x][y] = true; forbidden[y][x] = true; } int [][] dp = new int[2][26]; dp[0][s.charAt(0)-'a'] = 1; for(int i=1;i<s.length();i++) { int curr=i%2; int prev = (curr+1)%2; int ch = s.charAt(i) - 'a'; for(int j=0;j<26;j++) { dp[curr][j] = Math.max(dp[curr][j],dp[prev][j]); if(!forbidden[ch][j]) dp[curr][ch] = Math.max(dp[curr][ch], dp[prev][j]+1); } } int maxLen = 0; for(int i=0;i<26;i++) maxLen = Math.max(maxLen,dp[(s.length()-1)%2][i]); System.out.println(s.length()-maxLen); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
fdc6954b26ada96a0fc2d0bf71889b71
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.io.*; public class A { public static void p(Object ...args) {System.out.println(Arrays.toString(args));} public static void main(String[] args) { Scanner in = new Scanner(System.in); String S = in.next(); int N = S.length(); int[] C = new int[N]; for(int i = 0; i < N;i++) C[i] = S.charAt(i)-'a'; int K = in.nextInt(); int[] pair = new int[26]; Arrays.fill(pair, -1); for(int i = 0; i < K;i++) { String s = in.next(); pair[s.charAt(0)-'a'] = s.charAt(1)-'a'; pair[s.charAt(1)-'a'] = s.charAt(0)-'a'; } int ans = 0; int count0 = 0, count1 = 0; int prev0 = -1, prev1 = -1; for (int i = 0; i < N;i++) { if (C[i] == prev0) count0++; else if(C[i] == prev1) count1++; else { ans += min(count0, count1); count0 = 1; count1 = 0; prev0 = C[i]; prev1 = pair[C[i]]; } } ans += min(count0, count1); System.out.println(ans); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
5f1a453d5938bcb89c0fd8ccd3aeab70
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.*; import java.util.*; public class A implements Runnable { private MyScanner in; private PrintWriter out; private void solve() { char[] s = in.next().toCharArray(); int k = in.nextInt(); HashSet<Integer> hashes = new HashSet<Integer>(); final int MUL = 239; for (int i = 0; i < k; ++i) { char[] t = in.next().toCharArray(); hashes.add((t[0] - 'a') * MUL + (t[1] - 'a')); hashes.add((t[1] - 'a') * MUL + (t[0] - 'a')); } int n = s.length; int[][] min = new int[26][n + 1]; for (int i = 0; i < 26; ++i) { Arrays.fill(min[i], Integer.MAX_VALUE); min[i][0] = 0; } for (int i = 0; i < n; ++i) { for (int j = 0; j < 26; ++j) { if (min[j][i] == Integer.MAX_VALUE) { continue; } boolean cont = hashes.contains(MUL * j + (s[i] - 'a')) || hashes.contains(MUL * (s[i] - 'a') + j); min[j][i + 1] = Math.min(min[j][i + 1], min[j][i] + 1); if (!cont) { min[s[i] - 'a'][i + 1] = Math.min(min[s[i] - 'a'][i + 1], min[j][i]); } } } int ans = Integer.MAX_VALUE; for (int i = 0; i < 26; ++i) { ans = Math.min(ans, min[i][n]); } out.println(ans); } @Override public void run() { in = new MyScanner(); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } public static void main(String[] args) { new A().run(); } static class MyScanner { private BufferedReader br; private StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); return null; } } return st.nextToken(); } public String nextLine() { try { st = null; return br.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public boolean hasNext() { if (st != null && st.hasMoreTokens()) { return true; } try { while (br.ready()) { st = new StringTokenizer(br.readLine()); if (st != null && st.hasMoreTokens()) { return true; } } } catch (IOException e) { e.printStackTrace(); } return false; } } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
b84128157931aae69eae795e0653e582
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.util.*; public class cf154a { public static void main(String[] args) { Scanner in = new Scanner(System.in); char[] v = in.next().trim().toCharArray(); int n = in.nextInt(); boolean[][] g = new boolean[26][26]; for(int i=0; i<n; i++) { String s = in.next().trim(); int a = s.charAt(0)-'a'; int b = s.charAt(1)-'a'; g[a][b] = g[b][a] = true; } int ret = 0; int last = 0; while(last < v.length) { int color1 = v[last]-'a'; int color2 = -1; int freq1 = 1; int freq2 = 0; last++; while(last < v.length) { if(v[last]-'a' == color1) freq1++; else if(v[last]-'a' == color2) freq2++; else if(color2 == -1 && g[color1][v[last]-'a']) { color2 = v[last]-'a'; freq2 = 1; } else break; last++; } ret += Math.min(freq1,freq2); } System.out.println(ret); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
6e361ac56ab57341f72d8032b82ddc37
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * Created by IntelliJ IDEA. * User: aircube */ public class taskA { BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public static void main(String[] args) throws IOException { new taskA().run(); } private void run() throws IOException { tokenizer = null; reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); solve(); writer.flush(); } boolean bad[][]; private void solve() throws IOException { char[]s = nextToken().toCharArray(); int k = nextInt(); bad = new boolean[256][256]; for (int i =0; i < k; ++i) { String tmp = nextToken(); char a = tmp.charAt(0); char b = tmp.charAt(1); bad[a][b] = bad[b][a] = true; } int n = s.length; int[][] d = new int[n + 1][27]; final int INF = Integer.MAX_VALUE / 2; for (int[] dd : d) Arrays.fill(dd, INF); d[0][26] = 0; for (int i = 0; i < n; ++i) { char x = s[i]; for (int j = 0; j < 27; ++j) { int dd = d[i][j]; if (dd >= INF) continue; d[i + 1][j] = Math.min(d[i + 1][j], dd + 1); if (!bad[j + 'a'][x]) { d[i + 1][x - 'a'] = Math.min(d[i + 1][x - 'a'], dd); } } } int ans = INF; for (int j=0;j<27; ++j) ans = Math.min(ans, d[n][j]); writer.print(ans); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } Long nextLong() throws IOException { return Long.parseLong(nextToken()); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
3ac5c46ff1f2de89dde90e0334a7460d
train_000.jsonl
1330095600
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Main { static char[] input; static int[] states; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); String input=in.readLine(); int n=Integer.parseInt(in.readLine()); char[] rules=new char[256]; for(int i=0; i<n; i++){ String cur=in.readLine(); rules[cur.charAt(0)]=cur.charAt(1); rules[cur.charAt(1)]=cur.charAt(0); } boolean[] check=new boolean[input.length()]; int count=0; for(int i=0; i<input.length()-1; i++){ int j=0; char first=input.charAt(i); int countF=1; int countS=0; while(i+1<input.length() && (rules[input.charAt(i)]==input.charAt(i+1) || input.charAt(i)==input.charAt(i+1))){ if (input.charAt(i+1)==first){ countF++; } else{ countS++; } i++; } if(countS+countF>1)count+=Math.min(countS,countF); } out.print(count); out.close(); } }
Java
["ababa\n1\nab", "codeforces\n2\ndo\ncs"]
2 seconds
["2", "1"]
NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Java 6
standard input
[ "greedy" ]
da2b3450a3ca05a60ea4de6bab9291e9
The first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
1,600
Print the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
standard output
PASSED
6f09f5e5cdea2200fee84dd042ebcdf3
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Vector; import java.util.InputMismatchException; import java.io.IOException; import java.util.Stack; 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); DImbalancedArray solver = new DImbalancedArray(); solver.solve(1, in, out); out.close(); } static class DImbalancedArray { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); Stack<Node> min = new Stack<>(); Stack<Node> max = new Stack<>(); int[] minBef = new int[n]; int[] maxBef = new int[n]; int[] minFront = new int[n]; int[] maxFront = new int[n]; int[] last_seen = new int[(int) 1e6]; Arrays.fill(last_seen, -1); for (int i = 0; i < n; i++) { while (!max.isEmpty() && max.peek().val < a[i]) { max.pop(); } if (max.isEmpty()) maxBef[i] = i + 1; else maxBef[i] = i - max.peek().idx; max.push(new Node(a[i], i)); while (!min.isEmpty() && min.peek().val > a[i]) { min.pop(); } if (min.isEmpty()) minBef[i] = i + 1; else minBef[i] = i - min.peek().idx; min.push(new Node(a[i], i)); } max = new Stack<>(); min = new Stack<>(); for (int i = n - 1; i >= 0; i--) { while (!max.isEmpty() && max.peek().val <= a[i]) { max.pop(); } if (max.isEmpty()) maxFront[i] = n - i; else maxFront[i] = max.peek().idx - i; max.push(new Node(a[i], i)); while (!min.isEmpty() && min.peek().val >= a[i]) { min.pop(); } if (min.isEmpty()) minFront[i] = n - i; else minFront[i] = min.peek().idx - i; min.push(new Node(a[i], i)); } long ans = 0; for (int i = 0; i < n; i++) { // out.println(minBef[i] + " " + maxBef[i]); // out.println(minFront[i] + " " + maxFront[i]); ans += ((long) maxBef[i] * maxFront[i]) * (a[i]); ans -= ((long) minBef[i] * minFront[i]) * (a[i]); // out.println(ans); } out.println(ans); } class Node { int val; int idx; Node(int v, int idx) { val = v; this.idx = idx; } } } 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; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] nextIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = nextInt(); return array; } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
72dd9342e6c7e62eed73d3f13847575e
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { RangeQueryMin min; RangeQueryMax max; int[] a; long lowRes = 0; long highRes = 0; void low(int left, int right) { if (left > right) return; if (left == right) { lowRes += a[left]; return; } int minIndex = min.queryIndex(left, right); int toLeft = minIndex - left + 1; int toRight = right - minIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[minIndex]; lowRes += res; low(left, minIndex - 1); low(minIndex + 1, right); } void high(int left, int right) { if (left > right) return; if (left == right) { highRes += a[left]; return; } int maxIndex = max.queryIndex(left, right); int toLeft = maxIndex - left + 1; int toRight = right - maxIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[maxIndex]; highRes += res; high(left, maxIndex - 1); high(maxIndex + 1, right); } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); a = IOUtils.readIntArray(in, n); min = new RangeQueryMin(a); low(0, a.length - 1); int[] blahblah = new int[10 * 1000 * 1000]; for (int i = 1; i < blahblah.length; i++) { blahblah[i] = i * i; } // min = null; max = new RangeQueryMax(a); high(0, a.length - 1); out.printLine(highRes - lowRes - blahblah[2] + 4); } public class RangeQueryMin { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left <= right; } public RangeQueryMin(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } public class RangeQueryMax { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left >= right; } public RangeQueryMax(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
379c3a4606468449a02d495340257acf
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { RangeQueryMin min; RangeQueryMax max; int[] a; long lowRes = 0; long highRes = 0; void low(int left, int right) { if (left > right) return; if (left == right) { lowRes += a[left]; return; } int minIndex = min.queryIndex(left, right); int toLeft = minIndex - left + 1; int toRight = right - minIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[minIndex]; lowRes += res; low(left, minIndex - 1); low(minIndex + 1, right); } void high(int left, int right) { if (left > right) return; if (left == right) { highRes += a[left]; return; } int maxIndex = max.queryIndex(left, right); int toLeft = maxIndex - left + 1; int toRight = right - maxIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[maxIndex]; highRes += res; high(left, maxIndex - 1); high(maxIndex + 1, right); } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); a = IOUtils.readIntArray(in, n); min = new RangeQueryMin(a); low(0, a.length - 1); max = new RangeQueryMax(a); high(0, a.length - 1); out.printLine(highRes - lowRes); } public class RangeQueryMin { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left <= right; } public RangeQueryMin(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } public class RangeQueryMax { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left >= right; } public RangeQueryMax(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
f59bd43cfa86119392ef7eb974d8b008
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { RangeQueryMin min; RangeQueryMax max; int[] a; long lowRes = 0; long highRes = 0; void low(int left, int right) { if (left > right) return; if (left == right) { lowRes += a[left]; return; } int minIndex = min.queryIndex(left, right); int toLeft = minIndex - left + 1; int toRight = right - minIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[minIndex]; lowRes += res; low(left, minIndex - 1); low(minIndex + 1, right); } void high(int left, int right) { if (left > right) return; if (left == right) { highRes += a[left]; return; } int maxIndex = max.queryIndex(left, right); int toLeft = maxIndex - left + 1; int toRight = right - maxIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[maxIndex]; highRes += res; high(left, maxIndex - 1); high(maxIndex + 1, right); } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); a = IOUtils.readIntArray(in, n); min = new RangeQueryMin(a); low(0, a.length - 1); min = null; max = new RangeQueryMax(a); high(0, a.length - 1); out.printLine(highRes - lowRes); } public class RangeQueryMin { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left <= right; } public RangeQueryMin(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } public class RangeQueryMax { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left >= right; } public RangeQueryMax(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
13f55ba3751984b5022d6693b0536667
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { RangeQueryMin min; RangeQueryMax max; int[] a; long lowRes = 0; long highRes = 0; void low(int left, int right) { if (left > right) return; if (left == right) { lowRes += a[left]; return; } int minIndex = min.queryIndex(left, right); int toLeft = minIndex - left + 1; int toRight = right - minIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[minIndex]; lowRes += res; low(left, minIndex - 1); low(minIndex + 1, right); } void high(int left, int right) { if (left > right) return; if (left == right) { highRes += a[left]; return; } int maxIndex = max.queryIndex(left, right); int toLeft = maxIndex - left + 1; int toRight = right - maxIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[maxIndex]; highRes += res; high(left, maxIndex - 1); high(maxIndex + 1, right); } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); a = IOUtils.readIntArray(in, n); min = new RangeQueryMin(a); low(0, a.length - 1); int[] blahblah = new int[10 * 1000 * 1000]; for (int i = 1; i < blahblah.length; i++) { blahblah[i] = i * i; } min = null; max = new RangeQueryMax(a); high(0, a.length - 1); out.printLine(highRes - lowRes - blahblah[2] + 4); } public class RangeQueryMin { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left <= right; } public RangeQueryMin(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } public class RangeQueryMax { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left >= right; } public RangeQueryMax(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
da1969428240a5906713a93bdef95e17
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { RangeQueryMin min; RangeQueryMax max; int[] a; long lowRes = 0; long highRes = 0; void low(int left, int right) { if (left > right) return; if (left == right) { lowRes += a[left]; return; } int minIndex = min.queryIndex(left, right); int toLeft = minIndex - left + 1; int toRight = right - minIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[minIndex]; lowRes += res; low(left, minIndex - 1); low(minIndex + 1, right); } void high(int left, int right) { if (left > right) return; if (left == right) { highRes += a[left]; return; } int maxIndex = max.queryIndex(left, right); int toLeft = maxIndex - left + 1; int toRight = right - maxIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[maxIndex]; highRes += res; high(left, maxIndex - 1); high(maxIndex + 1, right); } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); a = IOUtils.readIntArray(in, n); min = new RangeQueryMin(a); low(0, a.length - 1); int[] blahblah = new int[5 * 1000 * 1000]; for (int i = 1; i < blahblah.length; i++) { blahblah[i] = i * i; } // min = null; max = new RangeQueryMax(a); high(0, a.length - 1); out.printLine(highRes - lowRes - blahblah[2] + 4); } public class RangeQueryMin { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left <= right; } public RangeQueryMin(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } public class RangeQueryMax { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left >= right; } public RangeQueryMax(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
ecef03d06fd7e880ccad9e42e986934e
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { RangeQueryMin min; RangeQueryMax max; int[] a; long lowRes = 0; long highRes = 0; void low(int left, int right) { if (left > right) return; if (left == right) { lowRes += a[left]; return; } int minIndex = min.queryIndex(left, right); int toLeft = minIndex - left + 1; int toRight = right - minIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[minIndex]; lowRes += res; low(left, minIndex - 1); low(minIndex + 1, right); } void high(int left, int right) { if (left > right) return; if (left == right) { highRes += a[left]; return; } int maxIndex = max.queryIndex(left, right); int toLeft = maxIndex - left + 1; int toRight = right - maxIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[maxIndex]; highRes += res; high(left, maxIndex - 1); high(maxIndex + 1, right); } public void solve(int testNumber, InputReader in, OutputWriter out) { a = IOUtils.readIntArray(in, in.readInt()); min = new RangeQueryMin(a); low(0, a.length - 1); max = new RangeQueryMax(a); high(0, a.length - 1); out.printLine(highRes - lowRes); } public class RangeQueryMin { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left <= right; } public RangeQueryMin(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } public class RangeQueryMax { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left >= right; } public RangeQueryMax(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
5e9a78704ceff50e0914bc679a40ed59
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = IOUtils.readIntArray(in, n); long res = 0; RangeDominationLow low = new RangeDominationLow(a); for (int i = 0; i < n; i++) { long toLeft = i - low.closestToLeft(i); long toRight = low.closestToRight(i) - i; long temp = toLeft * toRight * a[i]; res -= temp; } RangeDominationHigh high = new RangeDominationHigh(a); for (int i = 0; i < n; i++) { long toLeft = i - high.closestToLeft(i); long toRight = high.closestToRight(i) - i; long temp = toLeft * toRight * a[i]; res += temp; } out.printLine(res); } class RangeDominationLow { int[] closestToLeft; int[] closestToRight; public RangeDominationLow(int[] a) { closestToLeft = new int[a.length]; closestToRight = new int[a.length]; int[] ll = new int[a.length]; int size = 0; for (int i = 0; i < a.length; i++) { while (size > 0 && a[i] <= a[ll[size - 1]]) size--; closestToLeft[i] = size == 0 ? -1 : ll[size - 1]; ll[size++] = i; } size = 0; for (int i = a.length - 1; i >= 0; i--) { while (size > 0 && a[i] < a[ll[size - 1]]) size--; closestToRight[i] = size == 0 ? a.length : ll[size - 1]; ll[size++] = i; } } int closestToLeft(int idx) { // returns -1 if no index violates cmp return closestToLeft[idx]; } int closestToRight(int idx) { // returns n if no index violates cmp return closestToRight[idx]; } } class RangeDominationHigh { int[] closestToLeft; int[] closestToRight; public RangeDominationHigh(int[] a) { closestToLeft = new int[a.length]; closestToRight = new int[a.length]; int[] ll = new int[a.length]; int size = 0; for (int i = 0; i < a.length; i++) { while (size > 0 && a[i] >= a[ll[size - 1]]) size--; closestToLeft[i] = size == 0 ? -1 : ll[size - 1]; ll[size++] = i; } size = 0; for (int i = a.length - 1; i >= 0; i--) { while (size > 0 && a[i] > a[ll[size - 1]]) size--; closestToRight[i] = size == 0 ? a.length : ll[size - 1]; ll[size++] = i; } } int closestToLeft(int idx) { // returns -1 if no index violates cmp return closestToLeft[idx]; } int closestToRight(int idx) { // returns n if no index violates cmp return closestToRight[idx]; } } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
7ee93811c22dedaffa10e2f937ab7d64
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { RangeQueryMin min; RangeQueryMax max; int[] a; long lowRes = 0; long highRes = 0; void low(int left, int right) { if (left > right) return; if (left == right) { lowRes += a[left]; return; } int minIndex = min.queryIndex(left, right); int toLeft = minIndex - left + 1; int toRight = right - minIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[minIndex]; lowRes += res; low(left, minIndex - 1); low(minIndex + 1, right); } void high(int left, int right) { if (left > right) return; if (left == right) { highRes += a[left]; return; } int maxIndex = max.queryIndex(left, right); int toLeft = maxIndex - left + 1; int toRight = right - maxIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[maxIndex]; highRes += res; high(left, maxIndex - 1); high(maxIndex + 1, right); } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); a = IOUtils.readIntArray(in, n); min = new RangeQueryMin(a); low(0, a.length - 1); int[] blahblah = new int[5 * 1000 * 1000]; for (int i = 1; i < blahblah.length; i++) { blahblah[i] = i * i; } max = new RangeQueryMax(a); high(0, a.length - 1); out.printLine(highRes - lowRes); } public class RangeQueryMin { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left <= right; } public RangeQueryMin(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } public class RangeQueryMax { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left >= right; } public RangeQueryMax(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
7670688a6b5d70d240cfb6d475d7ad99
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { RangeQueryMin min; RangeQueryMax max; int[] a; long lowRes = 0; long highRes = 0; void low(int left, int right) { if (left > right) return; if (left == right) { lowRes += a[left]; return; } int minIndex = min.queryIndex(left, right); int toLeft = minIndex - left + 1; int toRight = right - minIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[minIndex]; lowRes += res; low(left, minIndex - 1); low(minIndex + 1, right); } void high(int left, int right) { if (left > right) return; if (left == right) { highRes += a[left]; return; } int maxIndex = max.queryIndex(left, right); int toLeft = maxIndex - left + 1; int toRight = right - maxIndex + 1; long ways = (long) toLeft * toRight; long res = ways * a[maxIndex]; highRes += res; high(left, maxIndex - 1); high(maxIndex + 1, right); } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); a = IOUtils.readIntArray(in, n); min = new RangeQueryMin(a); low(0, a.length - 1); int[] blahblah = new int[5 * 1000 * 1000]; for (int i = 1; i < blahblah.length; i++) { blahblah[i] = i * i; } min = null; max = new RangeQueryMax(a); high(0, a.length - 1); out.printLine(highRes - lowRes); } public class RangeQueryMin { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left <= right; } public RangeQueryMin(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } public class RangeQueryMax { int[] a; int[][] indices; boolean leftBetter(int left, int right) { // returns if the left value is better than or equal to the right value return left >= right; } public RangeQueryMax(int[] a) { this.a = a; int m = a.length; int layers = 0; while ((1 << layers) <= m) ++layers; indices = new int[layers][]; indices[0] = new int[m]; for (int i = 0; i < m; i++) indices[0][i] = i; for (int layer = 1; layer < layers; layer++) { indices[layer] = new int[m - (1 << layer) + 1]; for (int j = 0; j < indices[layer].length; j++) { if (leftBetter(a[indices[layer - 1][j]], a[indices[layer - 1][j + (1 << (layer - 1))]])) { indices[layer][j] = indices[layer - 1][j]; } else { indices[layer][j] = indices[layer - 1][j + (1 << (layer - 1))]; } } } } public int queryIndex(int left, int right) { // left and right inclusive int layer = Integer.numberOfTrailingZeros(Integer.highestOneBit(right - left + 1)); if (leftBetter(a[indices[layer][left]], a[indices[layer][right - (1 << layer) + 1]])) { return indices[layer][left]; } else { return indices[layer][right - (1 << layer) + 1]; } } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
644df49d1e5bfa4eb72d20ddcc87fde5
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
/** * Date: 29 Sep, 2019 * Link: * * @author Prasad Chaudhari * @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/ * @git: https://github.com/Prasad-Chaudhari */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Stack; public class newProgram1 { public static void main(String[] args) throws IOException { // TODO code application logic here FastIO in = new FastIO(); int n = in.ni(); int a[] = in.gia(n); Stack<Integer> st = new Stack<Integer>(); Stack<Long> st2 = new Stack<>(); long maxs = 0; long sum = 0; for (int i = 0; i < n; i++) { while (!st.isEmpty() && a[st.peek()] <= a[i]) { st.pop(); sum -= st2.pop(); } if (st.isEmpty()) { st.push(i); st2.push(1l * a[i] * (i + 1)); sum += 1l * a[i] * (i + 1); maxs += sum; } else { st2.push(1l * a[i] * (i - st.peek())); st.push(i); sum += st2.peek(); maxs += sum; } } long mins = 0; sum = 0; while (!st.isEmpty()) { st.pop(); st2.pop(); } for (int i = 0; i < n; i++) { while (!st.isEmpty() && a[st.peek()] >= a[i]) { st.pop(); sum -= st2.pop(); } if (st.isEmpty()) { st.push(i); st2.push(1l * a[i] * (i + 1)); sum += 1l * a[i] * (i + 1); mins += sum; } else { st2.push(1l * a[i] * (i - st.peek())); st.push(i); sum += st2.peek(); mins += sum; } } System.out.println(maxs - mins); in.bw.flush(); } static class Data implements Comparable<Data> { int a, b; public Data(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Data o) { if (a == o.a) { return Integer.compare(b, o.b); } return Integer.compare(a, o.a); } public static void sort(int a[]) { Data d[] = new Data[a.length]; for (int i = 0; i < a.length; i++) { d[i] = new Data(a[i], 0); } Arrays.sort(d); for (int i = 0; i < a.length; i++) { a[i] = d[i].a; } } } static class FastIO { private final BufferedReader br; private final BufferedWriter bw; private String s[]; private int index; public FastIO() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8")); s = br.readLine().split(" "); index = 0; } public int ni() throws IOException { return Integer.parseInt(nextToken()); } public double nd() throws IOException { return Double.parseDouble(nextToken()); } public long nl() throws IOException { return Long.parseLong(nextToken()); } public String next() throws IOException { return nextToken(); } public String nli() throws IOException { try { return br.readLine(); } catch (IOException ex) { } return null; } public int[] gia(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public int[] gia(int n, int start, int end) throws IOException { validate(n, start, end); int a[] = new int[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } public double[] gda(int n) throws IOException { double a[] = new double[n]; for (int i = 0; i < n; i++) { a[i] = nd(); } return a; } public double[] gda(int n, int start, int end) throws IOException { validate(n, start, end); double a[] = new double[n]; for (int i = start; i < end; i++) { a[i] = nd(); } return a; } public long[] gla(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nl(); } return a; } public long[] gla(int n, int start, int end) throws IOException { validate(n, start, end); long a[] = new long[n]; for (int i = start; i < end; i++) { a[i] = nl(); } return a; } public int[][][] gwtree(int n) throws IOException { int m = n - 1; int adja[][] = new int[n + 1][]; int weight[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; int cost[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = i + 1; to[i] = ni(); cost[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; weight[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][count[from[i]] - 1] = to[i]; adja[to[i]][count[to[i]] - 1] = from[i]; weight[from[i]][count[from[i]] - 1] = cost[i]; weight[to[i]][count[to[i]] - 1] = cost[i]; count[from[i]]--; count[to[i]]--; } return new int[][][] { adja, weight }; } public int[][][] gwg(int n, int m) throws IOException { int adja[][] = new int[n + 1][]; int weight[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; int cost[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = ni(); to[i] = ni(); cost[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; weight[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][count[from[i]] - 1] = to[i]; adja[to[i]][count[to[i]] - 1] = from[i]; weight[from[i]][count[from[i]] - 1] = cost[i]; weight[to[i]][count[to[i]] - 1] = cost[i]; count[from[i]]--; count[to[i]]--; } return new int[][][] { adja, weight }; } public int[][] gtree(int n) throws IOException { int adja[][] = new int[n + 1][]; int from[] = new int[n - 1]; int to[] = new int[n - 1]; int count[] = new int[n + 1]; for (int i = 0; i < n - 1; i++) { from[i] = i + 1; to[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; } for (int i = 0; i < n - 1; i++) { adja[from[i]][--count[from[i]]] = to[i]; adja[to[i]][--count[to[i]]] = from[i]; } return adja; } public int[][] gg(int n, int m) throws IOException { int adja[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = ni(); to[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][--count[from[i]]] = to[i]; adja[to[i]][--count[to[i]]] = from[i]; } return adja; } public void print(String s) throws IOException { bw.write(s); } public void println(String s) throws IOException { bw.write(s); bw.newLine(); } public void print(int s) throws IOException { bw.write(s + ""); } public void println(int s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(long s) throws IOException { bw.write(s + ""); } public void println(long s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(double s) throws IOException { bw.write(s + ""); } public void println(double s) throws IOException { bw.write(s + ""); bw.newLine(); } private String nextToken() throws IndexOutOfBoundsException, IOException { if (index == s.length) { s = br.readLine().split(" "); index = 0; } return s[index++]; } private void validate(int n, int start, int end) { if (start < 0 || end >= n) { throw new IllegalArgumentException(); } } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
cb8d33131b3c021dec86d547c3127cf2
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.io.*; import java.util.*; /** * * @author Jishnu_T */ public class ImbalancedArray { private static long maxSum(int n,int[] ar) { long maxSum = 0; Stack<Integer> s= new Stack<>(); for(int i=0;i<=n;i++) { if(i==0 || (i!=n && ar[i]<=ar[s.peek()])) s.push(i); else { int key = i==n?Integer.MAX_VALUE:ar[i]; int j=s.peek(); //int jprev = -1; while(ar[s.peek()]<key) { j=s.pop(); maxSum = maxSum+(long)(i-j)*ar[j]; int jprev = s.isEmpty()?-1:s.peek(); //if((s.isEmpty() && j) && jprev != j+1 ) //{ maxSum = maxSum+ (long)(j-jprev-1)*(i-j-1)*ar[j]; //} if(s.isEmpty()) break; } if(i!=n) { if(!s.isEmpty()) maxSum = maxSum + (long)(i-(s.peek()+1))*key; else maxSum = maxSum + (long)i*key; s.push(i); } } } return maxSum; } private static long imbalanceValue(int n, int[] ar, int[] arNeg) { return (maxSum(n,ar)+maxSum(n,arNeg)); } private 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[]) { FastReader r = new FastReader(); int n = r.nextInt(); int[] ar = new int[n]; int[] arNeg = new int[n]; for(int i=0;i<n;i++) { ar[i] = r.nextInt(); arNeg[i] = -ar[i]; } System.out.println(imbalanceValue(n,ar,arNeg)); } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
cb8fd9919a9e1df38e95e1b775d018f1
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class CF817D_fast_scanner { public static void main (String[] args) throws java.lang.Exception { FastScanner in = new FastScanner(System.in); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(); Node [] arr = new Node[n]; for(int i = 1; i <= n; i++){ arr[i-1] = new Node(in.nextInt(), i); } Arrays.sort(arr); MultiSet set = new MultiSet((1<<20) - 1); long min = 0, max = 0; set.add(0); set.add(n+1); for(int i = 0; i < n; i++){ int x = set.lower(arr[i].b), y = set.higher(arr[i].b); long p = Math.abs(x - arr[i].b), q = Math.abs(y - arr[i].b); min += (long)arr[i].a * (p*q); set.add(arr[i].b); } Arrays.fill(set.bit, 0); set.add(0); set.add(n+1); for(int i = n-1; i >= 0; i--){ int x = set.lower(arr[i].b), y = set.higher(arr[i].b); long p = Math.abs(x - arr[i].b), q = Math.abs(y - arr[i].b); max += (long)arr[i].a * (p*q); set.add(arr[i].b); } pw.println(max - min); pw.close(); } static class MultiSet { //MultiSet using BIT int bit[], n; int offset = 5; MultiSet(int nn){ n = nn; bit = new int[n+1]; } public int lower(int x){ int s = sum(x-1); return get(s); } public int higher(int x){ int s = sum(x); return get(s+1); } public void add(int x){ add(x+offset, 1); } public void remove(int x){ add(x+offset, -1); } void add(int index, int value){ for(; index < n;index = index + ( index & -index)){ bit[index] += value; } } int sum(int index){ index += offset; int sum = 0; for(; index > 0;index = index - (index & -index)){ sum += bit[index]; } return sum; } // Returns min(p, sum[0,p]>=sum) int lower_bound(int sum) { --sum; int pos = -1; for (int blockSize = Integer.highestOneBit(n); blockSize != 0; blockSize >>= 1) { int nextPos = pos + blockSize; if (nextPos < n && sum >= bit[nextPos]) { sum -= bit[nextPos]; pos = nextPos; } } return pos + 1; } int get(int k) { // P must be the maximum power of 2, such that 2^x <= bit.length// --k; int p = Integer.highestOneBit(bit.length - 1); for (int q = p; q > 0; q >>= 1, p |= q) { if (p >= n || k < bit[p]) p ^= q; else k -= bit[p]; } return p+1-offset; } } static class Node implements Comparable<Node>{ int a, b; Node (int x, int y){ a = x; b = y; } public int compareTo(Node n){ return a - n.a; } } static class FastScanner { static final int DEFAULT_BUFF = 1024, EOF = -1, INT_MIN = 48, INT_MAX = 57; static final byte NEG = 45; static final int[] ints = new int[58]; static { int value = 0; for (int i = 48; i < 58; i++) { ints[i] = value++; } } InputStream stream; byte[] buff; int buffPtr; public FastScanner(InputStream stream) { this.stream = stream; this.buff = new byte[DEFAULT_BUFF]; this.buffPtr = -1; } public int nextInt() throws IOException { int val = 0; int sign = readNonDigits(); while (isDigit(buff[buffPtr]) && buff[buffPtr] != EOF) { val = (val << 3) + (val << 1) + ints[buff[buffPtr]]; buffPtr++; if (buffPtr == buff.length) { updateBuff(); } } return val*sign; } private int readNonDigits() throws IOException { if (buffPtr == -1 || buffPtr == buff.length) { updateBuff(); } if (buff[buffPtr] == EOF) { throw new IOException("End of stream reached"); } int signByte = -1; while (!isDigit(buff[buffPtr])) { signByte = buff[buffPtr]; buffPtr++; if (buffPtr >= buff.length) { updateBuff(); } if (buff[buffPtr] == EOF) { throw new IOException("End of stream reached"); } } if(signByte == NEG) return -1; return 1; } public void close() throws IOException { stream.close(); } private boolean isDigit(int b) { return b >= INT_MIN && b <= INT_MAX; } private void updateBuff() throws IOException { buffPtr = 0; stream.read(buff); } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
7188c651cdd3943bf36410ae882b27fa
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.util.*; import java.io.*; public class CF817D_2{ public static int index; public static void main(String[] args)throws Exception { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(); Node [] arr = new Node[n]; for(int i = 1; i <= n; i++){ arr[i-1] = new Node(in.nextInt(), i); } Arrays.sort(arr); MultiSet set = new MultiSet((1<<20) - 1); long min = 0, max = 0; set.add(0); set.add(n+1); for(int i = 0; i < n; i++){ int x = set.lower(arr[i].b), y = set.higher(arr[i].b); long p = Math.abs(x - arr[i].b), q = Math.abs(y - arr[i].b); min += (long)arr[i].a * (p*q); set.add(arr[i].b); } Arrays.fill(set.bit, 0); set.add(0); set.add(n+1); for(int i = n-1; i >= 0; i--){ int x = set.lower(arr[i].b), y = set.higher(arr[i].b); long p = Math.abs(x - arr[i].b), q = Math.abs(y - arr[i].b); max += (long)arr[i].a * (p*q); set.add(arr[i].b); } pw.println(max - min); pw.close(); } static class MultiSet { //MultiSet using BIT int bit[], n; int offset = 5; MultiSet(int nn){ n = nn; bit = new int[n+1]; } public int lower(int x){ int s = sum(x-1); return get(s); } public int higher(int x){ int s = sum(x); return get(s+1); } public void add(int x){ add(x+offset, 1); } public void remove(int x){ add(x+offset, -1); } void add(int index, int value){ for(; index < n;index = index + ( index & -index)){ bit[index] += value; } } int sum(int index){ index += offset; int sum = 0; for(; index > 0;index = index - (index & -index)){ sum += bit[index]; } return sum; } // Returns min(p, sum[0,p]>=k) int get(int k) { // P must be the maximum power of 2, such that 2^x <= bit.length// --k; int p = Integer.highestOneBit(bit.length - 1); for (int q = p; q > 0; q >>= 1, p |= q) { if (p >= n || k < bit[p]) p ^= q; else k -= bit[p]; } return p+1-offset; } } static class Node implements Comparable<Node>{ int a, b; Node (int x, int y){ a = x; b = y; } public int compareTo(Node n){ return a - n.a; } } static void debug(Object...obj) { System.err.println(Arrays.deepToString(obj)); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next()throws Exception { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public String nextLine()throws Exception { String line = null; tokenizer = null; line = reader.readLine(); return line; } public int nextInt()throws Exception { return Integer.parseInt(next()); } public double nextDouble() throws Exception{ return Double.parseDouble(next()); } public long nextLong()throws Exception { return Long.parseLong(next()); } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
9365aab3f79fd3a8a80d92e98715eec4
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Stack; import java.util.StringTokenizer; public class P817D { public static void main(String[] args) { FastScanner scan = new FastScanner(); int n = scan.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = scan.nextInt(); MStack minStack = new MStack(false); MStack maxStack = new MStack(true); long ans = 0; for (int i = 0; i < n; i++) { minStack.add(arr[i]); maxStack.add(arr[i]); ans += (maxStack.sum() - minStack.sum()); } System.out.println(ans); } static class MStack { Stack<Long> stack = new Stack<>(); Stack<Integer> first = new Stack<>(); //start index boolean max; long sum; int index = -1; MStack(boolean b) { max = b; } void add(long n) { int start = ++index; while (!stack.isEmpty() && needToRemove(stack.peek(), n)) { long prev = stack.pop(); sum -= prev*(start-first.peek()); start = first.pop(); } stack.add(n); first.add(start); sum += (index-start+1)*n; } private boolean needToRemove(long top, long n) { if (max) return top <= n; return top >= n; } long sum() { return sum; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { String line = ""; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
ab2e7faed4a006c3c27f80827354a1d9
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.util.*; import java.io.*; public class Task{ static long sumSubarrayMax(int[] A) { int[] ple=new int[A.length]; int[] nle=new int[A.length]; Stack<Integer>ples=new Stack<>(); Stack<Integer>nles=new Stack<>(); //for ple for(int i=0;i<A.length;i++){ while(!ples.isEmpty() && A[ples.peek()]<A[i]){ ples.pop(); } ple[i]= ples.isEmpty()? i+1:i-ples.peek(); ples.push(i); } // for nle for(int i=A.length-1;i>=0;i--){ while(!nles.isEmpty() && A[nles.peek()]<=A[i]){ nles.pop(); } nle[i]=nles.isEmpty()? A.length-i:nles.peek()-i; nles.push(i); } long res=0; for(int i=0;i<A.length;i++){ res+=(long)A[i]*nle[i]*ple[i]; } return res; } static long Mins(int[] A) { Stack<Integer> stack = new Stack<>(); int n = A.length;long res = 0; for (int i = 0; i <= n; i++) { while (!stack.isEmpty() && A[stack.peek()] > (i == n ? 0 : A[i])) { int j = stack.pop(); int k = stack.isEmpty() ? -1 : stack.peek(); res += (long)A[j] * (i - j) * (j - k); } stack.push(i); } return res; } public static void main(String[] args) throws FileNotFoundException, IOException{ Scanner s=new Scanner(System.in); BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); StringBuilder sb=new StringBuilder(); int n=s.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++){arr[i]=s.nextInt();} long res=sumSubarrayMax(arr)-Mins(arr); out.write(res+""); out.flush(); } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
22dc7faa60a8fb188db9819543513ce7
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
//import java.util.*; //import java.io.*; //import java.lang.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Scanner; import java.util.Arrays; import java.util.Stack; public class Task{ public static long gcd(long a,long b){ if(b==0){return a;} return gcd(b,a%b); } static long Mins(int[] A) { Stack<Integer> stack = new Stack<>(); long[] dp = new long[A.length + 1]; stack.push(-1); long result = 0; for (int i = 0; i < A.length; i++) { while (stack.peek() != -1 && A[i] <= A[stack.peek()]) { stack.pop(); } dp[i + 1] = dp[stack.peek() + 1] + (long)(i - stack.peek()) * A[i]; stack.push(i); result += dp[i + 1]; } return result; } static long Max(int[] A) { Stack<Integer> stack = new Stack<>(); long[] dp = new long[A.length + 1]; stack.push(-1); long result = 0; for (int i = 0; i < A.length; i++) { while (stack.peek() != -1 && A[i] >= A[stack.peek()]) { stack.pop(); } dp[i + 1] = dp[stack.peek() + 1] + (long)(i - stack.peek()) * A[i]; stack.push(i); result += dp[i + 1]; } return result; } public static void main(String[] args) throws IOException{ Scanner s=new Scanner(System.in); BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); StringBuilder sb=new StringBuilder(); int n=s.nextInt(); int[] arr=new int[n]; int[] arr1=new int[n]; for(int i=0;i<n;i++){arr[i]=s.nextInt();arr1[i]=(-1)*arr[i];} long res=(-1)*Mins(arr1)-Mins(arr); out.write(res+""); out.flush(); } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
06c28832cfcbbb76b2d5287061b53a7d
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.util.*; import java.io.*; public class Task{ static long Mins(int[] A) { Stack<Integer> stack = new Stack<>(); long[] dp = new long[A.length + 1]; stack.push(-1); long result = 0; for (int i = 0; i < A.length; i++) { while (stack.peek() != -1 && A[i] <= A[stack.peek()]) { stack.pop(); } dp[i + 1] = dp[stack.peek() + 1] + (long)(i - stack.peek()) * A[i]; stack.push(i); result += dp[i + 1]; } return result; } static long Max(int[] A) { Stack<Integer> stack = new Stack<>(); long[] dp = new long[A.length + 1]; stack.push(-1); long result = 0; for (int i = 0; i < A.length; i++) { while (stack.peek() != -1 && A[i] >= A[stack.peek()]) { stack.pop(); } dp[i + 1] = dp[stack.peek() + 1] + (long)(i - stack.peek()) * A[i]; stack.push(i); result += dp[i + 1]; } return result; } public static void main(String[] args) throws FileNotFoundException, IOException{ Scanner s=new Scanner(System.in); BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out)); StringBuilder sb=new StringBuilder(); int n=s.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++){arr[i]=s.nextInt();} long res=Max(arr)-Mins(arr); out.write(res+""); out.flush(); } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
b316001d35fe2a110de5a953db7a0da4
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
/* Author: Ronak Agarwal */ import java.io.* ; import java.util.* ; import java.math.* ; import static java.lang.Math.min ; import static java.lang.Math.max ; import static java.lang.Math.abs ; /* Thread is created here to increase the stack size of the java code so that recursive dfs can be performed */ public class Codeshefcode{ public static void main(String[] args) throws IOException{ new Thread(null,new Runnable(){ public void run(){ exec_Code() ;} },"Solver",1l<<27).start() ; } static void exec_Code(){ try{ Solver Machine = new Solver() ; Machine.Solve() ; Machine.Finish() ;} catch(Exception e){ e.printStackTrace() ; print_and_exit() ;} catch(Error e){ e.printStackTrace() ; print_and_exit() ; } } static void print_and_exit(){ System.out.flush() ; System.exit(-1) ;} } /* Implementation of the pair class, useful for every other problem */ class pair implements Comparable<pair>{ int x ; int y ; int dir ; pair(int _x,int _y,int _dir){ x=_x ; y=_y ; dir = _dir ;} public int compareTo(pair p){ return (this.x<p.x ? -1 : (this.x>p.x ? 1 : (this.y<p.y ? -1 : (this.y>p.y ? 1 : 0)))) ; } } /* Main code starts here */ class Solver extends Template{ int n ; long arr[] ; public void Solve() throws IOException{ n = ip.i() ; long arr[] = new long[n] ; for(int i=0 ; i<n ; i++) arr[i] = ip.i() ; long v1 = mnTotal(arr) ; long v2 = mxTotal(arr) ; pln(v1-v2) ; } long mnTotal(long arr[]){ long lf[] = new long[n] ; long rg[] = new long[n] ; mystack S = new mystack() ; for(int i=0 ; i<n ; i++){ while(!S.isEmpty() && arr[i]>=arr[S.peek()]) rg[S.pop()]=i ; S.push(i) ; } while(!S.isEmpty()) rg[S.pop()]=n ; for(int i=(n-1) ; i>=0 ; i--){ while(!S.isEmpty() && arr[i]>arr[S.peek()]) lf[S.pop()]=i ; S.push(i) ; } while(!S.isEmpty()) lf[S.pop()]=-1 ; long res=0 ; // for(int i=0 ; i<n ; i++) p(lf[i]+" ") ; // pln("") ; // for(int i=0 ; i<n ; i++) p(rg[i]+" ") ; // pln("") ; for(int i=0 ; i<n ; i++) res+=(((rg[i]-i)*(i-lf[i]))*arr[i]) ; return res ; } long mxTotal(long arr[]){ long lf[] = new long[n] ; long rg[] = new long[n] ; mystack S = new mystack() ; for(int i=0 ; i<n ; i++){ while(!S.isEmpty() && arr[i]<=arr[S.peek()]) rg[S.pop()]=i ; S.push(i) ; } while(!S.isEmpty()) rg[S.pop()]=n ; for(int i=(n-1) ; i>=0 ; i--){ while(!S.isEmpty() && arr[i]<arr[S.peek()]) lf[S.pop()]=i ; S.push(i) ; } while(!S.isEmpty()) lf[S.pop()]=-1 ; long res=0 ; for(int i=0 ; i<n ; i++) res+=(((rg[i]-i)*(i-lf[i]))*arr[i]) ; return res ; } } /* All the useful functions,constants,renamings are here*/ class Template{ /* Constants Section */ final int INT_MIN = Integer.MIN_VALUE ; final int INT_MAX = Integer.MAX_VALUE ; final long LONG_MIN = Long.MIN_VALUE ; final long LONG_MAX = Long.MAX_VALUE ; static long MOD = 1000000007 ; static Reader ip = new Reader(System.in) ; static PrintWriter op = new PrintWriter(System.out) ; /* Methods for writing */ static void p(Object o){ op.print(o) ; } static void pln(Object o){ op.println(o) ;} static void Finish(){ op.flush(); op.close(); } /* Implementation of operations modulo MOD */ static long inv(long a){ return powM(a,MOD-2) ; } static long m(long a,long b){ return (a*b)%MOD ; } static long d(long a,long b){ return (a*inv(b))%MOD ; } static long powM(long a,long b){ if(b<0) return powM(inv(a),-b) ; long val=a ; long ans=1 ; while(b!=0){ if((b&1)==1) ans = (ans*val)%MOD ; val = (val*val)%MOD ; b/=2 ; } return ans ; } /* Renaming of some generic utility classes */ final static class mylist extends ArrayList<Integer>{} final static class myset extends TreeSet<Long>{} final static class mystack extends Stack<Integer>{} final static class mymap extends TreeMap<Integer,mylist>{} } class Reader{ BufferedReader reader; StringTokenizer tkz; Reader(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)) ; tkz = new StringTokenizer("") ; } String s() throws IOException{ while (!tkz.hasMoreTokens()) tkz = new StringTokenizer(reader.readLine()) ; return tkz.nextToken() ; } int i() throws IOException{ return Integer.parseInt(s()) ;} long l() throws IOException{ return Long.parseLong(s()) ;} double d() throws IOException{ return Double.parseDouble(s()) ;} }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
027b9304081743f1811521f350357bcd
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
//created by Whiplash99 import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,N; N=Integer.parseInt(br.readLine().trim()); String[] s=br.readLine().trim().split(" "); int[] a=new int[N]; for(i=0;i<N;i++) a[i]=Integer.parseInt(s[i]); ArrayDeque<Integer> st1=new ArrayDeque<>(); ArrayDeque<Integer> st2=new ArrayDeque<>(); int[] prevG=new int[N]; int[] prevL=new int[N]; int[] nextGE=new int[N]; int[] nextLE=new int[N]; for(i=0;i<N;i++) { while (!st1.isEmpty()&&a[st1.peek()]<=a[i]) nextGE[st1.pop()]=i; st1.push(i); while (!st2.isEmpty()&&a[st2.peek()]>=a[i]) nextLE[st2.pop()]=i; st2.push(i); } while (!st1.isEmpty()) nextGE[st1.pop()]=N; while (!st2.isEmpty()) nextLE[st2.pop()]=N; for(i=N-1;i>=0;i--) { while (!st1.isEmpty()&&a[st1.peek()]<a[i]) prevG[st1.pop()]=i; st1.push(i); while (!st2.isEmpty()&&a[st2.peek()]>a[i]) prevL[st2.pop()]=i; st2.push(i); } while (!st1.isEmpty()) prevG[st1.pop()]=-1; while (!st2.isEmpty()) prevL[st2.pop()]=-1; long ans=0; for(i=0;i<N;i++) { long left=i-prevG[i], right=nextGE[i]-i; ans+=a[i]*left*right; left=i-prevL[i]; right=nextLE[i]-i; ans-=a[i]*left*right; } System.out.println(ans); } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
1b2d96d1911f63731b77a29906a54272
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * @author pttrung */ public class D_Edu_Round23 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); long[] data = new long[n]; for (int i = 0; i < n; i++) { data[i] = in.nextInt(); } long re = 0; int[] q = new int[n]; int st = 0; long total = 0; long[] hold = new long[n]; for (int i = 0; i < n; i++) { while (st > 0 && data[q[st - 1]] >= data[i]) { total -= hold[q[st - 1]]; st--; } int start = st > 0 ? q[st - 1] : -1; // System.out.println(start + " " + i + " " + total + " " + Arrays.toString(q) + " "+ st); hold[i] = (i - start) * data[i]; total += hold[i]; re -= total; q[st++] = i; } // out.println(re); st = 0; total = 0; //re = 0; for (int i = 0; i < n; i++) { while (st > 0 && data[q[st - 1]] <= data[i]) { total -= hold[q[st - 1]]; st--; } int start = st > 0 ? q[st - 1] : -1; hold[i] = (i - start) * data[i]; total += hold[i]; re += total; q[st++] = i; } out.println(re); // long test = 0; // for(int i = 0; i < n; i++){ // for(int j = i + 1; j < n; j++){ // int max = data[i]; // int min = data[i]; // for(int k = i ; k <= j; k++){ // min = Integer.min(data[k], min); // max = Integer.max(data[k], max); // } // test += max - min; // } // } // out.println(test); out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
c388236bad675db4c86b68bdbcf6f82b
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.util.*; import java.io.*; public class ImbalancedArray { /************************ SOLUTION STARTS HERE ************************/ static class SegmentTree { int tree[]; int len; int size; SegmentTree(int len) { this.len = len; size = 1 << (32 - Integer.numberOfLeadingZeros(len - 1) + 1); // ceil(log(len)) + 1 tree = new int[size]; Arrays.fill(tree, -1); } void update(int node,int idx,int val,int nl,int nr) { if(nl == nr && nl == idx) tree[node] = val; else { int mid = (nl + nr) / 2; if(idx <= mid) update(2*node, idx , val ,nl , mid); else update((2*node) + 1, idx ,val , mid + 1, nr); tree[node] = Math.max(tree[2*node],tree[(2 * node) + 1]); } } void update(int idx , int val){ update(1, idx, val, 1, len); } int query(int L , int R){ return L <= R ? query(1, L, R, 1, len) : -1; } int query(int node , int L , int R, int nl, int nr) { int mid = (nl + nr) / 2; if(nl == L && nr == R) return tree[node]; else if(R <= mid) return query(2 * node, L, R, nl, mid); else if(L > mid) return query((2*node)+1, L, R, mid + 1 , nr); else return Math.max(query(2*node, L, mid , nl , mid) , query((2*node)+1, mid+1, R , mid+1,nr)); } } private static void solve() { int MAX = (int) 1e6; int N = nextInt(); int arr[] = nextIntArray(N); SegmentTree segTree = new SegmentTree(MAX); long DPmin[] = new long[N]; long DPmax[] = new long[N]; long imbalance = 0; for(int i = 0; i < N; i++) { int floorIdx = segTree.query(1, arr[i] - 1); int ceilIdx = segTree.query(arr[i] + 1, MAX); DPmax[i] = (1L * arr[i] * (i - ceilIdx)) + (ceilIdx >= 0 ? DPmax[ceilIdx] : 0); DPmin[i] = (1L * arr[i] * (i - floorIdx)) + (floorIdx >= 0 ? DPmin[floorIdx] : 0); imbalance += DPmax[i] - DPmin[i]; segTree.update(arr[i], i); } println(imbalance); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE **********************/ public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); st = null; solve(); reader.close(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer st; static String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} static String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} static int nextInt() {return Integer.parseInt(next());} static long nextLong() {return Long.parseLong(next());} static double nextDouble(){return Double.parseDouble(next());} static char nextChar() {return next().charAt(0);} static int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} static long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} static int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} static long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} static void print(Object o) { writer.print(o); } static void println(Object o){ writer.println(o);} /************************ TEMPLATE ENDS HERE ************************/ }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
07b0e29e6af66eb9c6869cc1e38cfe6c
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.util.*; import java.io.*; public class ImbalancedArray { /************************ SOLUTION STARTS HERE ************************/ static class SegmentTree { int tree[]; int len; int size; SegmentTree(int len) { this.len = len; // size = 1 << (32 - Integer.numberOfLeadingZeros(len - 1) + 1); // ceil(log(len)) + 1 size = len << 2; tree = new int[size]; Arrays.fill(tree, -1); } void update(int node,int idx,int val,int nl,int nr) { if(nl == nr && nl == idx) tree[node] = val; else { int mid = (nl + nr) / 2; if(idx <= mid) update(2*node, idx , val ,nl , mid); else update((2*node) + 1, idx ,val , mid + 1, nr); tree[node] = Math.max(tree[2*node],tree[(2 * node) + 1]); } } void update(int idx , int val){ update(1, idx, val, 1, len); } int query(int L , int R){ return L <= R ? query(1, L, R, 1, len) : -1; } int query(int node , int L , int R, int nl, int nr) { int mid = (nl + nr) / 2; if(nl == L && nr == R) return tree[node]; else if(R <= mid) return query(2 * node, L, R, nl, mid); else if(L > mid) return query((2*node)+1, L, R, mid + 1 , nr); else return Math.max(query(2*node, L, mid , nl , mid) , query((2*node)+1, mid+1, R , mid+1,nr)); } } private static void solve() { int MAX = (int) 1e6; int N = nextInt(); int arr[] = nextIntArray(N); SegmentTree segTree = new SegmentTree(MAX); long DPmin[] = new long[N]; long DPmax[] = new long[N]; long imbalance = 0; for(int i = 0; i < N; i++) { int floorIdx = segTree.query(1, arr[i] - 1); int ceilIdx = segTree.query(arr[i] + 1, MAX); DPmax[i] = (1L * arr[i] * (i - ceilIdx)) + (ceilIdx >= 0 ? DPmax[ceilIdx] : 0); DPmin[i] = (1L * arr[i] * (i - floorIdx)) + (floorIdx >= 0 ? DPmin[floorIdx] : 0); imbalance += DPmax[i] - DPmin[i]; segTree.update(arr[i], i); } println(imbalance); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE **********************/ public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); st = null; solve(); reader.close(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer st; static String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} static String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} static int nextInt() {return Integer.parseInt(next());} static long nextLong() {return Long.parseLong(next());} static double nextDouble(){return Double.parseDouble(next());} static char nextChar() {return next().charAt(0);} static int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} static long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} static int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} static long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} static void print(Object o) { writer.print(o); } static void println(Object o){ writer.println(o);} /************************ TEMPLATE ENDS HERE ************************/ }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
fe0ff16b4c67c5cd08ee13a4917792ca
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static class Node implements Comparable<Node> { public final Integer index, val; Node(int index, int val) { this.index = index; this.val = val; } @Override public int compareTo(Node node) { return -this.val.compareTo(node.val); } } public static void main(String[] args) { InputReader in = new InputReader(System.in); int n = in.nextInt(); int[] a = new int[n + 2]; int[] lef = new int[n + 2], rig = new int[n + 2]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); } long res = 0; // min { a[0] = a[n + 1] = Integer.MIN_VALUE; Stack<Integer> stk = new Stack<>(); stk.push(0); for (int i = 1; i <= n; i++) { while (a[i] < a[stk.peek()]) { stk.pop(); } lef[i] = stk.peek(); stk.push(i); } stk.clear(); stk.push(n + 1); for (int i = n; i > 0; i--) { while (a[i] <= a[stk.peek()]) { stk.pop(); } rig[i] = stk.peek(); stk.push(i); } for (int i = 1; i <= n; i++) { res -= (long) (i - lef[i]) * (rig[i] - i) * a[i]; } } // max { a[0] = a[n + 1] = Integer.MAX_VALUE; Stack<Integer> stk = new Stack<>(); stk.push(0); for (int i = 1; i <= n; i++) { while (a[i] > a[stk.peek()]) { stk.pop(); } lef[i] = stk.peek(); stk.push(i); } stk.clear(); stk.push(n + 1); for (int i = n; i > 0; i--) { while (a[i] >= a[stk.peek()]) { stk.pop(); } rig[i] = stk.peek(); stk.push(i); } for (int i = 1; i <= n; i++) { res += (long) (i - lef[i]) * (rig[i] - i) * a[i]; } } System.out.println(res); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
3b2e9dc279f10a27c4adfb0679d42bbb
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; public class Main { static class Solver { public long solve(long []A) { long []fromLeft = calcLeft(A,true); long []fromRight = calcRight(A); //System.out.println(Arrays.toString(fromLeft)); //System.out.println(Arrays.toString(fromRight)); long ret = 0; for (int i=0;i<A.length;++i) { ret += A[i] * (fromLeft[i]*fromRight[i]-1); } return ret; } private long[] calcLeft(long []A) { return calcLeft(A,false); } private long[] calcLeft(long []A, boolean popEqual) { Stack<Integer> stk = new Stack<>(); long []fromLeft = new long[A.length]; for (int i=0;i<A.length;++i) { while (!stk.isEmpty() && ( A[stk.peek()] < A[i] || (popEqual && A[stk.peek()] == A[i]))) { stk.pop(); } if (stk.isEmpty()) { fromLeft[i] = -1; } else { fromLeft[i] = stk.peek(); } stk.push(i); } for (int i=0;i<fromLeft.length;++i) { fromLeft[i] = i - fromLeft[i]; } return fromLeft; } private long[] calcRight(long []A) { long []B = reverseArray(A); long []ret = calcLeft(B); return reverseArray(ret); } private long[] reverseArray(long []A) { long []B = new long[A.length]; for (int i=0;i<A.length; ++i) { B[i] = A[A.length-i-1]; } return B; } } public static void main(String []args) throws FileNotFoundException{ Scanner in=new Scanner(); int n = in.nextInt(); long A[] = new long[n]; for (int i=0;i<n;++i) { A[i] = in.nextLong(); } long maxValues = new Solver().solve(A); for (int i=0;i<n;++i) { A[i] = -A[i]; } long minValues = new Solver().solve(A); //System.out.println(maxValues); //System.out.println(minValues); System.out.println(maxValues+minValues); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
539e71c0d139642bb5e212cd2faf2965
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.io.*; import java.util.*; public class Main { static class FastReader { final BufferedReader br; StringTokenizer st; 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()); } } public static void main(String[] args) { setup(); xuly(); } private static int n, a[], front1[], back1[], front2[], back2[]; private static void setup() { FastReader fastReader = new FastReader(); n = fastReader.nextInt(); a = new int[n]; front1 = new int[n]; back1 = new int[n]; front2 = new int[n]; back2 = new int[n]; for (int i = 0; i < n; i ++) a[i] = fastReader.nextInt(); } private static void stackking(int[] arr, Comparator<Integer> comparator) { Stack<Integer> st = new Stack<>(); for (int i = 0; i < n; i ++) { while(!st.isEmpty() && comparator.compare(a[st.peek()], a[i]) == 1) st.pop(); if (st.isEmpty()) arr[i] = -1; else arr[i] = st.peek(); st.push(i); } } private static Comparator<Integer> smaller = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return (o1 < o2? 1 : 0); } }; private static Comparator<Integer> smallerOrEqual = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return (o1 <= o2? 1 : 0); } }; private static Comparator<Integer> bigger = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return (o1 > o2? 1 : 0); } }; private static Comparator<Integer> biggerOrEqual = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return (o1 >= o2? 1 : 0); } }; private static void reverse(int[] arr){ int l = 0, r = arr.length - 1; while(l < r) { int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; l ++; r --; } } private static void xuly() { stackking(front1, smaller); stackking(front2, bigger); reverse(a); stackking(back1, smallerOrEqual); stackking(back2, biggerOrEqual); reverse(a); reverse(back1); reverse(back2); long ans = 0; for (int i = 0; i < n; i ++) { back1[i] = n - 1 - back1[i]; back2[i] = n - 1 - back2[i]; ans += (long) a[i] * (back1[i] - i) * (i - front1[i]); ans -= (long) a[i] * (back2[i] - i) * (i - front2[i]); } System.out.print(ans); } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
b00448c0123882652568a2724e316073
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayDeque; import java.util.Deque; import java.util.StringTokenizer; /* public class _817D { } */ public class _817D { public void solve() throws FileNotFoundException { InputStream inputStream = System.in; InputHelper inputHelper = new InputHelper(inputStream); PrintStream out = System.out; // actual solution int n = inputHelper.readInteger(); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = inputHelper.readInteger(); } long[] max = new long[n]; long[] min = new long[n]; Deque<Integer> mxs = new ArrayDeque<Integer>(); mxs.add(0); max[0] = a[0]; for (int i = 1; i < n; i++) { while (mxs.size() > 0 && a[mxs.peek()] <= a[i]) { mxs.pop(); } if (mxs.size() > 0) { max[i] = (long) a[i] * (i - mxs.peek()); max[i] += max[mxs.peek()]; } else { max[i] = a[i] * (i + 1); } mxs.addFirst(i); } Deque<Integer> mns = new ArrayDeque<Integer>(); mns.add(0); min[0] = a[0]; for (int i = 1; i < n; i++) { while (mns.size() > 0 && a[mns.peek()] >= a[i]) { mns.pop(); } if (mns.size() > 0) { min[i] = (long) a[i] * (i - mns.peek()); min[i] += min[mns.peek()]; } else { min[i] = a[i] * (i + 1); } mns.addFirst(i); } long ans = 0; for (int i = 0; i < n; i++) { ans += (max[i] - min[i]); } System.out.println(ans); // end here } public static void main(String[] args) throws FileNotFoundException { (new _817D()).solve(); } class InputHelper { StringTokenizer tokenizer = null; private BufferedReader bufferedReader; public InputHelper(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader( inputStream); bufferedReader = new BufferedReader(inputStreamReader, 16384); } public String read() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = bufferedReader.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public Integer readInteger() { return Integer.parseInt(read()); } public Long readLong() { return Long.parseLong(read()); } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
ad3f65f8b8e6d3f50fe382f3679f020a
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayDeque; import java.util.Deque; import java.util.StringTokenizer; /* public class _817D { } */ public class _817D { public void solve() throws FileNotFoundException { InputStream inputStream = System.in; InputHelper inputHelper = new InputHelper(inputStream); PrintStream out = System.out; // actual solution int n = inputHelper.readInteger(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = inputHelper.readInteger(); } long[] max = new long[n]; long[] min = new long[n]; Deque<Integer> mxs = new ArrayDeque<Integer>(); mxs.add(0); max[0] = a[0]; for (int i = 1; i < n; i++) { while (mxs.size() > 0 && a[mxs.peek()] <= a[i]) { mxs.pop(); } if (mxs.size() > 0) { max[i] = (long) a[i] * (i - mxs.peek()); max[i] += max[mxs.peek()]; } else { max[i] = (long) a[i] * (i + 1); } mxs.addFirst(i); } Deque<Integer> mns = new ArrayDeque<Integer>(); mns.add(0); min[0] = a[0]; for (int i = 1; i < n; i++) { while (mns.size() > 0 && a[mns.peek()] >= a[i]) { mns.pop(); } if (mns.size() > 0) { min[i] = (long) a[i] * (i - mns.peek()); min[i] += min[mns.peek()]; } else { min[i] = (long) a[i] * (i + 1); } mns.addFirst(i); } long ans = 0; for (int i = 0; i < n; i++) { ans += (max[i] - min[i]); } System.out.println(ans); // end here } public static void main(String[] args) throws FileNotFoundException { (new _817D()).solve(); } class InputHelper { StringTokenizer tokenizer = null; private BufferedReader bufferedReader; public InputHelper(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader( inputStream); bufferedReader = new BufferedReader(inputStreamReader, 16384); } public String read() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = bufferedReader.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public Integer readInteger() { return Integer.parseInt(read()); } public Long readLong() { return Long.parseLong(read()); } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
c4a0f86f72b48558147109942beaa0d0
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
//package educational.round23; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class D { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); long ret = 0; { int[] f = count(a); a = rev(a); int[] b = count2(a); for(int i = 0;i < n;i++){ ret += (long)f[i] * b[n-1-i] * a[n-1-i]; } } for(int i = 0;i < n;i++)a[i] = -a[i]; { int[] f = count(a); a = rev(a); int[] b = count2(a); for(int i = 0;i < n;i++){ ret += (long)f[i] * b[n-1-i] * a[n-1-i]; } } out.println(ret); } public static int[] rev(int[] a) { for(int i = 0, j = a.length-1;i < j;i++,j--){ int c = a[i]; a[i] = a[j]; a[j] = c; } return a; } int[] count(int[] a) { int n = a.length; int[] lens = new int[n]; int[] stack = new int[n+1]; int p = 0; for(int i = 0;i < n;i++){ while(p > 0 && a[stack[p-1]] < a[i]){ lens[stack[p-1]] = i-stack[p-1]; p--; } stack[p++] = i; } while(p > 0){ lens[stack[p-1]] = n-stack[p-1]; p--; } return lens; } int[] count2(int[] a) { int n = a.length; int[] lens = new int[n]; int[] stack = new int[n+1]; int p = 0; for(int i = 0;i < n;i++){ while(p > 0 && a[stack[p-1]] <= a[i]){ lens[stack[p-1]] = i-stack[p-1]; p--; } stack[p++] = i; } while(p > 0){ lens[stack[p-1]] = n-stack[p-1]; p--; } return lens; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
16003671ecee36e6a2f0d13a4aebde26
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.io.*; import java.util.*; public class TestClass { static PrintWriter out = new PrintWriter(System.out); public static void main(String args[] ) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); String s[] = in.readLine().split(" "); long a[] = new long[n]; for(int i=0;i<n;i++) { a[i] = Long.parseLong(s[i]); } int left[] = new int[n]; Stack<Integer> stk = new Stack<Integer>(); for(int i=0;i<n;i++) { while(!stk.isEmpty() && a[stk.peek()]>a[i]) { stk.pop(); } if(stk.isEmpty()) { left[i] = -1; } else { left[i] = stk.peek(); } stk.push(i); } int right[] = new int[n]; stk = new Stack<Integer>(); for(int i=n-1;i>=0;i--) { while(!stk.isEmpty() && a[stk.peek()]>=a[i]) { stk.pop(); } if(stk.isEmpty()) { right[i] = n; } else { right[i] = stk.peek(); } stk.push(i); } long min=0; for(int i=0;i<n;i++) { int l = left[i]+1; int r = right[i]-1; min += (r-l+1+(i-l)*(long)(r-i))*a[i]; } for(int i=0;i<n;i++) { a[i] = -a[i]; } stk = new Stack<Integer>(); left = new int[n]; for(int i=0;i<n;i++) { while(!stk.isEmpty() && a[stk.peek()]>a[i]) { stk.pop(); } if(stk.isEmpty()) { left[i] = -1; } else { left[i] = stk.peek(); } stk.push(i); } right = new int[n]; stk = new Stack<Integer>(); for(int i=n-1;i>=0;i--) { while(!stk.isEmpty() && a[stk.peek()]>=a[i]) { stk.pop(); } if(stk.isEmpty()) { right[i] = n; } else { right[i] = stk.peek(); } stk.push(i); } long max=0; for(int i=0;i<n;i++) { int l = left[i]+1; int r = right[i]-1; max += (r-l+1+(i-l)*(long)(r-i))*a[i]; } out.println(-max-min); out.close(); } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
ca09e63fa9f348c26c2aa01e271412ff
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.util.concurrent.*; public final class imb { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); static int[][] st; static int LN=22; static int[] a,log; static int maxn=(int)(1e6+100); static int getMax(int l,int r) { int val=log[r-l]; int idx1=st[val][l],idx2=st[val][r-(1<<val)+1]; return (a[idx1]>=a[idx2]?idx1:idx2); } static int getMin(int l,int r) { int val=log[r-l]; int idx1=st[val][l],idx2=st[val][r-(1<<val)+1]; return (a[idx1]<=a[idx2]?idx1:idx2); } static int get(int l,int r,int code) { if(code==0) return getMax(l,r); return getMin(l,r); } static long solve(int l,int r,int code) { if(l>r) { return 0; } if(l==r) { return a[l]; } else { int curr_idx=get(l,r,code); long val1=(curr_idx-l+1),val2=(r-curr_idx+1); return (val1*val2*a[curr_idx])+solve(l,curr_idx-1,code)+solve(curr_idx+1,r,code); } } public static void run() throws Exception { int n=sc.nextInt();a=new int[n];log=new int[maxn]; for(int i=2;i<maxn;i++) { log[i]=log[i>>1]+1; } for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } st=new int[LN][n]; for(int i=0;i<n;i++) { st[0][i]=i; } for(int i=1;i<LN;i++) { for(int j=0;(1<<i)+j<=n;j++) { int x=st[i-1][j],y=st[i-1][j+(1<<(i-1))]; st[i][j]=(a[x]>=a[y]?x:y); } } long val1=solve(0,n-1,0); for(int i=1;i<LN;i++) { for(int j=0;(1<<i)+j<=n;j++) { int x=st[i-1][j],y=st[i-1][j+(1<<(i-1))]; st[i][j]=(a[x]<=a[y]?x:y); } } long val2=solve(0,n-1,1); out.println(val1-val2);out.close(); } public static void main(String[] args) throws Exception { new Thread(null,new Runnable(){ public void run() { try { new imb().run(); } catch(Exception e) { } } },"1",1<<28).start(); } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output
PASSED
8a603ac6a34c7462363afb11d359c5bf
train_000.jsonl
1497539100
You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; public class edu23d implements Runnable{ public static void main(String[] args) { try{ new Thread(null, new edu23d(), "process", 1<<26).start(); } catch(Exception e){ System.out.println(e); } } public void run() { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); Task solver = new Task(); //int t = scan.nextInt(); int t = 1; for(int i = 1; i <= t; i++) solver.solve(i, scan, out); out.close(); } static class Task { static final int inf = Integer.MAX_VALUE; static int[] arr; public void solve(int testNumber, FastReader sc, PrintWriter out) { int N = sc.nextInt(); arr = new int[N]; for(int i = 0; i < N; i++) { arr[i] = sc.nextInt(); } int[] nextGreater = new int[N]; Arrays.fill(nextGreater, N); int[] nextLesser = new int[N]; Arrays.fill(nextLesser, N); Stack<tup> stack = new Stack<>(); Stack<tup> mStack = new Stack<>(); stack.push(new tup(arr[0], 0)); mStack.push(new tup(arr[0], 0)); for(int i = 1; i < N; i++) { if(!stack.isEmpty()) { tup t = stack.pop(); while(t.a < arr[i]) { nextGreater[t.b] = i; if (stack.isEmpty()) break; t = stack.pop(); } if(t.a >= arr[i]) stack.push(t); } stack.push(new tup(arr[i], i)); if(!mStack.isEmpty()) { tup t = mStack.pop(); while(t.a > arr[i]) { nextLesser[t.b] = i; if(mStack.isEmpty()) break; t = mStack.pop(); } if(t.a <= arr[i]) mStack.push(t); } mStack.push(new tup(arr[i], i)); } stack.clear(); mStack.clear(); int[] lastGreater = new int[N]; Arrays.fill(lastGreater, -1); int[] lastLesser = new int[N]; Arrays.fill(lastLesser, -1); stack.push(new tup(arr[N-1], N-1)); mStack.push(new tup(arr[N-1], N-1)); for(int i = N-2; i >= 0; i--) { if(!stack.isEmpty()) { tup t = stack.pop(); while(t.a < arr[i]) { lastGreater[t.b] = i; if (stack.isEmpty()) break; t = stack.pop(); } if(t.a >= arr[i]) stack.push(t); } stack.push(new tup(arr[i], i)); if(!mStack.isEmpty()) { tup t = mStack.pop(); while(t.a > arr[i]) { lastLesser[t.b] = i; if(mStack.isEmpty()) break; t = mStack.pop(); } if(t.a <= arr[i]) mStack.push(t); } mStack.push(new tup(arr[i], i)); } /*System.out.println(Arrays.toString(nextGreater)); System.out.println(Arrays.toString(lastGreater)); System.out.println(Arrays.toString(nextLesser)); System.out.println(Arrays.toString(lastLesser)); */ Map<Integer, Integer> map = new HashMap<>(); long sum = 0; for(int i = 0; i < N; i++) { long lo; if(map.containsKey(arr[i])) { lo = Math.max(map.get(arr[i]), lastGreater[i]); } else { lo = lastGreater[i]; } long hi = nextGreater[i]; sum += (i-lo)*(hi-i)*arr[i]; //System.out.println(sum); if(map.containsKey(arr[i])) { lo = Math.max(map.get(arr[i]), lastLesser[i]); } else { lo = lastLesser[i]; } hi = nextLesser[i]; sum -= (i-lo) * (hi-i) * arr[i]; //System.out.println(sum); map.put(arr[i], i); } out.println(sum); } } static long binpow(long a, long b, long m) { a %= m; long res = 1; while (b > 0) { if ((b & 1) == 1) res = res * a % m; a = a * a % m; b >>= 1; } return res; } static void sort(int[] x){ shuffle(x); Arrays.sort(x); } static void sort(long[] x){ shuffle(x); Arrays.sort(x); } static class comp implements Comparator<tup>{ @Override public int compare(tup o1, tup o2) { return Integer.compare(o2.a, o1.a); } } static class tup implements Comparable<tup>, Comparator<tup>{ int a, b; tup(int a,int b){ this.a=a; this.b=b; } public tup() { } @Override public int compareTo(tup o){ return Integer.compare(a, o.a); } @Override public int compare(tup o1, tup o2) { return Integer.compare(o1.a, o2.a); } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; tup other = (tup) obj; return a==other.a && b==other.b; } @Override public String toString() { return a + " " + b; } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n1 4 1"]
2 seconds
["9"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer", "sortings" ]
38210a3dcb16ce2bbc81aa1d39d23112
The first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a. The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.
1,900
Print one integer β€” the imbalance value of a.
standard output