src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringlengths 6
50
| from
stringclasses 1
value |
---|---|---|---|
import java.io.*;
import java.util.*;
public class CC {
public static void main(String[] args)throws Throwable {
MyScanner sc=new MyScanner();
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
int r=sc.nextInt();
int [] x=new int [n];
for(int i=0;i<n;i++)
x[i]=sc.nextInt();
double [] ans=new double [n];
ans[0]=r;
for(int i=1;i<n;i++){
ans[i]=r;
for(int j=0;j<i;j++){
double dx=Math.abs(x[i]-x[j]);
if(dx>2*r)
continue;
double y=Math.sqrt((4*r*r)-(dx*dx));
ans[i]=Math.max(ans[i], ans[j]+y);
}
}
for(double z : ans)
pw.print(z+" ");
pw.flush();
pw.close();
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {e.printStackTrace();}}
return st.nextToken();}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
String nextLine(){String str = "";
try {str = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return str;}
}
} | quadratic | 908_C. New Year and Curling | CODEFORCES |
public class Main {
private static void solve() {
int n = ni();
double r = ni();
double[][] p = new double[n][2];
double EPS = 0.0000000000001;
for (int i = 0; i < n; i ++) {
double x = ni();
double y = r;
for (int j = 0; j < i; j ++) {
double dx = Math.abs(p[j][0] - x);
if (dx <= r * 2 + EPS) {
double dy = Math.sqrt(4.0 * r * r - dx * dx);
y = Math.max(y, p[j][1] + dy);
}
}
out.printf("%.12f ", y);
p[i][0] = x;
p[i][1] = y;
}
out.println();
}
public static void main(String[] args) {
new Thread(null, new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
String debug = args.length > 0 ? args[0] : null;
if (debug != null) {
try {
is = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(debug));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
reader = new java.io.BufferedReader(new java.io.InputStreamReader(is), 32768);
solve();
out.flush();
tr((System.currentTimeMillis() - start) + "ms");
}
}, "", 64000000).start();
}
private static java.io.InputStream is = System.in;
private static java.io.PrintWriter out = new java.io.PrintWriter(System.out);
private static java.util.StringTokenizer tokenizer = null;
private static java.io.BufferedReader reader;
public static String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new java.util.StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
private static double nd() {
return Double.parseDouble(next());
}
private static long nl() {
return Long.parseLong(next());
}
private static int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private static char[] ns() {
return next().toCharArray();
}
private static long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private static int[][] ntable(int n, int m) {
int[][] table = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[i][j] = ni();
}
}
return table;
}
private static int[][] nlist(int n, int m) {
int[][] table = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[j][i] = ni();
}
}
return table;
}
private static int ni() {
return Integer.parseInt(next());
}
private static void tr(Object... o) {
if (is != System.in)
System.out.println(java.util.Arrays.deepToString(o));
}
}
| quadratic | 908_C. New Year and Curling | CODEFORCES |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
public class Main {
static PrintWriter out;
static InputReader ir;
static void solve() {
int n=ir.nextInt();
int r=ir.nextInt();
int[] x=ir.nextIntArray(n);
double[] ret=new double[n];
for(int i=0;i<n;i++){
double ma=r;
for(int j=0;j<i;j++){
if(Math.abs(x[i]-x[j])<=2*r){
ma=Math.max(ma,ret[j]+Math.sqrt(4*(double)Math.pow(r, 2)-Math.pow(x[i]-x[j],2)));
}
}
ret[i]=ma;
}
for(int i=0;i<n;i++){
out.print(ret[i]+(i==n-1?"\n":" "));
}
}
public static void main(String[] args) throws Exception {
ir = new InputReader(System.in);
out = new PrintWriter(System.out);
solve();
out.flush();
}
static class InputReader {
private InputStream in;
private byte[] buffer = new byte[1024];
private int curbuf;
private int lenbuf;
public InputReader(InputStream in) {
this.in = in;
this.curbuf = this.lenbuf = 0;
}
public boolean hasNextByte() {
if (curbuf >= lenbuf) {
curbuf = 0;
try {
lenbuf = in.read(buffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return false;
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[curbuf++];
else
return -1;
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private void skip() {
while (hasNextByte() && isSpaceChar(buffer[curbuf]))
curbuf++;
}
public boolean hasNext() {
skip();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (!isSpaceChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public char[][] nextCharMap(int n, int m) {
char[][] map = new char[n][m];
for (int i = 0; i < n; i++)
map[i] = next().toCharArray();
return map;
}
}
} | quadratic | 908_C. New Year and Curling | CODEFORCES |
import java.util.*;
import java.io.*;
public class NewYearsCurling {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(sc.nextLine());
int n = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
ArrayList<Integer> centers = new ArrayList<Integer>();
st = new StringTokenizer(sc.nextLine());
for (int i = 0; i < n; i++) {
centers.add(Integer.parseInt(st.nextToken()));
}
sc.close();
ArrayList<Point> finalpoints = new ArrayList<Point>();
for (int i = 0; i < n; i++) {
double maxy = r;
for (int j = 0; j < finalpoints.size(); j++) {
if (finalpoints.get(j).x - centers.get(i) > 2 * r || centers.get(i) - finalpoints.get(j).x > 2 * r)
continue;
double dist = Math.sqrt(
4 * r * r - (finalpoints.get(j).x - centers.get(i)) * (finalpoints.get(j).x - centers.get(i)))
+ finalpoints.get(j).y;
if(dist > maxy)
maxy = dist;
}
pw.print(maxy + " ");
finalpoints.add(new Point(centers.get(i), maxy));
}
pw.close();
}
public static class Point {
double x;
double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
}
| quadratic | 908_C. New Year and Curling | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
TaskC.InputReader in = new TaskC.InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.Solve(in, out);
out.close();
}
static class TaskC {
void Solve(InputReader in, PrintWriter out) {
int n = in.NextInt();
double r = in.NextInt();
double[] x = new double[n];
for (int i = 0; i < n; i++) x[i] = in.NextInt();
double[] y = new double[n];
for (int i = 0; i < n; i++) {
double maxY = r;
for (int j = 0; j < i; j++) {
if (Math.abs(x[i] - x[j]) <= 2 * r) {
double currentY = Math.sqrt((2 * r) * (2 * r) - (x[i] - x[j]) * (x[i] - x[j])) + y[j];
maxY = Math.max(maxY, currentY);
}
}
y[i] = maxY;
}
out.print(y[0]);
for (int i = 1; i < n; i++) {
out.print(" " + y[i]);
}
out.println();
}
static int GetMax(int[] ar) {
int max = Integer.MIN_VALUE;
for (int a : ar) {
max = Math.max(max, a);
}
return max;
}
static int GetMin(int[] ar) {
int min = Integer.MAX_VALUE;
for (int a : ar) {
min = Math.min(min, a);
}
return min;
}
static long GetSum(int[] ar) {
long s = 0;
for (int a : ar) s += a;
return s;
}
static int[] GetCount(int[] ar) {
return GetCount(ar, GetMax(ar));
}
static int[] GetCount(int[] ar, int maxValue) {
int[] dp = new int[maxValue + 1];
for (int a : ar) {
dp[a]++;
}
return dp;
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String Next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine(), " \t\n\r\f,");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
int NextInt() {
return Integer.parseInt(Next());
}
long NextLong() {
return Long.parseLong(Next());
}
double NextDouble() {
return Double.parseDouble(Next());
}
int[] NextIntArray(int n) {
return NextIntArray(n, 0);
}
int[] NextIntArray(int n, int offset) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = NextInt() - offset;
}
return a;
}
int[][] NextIntMatrix(int n, int m) {
return NextIntMatrix(n, m, 0);
}
int[][] NextIntMatrix(int n, int m, int offset) {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = NextInt() - offset;
}
}
return a;
}
}
}
}
| quadratic | 908_C. New Year and Curling | CODEFORCES |
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt(),r=in.nextInt();
double[] x=new double[n];
for(int i=0; i<n; i++)
x[i]=in.nextInt();
double[] y=new double[n];
for(int i=0; i<n; i++)
{
y[i]=r;
for(int j=0; j<i; j++)
{
if(Math.abs(x[j]-x[i])<=2*r)
{
y[i]=Math.max(y[i], y[j]+Math.sqrt(4*r*r-(x[i]-x[j])*(x[i]-x[j])));
}
}
}
for(int i=0; i<n; i++)
System.out.print(y[i]+" ");
}
} | quadratic | 908_C. New Year and Curling | CODEFORCES |
import java.io.*;
import java.util.HashSet;
import java.util.StringTokenizer;
public class GB_A {
FastScanner in;
PrintWriter out;
public static void main(String[] arg) {
new GB_A().run();
}
public void solve() throws IOException {
int n = in.nextInt();
int r = in.nextInt();
int[] a = new int[n];
double[] ans = new double[n];
a[0] = in.nextInt();
ans[0] = r;
for (int i = 1; i < n; i++) {
a[i] = in.nextInt();
double max = r;
for (int j = i - 1; j >= 0; j--) {
if (Math.abs(a[i] - a[j]) <= 2 * r) {
double d = Math.sqrt(4 * r * r - (a[i]- a[j]) * (a[i] - a[j])) + ans[j];
max = Math.max(max, d);
}
}
ans[i] = max;
}
for (int i = 0; i < n; i++) {
out.println(ans[i]);
}
}
public void run() {
try {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(BufferedReader bufferedReader) {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| quadratic | 908_C. New Year and Curling | CODEFORCES |
import java.io.*;
import java.util.*;
public class Codeforces908C {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
int[] x = new int[n];
st = new StringTokenizer(f.readLine());
for(int i = 0; i < n; i++) {
x[i] = Integer.parseInt(st.nextToken());
}
double[] y = new double[n];
y[0] = r;
double hypSq = 4*r*r;
for(int i = 1; i < n; i++) {
boolean hit = false;
double maxY = 0;
for(int j = 0; j < i; j++) {
int dx = Math.abs(x[i] - x[j]);
if(dx == 2*r) {
if(y[j] > maxY) {
maxY = y[j];
hit = true;
}
} else if(dx < 2*r) {
double newY = y[j] + Math.sqrt(hypSq - dx*dx);
if(newY > maxY) {
maxY = newY;
hit = true;
}
}
}
if(!hit) {
y[i] = r;
} else {
y[i] = maxY;
}
}
StringBuffer s = new StringBuffer("");
for(int i = 0; i < n; i++) {
s.append(y[i] + " ");
}
System.out.println(s.toString().trim());
}
}
| quadratic | 908_C. New Year and Curling | CODEFORCES |
import com.sun.org.apache.regexp.internal.RE;
import java.io.*;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.OpenOption;
import java.security.SecureRandom;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out));
//String test = "C-large";
//ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + test + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + test + "-out.txt")));
new Main(io).solve();
io.close();
}
ConsoleIO io;
Main(ConsoleIO io) {
this.io = io;
}
List<List<Integer>> gr = new ArrayList<>();
long MOD = 1_000_000_007;
public void solve() {
int n = io.ri(), r = io.ri();
double[] res = new double[n];
int[] xs = new int[n];
for(int i = 0;i<n;i++){
int x = io.ri();
xs[i] = x;
double max = r;
for(int j = 0;j<i;j++){
int dx = Math.abs(xs[j] - x);
int dx2 = dx*dx;
if(dx <= 2*r){
max = Math.max(max, Math.sqrt(4*r*r - dx2) + res[j]);
}
}
res[i] = max;
}
StringBuilder sb = new StringBuilder();
for(int i = 0;i<res.length;i++){
if(i>0)sb.append(' ');
sb.append(res[i]);
}
io.writeLine(sb.toString());
}
}
class ConsoleIO {
BufferedReader br;
PrintWriter out;
public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;}
public void flush(){this.out.flush();}
public void close(){this.out.close();}
public void writeLine(String s) {this.out.println(s);}
public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
public void writeWord(String s){
this.out.print(s);
}
public void writeIntArray(int[] a, int k, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < k; i++) {
if (i > 0) sb.append(separator);
sb.append(a[i]);
}
this.writeLine(sb.toString());
}
public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }}
public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
public long[] readLongArray() {
String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length];
for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
return r;
}
public int[] readIntArray() {
String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
return r;
}
public int[] readIntArray(int n) {
int[] res = new int[n];
char[] all = this.readLine().toCharArray();
int cur = 0;boolean have = false;
int k = 0;
boolean neg = false;
for(int i = 0;i<all.length;i++){
if(all[i]>='0' && all[i]<='9'){
cur = cur*10+all[i]-'0';
have = true;
}else if(all[i]=='-') {
neg = true;
}
else if(have){
res[k++] = neg?-cur:cur;
cur = 0;
have = false;
neg = false;
}
}
if(have)res[k++] = neg?-cur:cur;
return res;
}
public int ri() {
try {
int r = 0;
boolean start = false;
boolean neg = false;
while (true) {
int c = br.read();
if (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
start = true;
} else if (!start && c == '-') {
start = true;
neg = true;
} else if (start || c == -1) return neg ? -r : r;
}
} catch (Exception ex) {
return -1;
}
}
public long readLong() {
try {
long r = 0;
boolean start = false;
boolean neg = false;
while (true) {
int c = br.read();
if (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
start = true;
} else if (!start && c == '-') {
start = true;
neg = true;
} else if (start || c == -1) return neg ? -r : r;
}
} catch (Exception ex) {
return -1;
}
}
public String readWord() {
try {
boolean start = false;
StringBuilder sb = new StringBuilder();
while (true) {
int c = br.read();
if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') {
sb.append((char)c);
start = true;
} else if (start || c == -1) return sb.toString();
}
} catch (Exception ex) {
return "";
}
}
public char readSymbol() {
try {
while (true) {
int c = br.read();
if (c != ' ' && c != '\r' && c != '\n' && c != '\t') {
return (char) c;
}
}
} catch (Exception ex) {
return 0;
}
}
//public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }}
}
class Pair {
public Pair(int a, int b) {this.a = a;this.b = b;}
public int a;
public int b;
}
class PairLL {
public PairLL(long a, long b) {this.a = a;this.b = b;}
public long a;
public long b;
}
class Triple {
public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;}
public int a;
public int b;
public int c;
} | quadratic | 908_C. New Year and Curling | CODEFORCES |
import java.util.*;
public class PC1229 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int r = sc.nextInt();
int[] x = new int[n];
for(int i = 0; i < n; i++){
x[i] = sc.nextInt();
}
double[] ans = new double[n];
for(int i = 0; i < n; i++){
double maxY = r;
for(int j = 0; j < i; j++){
if(x[j] <= x[i] + 2*r && x[j] >= x[i] - 2*r){
maxY = Math.max(maxY, ans[j] + Math.sqrt(4 * r * r - (Math.abs(x[i] - x[j])) * (Math.abs(x[i] - x[j]))));
}
}
ans[i] = maxY;
}
for(int i = 0; i < n; i++){
System.out.println(ans[i]);
}
sc.close();
}
}
| quadratic | 908_C. New Year and Curling | CODEFORCES |
import java.util.Scanner;
public class C {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int r = in.nextInt();
double pos[][] = new double[n][2];
for(int i = 0; i < n; i++) {
pos[i][0] = in.nextInt();
double y = r;
for(int j = 0; j < i; j++) {
if(Math.abs(pos[i][0] - pos[j][0]) <= 2*r) {
double tempy = pos[j][1] + Math.sqrt(Math.pow(2*r, 2) - Math.pow(Math.abs(pos[i][0] - pos[j][0]), 2));
if(tempy > y) y = tempy;
}
}
pos[i][1] = y;
System.out.print(y + " ");
}
}
} | quadratic | 908_C. New Year and Curling | CODEFORCES |
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.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 ilyakor
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int r = in.nextInt();
ArrayList<PointDouble> centers = new ArrayList<>();
ArrayList<Integer> xs = new ArrayList<>();
for (int i = 0; i < n; ++i) {
int x = in.nextInt();
double y = r;
for (int j = 0; j < centers.size(); j++) {
int ox = xs.get(j);
if (Math.abs(ox - x) > 2 * r) continue;
PointDouble c = centers.get(j);
double t = Math.abs(ox - x);
double h = Math.sqrt(Math.abs(4.0 * r * r - t * t));
double val = c.y + h;
if (y < val) y = val;
}
out.print(String.format("%.20f ", y));
centers.add(new PointDouble(x, y));
xs.add(x);
}
out.printLine();
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
static class PointDouble {
public double x;
public double y;
public PointDouble(double x, double y) {
this.x = x;
this.y = y;
}
public PointDouble() {
x = 0;
y = 0;
}
}
}
| quadratic | 908_C. New Year and Curling | CODEFORCES |
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class C {
static double ycoord(double xi, double yi, double xj, double r) {
if(Math.abs(xi-xj) > 2*r) return r;
double dist = Math.sqrt((4*r*r)-((xi-xj)*(xi-xj)));
//System.out.println("dist" + dist);
return Math.max(yi+dist, r); //yi - dist?
}
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
double r = sc.nextInt();
double[] xcoords = new double[n];
double[] ycoords = new double[n];
Arrays.fill(ycoords, Integer.MIN_VALUE);
ycoords[0] = r;
for(int i = 0; i < n; i++) {
xcoords[i] = sc.nextDouble();
}
System.out.print(r + " ");
for(int i = 1; i < n; ++i) {
for(int j = 0; j < i; j++) {
ycoords[i] = Math.max(ycoord(xcoords[j], ycoords[j],xcoords[i],r),ycoords[i]);
}
System.out.print(ycoords[i] + " ");
}
out.flush();
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} | quadratic | 908_C. New Year and Curling | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.TreeMap;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.sqrt;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
import static java.util.Collections.reverse;
import static java.util.Collections.reverseOrder;
import static java.util.Collections.sort;
public class Main {
private FastScanner in;
private PrintWriter out;
private void solve() throws IOException {
solveC();
}
private void solveA() throws IOException {
HashSet<Character> set = new HashSet<>();
for (char c : new char[]{'a', 'e', 'i', 'o', 'u', '1', '3', '5', '7', '9'})
set.add(c);
int cnt = 0;
for (char c : in.nextLine().toCharArray())
if (set.contains(c))
cnt++;
out.println(cnt);
}
int n, m, cl;
char a[][];
int[] b;
int fromi, fromj, toi, toj;
private void solveB() throws IOException {
n = in.nextInt();
m = in.nextInt();
char[] c;
a = new char[n][m];
for (int i = 0; i < n; i++) {
a[i] = in.next().toCharArray();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a[i][j] == 'S') {
fromi = i;
fromj = j;
}
if (a[i][j] == 'E') {
toi = i;
toj = j;
}
}
}
c = in.next().toCharArray();
cl = c.length;
b = new int[cl];
for (int i = 0; i < cl; i++) {
b[i] = c[i] - '0';
}
ArrayList<Long> ar1 = new ArrayList<>(), ar2 = new ArrayList<>(), ar3 = new ArrayList<>(), ar4 = new ArrayList<>();
ar1.add((long) 12);
ar1.add((long) 10);
ar1.add((long) 01);
ar1.add((long) 21);
long[] str = new long[4];
int ans = 0;
for (long i : ar1) {
str[0] = i;
ar2.clear();
ar2.addAll(ar1);
ar2.remove(i);
for (long j : ar2) {
str[1] = j;
ar3.clear();
ar3.addAll(ar2);
ar3.remove(j);
for (long k : ar3) {
str[2] = k;
ar4.clear();
ar4.addAll(ar3);
ar4.remove(k);
str[3] = ar4.get(0);
if (bfs(str))
ans++;
}
}
}
out.println(ans);
}
private boolean bfs(long[] str) {
int[][] steps = {{(int) str[0] / 10 - 1, (int) str[0] % 10 - 1},
{(int) str[1] / 10 - 1, (int) str[1] % 10 - 1},
{(int) str[2] / 10 - 1, (int) str[2] % 10 - 1},
{(int) str[3] / 10 - 1, (int) str[3] % 10 - 1}};
for (int i = 0, ci = fromi, cj = fromj; i < cl; i++) {
ci += steps[b[i]][0];
cj += steps[b[i]][1];
if (ci >= n || ci < 0 || cj >= m || cj < 0 || a[ci][cj] == '#')
return false;
if (a[ci][cj] == 'E')
return true;
}
return false;
}
private void solveC() throws IOException {
int n = in.nextInt();
int r = in.nextInt();
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextInt();
}
double[] y = new double[n];
for (int i = 0; i < n; i++) {
y[i] = r;
for (int j = 0; j < i; j++) {
if (abs(x[i] - x[j]) <= 2 * r) {
y[i] = max(y[i], y[j] + sqrt(4.0 * r * r - (x[i] - x[j]) * (x[i] - x[j])));
}
}
}
for (double ty : y)
out.print(ty + " ");
out.println();
}
private void solveD() throws IOException {
}
private void solveE() throws IOException {
}
private void solveF() throws IOException {
}
class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
}
| quadratic | 908_C. New Year and Curling | CODEFORCES |
//package info.stochastic;
import java.io.*;
import java.util.*;
public class C {
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();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int r = in.nextInt();
int x[] = new int[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextInt();
}
double ans[] = new double[n];
ans[0] = r;
int index = 1;
for (int i = 1; i < n; i++) {
double maxY = r;
for (int j = 0; j < index; j++) {
int xDist = Math.abs(x[i] - x[j]);
if (xDist <= r * 2) {
double cur = Math.sqrt((r * 2)*(r * 2) - xDist * xDist) + ans[j];
//out.println(cur);
maxY = Math.max(maxY, cur);
}
}
//out.println();
ans[i] = maxY;
index++;
}
for (int i = 0; i < n; i++) {
out.print(ans[i] + " ");
}
}
}
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());
}
}
}
| quadratic | 908_C. New Year and Curling | CODEFORCES |
//package codeforces;
import java.util.Scanner;
public class Fingerprints {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] code = new int[scanner.nextInt()];
int[] prints = new int[scanner.nextInt()];
for (int i = 0; i < code.length; i++) {
code[i] = scanner.nextInt();
}
for (int i = 0; i < prints.length; i++) {
prints[i] = scanner.nextInt();
}
for (int i = 0; i < code.length; i++) {
for (int j = 0; j < prints.length; j++) {
if (code[i] == prints[j]) {
System.out.print(prints[j] + " ");
}
}
}
scanner.close();
}
}
| quadratic | 994_A. Fingerprints | CODEFORCES |
/**
* Created by Baelish on 8/28/2018.
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class F_DSU {
public static void main(String[] args)throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = in.nextInt();
int brr[] = new int[2*n];
for (int i = 0; i < 2*n; i+= 2) {
brr[i] = in.nextInt();
brr[i+1] = in.nextInt();
}
arr = shrink(brr);
int imap[] = new int[2*n];
for (int i = 0; i < 2*n; i++) {
imap[arr[i]] = brr[i];
}
int idx = binarySearch(arr.length);
if(idx >= arr.length) pw.println(-1);
else pw.println(imap[idx]);
pw.close();
}
static int n, arr[];
static int binarySearch(int H) {
int lo = 0, hi = H, mid;
while (lo < hi) {
mid = (lo + hi) / 2;
if (check(mid)) hi = mid;
else lo = mid + 1;
}
if(lo > 0 && check(lo-1)) return lo-1;
return lo;
}
static boolean check(int m){
DSU dsu = new DSU(2*n);
for (int i = 0; i < n; i++) {
int u = arr[2*i], v = arr[2*i+1];
if(u > m) return false;
if(v > m){
if(++dsu.cycle[dsu.find(u)] >= 2) return false;
}
else{
if(!dsu.union(u, v)){
if(++dsu.cycle[dsu.find(u)] >= 2) return false;
}
else{
if(dsu.cycle[dsu.find(u)] >= 2) return false;
}
}
}
return true;
}
static class DSU{
int parent[], cycle[], n;
DSU(int N){
n = N;
parent = new int[N];
cycle = new int[N];
for(int i = 0; i < N; i++){
parent[i] = i;
}
}
DSU(int [] p){
parent = p; n = p.length;
}
int find(int i) {
int p = parent[i];
if (i == p) return i;
return parent[i] = find(p);
}
boolean equiv(int u, int v){
return find(u) == find(v);
}
boolean union(int u, int v){
u = find(u); v = find(v);
if(u != v) {
parent[u] = parent[v];
cycle[v] += cycle[u];
}
return u != v;
}
int count(){
int cnt = 0;
for(int i = 0; i < n; i++){
if(i == find(i)) cnt++;
}
return cnt;
}
}
public static 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;
}
static void debug(Object...obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
static final int ints[] = new int[128];
public FastReader(InputStream is){
for(int i='0';i<='9';i++) ints[i]=i-'0';
this.is = is;
}
public 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++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while((b = readByte()) != -1 && isSpaceChar(b));
return b;
}
public String next(){
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt(){
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<<3) + (num<<1) + ints[b];
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
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<<3) + (num<<1) + ints[b];
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
/* public char nextChar() {
return (char)skip();
}*/
public char[] next(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 buff[] = new char[1005];
public char[] nextCharArray(){
int b = skip(), p = 0;
while(!(isSpaceChar(b))){
buff[p++] = (char)b;
b = readByte();
}
return Arrays.copyOf(buff, p);
}*/
}
} | quadratic | 1027_F. Session in BSU | CODEFORCES |
import java.util.Scanner;
public class FUck {
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int k=scan.nextInt();
String t=scan.next();
int mx=0;
for(int i=1;i<n;i++)
{
int gd=1;
for(int j=0;j<i;j++)
{
if(t.charAt(j)!=t.charAt((n-i)+j))
{
gd=0;
// i think i can break here
}
}
if(gd==1){
mx=i;
}
}
System.out.print(t);
for(int i=2;i<=k;i++)
{
for(int j=mx;j<n;j++)
{
System.out.print(t.charAt(j));
}
}
}
}
| quadratic | 1029_A. Many Equal Substrings | CODEFORCES |
import java.util.*;
public class TestClass
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int arr[] = new int[n+1];
for(int i =0;i<n;i++)
arr[i+1]= in.nextInt();
long sum[] = new long [n+1];
for(int i=1;i<=n;i++)
sum[i]=sum[i-1]+arr[i];
long dp[] = new long[n+1];
for(int i =1;i<=n;i++)
{
for(int j=i;j>i-m&&j>=1;j--)
{
long val = sum[i]-sum[j-1]+dp[j-1]-k;
dp[i]= Math.max(dp[i],val);
}
}
long max =0;
for(int i =1;i<=n;i++)
max=Math.max(max,dp[i]);
System.out.println(max);
}
} | quadratic | 1197_D. Yet Another Subarray Problem | CODEFORCES |
import java.util.*;
import javax.lang.model.util.ElementScanner6;
import java.io.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(inp, out);
out.close();
}
static class Solver {
class pair implements Comparable<pair>{
int i;
long dist;
public pair(int i,long dist)
{
this.i=i;
this.dist=dist;
}
public int compareTo(pair p)
{
return Long.compare(this.dist,p.dist);
}
}
class Node implements Comparable < Node > {
int i;
int cnt;
Node(int i, int cnt) {
this.i = i;
this.cnt = cnt;
}
public int compareTo(Node n) {
if (this.cnt == n.cnt) {
return Integer.compare(this.i, n.i);
}
return Integer.compare(this.cnt, n.cnt);
}
}
public boolean done(int[] sp, int[] par) {
int root;
root = findSet(sp[0], par);
for (int i = 1; i < sp.length; i++) {
if (root != findSet(sp[i], par))
return false;
}
return true;
}
public int findSet(int i, int[] par) {
int x = i;
boolean flag = false;
while (par[i] >= 0) {
flag = true;
i = par[i];
}
if (flag)
par[x] = i;
return i;
}
public void unionSet(int i, int j, int[] par) {
int x = findSet(i, par);
int y = findSet(j, par);
if (x < y) {
par[y] = x;
} else {
par[x] = y;
}
}
public 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;
}
}
public boolean isPrime(int n)
{
for(int i=2;i<n;i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
public void minPrimeFactor(int n, int[] s) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
s[1] = 1;
s[2] = 2;
for (int i = 4; i <= n; i += 2) {
prime[i] = false;
s[i] = 2;
}
for (int i = 3; i <= n; i += 2) {
if (prime[i]) {
s[i] = i;
for (int j = 2 * i; j <= n; j += i) {
prime[j] = false;
s[j] = i;
}
}
}
}
public void findAllPrime(int n, ArrayList < Node > al, int s[]) {
int curr = s[n];
int cnt = 1;
while (n > 1) {
n /= s[n];
if (curr == s[n]) {
cnt++;
continue;
}
Node n1 = new Node(curr, cnt);
al.add(n1);
curr = s[n];
cnt = 1;
}
}
public int binarySearch(int n, int k) {
int left = 1;
int right = 100000000 + 5;
int ans = 0;
while (left <= right) {
int mid = (left + right) / 2;
if (n / mid >= k) {
left = mid + 1;
ans = mid;
} else {
right = mid - 1;
}
}
return ans;
}
public boolean checkPallindrom(String s) {
char ch[] = s.toCharArray();
for (int i = 0; i < s.length() / 2; i++) {
if (ch[i] != ch[s.length() - 1 - i])
return false;
}
return true;
}
public void remove(ArrayList < Integer > [] al, int x) {
for (int i = 0; i < al.length; i++) {
for (int j = 0; j < al[i].size(); j++) {
if (al[i].get(j) == x)
al[i].remove(j);
}
}
}
public long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public void printDivisors(long n, ArrayList < Long > al) {
// Note that this loop runs till square root
for (long i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
// If divisors are equal, print only one
if (n / i == i) {
al.add(i);
} else // Otherwise print both
{
al.add(i);
al.add(n / i);
}
}
}
}
public static long constructSegment(long seg[], long arr[], int low, int high, int pos) {
if (low == high) {
seg[pos] = arr[low];
return seg[pos];
}
int mid = (low + high) / 2;
long t1 = constructSegment(seg, arr, low, mid, (2 * pos) + 1);
long t2 = constructSegment(seg, arr, mid + 1, high, (2 * pos) + 2);
seg[pos] = t1 + t2;
return seg[pos];
}
public static long querySegment(long seg[], int low, int high, int qlow, int qhigh, int pos) {
if (qlow <= low && qhigh >= high) {
return seg[pos];
} else if (qlow > high || qhigh < low) {
return 0;
} else {
long ans = 0;
int mid = (low + high) / 2;
ans += querySegment(seg, low, mid, qlow, qhigh, (2 * pos) + 1);
ans += querySegment(seg, mid + 1, high, qlow, qhigh, (2 * pos) + 2);
return ans;
}
}
public static int lcs(char[] X, char[] Y, int m, int n) {
if (m == 0 || n == 0)
return 0;
if (X[m - 1] == Y[n - 1])
return 1 + lcs(X, Y, m - 1, n - 1);
else
return Integer.max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));
}
public static long recursion(long start, long end, long cnt[], int a, int b) {
long min = 0;
long count = 0;
int ans1 = -1;
int ans2 = -1;
int l = 0;
int r = cnt.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (cnt[mid] >= start) {
ans1 = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
l = 0;
r = cnt.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (cnt[mid] <= end) {
ans2 = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
if (ans1 == -1 || ans2 == -1 || ans2 < ans1) {
// System.out.println("min1 "+min);
min = a;
return a;
} else {
min = b * (end - start + 1) * (ans2 - ans1 + 1);
}
if (start == end) {
// System.out.println("min "+min);
return min;
}
long mid = (end + start) / 2;
min = Long.min(min, recursion(start, mid, cnt, a, b) + recursion(mid + 1, end, cnt, a, b));
// System.out.println("min "+min);
return min;
}
public int dfs_util(ArrayList < Integer > [] al, boolean vis[], int x, int[] s, int lvl[]) {
vis[x] = true;
int cnt = 1;
for (int i = 0; i < al[x].size(); i++) {
if (!vis[al[x].get(i)]) {
lvl[al[x].get(i)] = lvl[x] + 1;
cnt += dfs_util(al, vis, al[x].get(i), s, lvl);
}
}
s[x] = cnt;
return s[x];
}
public void dfs(ArrayList[] al, int[] s, int[] lvl) {
boolean vis[] = new boolean[al.length];
for (int i = 0; i < al.length; i++) {
if (!vis[i]) {
lvl[i] = 1;
dfs_util(al, vis, i, s, lvl);
}
}
}
public int[] computeLps(String s)
{
int ans[] =new int[s.length()];
char ch[] = s.toCharArray();
int n = s.length();
int i=1;
int len=0;
ans[0]=0;
while(i<n)
{
if(ch[i]==ch[len])
{
len++;
ans[i]=len;
i++;
}
else
{
if(len!=0)
{
len=ans[len-1];
}
else
{
ans[i]=len;
i++;
}
}
}
return ans;
}
private void solve(InputReader inp, PrintWriter out1) {
int n = inp.nextInt();
int m = inp.nextInt();
long k = inp.nextLong();
long arr[] = new long[n];
for(int i=0;i<n;i++)
{
arr[i] = inp.nextLong();
}
long ans=0;
for(int i=0;i<m;i++)
{
long sum=0;
for(int j=i;j<n;j++)
{
if(j%m==i)
{
if(sum<0)
{
sum=0;
}
sum-=k;
}
sum+=arr[j];
ans=Math.max(ans,sum);
}
}
System.out.println(ans);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
class ele implements Comparable < ele > {
int value;
int i;
boolean flag;
public ele(int value, int i) {
this.value = value;
this.i = i;
this.flag = false;
}
public int compareTo(ele e) {
return Integer.compare(this.value, e.value);
}
} | quadratic | 1197_D. Yet Another Subarray Problem | CODEFORCES |
import java.util.*;
import java.math.*;
public class Solution{
private long [] sums;
private void solve(){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int [] arr = new int[n];
this.sums = new long[n];
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
sums[i] = arr[i] + (i == 0 ? 0 : sums[i - 1]);
}
long ans = 0;
for(int i = 1; i <= n && i <= m; i++){
ans = Math.max(ans, sum(0, i - 1) - k);
}
long [] dp = new long[n];
for(int i = 0; i < n; i++){
if(i + 1 >= m){
long cur = sum(i - m + 1, i) - k;
if(i - m >= 0){
cur += dp[i - m];
}
dp[i] = Math.max(dp[i], cur);
}
for(int j = 0; j <= m && i + j < n; j++){
ans = Math.max(ans, dp[i] + sum(i + 1, i + j) - k * (j > 0 ? 1 : 0));
}
}
System.out.println(ans);
}
private long sum(int l, int r){
if(l <= 0){
return sums[r];
}else{
return sums[r] - sums[l - 1];
}
}
public static void main(String [] args){
new Solution().solve();
}
} | quadratic | 1197_D. Yet Another Subarray Problem | CODEFORCES |
//package ContestEd69;
import java.io.*;
import java.util.StringTokenizer;
public class mainD {
public static PrintWriter out = new PrintWriter(System.out);
public static FastScanner enter = new FastScanner(System.in);
public static long[] arr;
public static void main(String[] args) throws IOException {
int n=enter.nextInt();
int m=enter.nextInt();
long k=enter.nextLong();
arr=new long[n+1];
for (int i = 1; i <n+1 ; i++) {
arr[i]=enter.nextLong();
}
long[] summ=new long[n+1];
for (int i = 1; i <n+1 ; i++) {
summ[i]+=arr[i]+summ[i-1];
}
long[] best=new long[n+1];
for (int i = 1; i <n+1 ; i++) {
best[i]=Math.max(0, ((i-m>=0) ? best[i-m]+summ[i]-summ[i-m]-k:0));
}
long ans=best[1];
for (int i = 1; i <n+1 ; i++) {
ans=Math.max(ans,best[i]);
for (int j = 1; j <m ; j++) {
ans=Math.max(ans, ((i-j>=0) ? best[i-j] -k +summ[i]-summ[i-j]:0));
}
}
System.out.println(ans);
}
static class FastScanner {
BufferedReader br;
StringTokenizer stok;
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return null;
}
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
char nextChar() throws IOException {
return (char) (br.read());
}
String nextLine() throws IOException {
return br.readLine();
}
}
}
| quadratic | 1197_D. Yet Another Subarray Problem | CODEFORCES |
//package goodbye2017;
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 G {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
char[] s = ns().toCharArray();
int mod = 1000000007;
int m = 702;
long[] bases = new long[m+1];
bases[0] = 1;
for(int i = 1;i <= m;i++)bases[i] = bases[i-1] * 10 % mod;
// 10*700^3*10
long ans = 0;
for(int d = 9;d >= 1;d--){
int n = s.length;
long[] sum = new long[m]; // base
long[] num = new long[m]; // base
long esum = 0;
int ebase = 0;
for(int i = 0;i < n;i++){
long[] nsum = new long[m]; // base
long[] nnum = new long[m]; // base
for(int j = 0;j < m;j++){
for(int k = 0;k <= 9;k++){
if(k > d && j+1 < m){
nsum[j+1] += sum[j] * 10;
nsum[j+1] %= mod;
nnum[j+1] += num[j];
if(nnum[j+1] >= mod)nnum[j+1] -= mod;
}
if(k == d){
nsum[j] += sum[j] * 10 + num[j] * bases[j];
nsum[j] %= mod;
nnum[j] += num[j];
if(nnum[j] >= mod)nnum[j] -= mod;
}
if(k < d){
nsum[j] += sum[j];
if(nsum[j] >= mod)nsum[j] -= mod;
nnum[j] += num[j];
if(nnum[j] >= mod)nnum[j] -= mod;
}
}
}
for(int k = 0;k < s[i]-'0';k++){
if(k > d){
nsum[ebase+1] += esum * 10;
nsum[ebase+1] %= mod;
nnum[ebase+1] += 1;
if(nnum[ebase+1] >= mod)nnum[ebase+1] -= mod;
}
if(k == d){
nsum[ebase] += esum * 10 + bases[ebase];
nsum[ebase] %= mod;
nnum[ebase] += 1;
if(nnum[ebase] >= mod)nnum[ebase] -= mod;
}
if(k < d){
nsum[ebase] += esum;
if(nsum[ebase] >= mod)nsum[ebase] -= mod;
nnum[ebase] += 1;
if(nnum[ebase] >= mod)nnum[ebase] -= mod;
}
}
if(s[i]-'0' > d){
esum = esum * 10;
esum %= mod;
ebase++;
}else if(s[i]-'0' == d){
esum = esum * 10 + bases[ebase];
esum %= mod;
}
sum = nsum;
num = nnum;
}
long all = esum;
for(int j = 0;j < m;j++){
all += sum[j];
}
ans += all % mod * d;
}
out.println(ans%mod);
}
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 G().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)); }
}
| quadratic | 908_G. New Year and Original Order | CODEFORCES |
import java.io.*;
import java.util.*;
public class MainG {
static StdIn in = new StdIn();
static PrintWriter out = new PrintWriter(System.out);
static long M=(long)1e9+7;
static int n, dig;
static int[] x;
static long[] p10, s;
static long[][][] dp;
public static void main(String[] args) {
char[] cs = in.next().toCharArray();
n=cs.length;
x = new int[n];
for(int i=0; i<n; ++i)
x[i]=cs[i]-'0';
p10 = new long[n];
p10[0]=1;
for(int i=1; i<n; ++i)
p10[i]=p10[i-1]*10%M;
s = new long[n+1];
s[n]=1;
for(int i=n-1; i>=0; --i)
s[i]=(s[i+1]+x[i]*p10[n-1-i])%M;
long ans=0;
dp = new long[2][n][n+1];
for(dig=1; dig<=9; ++dig) {
for(int i=0; i<n; ++i) {
Arrays.fill(dp[0][i], -1);
Arrays.fill(dp[1][i], -1);
}
for(int i=1; i<=n; ++i)
ans=(ans+p10[i-1]*dp(0, 0, i))%M;
}
out.println(ans);
out.close();
}
static long dp(int less, int ignore, int need) {
if(need==0)
return less==1?p10[n-ignore]:s[ignore];
if(ignore==n)
return 0;
if(dp[less][ignore][need]!=-1)
return dp[less][ignore][need];
long res=0;
int lim=less==1?9:x[ignore];
for(int i=0; i<=lim; ++i)
res=(res+dp(less|(i<lim?1:0), ignore+1, need-(i>=dig?1:0)))%M;
return dp[less][ignore][need]=res;
}
interface Input {
public String next();
public String nextLine();
public int nextInt();
public long nextLong();
public double nextDouble();
}
static class StdIn implements Input {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public StdIn() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public StdIn(InputStream in) {
try{
din = new DataInputStream(in);
} catch(Exception e) {
throw new RuntimeException();
}
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == ' ' || c == '\n'||c=='\r')
break;
s.append((char)c);
c=read();
}
return s.toString();
}
public String nextLine() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == '\n'||c=='\r')
break;
s.append((char)c);
c = read();
}
return s.toString();
}
public int nextInt() {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int n) {
int[] ar = new int[n];
for(int i=0; i<n; ++i)
ar[i]=nextInt();
return ar;
}
public long nextLong() {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long[] readLongArray(int n) {
long[] ar = new long[n];
for(int i=0; i<n; ++i)
ar[i]=nextLong();
return ar;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() {
try{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
} catch(IOException e) {
throw new RuntimeException();
}
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
} | quadratic | 908_G. New Year and Original Order | CODEFORCES |
import java.io.*;
import java.util.*;
public class G {
static final int P = 1_000_000_007;
int[][] ways;
int[][] pow;
void preCalc(int sz) {
ways = new int[sz][];
for (int i = 0; i < ways.length; i++) {
ways[i] = new int[i + 1];
ways[i][0] = ways[i][i] = 1;
for (int j = 1; j < i; j++) {
ways[i][j] = (ways[i - 1][j] + ways[i - 1][j - 1]) % P;
}
}
pow = new int[10][sz];
pow[0] = null;
for (int i = 1; i <= 9; i++) {
pow[i][0] = 1;
for (int j = 1; j < sz; j++) {
pow[i][j] = (int) ((long) pow[i][j - 1] * i % P);
}
}
}
int solve(String ss) {
int n = ss.length();
int[] s = new int[n];
for (int i = 0; i < n; i++) {
s[i] = ss.charAt(i) - '0';
}
preCalc(n + 10);
int[] ans = new int[n + 1];
int[] cnt = new int[10];
for (int i = 0; i < n; i++) {
int rest = n - i - 1;
int dig = s[i];
for (int j = 0; j <= (i == n - 1 ? dig : dig - 1); j++) {
cnt[j]++; // now we have one more digit >= j
for (int use = 1; use < 10; use++) {
// use digits are bad, 10 - use are good
for (int cntGood = 0; cntGood <= rest; cntGood++) {
int delta = (int) ((long) ways[rest][cntGood]
* pow[use][rest - cntGood] % P
* pow[10 - use][cntGood] % P);
int idx = cnt[use] + cntGood;
ans[idx] += delta;
if (ans[idx] >= P) {
ans[idx] -= P;
}
}
}
// System.err.println(Arrays.toString(ans));
}
cnt[dig]++;
}
int ret = 0;
long mult = 0;
for (int i = 1; i < ans.length; i++) {
mult = (10L * mult + 1) % P;
ret += (int)(mult * ans[i] % P);
if (ret >= P) {
ret -= P;
}
}
return ret;
}
void submit() {
out.println(solve(nextToken()));
}
void stress() {
}
void test() {
StringBuilder sb = new StringBuilder("1");
for (int i = 0; i < 700; i++) {
sb.append('0');
}
solve(sb.toString());
}
G() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
submit();
// stress();
// test();
out.close();
}
static final Random rng = new Random();
static int rand(int l, int r) {
return l + rng.nextInt(r - l + 1);
}
public static void main(String[] args) throws IOException {
new G();
}
BufferedReader br;
PrintWriter out;
StringTokenizer st;
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
| quadratic | 908_G. New Year and Original Order | CODEFORCES |
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.exit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class G {
static final int MOD = 1000000007;
static int add(int a, int b) {
int res = a + b;
return res >= MOD ? res - MOD : res;
}
static int sub(int a, int b) {
int res = a - b;
return res < 0 ? res + MOD : res;
}
static int mul(int a, int b) {
int res = (int) ((long) a * b % MOD);
return res < 0 ? res + MOD : res;
}
static int pow(int a, int e) {
if (e == 0) {
return 1;
}
int r = a;
for (int i = 30 - Integer.numberOfLeadingZeros(e); i >= 0; i--) {
r = mul(r, r);
if ((e & (1 << i)) != 0) {
r = mul(r, a);
}
}
return r;
}
static int inv(int a) {
return pow(a, MOD - 2);
}
static void solve() throws Exception {
String x = scanString();
// char xx[] = new char[700];
// fill(xx, '9');
// String x = new String(xx);
int n = x.length();
int pows[][] = new int[10][n];
for (int i = 0; i < 10; i++) {
pows[i][0] = 1;
for (int j = 1; j < n; j++) {
pows[i][j] = mul(pows[i][j - 1], i);
}
}
int ru[] = new int[n + 1];
for (int i = 1; i <= n; i++) {
ru[i] = add(1, mul(10, ru[i - 1]));
}
int facts[] = new int[n];
facts[0] = 1;
for (int i = 1; i < n; i++) {
facts[i] = mul(facts[i - 1], i);
}
int factsInv[] = new int[n];
factsInv[n - 1] = inv(facts[n - 1]);
for (int i = n - 1; i > 0; i--) {
factsInv[i - 1] = mul(factsInv[i], i);
}
int ans = 0;
int off[] = new int[10];
for (int i = 0; i < n; i++) {
int cd = x.charAt(i) - '0';
int l = n - i - 1;
for (int d = 1; d < 10; d++) {
for (int p = 0; p <= l; p++) {
int mul = d < cd ? add(mul(d, ru[p + off[d]]), mul(cd - d, ru[p + off[d] + 1])) : mul(cd, ru[p + off[d]]);
ans = add(ans, mul(mul, mul(mul(pows[d][l - p], pows[10 - d][p]), mul(facts[l], mul(factsInv[p], factsInv[l - p])))));
}
}
for (int d = 0; d <= cd; d++) {
++off[d];
}
}
for (int d = 1; d < 10; d++) {
ans = add(ans, ru[off[d]]);
}
out.print(ans);
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static String scanString() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
public static void main(String[] args) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
} | quadratic | 908_G. New Year and Original Order | CODEFORCES |
import java.io.*;
import java.util.*;
public class MainG {
static StdIn in = new StdIn();
static PrintWriter out = new PrintWriter(System.out);
static long M=(long)1e9+7;
static int n, dig;
static int[] x;
static long[] p10, s;
static long[][][] dp;
public static void main(String[] args) {
char[] cs = in.next().toCharArray();
n=cs.length;
x = new int[n];
for(int i=0; i<n; ++i)
x[i]=cs[i]-'0';
p10 = new long[n];
p10[0]=1;
for(int i=1; i<n; ++i)
p10[i]=p10[i-1]*10%M;
s = new long[n+1];
s[n]=1;
for(int i=n-1; i>=0; --i)
s[i]=(s[i+1]+x[i]*p10[n-1-i])%M;
long ans=0;
dp = new long[2][n][n+1];
for(dig=1; dig<=9; ++dig) {
for(int i=0; i<n; ++i) {
Arrays.fill(dp[0][i], -1);
Arrays.fill(dp[1][i], -1);
}
for(int i=1; i<=n; ++i)
ans=(ans+p10[i-1]*dp(0, 0, i))%M;
}
out.println(ans);
out.close();
}
static long dp(int less, int ignore, int need) {
if(need==0)
return less==1?p10[n-ignore]:s[ignore];
if(ignore==n)
return 0;
if(dp[less][ignore][need]!=-1)
return dp[less][ignore][need];
long res=0;
int lim=less==1?9:x[ignore];
for(int i=0; i<=lim; ++i)
res=(res+dp(less|(i<lim?1:0), ignore+1, need-(i>=dig?1:0)));
res%=M;
return dp[less][ignore][need]=res;
}
interface Input {
public String next();
public String nextLine();
public int nextInt();
public long nextLong();
public double nextDouble();
}
static class StdIn implements Input {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public StdIn() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public StdIn(InputStream in) {
try{
din = new DataInputStream(in);
} catch(Exception e) {
throw new RuntimeException();
}
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == ' ' || c == '\n'||c=='\r')
break;
s.append((char)c);
c=read();
}
return s.toString();
}
public String nextLine() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == '\n'||c=='\r')
break;
s.append((char)c);
c = read();
}
return s.toString();
}
public int nextInt() {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int n) {
int[] ar = new int[n];
for(int i=0; i<n; ++i)
ar[i]=nextInt();
return ar;
}
public long nextLong() {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long[] readLongArray(int n) {
long[] ar = new long[n];
for(int i=0; i<n; ++i)
ar[i]=nextLong();
return ar;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() {
try{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
} catch(IOException e) {
throw new RuntimeException();
}
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
} | quadratic | 908_G. New Year and Original Order | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
public class Main {
private static int REM = 1000000007;
private static int dig;
private static int[][][] dp = new int[701][701][2];
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String X = in.next();
int N = X.length();
int[] P = new int[701];
P[0] = 1;
for (int i=1; i<P.length; ++i) {
P[i] = (int)((long)P[i-1] * 10 % REM);
}
int ans = 0;
for (int d=1; d<=9; ++d) { //at least d
dig = d;
for (int[][] array2 : dp) {
for (int[] array1 : array2) {
Arrays.fill(array1, -1);
}
}
for (int c=1; c<=N; ++c) { //exact count of at least d
for (int k=0; k<c; ++k) {
ans = (int)((ans + (long)f(0, c, false, X) * P[k]) % REM);
}
}
}
System.out.println(ans);
}
private static int f(int ps, int needed, boolean less, final String X) {
if (needed < 0) {return 0;}
if (dp[ps][needed][less?0:1] != -1) {return dp[ps][needed][less?0:1];}
if (ps == X.length()) {
if (needed == 0) {return 1;}
return 0;
}
int dg = X.charAt(ps)-'0';
int ans = 0;
for (int d=0; d<=9; ++d) {
if (!less && d>dg) {continue;}
boolean nless = less || d < dg;
ans = (int)((ans + (long)f(ps+1, needed-(d>=dig?1:0), nless, X)) % REM);
}
dp[ps][needed][less?0:1] = ans;
return ans;
}
}
| quadratic | 908_G. New Year and Original Order | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jialin Ouyang ([email protected])
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskG solver = new TaskG();
solver.solve(1, in, out);
out.close();
}
static class TaskG {
static int MAXL = 700 + 1;
static IntModular MOD = new IntModular();
int n;
char[] digits;
int[] pow10;
int[] ones;
int[][][] way;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
digits = new char[MAXL];
n = in.next(digits);
initPow();
int res = MOD.mul(calc(9), 9);
for (int digit = 0; digit < 9; ++digit) {
res = MOD.sub(res, calc(digit));
}
out.println(res);
}
void initPow() {
pow10 = new int[n + 1];
ones = new int[n + 1];
pow10[0] = 1;
for (int i = 1; i <= n; ++i) {
pow10[i] = MOD.mul(pow10[i - 1], 10);
ones[i] = MOD.add(MOD.mul(ones[i - 1], 10), 1);
}
}
int calc(int targetDigit) {
if (way == null) {
way = new int[2][2][n + 1];
}
int t = 0;
clearCnt(t);
way[t][0][0] = 1;
for (int i = 0; i < n; ++i) {
int digit = digits[i] - '0';
clearCnt(t ^ 1);
// not free
for (int cnt = 0; cnt <= n; ++cnt)
if (way[t][0][cnt] > 0) {
// not free
int newCnt = targetDigit < digit ? cnt + 1 : cnt;
way[t ^ 1][0][newCnt] = MOD.add(
way[t ^ 1][0][newCnt],
way[t][0][cnt]);
// free
way[t ^ 1][1][cnt] = MOD.add(
way[t ^ 1][1][cnt],
MOD.mul(
Math.min(targetDigit + 1, digit),
way[t][0][cnt]));
way[t ^ 1][1][cnt + 1] = MOD.add(
way[t ^ 1][1][cnt + 1],
MOD.mul(
Math.max(digit - targetDigit - 1, 0),
way[t][0][cnt]));
}
// free
for (int cnt = 0; cnt <= n; ++cnt)
if (way[t][1][cnt] > 0) {
way[t ^ 1][1][cnt] = MOD.add(
way[t ^ 1][1][cnt],
MOD.mul(
targetDigit + 1,
way[t][1][cnt]));
way[t ^ 1][1][cnt + 1] = MOD.add(
way[t ^ 1][1][cnt + 1],
MOD.mul(
9 - targetDigit,
way[t][1][cnt]));
}
t ^= 1;
}
int res = 0;
for (int cnt = 0; cnt <= n; ++cnt) {
res = MOD.add(
res,
MOD.mul(MOD.mul(
ones[n - cnt],
pow10[cnt]),
MOD.add(way[t][0][cnt], way[t][1][cnt])));
}
return res;
}
void clearCnt(int t) {
for (int free = 0; free < 2; ++free) {
Arrays.fill(way[t][free], 0);
}
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; ++i) {
if (i > 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class IntModular {
private static final int MOD = 1000000007;
public final int mod;
private final int[] x;
public IntModular() {
this(MOD);
}
public IntModular(int mod) {
this.mod = mod;
this.x = new int[2];
}
public int add(int a, int b) {
return fix(a + b, mod);
}
public int sub(int a, int b) {
return fix(a - b, mod);
}
public int mul(int a, int b) {
return mul(a, b, mod);
}
public static int mul(int a, int b, int mod) {
return a > 0
? (b < mod / a ? a * b : (int) ((long) a * b % mod))
: 0;
}
public static int fix(int a, int mod) {
a = slightFix(a, mod);
return 0 <= a && a < mod ? a : slightFix(a % mod, mod);
}
private static int slightFix(int a, int mod) {
return a >= mod
? a - mod
: a < 0 ? a + mod : a;
}
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPosition;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPosition = 0;
this.numberOfChars = 0;
}
public int next(char[] s) {
return next(s, 0);
}
public int next(char[] s, int startIdx) {
int b = nextNonSpaceChar();
int res = 0;
do {
s[startIdx++] = (char) b;
b = nextChar();
++res;
} while (!isSpaceChar(b));
return res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPosition >= numberOfChars) {
currentPosition = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPosition++];
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\t' || isEndOfLineChar(c);
}
public boolean isEndOfLineChar(int c) {
return c == '\n' || c == '\r' || c < 0;
}
}
}
| quadratic | 908_G. New Year and Original Order | CODEFORCES |
import java.io.*;
import java.util.*;
public class CF {
private FastScanner in;
private PrintWriter out;
final int mod = (int) 1e9 + 7;
private long f(String s, int digit) {
final int n = s.length();
int[][] dp = new int[2][n + 1]; // [less][cntBigger] -> sum
dp[0][0] = 1;
int[][] ndp = new int[2][n + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2; j++) {
Arrays.fill(ndp[j], 0);
}
for (int less = 0; less < 2; less++) {
for (int cntBigger = 0; cntBigger <= n; cntBigger++) {
int cur = dp[less][cntBigger];
if (cur == 0) {
continue;
}
int max = less == 1 ? 9 : (s.charAt(i) - '0');
for (int next = 0; next <= max; next++) {
int nextLess = (less == 1) || (next < max) ? 1 : 0;
int nextCntBigger = cntBigger + ((next >= digit) ? 1 : 0);
ndp[nextLess][nextCntBigger] += cur;
while (ndp[nextLess][nextCntBigger] >= mod) {
ndp[nextLess][nextCntBigger] -= mod;
}
}
}
}
int[][] tmp = dp;
dp = ndp;
ndp = tmp;
}
long result = 0;
for (int less = 0; less < 2; less++) {
long sum = 0;
for (int cntBigger = 1; cntBigger <= n; cntBigger++) {
sum = (sum * 10 + 1) % mod;
result = (result + sum * dp[less][cntBigger]) % mod;
}
}
return result % mod;
}
private void solve() {
final String number = in.next();
long result = 0;
for (int digit = 1; digit < 10; digit++) {
long cur = f(number, digit);
result += cur;
}
out.println(result % mod);
}
private void run() {
try {
in = new FastScanner(new File("CF.in"));
out = new PrintWriter(new File("CF.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
private class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new CF().runIO();
}
} | quadratic | 908_G. New Year and Original Order | CODEFORCES |
import java.io.*;
import java.util.*;
public class cf908G {
final static int MOD = 1_000_000_007;
public static void main(String[] argv) {
cf908G pro = new cf908G();
InputStream fin = null;
if (System.getProperty("ONLINE_JUDGE") == null) {
try {
fin = new FileInputStream("input.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
fin = System.in;
}
pro.solve(new Scanner(fin), System.out);
}
private void solve(Scanner scanner, PrintStream out) {
long ans = 0;
String X = scanner.next();
for (int x = 0; x < 9; x++) {
ans = (ans + solve2(x, X)) % MOD;
}
out.println((ans % MOD + MOD) % MOD);
}
private long solve2(int x, String X) {
int[][][] f = new int[X.length() + 1][X.length() + 1][2];
f[0][0][1] = 1;
int n = X.length();
for (int i = 0; i < n; i++) {
for (int j = 0; j <= n; j++) {
for (int u = 0; u < 2; u++) {
int val = f[i][j][u];
if (val == 0) continue;
for (int num = 0; num < 10; num++) {
int Xi = X.charAt(i) - '0';
if (u == 1 && num > Xi) break;
int _i = i + 1;
int _j = num <= x ? j + 1 : j;
int _u = u == 1 && num == Xi ? 1 : 0;
f[_i][_j][_u] = (f[_i][_j][_u] + val) % MOD;
}
}
}
}
long base = 1;
long ret = 0;
for (int i = n; i > 0; i--) {
long t = 0;
for (int j = 0; j < i; j++) {
t = (t + f[n][j][0] + f[n][j][1]) % MOD;
}
ret = (ret + base * t) % MOD;
base = (base * 10) % MOD;
}
return ret;
}
} | quadratic | 908_G. New Year and Original Order | CODEFORCES |
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.atomic.AtomicIntegerArray;
public class Solution {
public static void main(String[] args) throws Exception {
MyReader reader = new MyReader(System.in);
// MyReader reader = new MyReader(new FileInputStream("input.txt"));
MyWriter writer = new MyWriter(System.out);
new Solution().run(reader, writer);
writer.close();
}
private void run(MyReader reader, MyWriter writer) throws Exception {
char[] c = reader.nextCharArray();
int n = c.length;
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = c[i] - '0';
}
long mod = 1_000_000_007;
long[] p = new long[n + 1];
long[] s = new long[n + 1];
p[0] = 1;
for (int i = 1; i <= n; i++) {
p[i] = p[i - 1] * 10 % mod;
}
s[n] = 1;
for (int i = n - 1; i >= 0; i--) {
s[i] = (p[n - i - 1] * x[i] + s[i + 1]) % mod;
}
long[][][] d = new long[n + 1][n + 1][2];
long ans = 0;
for (int i = 1; i < 10; i++) {
for (long[][] q : d) {
for (long[] w : q) {
Arrays.fill(w, 0);
}
}
for (int j = 0; j <= n; j++) {
d[j][0][0] = s[j];
d[j][0][1] = p[n - j];
}
for (int j = n - 1; j >= 0; j--) {
for (int k = 1; k <= n; k++) {
for (int l = 1; l >= 0; l--) {
int lim = l == 1 ? 10 : x[j] + 1;
for (int m = 0; m < lim; m++) {
d[j][k][l] += d[j + 1][k - (m >= i ? 1 : 0)][l == 1 || m < x[j] ? 1 : 0];
d[j][k][l] %= mod;
}
}
if (j == 0) {
ans = (ans + p[k - 1] * d[0][k][0]) % mod;
}
}
}
}
System.out.println(ans);
}
static class MyReader {
final BufferedInputStream in;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = bufSize;
int k = bufSize;
boolean end = false;
final StringBuilder str = new StringBuilder();
MyReader(InputStream in) {
this.in = new BufferedInputStream(in, bufSize);
}
int nextInt() throws IOException {
return (int) nextLong();
}
int[] nextIntArray(int n) throws IOException {
int[] m = new int[n];
for (int i = 0; i < n; i++) {
m[i] = nextInt();
}
return m;
}
int[][] nextIntMatrix(int n, int m) throws IOException {
int[][] a = new int[n][0];
for (int j = 0; j < n; j++) {
a[j] = nextIntArray(m);
}
return a;
}
long nextLong() throws IOException {
int c;
long x = 0;
boolean sign = true;
while ((c = nextChar()) <= 32) ;
if (c == '-') {
sign = false;
c = nextChar();
}
if (c == '+') {
c = nextChar();
}
while (c >= '0') {
x = x * 10 + (c - '0');
c = nextChar();
}
return sign ? x : -x;
}
long[] nextLongArray(int n) throws IOException {
long[] m = new long[n];
for (int i = 0; i < n; i++) {
m[i] = nextLong();
}
return m;
}
int nextChar() throws IOException {
if (i == k) {
k = in.read(buf, 0, bufSize);
i = 0;
}
return i >= k ? -1 : buf[i++];
}
String nextString() throws IOException {
if (end) {
return null;
}
str.setLength(0);
int c;
while ((c = nextChar()) <= 32 && c != -1) ;
if (c == -1) {
end = true;
return null;
}
while (c > 32) {
str.append((char) c);
c = nextChar();
}
return str.toString();
}
String nextLine() throws IOException {
if (end) {
return null;
}
str.setLength(0);
int c = nextChar();
while (c != '\n' && c != '\r' && c != -1) {
str.append((char) c);
c = nextChar();
}
if (c == -1) {
end = true;
if (str.length() == 0) {
return null;
}
}
if (c == '\r') {
nextChar();
}
return str.toString();
}
char[] nextCharArray() throws IOException {
return nextString().toCharArray();
}
char[][] nextCharMatrix(int n) throws IOException {
char[][] a = new char[n][0];
for (int i = 0; i < n; i++) {
a[i] = nextCharArray();
}
return a;
}
}
static class MyWriter {
final BufferedOutputStream out;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = 0;
final byte c[] = new byte[30];
static final String newLine = System.getProperty("line.separator");
MyWriter(OutputStream out) {
this.out = new BufferedOutputStream(out, bufSize);
}
void print(long x) throws IOException {
int j = 0;
if (i + 30 >= bufSize) {
flush();
}
if (x < 0) {
buf[i++] = (byte) ('-');
x = -x;
}
while (j == 0 || x != 0) {
c[j++] = (byte) (x % 10 + '0');
x /= 10;
}
while (j-- > 0)
buf[i++] = c[j];
}
void print(int[] m) throws IOException {
for (int a : m) {
print(a);
print(' ');
}
}
void print(long[] m) throws IOException {
for (long a : m) {
print(a);
print(' ');
}
}
void print(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
print(s.charAt(i));
}
}
void print(char x) throws IOException {
if (i == bufSize) {
flush();
}
buf[i++] = (byte) x;
}
void print(char[] m) throws IOException {
for (char c : m) {
print(c);
}
}
void println(String s) throws IOException {
print(s);
println();
}
void println() throws IOException {
print(newLine);
}
void flush() throws IOException {
out.write(buf, 0, i);
out.flush();
i = 0;
}
void close() throws IOException {
flush();
out.close();
}
}
} | quadratic | 908_G. New Year and Original Order | CODEFORCES |
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
*/
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);
TaskG solver = new TaskG();
solver.solve(1, in, out);
out.close();
}
static class TaskG {
static final long MODULO = (long) (1e9 + 7);
public void solve(int testNumber, InputReader in, PrintWriter out) {
String x = in.next();
int[][] comb = new int[x.length() + 2][x.length() + 2];
comb[0][0] = 1;
for (int i = 1; i < comb.length; ++i) {
comb[i][0] = 1;
for (int j = 1; j < comb.length; ++j) {
comb[i][j] = (comb[i - 1][j - 1] + comb[i - 1][j]) % (int) MODULO;
}
}
int[][] pow = new int[11][x.length() + 2];
for (int i = 0; i < pow.length; ++i) {
pow[i][0] = 1;
for (int j = 1; j < pow[i].length; ++j) {
pow[i][j] = (int) (i * (long) pow[i][j - 1] % MODULO);
}
}
int[] oneSum = new int[x.length() + 2];
for (int i = 1; i < oneSum.length; ++i) {
oneSum[i] = (int) ((10 * (long) oneSum[i - 1] + 1) % MODULO);
}
int[][] s1 = new int[10][x.length() + 1];
int[][] s2 = new int[10][x.length() + 1];
for (int what = 1; what <= 9; ++what) {
for (int max = 0; max <= x.length(); ++max) {
long sum1 = 0;
long sum2 = 0;
for (int equalExtra = 0; equalExtra <= max; ++equalExtra) {
long cways = 1;
cways *= comb[max][equalExtra];
cways %= MODULO;
cways *= pow[what][max - equalExtra];
cways %= MODULO;
sum1 += cways * oneSum[equalExtra];
sum1 %= MODULO;
sum2 += cways;
sum2 %= MODULO;
}
s1[what][max] = (int) sum1;
s2[what][max] = (int) sum2;
}
}
int[] sofar = new int[10];
long res = 0;
for (int firstLess = 0; firstLess < x.length(); ++firstLess) {
int min = 0;
int max = x.charAt(firstLess) - '0';
if (firstLess < x.length() - 1) --max;
for (int dig = min; dig <= max; ++dig) {
++sofar[dig];
int totalSofar = firstLess + 1;
int sofarBigger = 0;
for (int what = 9; what >= 1; --what) {
int sofarThisOrLess = totalSofar - sofarBigger;
int sofarThis = sofar[what];
int sofarLess = sofarThisOrLess - sofarThis;
for (int bigger = sofarBigger; bigger + sofarThisOrLess <= x.length(); ++bigger) {
long ways = comb[x.length() - totalSofar][bigger - sofarBigger];
ways *= pow[9 - what][bigger - sofarBigger];
ways %= MODULO;
long sum1 = s1[what][x.length() - bigger - sofarThisOrLess];
long sum2 = s2[what][x.length() - bigger - sofarThisOrLess];
long sum = (sum1 * (long) pow[10][sofarThis] + sum2 * oneSum[sofarThis]) % MODULO;
sum *= pow[10][bigger];
sum %= MODULO;
res = (res + sum * ways % MODULO * what) % MODULO;
}
sofarBigger += sofarThis;
}
--sofar[dig];
}
++sofar[x.charAt(firstLess) - '0'];
}
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();
}
}
}
| quadratic | 908_G. New Year and Original Order | CODEFORCES |
import java.io.*;
import java.util.*;
public class MainG {
static StdIn in = new StdIn();
static PrintWriter out = new PrintWriter(System.out);
static long M=(long)1e9+7;
public static void main(String[] args) {
char[] cs = in.next().toCharArray();
int n=cs.length;
int[] x = new int[n];
for(int i=0; i<n; ++i)
x[i]=cs[i]-'0';
long[] dp1 = new long[n+1];
for(int i=0; i<n; ++i)
dp1[i+1]=(x[i]+dp1[i]*10)%M;
long ans=0;
for(int d1=1; d1<=9; ++d1) {
long[][] dp2 = new long[2][n+1];
for(int i=0; i<n; ++i) {
dp2[0][i+1]=x[i]>=d1?(10*dp2[0][i]+1)%M:dp2[0][i];
for(int d2=0; d2<x[i]; ++d2)
dp2[1][i+1]=((d2>=d1?10*(dp2[0][i]+dp2[1][i])+dp1[i]+1:dp2[0][i]+dp2[1][i])+dp2[1][i+1])%M;
for(int d2=x[i]; d2<=9; ++d2)
dp2[1][i+1]=((d2>=d1?10*dp2[1][i]+dp1[i]:dp2[1][i])+dp2[1][i+1])%M;
}
ans+=dp2[0][n]+dp2[1][n];
}
out.println(ans%M);
out.close();
}
interface Input {
public String next();
public String nextLine();
public int nextInt();
public long nextLong();
public double nextDouble();
}
static class StdIn implements Input {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public StdIn() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public StdIn(InputStream in) {
try{
din = new DataInputStream(in);
} catch(Exception e) {
throw new RuntimeException();
}
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == ' ' || c == '\n'||c=='\r')
break;
s.append((char)c);
c=read();
}
return s.toString();
}
public String nextLine() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == '\n'||c=='\r')
break;
s.append((char)c);
c = read();
}
return s.toString();
}
public int nextInt() {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int n) {
int[] ar = new int[n];
for(int i=0; i<n; ++i)
ar[i]=nextInt();
return ar;
}
public long nextLong() {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long[] readLongArray(int n) {
long[] ar = new long[n];
for(int i=0; i<n; ++i)
ar[i]=nextLong();
return ar;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() {
try{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
} catch(IOException e) {
throw new RuntimeException();
}
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
} | quadratic | 908_G. New Year and Original Order | CODEFORCES |
import java.io.*;
import java.util.*;
public class MainG {
static StdIn in = new StdIn();
static PrintWriter out = new PrintWriter(System.out);
static long M=(long)1e9+7;
public static void main(String[] args) {
char[] cs = in.next().toCharArray();
int n=cs.length;
int[] x = new int[n];
for(int i=0; i<n; ++i)
x[i]=cs[i]-'0';
long[] dp1 = new long[n+1];
for(int i=0; i<n; ++i)
dp1[i+1]=(x[i]+dp1[i]*10)%M;
//out.println(Arrays.toString(dp1));
long ans=0;
for(int d1=1; d1<=9; ++d1) {
long[][] dp2 = new long[2][n+1];
for(int i=0; i<n; ++i) {
dp2[0][i+1]=x[i]>=d1?(10*dp2[0][i]+1)%M:dp2[0][i];
dp2[1][i+1]=x[i]>=d1?(10*dp2[1][i]+dp1[i])%M:dp2[1][i];
for(int d2=0; d2<x[i]; ++d2)
dp2[1][i+1]=((d2>=d1?10*(dp2[0][i]+dp2[1][i])+dp1[i]+1:dp2[0][i]+dp2[1][i])+dp2[1][i+1])%M;
for(int d2=x[i]+1; d2<=9; ++d2)
dp2[1][i+1]=((d2>=d1?10*dp2[1][i]+dp1[i]:dp2[1][i])+dp2[1][i+1])%M;
}
ans+=dp2[0][n]+dp2[1][n];
//out.println(dp2[0][n]+" "+dp2[1][n]);
}
out.println(ans%M);
out.close();
}
interface Input {
public String next();
public String nextLine();
public int nextInt();
public long nextLong();
public double nextDouble();
}
static class StdIn implements Input {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public StdIn() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public StdIn(InputStream in) {
try{
din = new DataInputStream(in);
} catch(Exception e) {
throw new RuntimeException();
}
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == ' ' || c == '\n'||c=='\r')
break;
s.append((char)c);
c=read();
}
return s.toString();
}
public String nextLine() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == '\n'||c=='\r')
break;
s.append((char)c);
c = read();
}
return s.toString();
}
public int nextInt() {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int n) {
int[] ar = new int[n];
for(int i=0; i<n; ++i)
ar[i]=nextInt();
return ar;
}
public long nextLong() {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long[] readLongArray(int n) {
long[] ar = new long[n];
for(int i=0; i<n; ++i)
ar[i]=nextLong();
return ar;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() {
try{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
} catch(IOException e) {
throw new RuntimeException();
}
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
} | quadratic | 908_G. New Year and Original Order | CODEFORCES |
import java.util.Arrays;
public class Main {
private static void solve() {
int n = ni();
String[] lines = new String[n];
for(int i = 0; i < n; i ++) {
lines[i] = next();
}
int mod = 1000000000 + 7;
long[][] dp = new long[2][n + 1];
dp[0][0] = 1;
for (int i = 0; i < n; i ++) {
int from = i % 2;
int to = (i + 1) % 2;
boolean flg = i == 0 || lines[i - 1].equals("s");
if (flg) {
long v = Arrays.stream(dp[from]).sum();
for (int j = 0; j <= n; j ++) {
dp[to][j] += v;
dp[to][j] %= mod;
v -= dp[from][j];
}
} else {
for (int j = 0; j < n; j ++) {
dp[to][j + 1] += dp[from][j];
dp[to][j + 1] %= mod;
}
}
Arrays.fill(dp[from], 0);
}
long ret = Arrays.stream(dp[n % 2]).sum() % mod;
System.out.println(ret);
}
public static void main(String[] args) {
new Thread(null, new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
String debug = args.length > 0 ? args[0] : null;
if (debug != null) {
try {
is = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(debug));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
reader = new java.io.BufferedReader(new java.io.InputStreamReader(is), 32768);
solve();
out.flush();
tr((System.currentTimeMillis() - start) + "ms");
}
}, "", 64000000).start();
}
private static java.io.InputStream is = System.in;
private static java.io.PrintWriter out = new java.io.PrintWriter(System.out);
private static java.util.StringTokenizer tokenizer = null;
private static java.io.BufferedReader reader;
public static String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new java.util.StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
private static double nd() {
return Double.parseDouble(next());
}
private static long nl() {
return Long.parseLong(next());
}
private static int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private static char[] ns() {
return next().toCharArray();
}
private static long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private static int[][] ntable(int n, int m) {
int[][] table = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[i][j] = ni();
}
}
return table;
}
private static int[][] nlist(int n, int m) {
int[][] table = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[j][i] = ni();
}
}
return table;
}
private static int ni() {
return Integer.parseInt(next());
}
private static void tr(Object... o) {
if (is != System.in)
System.out.println(java.util.Arrays.deepToString(o));
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class C {
static final long MOD = 1_000_000_007;
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
long[][] dp = new long[N][N];
dp[0][0] = 1L;
for(int i = 0; i < N-1; i++) {
char oper = sc.next().charAt(0);
if(oper == 'f') {
dp[i+1][0] = 0L;
for(int j = 1; j < N; j++) {
dp[i+1][j] = dp[i][j-1];
}
}
else {
dp[i+1][N-1] = dp[i][N-1];
for(int j = N-2; j >= 0; j--) {
dp[i+1][j] = (dp[i+1][j+1] + dp[i][j]) % MOD;
}
}
}
long res = 0;
for(int i = 0; i < N; i++) {
res += dp[N-1][i];
res %= MOD;
}
out.println(res);
out.flush();
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args){
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
n = scan.nextInt(); mod = (int)1e9+7;
in = new char[n];
for(int i = 0; i < n; i++) in[i] = scan.next().charAt(0);
dp = new Long[n][n];
out.println(go(0, 0));
out.close();
}
static long go(int at, int i) {
if(at == n-1) return 1;
if(dp[at][i] != null) return dp[at][i];
long res = 0;
if(in[at] == 's') {
res += go(at+1, i);
res %= mod;
if(i > 0) {
res += go(at, i-1);
res %= mod;
}
} else {
res += go(at+1, i+1);
res %= mod;
}
return dp[at][i] = res;
}
static Long[][] dp;
static int n, mod;
static char[] in;
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n){
long[] a = new long[n];
for(int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public double[] nextDoubleArray(int n){
double[] a = new double[n];
for(int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public char[][] nextGrid(int n, int m){
char[][] grid = new char[n][m];
for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
return grid;
}
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.* ;
public class PythonIndentation
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in) ;
int n = in.nextInt() ;
boolean[] lst = new boolean[n] ;
for(int i=0;i<n;i++)
{
lst[i] = (in.next().equals("s"))?false:true ;
}
System.out.println(dp(lst)) ;
}
static void arrayPrinter(int[][] dp)
{
System.out.println(":::") ;
for(int i=0;i<dp.length;i++)
{
for(int j=0;j<dp[0].length;j++)
{
System.out.print(dp[i][j]+" ") ;
}
System.out.println() ;
}
}
static int dp(boolean[] lst)
{//false in lst means an "s" (simple statement), and true a "f"(for loop)
int[][] dp = new int[2][lst.length] ;
dp[0][0] = 1 ;
for(int i=1;i<lst.length;i++)
{
// arrayPrinter(dp) ;
for(int j=0;j<lst.length;j++)
{
if(lst[i-1])//(i-1)st statement is a for loop
{
if(j==0)
dp[i%2][j] = 0 ;
else
dp[i%2][j] = dp[(i-1)%2][j-1] ;
}
else//i-1 st statement is a simple statement
{
if(j==0)
{
int temp = 0 ;
for(int k=0;k<lst.length;k++)
temp = (temp+dp[(i-1)%2][k])%1000000007 ;
dp[i%2][j] = temp ;
}
else
dp[i%2][j] = (dp[i%2][j-1]-dp[(i-1)%2][j-1])%1000000007 ;
}
}
}
int ans = 0 ;
for(int i=0;i<lst.length;i++)
{
ans = (ans + dp[(lst.length-1)%2][i])%1000000007 ;
}
if(ans<0)
ans = ans + 1000000007 ;
// arrayPrinter(dp) ;
return ans ;
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.*;
import java.util.*;
public final class PythonIndentation
{
public static void main(String[] args)
{
new PythonIndentation(System.in, System.out);
}
static class Solver implements Runnable
{
static final int MOD = (int) 1e9 + 7;
int n;
char[] arr;
long[][] dp;
BufferedReader in;
PrintWriter out;
void solve() throws IOException
{
n = Integer.parseInt(in.readLine());
arr = new char[n];
dp = new long[n + 1][n + 1];
for (int i = 0; i < n; i++)
arr[i] = in.readLine().charAt(0);
for (int i = 0; i <= n; i++)
Arrays.fill(dp[i], -1);
dp[0][0] = 1;
if (arr[0] == 's')
out.println(find(1, 0));
else
out.println(find(1, 1));
/* System.out.println("dp :");
for (int i = 0; i <= n; i++)
{
System.out.print("i : " + i + " => ");
for (int j = 0; j <= n; j++)
System.out.print(dp[i][j] + " ");
System.out.println();
}*/
}
long find(int curr, int backIndents)
{
// System.out.println("curr : " + curr + ", bI : " + backIndents);
if (backIndents < 0)
return 0;
if (curr == n)
return dp[curr][backIndents] = 1;
if (dp[curr][backIndents] != -1)
return dp[curr][backIndents];
long ans;
if (arr[curr] == 's')
{
if (arr[curr - 1] == 'f')
ans = find(curr + 1, backIndents);
else
ans = CMath.mod(find(curr + 1, backIndents) + find(curr, backIndents - 1), MOD);
}
else
{
ans = find(curr + 1, backIndents + 1);
if (arr[curr - 1] != 'f')
{
// System.out.println("calling from curr : " + curr + ", bI : " + backIndents);
ans = CMath.mod(ans + find(curr, backIndents - 1), MOD);
}
}
return dp[curr][backIndents] = ans;
}
public Solver(BufferedReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
@Override public void run()
{
try
{
solve();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
static class CMath
{
static long mod(long number, long mod)
{
return number - (number / mod) * mod;
}
}
private PythonIndentation(InputStream inputStream, OutputStream outputStream)
{
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
PrintWriter out = new PrintWriter(outputStream);
Thread thread = new Thread(null, new Solver(in, out), "PythonIndentation", 1 << 29);
try
{
thread.start();
thread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
out.flush();
out.close();
}
}
}
/*
6
f
f
s
s
s
s
: 10
*/
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.* ;
import java.io.* ;
public class PythonIndentation
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in) ;
int n = in.nextInt() ;
boolean[] lst = new boolean[n] ;
for(int i=0;i<n;i++)
{
lst[i] = (in.next().equals("s"))?false:true ;
}
System.out.println(dp(lst)) ;
}
// static void arrayPrinter(int[][] dp)
// {
// System.out.println(":::") ;
// for(int i=0;i<dp.length;i++)
// {
// for(int j=0;j<dp[0].length;j++)
// {
// System.out.print(dp[i][j]+" ") ;
// }
// System.out.println() ;
// }
// }
static long dp(boolean[] lst)
{//false in lst means an "s" (simple statement), and true a "f"(for loop)
long[][] dp = new long[lst.length][lst.length] ;
dp[0][0] = 1 ;
for(int i=1;i<lst.length;i++)
{
// int sum_i = 0;
// for(int j=0;j<lst.length;j++)
// sum_i = (sum_i+dp[i-1][j])%1000000007 ;
for(int j=0;j<lst.length;j++)
{
if(lst[i-1])//(i-1)st statement is a for loop
{
if(j==0)
dp[i][j] = 0 ;
else
dp[i][j] = dp[i-1][j-1] ;
}
else//i-1 st statement is a simple statement
{
if(j==0)
{
for(int k=0;k<lst.length;k++)
dp[i][j] = (dp[i][j]+dp[i-1][k])%1000000007 ;
}
else
dp[i][j] = (dp[i][j-1]-dp[i-1][j-1])%1000000007 ;
// if(j==lst.length-1)
// dp[i][j] = dp[i][j-1] ;
// else
// dp[i][j] = (dp[i-1][j]+dp[i][j+1])%1000000007 ;
}
}
}
// for(int i=0;i<lst.length;i++)
// System.out.print(dp[lst.length-1][i]+" ") ;
// System.out.println() ;
long ans = 0 ;
for(int i=0;i<lst.length;i++)
{
ans = (ans + dp[lst.length-1][i])%1000000007 ;
}
if(ans<0)
ans = ans + 1000000007 ;
return ans ;
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
public class Test {
int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
final int N = 5010;
final int M = 1_000_000_007;
long[][] dp = new long[2][N];
long[] sums = new long[N];
char[] p = new char[N];
Scanner sca = new Scanner(System.in);
void start() {
int n = Integer.parseInt(sca.nextLine());
int idx = 0;
Arrays.fill(dp[idx], 0);
dp[idx][0] = 1;
for (int i = 0; i < n; i++) p[i] = sca.nextLine().charAt(0);
for (int i = 0; i < n;) {
int nidx = idx ^ 1;
Arrays.fill(dp[nidx], 0);
Arrays.fill(sums, 0);
int j = i;
while (p[j] != 's') j++;
int levels = j - i;
i = j+1;
for (j = n; j >= 0; j--) {
sums[j] = sums[j + 1] + dp[idx][j];
if (sums[j] >= M) sums[j] -= M;
}
for (j = 0; j <= n; j++) {
int ind = j + levels;
if (ind > n) continue;
dp[nidx][ind] = sums[j];
}
idx = nidx;
}
long ans = 0;
for (int i = 0; i <= n; i++) {
ans += dp[idx][i];
if (ans >= M) ans -=M;
}
System.out.println(ans);
}
public static void main(String[] args) {
new Test().start();
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
/*
* PDPM IIITDM Jabalpur
* Asutosh Rana
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
long MOD = 1000000007;
InputReader in;
BufferedReader br;
PrintWriter out;
public static void main(String[] args) throws java.lang.Exception {
Main solver = new Main();
solver.in = new InputReader(System.in);
solver.br = new BufferedReader(new InputStreamReader(System.in));
solver.out = new PrintWriter(System.out);
solver.solve();
solver.out.flush();
solver.out.close();
}
int[] A;
int N;
public void solve() {
int tc = 1;//in.readInt();
for (int cas = 1; cas <= tc; cas++) {
N = in.readInt();
A = new int[N];
for(int i =0;i<A.length;i++){
String str = in.readString();
if(str.equals("f"))
A[i] = 1;
}
long[][] dp = new long[N+1][N+1];
for(int i=0;i<N;i++){
if(i==0){
dp[i][0] = 1;
}
else if(A[i-1]!=1){
dp[i][N] = dp[i-1][N];
for(int j=N-1;j>=0;j--){
/* sum of all positions from */
dp[i][j] = (dp[i-1][j] + dp[i][j+1])%MOD;
}
}
else{
for(int j=1;j<=N;j++){
dp[i][j] = dp[i-1][j-1]%MOD;
}
}
}
long res = 0;
for(int i=0;i<=N;i++){
res = (res + dp[N-1][i])%MOD;
}
out.println(res);
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public void readInt(int[] A) {
for (int i = 0; i < A.length; i++)
A[i] = readInt();
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public void readLong(long[] A) {
for (int i = 0; i < A.length; i++)
A[i] = readLong();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public char[] readCharA() {
return readString().toCharArray();
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.*;
import java.util.*;
public class CC {
public static void main(String[] args)throws Throwable {
MyScanner sc=new MyScanner();
PrintWriter pw=new PrintWriter(System.out);
n=sc.nextInt();
s=new char [n];
for(int i=0;i<n;i++)
s[i]=sc.next().charAt(0);
mem=new int [2*n+1][n+1];
for(int [] x : mem)
Arrays.fill(x, -1);
pw.println(dp(0, 0));
pw.flush();
pw.close();
}
static int n;
static char [] s;
static int [][] mem;
static int dp(int i,int j){
if(i==n)
return j==0? 1 : 0;
if(mem[i][j]!=-1)
return mem[i][j];
int ans=0;
if(s[i]=='f'){
ans+=dp(i+1, j+1);
ans%=mod;
}else{
ans+=dp(i+1, j);
ans%=mod;
if(j>0){
ans+=dp(i, j-1);
ans%=mod;
}
}
return mem[i][j]=ans;
}
static int mod=(int)(1e9+7);
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {e.printStackTrace();}}
return st.nextToken();}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
String nextLine(){String str = "";
try {str = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return str;}
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class C_455
{
public static final long[] POWER2 = generatePOWER2();
public static final IteratorBuffer<Long> ITERATOR_BUFFER_PRIME = new IteratorBuffer<>(streamPrime(1000000).iterator());
private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer stringTokenizer = null;
private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static class Array<Type> implements Iterable<Type>
{
private final Object[] array;
public Array(int size)
{
this.array = new Object[size];
}
public Array(int size, Type element)
{
this(size);
Arrays.fill(this.array, element);
}
public Array(Array<Type> array, Type element)
{
this(array.size() + 1);
for (int index = 0; index < array.size(); index++)
{
set(index, array.get(index));
}
set(size() - 1, element);
}
public Array(List<Type> list)
{
this(list.size());
int index = 0;
for (Type element : list)
{
set(index, element);
index += 1;
}
}
public Type get(int index)
{
return (Type) this.array[index];
}
@Override
public Iterator<Type> iterator()
{
return new Iterator<Type>()
{
int index = 0;
@Override
public boolean hasNext()
{
return this.index < size();
}
@Override
public Type next()
{
Type result = Array.this.get(index);
index += 1;
return result;
}
};
}
public Array set(int index, Type value)
{
this.array[index] = value;
return this;
}
public int size()
{
return this.array.length;
}
public List<Type> toList()
{
List<Type> result = new ArrayList<>();
for (Type element : this)
{
result.add(element);
}
return result;
}
@Override
public String toString()
{
return "[" + C_455.toString(this, ", ") + "]";
}
}
static class BIT
{
private static int lastBit(int index)
{
return index & -index;
}
private final long[] tree;
public BIT(int size)
{
this.tree = new long[size];
}
public void add(int index, long delta)
{
index += 1;
while (index <= this.tree.length)
{
tree[index - 1] += delta;
index += lastBit(index);
}
}
public long prefix(int end)
{
long result = 0;
while (end > 0)
{
result += this.tree[end - 1];
end -= lastBit(end);
}
return result;
}
public int size()
{
return this.tree.length;
}
public long sum(int start, int end)
{
return prefix(end) - prefix(start);
}
}
static abstract class Edge<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>>
{
public final TypeVertex vertex0;
public final TypeVertex vertex1;
public final boolean bidirectional;
public Edge(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
{
this.vertex0 = vertex0;
this.vertex1 = vertex1;
this.bidirectional = bidirectional;
this.vertex0.edges.add(getThis());
if (this.bidirectional)
{
this.vertex1.edges.add(getThis());
}
}
public abstract TypeEdge getThis();
public TypeVertex other(Vertex<TypeVertex, TypeEdge> vertex)
{
TypeVertex result;
if (vertex0 == vertex)
{
result = vertex1;
}
else
{
result = vertex0;
}
return result;
}
public void remove()
{
this.vertex0.edges.remove(getThis());
if (this.bidirectional)
{
this.vertex1.edges.remove(getThis());
}
}
@Override
public String toString()
{
return this.vertex0 + "->" + this.vertex1;
}
}
public static class EdgeDefault<TypeVertex extends Vertex<TypeVertex, EdgeDefault<TypeVertex>>> extends Edge<TypeVertex, EdgeDefault<TypeVertex>>
{
public EdgeDefault(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
{
super(vertex0, vertex1, bidirectional);
}
@Override
public EdgeDefault<TypeVertex> getThis()
{
return this;
}
}
public static class EdgeDefaultDefault extends Edge<VertexDefaultDefault, EdgeDefaultDefault>
{
public EdgeDefaultDefault(VertexDefaultDefault vertex0, VertexDefaultDefault vertex1, boolean bidirectional)
{
super(vertex0, vertex1, bidirectional);
}
@Override
public EdgeDefaultDefault getThis()
{
return this;
}
}
public static class FIFO<Type>
{
public SingleLinkedList<Type> start;
public SingleLinkedList<Type> end;
public FIFO()
{
this.start = null;
this.end = null;
}
public boolean isEmpty()
{
return this.start == null;
}
public Type peek()
{
return this.start.element;
}
public Type pop()
{
Type result = this.start.element;
this.start = this.start.next;
return result;
}
public void push(Type element)
{
SingleLinkedList<Type> list = new SingleLinkedList<>(element, null);
if (this.start == null)
{
this.start = list;
this.end = list;
}
else
{
this.end.next = list;
this.end = list;
}
}
}
static class Fraction implements Comparable<Fraction>
{
public static final Fraction ZERO = new Fraction(0, 1);
public static Fraction fraction(long whole)
{
return fraction(whole, 1);
}
public static Fraction fraction(long numerator, long denominator)
{
Fraction result;
if (denominator == 0)
{
throw new ArithmeticException();
}
if (numerator == 0)
{
result = Fraction.ZERO;
}
else
{
int sign;
if (numerator < 0 ^ denominator < 0)
{
sign = -1;
numerator = Math.abs(numerator);
denominator = Math.abs(denominator);
}
else
{
sign = 1;
}
long gcd = gcd(numerator, denominator);
result = new Fraction(sign * numerator / gcd, denominator / gcd);
}
return result;
}
public final long numerator;
public final long denominator;
private Fraction(long numerator, long denominator)
{
this.numerator = numerator;
this.denominator = denominator;
}
public Fraction add(Fraction fraction)
{
return fraction(this.numerator * fraction.denominator + fraction.numerator * this.denominator, this.denominator * fraction.denominator);
}
@Override
public int compareTo(Fraction that)
{
return Long.compare(this.numerator * that.denominator, that.numerator * this.denominator);
}
public Fraction divide(Fraction fraction)
{
return multiply(fraction.inverse());
}
public boolean equals(Fraction that)
{
return this.compareTo(that) == 0;
}
public boolean equals(Object that)
{
return this.compareTo((Fraction) that) == 0;
}
public Fraction getRemainder()
{
return fraction(this.numerator - getWholePart() * denominator, denominator);
}
public long getWholePart()
{
return this.numerator / this.denominator;
}
public Fraction inverse()
{
return fraction(this.denominator, this.numerator);
}
public Fraction multiply(Fraction fraction)
{
return fraction(this.numerator * fraction.numerator, this.denominator * fraction.denominator);
}
public Fraction neg()
{
return fraction(-this.numerator, this.denominator);
}
public Fraction sub(Fraction fraction)
{
return add(fraction.neg());
}
@Override
public String toString()
{
String result;
if (getRemainder().equals(Fraction.ZERO))
{
result = "" + this.numerator;
}
else
{
result = this.numerator + "/" + this.denominator;
}
return result;
}
}
static class IteratorBuffer<Type>
{
private Iterator<Type> iterator;
private List<Type> list;
public IteratorBuffer(Iterator<Type> iterator)
{
this.iterator = iterator;
this.list = new ArrayList<Type>();
}
public Iterator<Type> iterator()
{
return new Iterator<Type>()
{
int index = 0;
@Override
public boolean hasNext()
{
return this.index < list.size() || IteratorBuffer.this.iterator.hasNext();
}
@Override
public Type next()
{
if (list.size() <= this.index)
{
list.add(iterator.next());
}
Type result = list.get(index);
index += 1;
return result;
}
};
}
}
public static class MapCount<Type> extends SortedMapAVL<Type, Long>
{
private int count;
public MapCount(Comparator<? super Type> comparator)
{
super(comparator);
this.count = 0;
}
public long add(Type key, Long delta)
{
long result;
if (delta > 0)
{
Long value = get(key);
if (value == null)
{
value = delta;
}
else
{
value += delta;
}
put(key, value);
result = delta;
}
else
{
result = 0;
}
this.count += result;
return result;
}
public int count()
{
return this.count;
}
public List<Type> flatten()
{
List<Type> result = new ArrayList<>();
for (Entry<Type, Long> entry : entrySet())
{
for (long index = 0; index < entry.getValue(); index++)
{
result.add(entry.getKey());
}
}
return result;
}
@Override
public SortedMapAVL<Type, Long> headMap(Type keyEnd)
{
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map<? extends Type, ? extends Long> map)
{
throw new UnsupportedOperationException();
}
public long remove(Type key, Long delta)
{
long result;
if (delta > 0)
{
Long value = get(key) - delta;
if (value <= 0)
{
result = delta + value;
remove(key);
}
else
{
result = delta;
put(key, value);
}
}
else
{
result = 0;
}
this.count -= result;
return result;
}
@Override
public Long remove(Object key)
{
Long result = super.remove(key);
this.count -= result;
return result;
}
@Override
public SortedMapAVL<Type, Long> subMap(Type keyStart, Type keyEnd)
{
throw new UnsupportedOperationException();
}
@Override
public SortedMapAVL<Type, Long> tailMap(Type keyStart)
{
throw new UnsupportedOperationException();
}
}
public static class MapSet<TypeKey, TypeValue> extends SortedMapAVL<TypeKey, SortedSetAVL<TypeValue>> implements Iterable<TypeValue>
{
private Comparator<? super TypeValue> comparatorValue;
public MapSet(Comparator<? super TypeKey> comparatorKey, Comparator<? super TypeValue> comparatorValue)
{
super(comparatorKey);
this.comparatorValue = comparatorValue;
}
public MapSet(Comparator<? super TypeKey> comparatorKey, SortedSetAVL<Entry<TypeKey, SortedSetAVL<TypeValue>>> entrySet, Comparator<? super TypeValue> comparatorValue)
{
super(comparatorKey, entrySet);
this.comparatorValue = comparatorValue;
}
public boolean add(TypeKey key, TypeValue value)
{
SortedSetAVL<TypeValue> set = computeIfAbsent(key, k -> new SortedSetAVL<>(comparatorValue));
return set.add(value);
}
public TypeValue firstValue()
{
TypeValue result;
Entry<TypeKey, SortedSetAVL<TypeValue>> firstEntry = firstEntry();
if (firstEntry == null)
{
result = null;
}
else
{
result = firstEntry.getValue().first();
}
return result;
}
@Override
public MapSet<TypeKey, TypeValue> headMap(TypeKey keyEnd)
{
return new MapSet<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)), this.comparatorValue);
}
public Iterator<TypeValue> iterator()
{
return new Iterator<TypeValue>()
{
Iterator<SortedSetAVL<TypeValue>> iteratorValues = values().iterator();
Iterator<TypeValue> iteratorValue = null;
@Override
public boolean hasNext()
{
return iteratorValues.hasNext() || (iteratorValue != null && iteratorValue.hasNext());
}
@Override
public TypeValue next()
{
if (iteratorValue == null || !iteratorValue.hasNext())
{
iteratorValue = iteratorValues.next().iterator();
}
return iteratorValue.next();
}
};
}
public TypeValue lastValue()
{
TypeValue result;
Entry<TypeKey, SortedSetAVL<TypeValue>> lastEntry = lastEntry();
if (lastEntry == null)
{
result = null;
}
else
{
result = lastEntry.getValue().last();
}
return result;
}
public boolean removeSet(TypeKey key, TypeValue value)
{
boolean result;
SortedSetAVL<TypeValue> set = get(key);
if (set == null)
{
result = false;
}
else
{
result = set.remove(value);
if (set.size() == 0)
{
remove(key);
}
}
return result;
}
@Override
public MapSet<TypeKey, TypeValue> tailMap(TypeKey keyStart)
{
return new MapSet<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)), this.comparatorValue);
}
}
public static class Matrix
{
public final int rows;
public final int columns;
public final Fraction[][] cells;
public Matrix(int rows, int columns)
{
this.rows = rows;
this.columns = columns;
this.cells = new Fraction[rows][columns];
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
set(row, column, Fraction.ZERO);
}
}
}
public void add(int rowSource, int rowTarget, Fraction fraction)
{
for (int column = 0; column < columns; column++)
{
this.cells[rowTarget][column] = this.cells[rowTarget][column].add(this.cells[rowSource][column].multiply(fraction));
}
}
private int columnPivot(int row)
{
int result = this.columns;
for (int column = this.columns - 1; 0 <= column; column--)
{
if (this.cells[row][column].compareTo(Fraction.ZERO) != 0)
{
result = column;
}
}
return result;
}
public void reduce()
{
for (int rowMinimum = 0; rowMinimum < this.rows; rowMinimum++)
{
int rowPivot = rowPivot(rowMinimum);
if (rowPivot != -1)
{
int columnPivot = columnPivot(rowPivot);
Fraction current = this.cells[rowMinimum][columnPivot];
Fraction pivot = this.cells[rowPivot][columnPivot];
Fraction fraction = pivot.inverse().sub(current.divide(pivot));
add(rowPivot, rowMinimum, fraction);
for (int row = rowMinimum + 1; row < this.rows; row++)
{
if (columnPivot(row) == columnPivot)
{
add(rowMinimum, row, this.cells[row][columnPivot(row)].neg());
}
}
}
}
}
private int rowPivot(int rowMinimum)
{
int result = -1;
int pivotColumnMinimum = this.columns;
for (int row = rowMinimum; row < this.rows; row++)
{
int pivotColumn = columnPivot(row);
if (pivotColumn < pivotColumnMinimum)
{
result = row;
pivotColumnMinimum = pivotColumn;
}
}
return result;
}
public void set(int row, int column, Fraction value)
{
this.cells[row][column] = value;
}
public String toString()
{
String result = "";
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
result += this.cells[row][column] + "\t";
}
result += "\n";
}
return result;
}
}
public static class Node<Type>
{
public static <Type> Node<Type> balance(Node<Type> result)
{
while (result != null && 1 < Math.abs(height(result.left) - height(result.right)))
{
if (height(result.left) < height(result.right))
{
Node<Type> right = result.right;
if (height(right.right) < height(right.left))
{
result = new Node<>(result.value, result.left, right.rotateRight());
}
result = result.rotateLeft();
}
else
{
Node<Type> left = result.left;
if (height(left.left) < height(left.right))
{
result = new Node<>(result.value, left.rotateLeft(), result.right);
}
result = result.rotateRight();
}
}
return result;
}
public static <Type> Node<Type> clone(Node<Type> result)
{
if (result != null)
{
result = new Node<>(result.value, clone(result.left), clone(result.right));
}
return result;
}
public static <Type> Node<Type> delete(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
if (node.left == null)
{
result = node.right;
}
else
{
if (node.right == null)
{
result = node.left;
}
else
{
Node<Type> first = first(node.right);
result = new Node<>(first.value, node.left, delete(node.right, first.value, comparator));
}
}
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, delete(node.left, value, comparator), node.right);
}
else
{
result = new Node<>(node.value, node.left, delete(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static <Type> Node<Type> first(Node<Type> result)
{
while (result.left != null)
{
result = result.left;
}
return result;
}
public static <Type> Node<Type> get(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = node;
}
else
{
if (compare < 0)
{
result = get(node.left, value, comparator);
}
else
{
result = get(node.right, value, comparator);
}
}
}
return result;
}
public static <Type> Node<Type> head(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = node.left;
}
else
{
if (compare < 0)
{
result = head(node.left, value, comparator);
}
else
{
result = new Node<>(node.value, node.left, head(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static int height(Node node)
{
return node == null ? 0 : node.height;
}
public static <Type> Node<Type> insert(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = new Node<>(value, null, null);
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = new Node<>(value, node.left, node.right);
;
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, insert(node.left, value, comparator), node.right);
}
else
{
result = new Node<>(node.value, node.left, insert(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static <Type> Node<Type> last(Node<Type> result)
{
while (result.right != null)
{
result = result.right;
}
return result;
}
public static int size(Node node)
{
return node == null ? 0 : node.size;
}
public static <Type> Node<Type> tail(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = new Node<>(node.value, null, node.right);
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, tail(node.left, value, comparator), node.right);
}
else
{
result = tail(node.right, value, comparator);
}
}
result = balance(result);
}
return result;
}
public static <Type> void traverseOrderIn(Node<Type> node, Consumer<Type> consumer)
{
if (node != null)
{
traverseOrderIn(node.left, consumer);
consumer.accept(node.value);
traverseOrderIn(node.right, consumer);
}
}
public final Type value;
public final Node<Type> left;
public final Node<Type> right;
public final int size;
private final int height;
public Node(Type value, Node<Type> left, Node<Type> right)
{
this.value = value;
this.left = left;
this.right = right;
this.size = 1 + size(left) + size(right);
this.height = 1 + Math.max(height(left), height(right));
}
public Node<Type> rotateLeft()
{
Node<Type> left = new Node<>(this.value, this.left, this.right.left);
return new Node<>(this.right.value, left, this.right.right);
}
public Node<Type> rotateRight()
{
Node<Type> right = new Node<>(this.value, this.left.right, this.right);
return new Node<>(this.left.value, this.left.left, right);
}
}
public static class SingleLinkedList<Type>
{
public final Type element;
public SingleLinkedList<Type> next;
public SingleLinkedList(Type element, SingleLinkedList<Type> next)
{
this.element = element;
this.next = next;
}
public void toCollection(Collection<Type> collection)
{
if (this.next != null)
{
this.next.toCollection(collection);
}
collection.add(this.element);
}
}
public static class SmallSetIntegers
{
public static final int SIZE = 20;
public static final int[] SET = generateSet();
public static final int[] COUNT = generateCount();
public static final int[] INTEGER = generateInteger();
private static int count(int set)
{
int result = 0;
for (int integer = 0; integer < SIZE; integer++)
{
if (0 < (set & set(integer)))
{
result += 1;
}
}
return result;
}
private static final int[] generateCount()
{
int[] result = new int[1 << SIZE];
for (int set = 0; set < result.length; set++)
{
result[set] = count(set);
}
return result;
}
private static final int[] generateInteger()
{
int[] result = new int[1 << SIZE];
Arrays.fill(result, -1);
for (int integer = 0; integer < SIZE; integer++)
{
result[SET[integer]] = integer;
}
return result;
}
private static final int[] generateSet()
{
int[] result = new int[SIZE];
for (int integer = 0; integer < result.length; integer++)
{
result[integer] = set(integer);
}
return result;
}
private static int set(int integer)
{
return 1 << integer;
}
}
public static class SortedMapAVL<TypeKey, TypeValue> implements SortedMap<TypeKey, TypeValue>
{
public final Comparator<? super TypeKey> comparator;
public final SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet;
public SortedMapAVL(Comparator<? super TypeKey> comparator)
{
this(comparator, new SortedSetAVL<>((entry0, entry1) -> comparator.compare(entry0.getKey(), entry1.getKey())));
}
private SortedMapAVL(Comparator<? super TypeKey> comparator, SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet)
{
this.comparator = comparator;
this.entrySet = entrySet;
}
@Override
public void clear()
{
this.entrySet.clear();
}
@Override
public Comparator<? super TypeKey> comparator()
{
return this.comparator;
}
@Override
public boolean containsKey(Object key)
{
return this.entrySet().contains(new AbstractMap.SimpleEntry<>((TypeKey) key, null));
}
@Override
public boolean containsValue(Object value)
{
throw new UnsupportedOperationException();
}
@Override
public SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet()
{
return this.entrySet;
}
public Entry<TypeKey, TypeValue> firstEntry()
{
return this.entrySet.first();
}
@Override
public TypeKey firstKey()
{
return firstEntry().getKey();
}
@Override
public TypeValue get(Object key)
{
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
entry = this.entrySet.get(entry);
return entry == null ? null : entry.getValue();
}
@Override
public SortedMapAVL<TypeKey, TypeValue> headMap(TypeKey keyEnd)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)));
}
@Override
public boolean isEmpty()
{
return this.entrySet.isEmpty();
}
@Override
public Set<TypeKey> keySet()
{
return new SortedSet<TypeKey>()
{
@Override
public boolean add(TypeKey typeKey)
{
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends TypeKey> collection)
{
throw new UnsupportedOperationException();
}
@Override
public void clear()
{
throw new UnsupportedOperationException();
}
@Override
public Comparator<? super TypeKey> comparator()
{
throw new UnsupportedOperationException();
}
@Override
public boolean contains(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public TypeKey first()
{
throw new UnsupportedOperationException();
}
@Override
public SortedSet<TypeKey> headSet(TypeKey typeKey)
{
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty()
{
return size() == 0;
}
@Override
public Iterator<TypeKey> iterator()
{
final Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator();
return new Iterator<TypeKey>()
{
@Override
public boolean hasNext()
{
return iterator.hasNext();
}
@Override
public TypeKey next()
{
return iterator.next().getKey();
}
};
}
@Override
public TypeKey last()
{
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public int size()
{
return SortedMapAVL.this.entrySet.size();
}
@Override
public SortedSet<TypeKey> subSet(TypeKey typeKey, TypeKey e1)
{
throw new UnsupportedOperationException();
}
@Override
public SortedSet<TypeKey> tailSet(TypeKey typeKey)
{
throw new UnsupportedOperationException();
}
@Override
public Object[] toArray()
{
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] ts)
{
throw new UnsupportedOperationException();
}
};
}
public Entry<TypeKey, TypeValue> lastEntry()
{
return this.entrySet.last();
}
@Override
public TypeKey lastKey()
{
return lastEntry().getKey();
}
@Override
public TypeValue put(TypeKey key, TypeValue value)
{
TypeValue result = get(key);
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>(key, value);
this.entrySet().add(entry);
return result;
}
@Override
public void putAll(Map<? extends TypeKey, ? extends TypeValue> map)
{
map.entrySet()
.forEach(entry -> put(entry.getKey(), entry.getValue()));
}
@Override
public TypeValue remove(Object key)
{
TypeValue result = get(key);
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
this.entrySet.remove(entry);
return result;
}
@Override
public int size()
{
return this.entrySet().size();
}
@Override
public SortedMapAVL<TypeKey, TypeValue> subMap(TypeKey keyStart, TypeKey keyEnd)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.subSet(new AbstractMap.SimpleEntry<>(keyStart, null), new AbstractMap.SimpleEntry<>(keyEnd, null)));
}
@Override
public SortedMapAVL<TypeKey, TypeValue> tailMap(TypeKey keyStart)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)));
}
@Override
public String toString()
{
return this.entrySet().toString();
}
@Override
public Collection<TypeValue> values()
{
return new Collection<TypeValue>()
{
@Override
public boolean add(TypeValue typeValue)
{
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends TypeValue> collection)
{
throw new UnsupportedOperationException();
}
@Override
public void clear()
{
throw new UnsupportedOperationException();
}
@Override
public boolean contains(Object value)
{
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty()
{
return SortedMapAVL.this.entrySet.isEmpty();
}
@Override
public Iterator<TypeValue> iterator()
{
return new Iterator<TypeValue>()
{
Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator();
@Override
public boolean hasNext()
{
return this.iterator.hasNext();
}
@Override
public TypeValue next()
{
return this.iterator.next().getValue();
}
};
}
@Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public int size()
{
return SortedMapAVL.this.entrySet.size();
}
@Override
public Object[] toArray()
{
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] ts)
{
throw new UnsupportedOperationException();
}
};
}
}
public static class SortedSetAVL<Type> implements SortedSet<Type>
{
public Comparator<? super Type> comparator;
public Node<Type> root;
private SortedSetAVL(Comparator<? super Type> comparator, Node<Type> root)
{
this.comparator = comparator;
this.root = root;
}
public SortedSetAVL(Comparator<? super Type> comparator)
{
this(comparator, null);
}
public SortedSetAVL(Collection<? extends Type> collection, Comparator<? super Type> comparator)
{
this(comparator, null);
this.addAll(collection);
}
public SortedSetAVL(SortedSetAVL<Type> sortedSetAVL)
{
this(sortedSetAVL.comparator, Node.clone(sortedSetAVL.root));
}
@Override
public boolean add(Type value)
{
int sizeBefore = size();
this.root = Node.insert(this.root, value, this.comparator);
return sizeBefore != size();
}
@Override
public boolean addAll(Collection<? extends Type> collection)
{
return collection.stream()
.map(this::add)
.reduce(true, (x, y) -> x | y);
}
@Override
public void clear()
{
this.root = null;
}
@Override
public Comparator<? super Type> comparator()
{
return this.comparator;
}
@Override
public boolean contains(Object value)
{
return Node.get(this.root, (Type) value, this.comparator) != null;
}
@Override
public boolean containsAll(Collection<?> collection)
{
return collection.stream()
.allMatch(this::contains);
}
@Override
public Type first()
{
return Node.first(this.root).value;
}
public Type get(Type value)
{
Node<Type> node = Node.get(this.root, value, this.comparator);
return node == null ? null : node.value;
}
@Override
public SortedSetAVL<Type> headSet(Type valueEnd)
{
return new SortedSetAVL<>(this.comparator, Node.head(this.root, valueEnd, this.comparator));
}
@Override
public boolean isEmpty()
{
return this.root == null;
}
@Override
public Iterator<Type> iterator()
{
Stack<Node<Type>> path = new Stack<>();
return new Iterator<Type>()
{
{
push(SortedSetAVL.this.root);
}
@Override
public boolean hasNext()
{
return !path.isEmpty();
}
@Override
public Type next()
{
if (path.isEmpty())
{
throw new NoSuchElementException();
}
else
{
Node<Type> node = path.peek();
Type result = node.value;
if (node.right != null)
{
push(node.right);
}
else
{
do
{
node = path.pop();
}
while (!path.isEmpty() && path.peek().right == node);
}
return result;
}
}
public void push(Node<Type> node)
{
while (node != null)
{
path.push(node);
node = node.left;
}
}
};
}
@Override
public Type last()
{
return Node.last(this.root).value;
}
@Override
public boolean remove(Object value)
{
int sizeBefore = size();
this.root = Node.delete(this.root, (Type) value, this.comparator);
return sizeBefore != size();
}
@Override
public boolean removeAll(Collection<?> collection)
{
return collection.stream()
.map(this::remove)
.reduce(true, (x, y) -> x | y);
}
@Override
public boolean retainAll(Collection<?> collection)
{
SortedSetAVL<Type> set = new SortedSetAVL<>(this.comparator);
collection.stream()
.map(element -> (Type) element)
.filter(this::contains)
.forEach(set::add);
boolean result = size() != set.size();
this.root = set.root;
return result;
}
@Override
public int size()
{
return this.root == null ? 0 : this.root.size;
}
@Override
public SortedSetAVL<Type> subSet(Type valueStart, Type valueEnd)
{
return tailSet(valueStart).headSet(valueEnd);
}
@Override
public SortedSetAVL<Type> tailSet(Type valueStart)
{
return new SortedSetAVL<>(this.comparator, Node.tail(this.root, valueStart, this.comparator));
}
@Override
public Object[] toArray()
{
return toArray(new Object[0]);
}
@Override
public <T> T[] toArray(T[] ts)
{
List<Object> list = new ArrayList<>();
Node.traverseOrderIn(this.root, list::add);
return list.toArray(ts);
}
@Override
public String toString()
{
return "{" + C_455.toString(this, ", ") + "}";
}
}
public static class Tree2D
{
public static final int SIZE = 1 << 30;
public static final Tree2D[] TREES_NULL = new Tree2D[] { null, null, null, null };
public static boolean contains(int x, int y, int left, int bottom, int size)
{
return left <= x && x < left + size && bottom <= y && y < bottom + size;
}
public static int count(Tree2D[] trees)
{
int result = 0;
for (int index = 0; index < 4; index++)
{
if (trees[index] != null)
{
result += trees[index].count;
}
}
return result;
}
public static int count
(
int rectangleLeft,
int rectangleBottom,
int rectangleRight,
int rectangleTop,
Tree2D tree,
int left,
int bottom,
int size
)
{
int result;
if (tree == null)
{
result = 0;
}
else
{
int right = left + size;
int top = bottom + size;
int intersectionLeft = Math.max(rectangleLeft, left);
int intersectionBottom = Math.max(rectangleBottom, bottom);
int intersectionRight = Math.min(rectangleRight, right);
int intersectionTop = Math.min(rectangleTop, top);
if (intersectionRight <= intersectionLeft || intersectionTop <= intersectionBottom)
{
result = 0;
}
else
{
if (intersectionLeft == left && intersectionBottom == bottom && intersectionRight == right && intersectionTop == top)
{
result = tree.count;
}
else
{
size = size >> 1;
result = 0;
for (int index = 0; index < 4; index++)
{
result += count
(
rectangleLeft,
rectangleBottom,
rectangleRight,
rectangleTop,
tree.trees[index],
quadrantLeft(left, size, index),
quadrantBottom(bottom, size, index),
size
);
}
}
}
}
return result;
}
public static int quadrantBottom(int bottom, int size, int index)
{
return bottom + (index >> 1) * size;
}
public static int quadrantLeft(int left, int size, int index)
{
return left + (index & 1) * size;
}
public final Tree2D[] trees;
public final int count;
private Tree2D(Tree2D[] trees, int count)
{
this.trees = trees;
this.count = count;
}
public Tree2D(Tree2D[] trees)
{
this(trees, count(trees));
}
public Tree2D()
{
this(TREES_NULL);
}
public int count(int rectangleLeft, int rectangleBottom, int rectangleRight, int rectangleTop)
{
return count
(
rectangleLeft,
rectangleBottom,
rectangleRight,
rectangleTop,
this,
0,
0,
SIZE
);
}
public Tree2D setPoint
(
int x,
int y,
Tree2D tree,
int left,
int bottom,
int size
)
{
Tree2D result;
if (contains(x, y, left, bottom, size))
{
if (size == 1)
{
result = new Tree2D(TREES_NULL, 1);
}
else
{
size = size >> 1;
Tree2D[] trees = new Tree2D[4];
for (int index = 0; index < 4; index++)
{
trees[index] = setPoint
(
x,
y,
tree == null ? null : tree.trees[index],
quadrantLeft(left, size, index),
quadrantBottom(bottom, size, index),
size
);
}
result = new Tree2D(trees);
}
}
else
{
result = tree;
}
return result;
}
public Tree2D setPoint(int x, int y)
{
return setPoint
(
x,
y,
this,
0,
0,
SIZE
);
}
}
public static class Tuple2<Type0, Type1>
{
public final Type0 v0;
public final Type1 v1;
public Tuple2(Type0 v0, Type1 v1)
{
this.v0 = v0;
this.v1 = v1;
}
@Override
public String toString()
{
return "(" + this.v0 + ", " + this.v1 + ")";
}
}
public static class Tuple2Comparable<Type0 extends Comparable<? super Type0>, Type1 extends Comparable<? super Type1>> extends Tuple2<Type0, Type1> implements Comparable<Tuple2Comparable<Type0, Type1>>
{
public Tuple2Comparable(Type0 v0, Type1 v1)
{
super(v0, v1);
}
@Override
public int compareTo(Tuple2Comparable<Type0, Type1> that)
{
int result = this.v0.compareTo(that.v0);
if (result == 0)
{
result = this.v1.compareTo(that.v1);
}
return result;
}
}
public static class Tuple3<Type0, Type1, Type2>
{
public final Type0 v0;
public final Type1 v1;
public final Type2 v2;
public Tuple3(Type0 v0, Type1 v1, Type2 v2)
{
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
}
@Override
public String toString()
{
return "(" + this.v0 + ", " + this.v1 + ", " + this.v2 + ")";
}
}
public static class Vertex
<
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>
>
implements Comparable<Vertex<? super TypeVertex, ? super TypeEdge>>
{
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>,
TypeResult
> TypeResult breadthFirstSearch
(
TypeVertex vertex,
TypeEdge edge,
BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
Array<Boolean> visited,
FIFO<TypeVertex> verticesNext,
FIFO<TypeEdge> edgesNext,
TypeResult result
)
{
if (!visited.get(vertex.index))
{
visited.set(vertex.index, true);
result = function.apply(vertex, edge, result);
for (TypeEdge edgeNext : vertex.edges)
{
TypeVertex vertexNext = edgeNext.other(vertex);
if (!visited.get(vertexNext.index))
{
verticesNext.push(vertexNext);
edgesNext.push(edgeNext);
}
}
}
return result;
}
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>,
TypeResult
>
TypeResult breadthFirstSearch
(
Array<TypeVertex> vertices,
int indexVertexStart,
BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
TypeResult result
)
{
Array<Boolean> visited = new Array<>(vertices.size(), false);
FIFO<TypeVertex> verticesNext = new FIFO<>();
verticesNext.push(vertices.get(indexVertexStart));
FIFO<TypeEdge> edgesNext = new FIFO<>();
edgesNext.push(null);
while (!verticesNext.isEmpty())
{
result = breadthFirstSearch(verticesNext.pop(), edgesNext.pop(), function, visited, verticesNext, edgesNext, result);
}
return result;
}
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>
>
boolean
cycle
(
TypeVertex start,
SortedSet<TypeVertex> result
)
{
boolean cycle = false;
Stack<TypeVertex> stackVertex = new Stack<>();
Stack<TypeEdge> stackEdge = new Stack<>();
stackVertex.push(start);
stackEdge.push(null);
while (!stackVertex.isEmpty())
{
TypeVertex vertex = stackVertex.pop();
TypeEdge edge = stackEdge.pop();
if (!result.contains(vertex))
{
result.add(vertex);
for (TypeEdge otherEdge : vertex.edges)
{
if (otherEdge != edge)
{
TypeVertex otherVertex = otherEdge.other(vertex);
if (result.contains(otherVertex))
{
cycle = true;
}
else
{
stackVertex.push(otherVertex);
stackEdge.push(otherEdge);
}
}
}
}
}
return cycle;
}
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>
>
SortedSet<TypeVertex>
depthFirstSearch
(
TypeVertex start,
BiConsumer<TypeVertex, TypeEdge> functionVisitPre,
BiConsumer<TypeVertex, TypeEdge> functionVisitPost
)
{
SortedSet<TypeVertex> result = new SortedSetAVL<>(Comparator.naturalOrder());
Stack<TypeVertex> stackVertex = new Stack<>();
Stack<TypeEdge> stackEdge = new Stack<>();
stackVertex.push(start);
stackEdge.push(null);
while (!stackVertex.isEmpty())
{
TypeVertex vertex = stackVertex.pop();
TypeEdge edge = stackEdge.pop();
if (result.contains(vertex))
{
functionVisitPost.accept(vertex, edge);
}
else
{
result.add(vertex);
stackVertex.push(vertex);
stackEdge.push(edge);
functionVisitPre.accept(vertex, edge);
for (TypeEdge otherEdge : vertex.edges)
{
TypeVertex otherVertex = otherEdge.other(vertex);
if (!result.contains(otherVertex))
{
stackVertex.push(otherVertex);
stackEdge.push(otherEdge);
}
}
}
}
return result;
}
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>
>
SortedSet<TypeVertex>
depthFirstSearch
(
TypeVertex start,
Consumer<TypeVertex> functionVisitPreVertex,
Consumer<TypeVertex> functionVisitPostVertex
)
{
BiConsumer<TypeVertex, TypeEdge> functionVisitPreVertexEdge = (vertex, edge) ->
{
functionVisitPreVertex.accept(vertex);
};
BiConsumer<TypeVertex, TypeEdge> functionVisitPostVertexEdge = (vertex, edge) ->
{
functionVisitPostVertex.accept(vertex);
};
return depthFirstSearch(start, functionVisitPreVertexEdge, functionVisitPostVertexEdge);
}
public final int index;
public final List<TypeEdge> edges;
public Vertex(int index)
{
this.index = index;
this.edges = new ArrayList<>();
}
@Override
public int compareTo(Vertex<? super TypeVertex, ? super TypeEdge> that)
{
return Integer.compare(this.index, that.index);
}
@Override
public String toString()
{
return "" + this.index;
}
}
public static class VertexDefault<TypeEdge extends Edge<VertexDefault<TypeEdge>, TypeEdge>> extends Vertex<VertexDefault<TypeEdge>, TypeEdge>
{
public VertexDefault(int index)
{
super(index);
}
}
public static class VertexDefaultDefault extends Vertex<VertexDefaultDefault, EdgeDefaultDefault>
{
public static Array<VertexDefaultDefault> vertices(int n)
{
Array<VertexDefaultDefault> result = new Array<>(n);
for (int index = 0; index < n; index++)
{
result.set(index, new VertexDefaultDefault(index));
}
return result;
}
public VertexDefaultDefault(int index)
{
super(index);
}
}
public static class Wrapper<Type>
{
public Type value;
public Wrapper(Type value)
{
this.value = value;
}
public Type get()
{
return this.value;
}
public void set(Type value)
{
this.value = value;
}
@Override
public String toString()
{
return this.value.toString();
}
}
public static void add(int delta, int[] result)
{
for (int index = 0; index < result.length; index++)
{
result[index] += delta;
}
}
public static void add(int delta, int[]... result)
{
for (int index = 0; index < result.length; index++)
{
add(delta, result[index]);
}
}
public static int binarySearchMaximum(Function<Integer, Boolean> filter, int start, int end)
{
return -binarySearchMinimum(x -> filter.apply(-x), -end, -start);
}
public static int binarySearchMinimum(Function<Integer, Boolean> filter, int start, int end)
{
int result;
if (start == end)
{
result = end;
}
else
{
int middle = start + (end - start) / 2;
if (filter.apply(middle))
{
result = binarySearchMinimum(filter, start, middle);
}
else
{
result = binarySearchMinimum(filter, middle + 1, end);
}
}
return result;
}
public static void close()
{
out.close();
}
public static List<List<Integer>> combinations(int n, int k)
{
List<List<Integer>> result = new ArrayList<>();
if (k == 0)
{
}
else
{
if (k == 1)
{
List<Integer> combination = new ArrayList<>();
combination.add(n);
result.add(combination);
}
else
{
for (int index = 0; index <= n; index++)
{
for (List<Integer> combination : combinations(n - index, k - 1))
{
combination.add(index);
result.add(combination);
}
}
}
}
return result;
}
public static <Type> int compare(Iterator<Type> iterator0, Iterator<Type> iterator1, Comparator<Type> comparator)
{
int result = 0;
while (result == 0 && iterator0.hasNext() && iterator1.hasNext())
{
result = comparator.compare(iterator0.next(), iterator1.next());
}
if (result == 0)
{
if (iterator1.hasNext())
{
result = -1;
}
else
{
if (iterator0.hasNext())
{
result = 1;
}
}
}
return result;
}
public static <Type> int compare(Iterable<Type> iterable0, Iterable<Type> iterable1, Comparator<Type> comparator)
{
return compare(iterable0.iterator(), iterable1.iterator(), comparator);
}
public static long divideCeil(long x, long y)
{
return (x + y - 1) / y;
}
public static Set<Long> divisors(long n)
{
SortedSetAVL<Long> result = new SortedSetAVL<>(Comparator.naturalOrder());
result.add(1L);
for (Long factor : factors(n))
{
SortedSetAVL<Long> divisors = new SortedSetAVL<>(result);
for (Long divisor : result)
{
divisors.add(divisor * factor);
}
result = divisors;
}
return result;
}
public static LinkedList<Long> factors(long n)
{
LinkedList<Long> result = new LinkedList<>();
Iterator<Long> primes = ITERATOR_BUFFER_PRIME.iterator();
Long prime;
while (n > 1 && (prime = primes.next()) * prime <= n)
{
while (n % prime == 0)
{
result.add(prime);
n /= prime;
}
}
if (n > 1)
{
result.add(n);
}
return result;
}
public static long faculty(int n)
{
long result = 1;
for (int index = 2; index <= n; index++)
{
result *= index;
}
return result;
}
public static long gcd(long a, long b)
{
while (a != 0 && b != 0)
{
if (a > b)
{
a %= b;
}
else
{
b %= a;
}
}
return a + b;
}
public static long[] generatePOWER2()
{
long[] result = new long[63];
for (int x = 0; x < result.length; x++)
{
result[x] = 1L << x;
}
return result;
}
public static boolean isPrime(long x)
{
boolean result = x > 1;
Iterator<Long> iterator = ITERATOR_BUFFER_PRIME.iterator();
Long prime;
while ((prime = iterator.next()) * prime <= x)
{
result &= x % prime > 0;
}
return result;
}
public static long knapsack(List<Tuple3<Long, Integer, Integer>> itemsValueWeightCount, int weightMaximum)
{
long[] valuesMaximum = new long[weightMaximum + 1];
for (Tuple3<Long, Integer, Integer> itemValueWeightCount : itemsValueWeightCount)
{
long itemValue = itemValueWeightCount.v0;
int itemWeight = itemValueWeightCount.v1;
int itemCount = itemValueWeightCount.v2;
for (int weight = weightMaximum; 0 <= weight; weight--)
{
for (int index = 1; index <= itemCount && 0 <= weight - index * itemWeight; index++)
{
valuesMaximum[weight] = Math.max(valuesMaximum[weight], valuesMaximum[weight - index * itemWeight] + index * itemValue);
}
}
}
long result = 0;
for (long valueMaximum : valuesMaximum)
{
result = Math.max(result, valueMaximum);
}
return result;
}
public static boolean knapsackPossible(List<Tuple2<Integer, Integer>> itemsWeightCount, int weightMaximum)
{
boolean[] weightPossible = new boolean[weightMaximum + 1];
weightPossible[0] = true;
int weightLargest = 0;
for (Tuple2<Integer, Integer> itemWeightCount : itemsWeightCount)
{
int itemWeight = itemWeightCount.v0;
int itemCount = itemWeightCount.v1;
for (int weightStart = 0; weightStart < itemWeight; weightStart++)
{
int count = 0;
for (int weight = weightStart; weight <= weightMaximum && (0 < count || weight <= weightLargest); weight += itemWeight)
{
if (weightPossible[weight])
{
count = itemCount;
}
else
{
if (0 < count)
{
weightPossible[weight] = true;
weightLargest = weight;
count -= 1;
}
}
}
}
}
return weightPossible[weightMaximum];
}
public static long lcm(int a, int b)
{
return a * b / gcd(a, b);
}
public static void main(String[] args)
{
try
{
solve();
}
catch (IOException exception)
{
exception.printStackTrace();
}
close();
}
public static double nextDouble() throws IOException
{
return Double.parseDouble(nextString());
}
public static int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
public static void nextInts(int n, int[]... result) throws IOException
{
for (int index = 0; index < n; index++)
{
for (int value = 0; value < result.length; value++)
{
result[value][index] = nextInt();
}
}
}
public static int[] nextInts(int n) throws IOException
{
int[] result = new int[n];
nextInts(n, result);
return result;
}
public static String nextLine() throws IOException
{
return bufferedReader.readLine();
}
public static long nextLong() throws IOException
{
return Long.parseLong(nextString());
}
public static void nextLongs(int n, long[]... result) throws IOException
{
for (int index = 0; index < n; index++)
{
for (int value = 0; value < result.length; value++)
{
result[value][index] = nextLong();
}
}
}
public static long[] nextLongs(int n) throws IOException
{
long[] result = new long[n];
nextLongs(n, result);
return result;
}
public static String nextString() throws IOException
{
while ((stringTokenizer == null) || (!stringTokenizer.hasMoreTokens()))
{
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
}
return stringTokenizer.nextToken();
}
public static String[] nextStrings(int n) throws IOException
{
String[] result = new String[n];
{
for (int index = 0; index < n; index++)
{
result[index] = nextString();
}
}
return result;
}
public static <T> List<T> permutation(long p, List<T> x)
{
List<T> copy = new ArrayList<>();
for (int index = 0; index < x.size(); index++)
{
copy.add(x.get(index));
}
List<T> result = new ArrayList<>();
for (int indexTo = 0; indexTo < x.size(); indexTo++)
{
int indexFrom = (int) p % copy.size();
p = p / copy.size();
result.add(copy.remove(indexFrom));
}
return result;
}
public static <Type> List<List<Type>> permutations(List<Type> list)
{
List<List<Type>> result = new ArrayList<>();
result.add(new ArrayList<>());
for (Type element : list)
{
List<List<Type>> permutations = result;
result = new ArrayList<>();
for (List<Type> permutation : permutations)
{
for (int index = 0; index <= permutation.size(); index++)
{
List<Type> permutationNew = new ArrayList<>(permutation);
permutationNew.add(index, element);
result.add(permutationNew);
}
}
}
return result;
}
public static Stream<BigInteger> streamFibonacci()
{
return Stream.generate(new Supplier<BigInteger>()
{
private BigInteger n0 = BigInteger.ZERO;
private BigInteger n1 = BigInteger.ONE;
@Override
public BigInteger get()
{
BigInteger result = n0;
n0 = n1;
n1 = result.add(n0);
return result;
}
});
}
public static Stream<Long> streamPrime(int sieveSize)
{
return Stream.generate(new Supplier<Long>()
{
private boolean[] isPrime = new boolean[sieveSize];
private long sieveOffset = 2;
private List<Long> primes = new ArrayList<>();
private int index = 0;
public void filter(long prime, boolean[] result)
{
if (prime * prime < this.sieveOffset + sieveSize)
{
long remainingStart = this.sieveOffset % prime;
long start = remainingStart == 0 ? 0 : prime - remainingStart;
for (long index = start; index < sieveSize; index += prime)
{
result[(int) index] = false;
}
}
}
public void generatePrimes()
{
Arrays.fill(this.isPrime, true);
this.primes.forEach(prime -> filter(prime, isPrime));
for (int index = 0; index < sieveSize; index++)
{
if (isPrime[index])
{
this.primes.add(this.sieveOffset + index);
filter(this.sieveOffset + index, isPrime);
}
}
this.sieveOffset += sieveSize;
}
@Override
public Long get()
{
while (this.primes.size() <= this.index)
{
generatePrimes();
}
Long result = this.primes.get(this.index);
this.index += 1;
return result;
}
});
}
public static <Type> String toString(Iterator<Type> iterator, String separator)
{
StringBuilder stringBuilder = new StringBuilder();
if (iterator.hasNext())
{
stringBuilder.append(iterator.next());
}
while (iterator.hasNext())
{
stringBuilder.append(separator);
stringBuilder.append(iterator.next());
}
return stringBuilder.toString();
}
public static <Type> String toString(Iterator<Type> iterator)
{
return toString(iterator, " ");
}
public static <Type> String toString(Iterable<Type> iterable, String separator)
{
return toString(iterable.iterator(), separator);
}
public static <Type> String toString(Iterable<Type> iterable)
{
return toString(iterable, " ");
}
public static long totient(long n)
{
Set<Long> factors = new SortedSetAVL<>(factors(n), Comparator.naturalOrder());
long result = n;
for (long p : factors)
{
result -= result / p;
}
return result;
}
interface BiFunctionResult<Type0, Type1, TypeResult>
{
TypeResult apply(Type0 x0, Type1 x1, TypeResult x2);
}
public static final long BIG = 1000000007;
public static long bigAdd(long x, long y)
{
return (x + y) % BIG;
}
public static long bigMultiply(long x, long y)
{
return (x * y) % BIG;
}
public static int convert(int n, int start, int end)
{
return n * start + end;
}
public static long solve(long[] results, boolean[] statements, int start, int end)
{
int converted = convert(statements.length, start, end);
long result = results[converted];
if (result == -1)
{
if (start == end)
{
result = 1L;
}
else
{
if (statements[start])
{
result = solve(results, statements, start + 1, end);
}
else
{
result = 0L;
for (int index = start + 2; index <= end; index++)
{
long inside = solve(results, statements, start + 1, index);
long outside = solve(results, statements, index, end);
result = C_455.bigAdd(result, C_455.bigMultiply(inside, outside));
}
}
}
results[converted] = result;
}
return result;
}
public static long solve(boolean[] statements)
{
long[] results = new long[(statements.length + 1) * (statements.length + 1)];
Arrays.fill(results, -1);
return solve(results, statements, 0, statements.length);
}
public static long solveFast(boolean[] statements)
{
long[] indent2Count = new long[statements.length];
indent2Count[0] = 1;
for (boolean statement: statements)
{
if (statement)
{
long count = 0;
for (int index = statements.length - 1; 0 <= index; index--)
{
count = bigAdd(count, indent2Count[index]);
indent2Count[index] = count;
}
}
else
{
for (int index = statements.length - 1; 1 <= index; index--)
{
indent2Count[index] = indent2Count[index - 1];
}
indent2Count[0] = 0;
}
}
return indent2Count[0];
}
public static void solve() throws IOException
{
int n = nextInt();
boolean[] statements = new boolean[n];
for (int index = 0; index < n; index++)
{
statements[index] = nextString().equals("s");
}
out.println(solveFast(statements));
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.*;
import java.io.*;
public class PythonIndentation {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(in.readLine());
int[][] dp = new int[N][N];
dp[0][0] = 1;
for(int i = 1; i < N; ++i) {
char lastCmd = in.readLine().charAt(0);
int[] sum = new int[N];
sum[N - 1] = dp[i - 1][N - 1];
for(int j = N - 2; j >= 0; --j)
sum[j] = (sum[j + 1] + dp[i - 1][j]) % 1000000007;
for(int j = 0; j < N; ++j) {
if(lastCmd == 'f' && j > 0)
dp[i][j] = dp[i - 1][j - 1];
else if(lastCmd == 's')
dp[i][j] = sum[j];
}
}
int ans = 0;
for(int i = 0; i < N; ++i)
ans = (ans + dp[N - 1][i]) % 1000000007;
System.out.println(ans);
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author pandusonu
*/
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();
}
static class TaskC {
public int mod = (int) Math.pow(10, 9) + 7;
public void solve(int testNumber, InputReader in, PrintWriter out) {
// out.print("Case #" + testNumber + ": ");
int n = in.readInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.readString().charAt(0) == 'f' ? 1 : 0;
}
long[][] ans = new long[n][n + 2];
ans[0][0] = 1;
int indent = 0;
if (a[0] == 1) indent++;
for (int i = 1; i < n; i++) {
if (a[i - 1] == 1) {
for (int j = indent - 1; j >= 1; j--) {
ans[i][j] = ans[i - 1][j - 1];
}
ans[i][indent] = 1;
} else {
for (int j = indent; j >= 0; j--) {
ans[i][j] = (ans[i][j + 1] + ans[i - 1][j]) % mod;
}
}
indent += a[i];
}/*
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
out.print(ans[i][j]+" ");
}
out.println();
}*/
long aa = 0;
for (int i = 0; i < n + 2; i++) {
aa = (aa + ans[n - 1][i]) % mod;
}
out.println(aa);
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
try {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0)
return -1;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return buf[curChar++];
}
public int readInt() {
return (int) readLong();
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
if (c == -1) throw new RuntimeException();
}
boolean negative = false;
if (c == '-') {
negative = true;
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 negative ? (-res) : (res);
}
public String readString() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
/**
* @author: Mehul Raheja
*/
import java.util.*;
import java.io.*;
public class indent {
/*
Runtime = O()
*/
static int N, M, K;
static String s;
static StringTokenizer st;
static int[] d;
static long MOD = (int)1e9 + 7;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
char[] d = new char[N];
for (int i = 0; i < N; i++) {
d[i] = br.readLine().charAt(0);
}
long[][] dp = new long[N][N];
boolean det = d[0] == 'f';
//Arrays.fill(dp[0], 1);
dp[0][0] = 1;
for (int i = 1; i < N; i++) {
// System.out.println(Arrays.toString(dp[i-1]));
long sum = 0;
for (int j = 0; j < N; j++) {
sum = (dp[i - 1][j]%MOD + sum%MOD + MOD) % MOD;
}
// System.out.println(sum);
if (d[i] == 'f') {
if(det){
for (int j = 1; j < N; j++) {
dp[i][j] = dp[i-1][j-1]%MOD;
}
continue;
}
for (int j = 0; j < N; j++) {
dp[i][j] = sum%MOD;
sum -= dp[i - 1][j]%MOD;
}
det = true;
//System.out.println(Arrays.toString(dp[i]));
} else if (d[i] == 's') {
// System.out.println("HERE1" + det);
if(det){
//System.out.println("HERE2");
det = false;
for (int j = 1; j < N; j++) {
dp[i][j] = dp[i-1][j-1]%MOD;
}
//System.out.println("HERE " + Arrays.toString(dp[i]));
continue;
}
//System.out.println("HERE3" + sum);
for (int j = 0; j < N; j++) {
dp[i][j] = sum%MOD;
sum = ((sum - dp[i - 1][j])%MOD + MOD)%MOD;
}
}
//System.out.println(Arrays.toString(dp[i]));
}
//System.out.println(Arrays.toString(dp[dp.length-1]));
long ans = 0;
for (long e: dp[dp.length-1]) {
ans = (ans + e + MOD) % MOD;
}
System.out.println(ans);
// boolean det = false;
// int maxlayer = 1;
// long ans = 1;
// for (int i = 0; i < N; i++) {
// if (d[i] == 'f') {
// if (!det) {
// //System.out.println("HERE" + maxlayer);
// ans = ans * maxlayer;
// }
// det = true;
// maxlayer++;
// //System.out.println("HERE");
// } else if (d[i] == 's') {
// if (det) {
// det = false;
// continue;
// }
// det = false;
// System.out.println(maxlayer);
// ans = ans * maxlayer;
// }
// }
//
// System.out.println(ans);
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.* ;
import java.io.* ;
public class PythonIndentation
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in) ;
int n = in.nextInt() ;
boolean[] lst = new boolean[n] ;
for(int i=0;i<n;i++)
{
lst[i] = (in.next().equals("s"))?false:true ;
}
System.out.println(dp(lst)) ;
}
static long dp(boolean[] lst)
{//false in lst means an "s" (simple statement), and true a "f"(for loop)
long[][] dp = new long[lst.length][lst.length] ;
dp[0][0] = 1 ;
for(int i=1;i<lst.length;i++)
{
for(int j=0;j<lst.length;j++)
{
if(lst[i-1])//(i-1)st statement is a for loop
{
if(j==0)
dp[i][j] = 0 ;
else
dp[i][j] = dp[i-1][j-1] ;
}
else//i-1 st statement is a simple statement
{
if(j==0)
{
for(int k=0;k<lst.length;k++)
dp[i][j] = (dp[i][j]+dp[i-1][k])%1000000007 ;
}
else
dp[i][j] = (dp[i][j-1]-dp[i-1][j-1])%1000000007 ;
}
}
}
long ans = 0 ;
for(int i=0;i<lst.length;i++)
{
ans = (ans + dp[lst.length-1][i])%1000000007 ;
}
if(ans<0)
ans = ans + 1000000007 ;
return ans ;
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.*;
import java.io.*;
public class c implements Runnable{
int N;
int[] arr;
public static void main(String[] args) { new Thread(null, new c(), "", 1<<27).start(); } public void run() {
arr = new int[N = nextInt()];
for(int n=0;n<N;n++) {
// System.out.println(n+" s");
if(nextString().charAt(0) == 'f') {
arr[n] = 1;
}
}
long[][] dp = new long[N+1][N+1];
dp[0][0] = 1;
for(int i = 0; i < N; i++) {
// if this is an s
if(arr[i] == 0) {
// transition from the one directly above and everything to the right of that
// for each dp space. using cumulative sums will make this easier
long sum = 0;
for(int j = N; j >= 0; j--) {
sum += dp[i][j];
sum %= 1_000_000_007L;
dp[i+1][j] += sum;
dp[i+1][j] %= 1_000_000_007L;
}
}
// otherwise, this is an f
else {
// transition from the spot on the top left
for(int j = 1; j <= N; j++) {
dp[i+1][j] += dp[i][j-1];
dp[i+1][j] %= 1_000_000_007L;
}
}
}
// answer is the sum of the last row
long ans = 0;
for(long l : dp[N-1]) ans = (ans + l) % 1_000_000_007;
System.out.println(ans);
}
// fast scanner stuff
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = null; int line_ptr = 0;
void read() {
try {
line = br.readLine().split(" ");
}
catch(IOException ioe) {
System.err.println("bad input");
line = null;
}
}
void ensure() {
while(line == null || line.length <= line_ptr) {
read();
line_ptr = 0;
}
}
int nextInt() {
ensure();
return Integer.parseInt(line[line_ptr++]);
}
long nextLong() {
ensure();
return Integer.parseInt(line[line_ptr++]);
}
String nextString() {
ensure();
return line[line_ptr++];
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class C {
static int MOD = 1_000_000_007;
public static void main(String[] args) {
MyScanner in = new MyScanner();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
char prev = ' ';
// index, maxNumOfIntents -> count
int[][] dp = new int[n+1][n+2];
dp[0][0] = 1;
for(int i=0;i<n;++i){
char ch = in.next().charAt(0);
if(prev == 's'){
int sum = 0;
for(int j=n;j>=0;--j){
sum = (sum + dp[i-1][j]) % MOD;
dp[i][j] = sum;
}
}else if(prev == 'f'){
for(int j=0;j<n;++j){
dp[i][j+1] = dp[i-1][j];
}
}
prev = ch;
}
int result = 0;
for(int i=0;i<=n;++i){
result = (result + dp[n-1][i]) % MOD;
}
out.println(result);
out.close();
}
// -----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// --------------------------------------------------------
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.*;
public class PythonIndentation {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
int a[]=new int[t];
int c=0;
a[0]=1;
long mod=(long) (1e9+7);
sc.nextLine();
for(int i=0;i<t;i++)
{
String s=sc.nextLine();
if(s.equals("f"))
c++;
else
{
for(int j=1;j<=c;j++)
{
a[j]=(int) (((a[j]%mod)+(a[j-1]%mod))%mod);
}
}
}
System.out.println(a[c]);
sc.close();
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.Scanner;
public class Main3 implements Runnable {
public static void main(String[] args) {
new Thread(null, new Main3(), "", 128 * 1024 * 1024).start();
}
private static Scanner in = new Scanner(System.in);
public void run() {
int n = in.nextInt();
int m = 1_000_000_007;
boolean[] state = new boolean[n];
for (int i = 0; i < n; i++) {
state[i] = in.next().equals("f");
}
// 使うのは[n][n]だけど、j+1==nのときif分岐せずに済むようにn+1にしてる
long[][] dp = new long[n][n + 1];
dp[0][0] = 1;
// iは既に埋まっていてi+1に書き込んでいくから、i<n-1まででいい
for (int i = 0; i < n - 1; i++) {
if (state[i]) {
// 右下にコピーしていくから溢れないようにj<n-1
for (int j = 0; j < n - 1; j++) {
dp[i + 1][j + 1] = dp[i][j];
}
} else {
// 何通りかというのを右から埋めていくからj--で進める
for (int j = n - 1; j >= 0; j--) {
// 足していくと大きくなるからこの時点でもう%mしておく
dp[i + 1][j] = (dp[i][j] + dp[i + 1][j + 1]) % m;
}
}
}
long sum = 0;
for (int i = 0; i < n; i++) {
sum += dp[n - 1][i] % m;
}
System.out.println(sum % m);
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.* ;
import java.util.* ;
import java.text.* ;
import java.math.* ;
import static java.lang.Math.min ;
import static java.lang.Math.max ;
public class Codeshefcode{
public static void main(String[] args) throws IOException{
Solver Machine = new Solver() ;
Machine.Solve() ;
Machine.Finish() ;
// new Thread(null,new Runnable(){
// public void run(){
// Solver Machine = new Solver() ;
// try{
// Machine.Solve() ;
// Machine.Finish() ;
// }catch(Exception e){
// e.printStackTrace() ;
// System.out.flush() ;
// System.exit(-1) ;
// }catch(Error e){
// e.printStackTrace() ;
// System.out.flush() ;
// System.exit(-1) ;
// }
// }
// },"Solver",1l<<27).start() ;
}
}
class Mod{
static long mod=1000000007 ;
static long d(long a,long b){ return (a*MI(b))%mod ; }
static long m(long a,long b){ return (a*b)%mod ; }
static private long MI(long a){ return pow(a,mod-2) ; }
static long pow(long a,long b){
if(b<0) return pow(MI(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 ;
}
}
class pair implements Comparable<pair>{
int x ; int y ;
pair(int x,int y){ this.x=x ; this.y=y ;}
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)))) ;
}
}
class Solver{
Reader ip = new Reader(System.in) ;
PrintWriter op = new PrintWriter(System.out) ;
long dp[][] ;
public void Solve() throws IOException{
int n = ip.i() ;
int arr[] = new int[n] ;
dp = new long[n][n] ;
for(int i=0 ; i<n ; i++)
for(int j=0 ; j<n ; j++)
dp[i][j]=-1 ;
for(int i=0 ; i<n ; i++){
String s = ip.s() ;
if(s.compareTo("s")==0) arr[i]=0 ;
else if(s.compareTo("f")==0) arr[i]=1 ;
else throw new IOException() ;
}
for(int j=0 ; j<n ; j++) dp[n-1][j] = 1 ;
for(int i=(n-2) ; i>=0 ; i--){
long cuml[] = new long[n] ;
for(int j=0 ; j<n ; j++) cuml[j] = (dp[i+1][j]+(j==0 ? 0 : cuml[j-1]))%Mod.mod ;
for(int j=0 ; j<n ; j++)
dp[i][j] = (arr[i]==0 ? cuml[j] : (j==(n-1) ? -1 : dp[i+1][j+1])) ;
}
pln(dp[0][0]) ;
}
void Finish(){
op.flush();
op.close();
}
void p(Object o){
op.print(o) ;
}
void pln(Object o){
op.println(o) ;
}
}
class mylist extends ArrayList<String>{}
class myset extends TreeSet<Integer>{}
class mystack extends Stack<Integer>{}
class mymap extends TreeMap<Long,Integer>{}
class Reader {
BufferedReader reader;
StringTokenizer tokenizer;
Reader(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("") ;
}
String s() throws IOException {
while (!tokenizer.hasMoreTokens()){
tokenizer = new StringTokenizer(
reader.readLine()) ;
}
return tokenizer.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()) ;
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.*;
import java.util.*;
public final class PythonIndentation
{
public static void main(String[] args)
{
new PythonIndentation(System.in, System.out);
}
static class Solver implements Runnable
{
static final int MOD = (int) 1e9 + 7;
int n;
char[] arr;
long[][] dp;
BufferedReader in;
PrintWriter out;
void solve() throws IOException
{
n = Integer.parseInt(in.readLine());
arr = new char[n];
dp = new long[n + 1][n + 1];
for (int i = 0; i < n; i++)
arr[i] = in.readLine().charAt(0);
for (int i = 0; i <= n; i++)
Arrays.fill(dp[i], -1);
dp[0][0] = 1;
if (arr[0] == 's')
out.println(find(1, 0));
else
out.println(find(1, 1));
}
long find(int curr, int backIndents)
{
if (backIndents < 0)
return 0;
if (curr == n)
return 1;
if (dp[curr][backIndents] != -1)
return dp[curr][backIndents];
long ans;
if (arr[curr] == 's')
{
if (arr[curr - 1] == 'f')
ans = find(curr + 1, backIndents);
else
ans = CMath.mod(find(curr + 1, backIndents) + find(curr, backIndents - 1), MOD);
}
else
{
ans = find(curr + 1, backIndents + 1);
if (arr[curr - 1] != 'f')
ans = CMath.mod(ans + find(curr, backIndents - 1), MOD);
}
return dp[curr][backIndents] = ans;
}
public Solver(BufferedReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
@Override public void run()
{
try
{
solve();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
static class CMath
{
static long mod(long number, long mod)
{
return number - (number / mod) * mod;
}
}
private PythonIndentation(InputStream inputStream, OutputStream outputStream)
{
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
PrintWriter out = new PrintWriter(outputStream);
Thread thread = new Thread(null, new Solver(in, out), "PythonIndentation", 1 << 29);
try
{
thread.start();
thread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
out.flush();
out.close();
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
static char[] arr;
static int mod = (int) 1e9 + 7;
static int[][] memo;
static int n;
static int solve(int idx, int depth) {
if (idx == n) {
return depth == 0 ? 1 : 0;
}
if (memo[idx][depth] != -1)
return memo[idx][depth];
int ret = 0;
if (arr[idx] == 's') {
if (depth > 0)
ret = ret + solve(idx, depth - 1);
ret = (ret + solve(idx + 1, depth)) % mod;
}
if (arr[idx] == 'f' || arr[idx] == 'z')
ret = (ret + solve(idx + 1, depth + 1)) % mod;
return memo[idx][depth] = ret;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
arr = new char[n];
for (int i = 0; i < n; i++)
arr[i] = sc.next().charAt(0);
memo = new int[n + 1][n + 1];
for (int[] x : memo)
Arrays.fill(x, -1);
System.out.println(solve(0, 0));
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.Scanner;
public class maestro{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
long mod = (long)Math.pow(10,9)+7;
long[][] arr = new long[N][N];
arr[0][0]=1;
for (int i=1;i<N;i++){
char c = sc.next().charAt(0);
if (c=='f'){
for (int j=1;j<N;j++) arr[i][j] = arr[i - 1][j - 1];
}
else {
long sum=0;
for (int j=N-1;j>=0;j--){
sum=(sum+arr[i-1][j])%mod;
arr[i][j] = sum;
}
}
}
long ans=0;
for (int i=0;i<N;i++) ans=(ans+arr[N-1][i])%mod;
System.out.println(ans);
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.* ;
public class PythonIndentation
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in) ;
int n = in.nextInt() ;
boolean[] lst = new boolean[n] ;
for(int i=0;i<n;i++)
{
lst[i] = (in.next().equals("s"))?false:true ;
}
System.out.println(dp(lst)) ;
}
static int dp(boolean[] lst)
{//false in lst means an "s" (simple statement), and true a "f"(for loop)
int[][] dp = new int[2][lst.length] ;
dp[0][0] = 1 ;
for(int i=1;i<lst.length;i++)
{
for(int j=0;j<lst.length;j++)
{
if(lst[i-1])//(i-1)st statement is a for loop
{
if(j==0)
dp[i%2][j] = 0 ;
else
dp[i%2][j] = dp[(i-1)%2][j-1] ;
}
else//i-1 st statement is a simple statement
{
if(j==0)
{
int temp = 0 ;
for(int k=0;k<lst.length;k++)
temp = (temp+dp[(i-1)%2][k])%1000000007 ;
dp[i%2][j] = temp ;
}
else
dp[i%2][j] = (dp[i%2][j-1]-dp[(i-1)%2][j-1])%1000000007 ;
}
}
}
int ans = 0 ;
for(int i=0;i<lst.length;i++)
{
ans = (ans + dp[(lst.length-1)%2][i])%1000000007 ;
}
if(ans<0)
ans = ans + 1000000007 ;
return ans ;
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.*;
/**
*
* @author rohan
*/
public class Main {
static int mod = (int) (1e9+7);
static int MAX = (int)2e5+5;
static void solve()
{
int n = i();
String[] s = new String[n];
for(int i = 0 ; i<n ; i++)
{
s[i] = s();
}
int[][] dp = new int[n][n];
dp[0][0] = 1;
for(int i = 1; i<n; i++)
{
if(s[i-1].equals("f"))
{
for (int j = i-1 ; j>=0 ; j--)
{
dp[i][j+1] = dp[i-1][j];
}
}
else
{
int suff = 0;
for(int j = i-1; j>=0 ; j--)
{
suff += dp[i-1][j];
if(suff>=mod) suff-= mod;
dp[i][j] = suff;
}
}
}
int sum = 0;
for (int i=0 ; i<n; i++)
{
sum = sum+dp[n-1][i];
if(sum>=mod)
sum-=mod;
}
out.println(sum);
out.close();
}
///////////////////////////////////////////////////////////////////
static InputReader sc = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args)
{
new Thread(null,new Runnable() {
@Override
public void run() {
try{
solve();
}
catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<26).start();
}
static class Pair implements Comparable<Pair>{
int x,y,i;
Pair (int x,int y,int i)
{
this.x = x;
this.y = y;
this.i = i;
}
Pair (int x,int y)
{
this.x = x;
this.y = y;
}
public int compareTo(Pair o)
{
return -(this.y-o.y);
}
public boolean equals(Object o)
{
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y==y;
}
return false;
}
@Override
public String toString()
{
return x + " "+ y + " "+i;
}
public int hashCode()
{
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}
}
static class Merge
{
public static void sort(int inputArr[])
{
int length = inputArr.length;
doMergeSort(inputArr,0, length - 1);
}
private static void doMergeSort(int[] arr,int lowerIndex, int higherIndex) {
if (lowerIndex < higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
doMergeSort(arr,lowerIndex, middle);
doMergeSort(arr,middle + 1, higherIndex);
mergeParts(arr,lowerIndex, middle, higherIndex);
}
}
private static void mergeParts(int[]array,int lowerIndex, int middle, int higherIndex)
{
int[] temp=new int[higherIndex-lowerIndex+1];
for (int i = lowerIndex; i <= higherIndex; i++) {
temp[i-lowerIndex] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (temp[i-lowerIndex] < temp[j-lowerIndex])
{
array[k] = temp[i-lowerIndex];
i++;
}
else
{
array[k] = temp[j-lowerIndex];
j++;
}
k++;
}
while (i <= middle) {
array[k] = temp[i-lowerIndex];
k++;
i++;
}
while(j<=higherIndex){
array[k]=temp[j-lowerIndex];
k++;
j++;
}
}
}
static long add(long a,long b){
long x=(a+b);
while(x>=mod) x-=mod;
return x;
}
static long sub(long a,long b){
long x=(a-b);
while(x<0) x+=mod;
return x;
}
static long mul(long a,long b){
a%=mod;
b%=mod;
long x=(a*b);
return x%mod;
}
static boolean isPal(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long gcd(long x,long y){
if(y==0)
return x;
else
return gcd(y,x%y);
}
static int gcd(int x,int y){
if(y==0)
return x;
else
return gcd(y,x%y);
}
static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
static long mulmod(long a,long b,long m) {
if (m <= 1000000009) return a * b % m;
long res = 0;
while (a > 0)
{
if ((a&1)!=0)
{
res += b;
if (res >= m) res -= m;
}
a >>= 1;
b <<= 1;
if (b >= m) b -= m;
}
return res;
}
static int abs(int a,int b){
return (int)Math.abs(a-b);
}
public static long abs(long a,long b){
return (long)Math.abs(a-b);
}
static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int 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 long[] nextLongArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
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);
}
}
static int i()
{
return sc.nextInt();
}
static long l(){
return sc.nextLong();
}
static int[] iarr(int n)
{
return sc.nextIntArray(n);
}
static long[] larr(int n)
{
return sc.nextLongArray(n);
}
static String s(){
return sc.nextLine();
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class C {
static int MOD = 1_000_000_007;
public static void main(String[] args) {
MyScanner in = new MyScanner();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
char prev = ' ';
// index, maxNumOfIntents -> count
int[][] dp = new int[n+1][n+2];
dp[0][0] = 1;
for(int i=0;i<n;++i){
char ch = in.next().charAt(0);
if(prev == 's'){
int sum = 0;
for(int j=n;j>=0;--j){
sum = (sum + dp[i-1][j]) % MOD;
dp[i][j] = sum;
}
}else if(prev == 'f'){
for(int j=0;j<n;++j){
dp[i][j+1] = dp[i-1][j];
}
}
prev = ch;
}
int result = 0;
for(int i=0;i<=n;++i){
result = (result + dp[n-1][i]) % MOD;
}
out.println(result);
out.close();
}
// -----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// --------------------------------------------------------
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class C {
//why am I MLE'ing???
int n;
char[] a;
long[][] memo;
long mod = (long) 1e9 + 7;
boolean lastFor(int i) {
if(i == 0) return false;
return a[i - 1] == 'f';
}
long dp(int ind, int curIndent) {
if(ind == n) return 1;
if(curIndent < 0) return 0;
if(memo[ind][curIndent] != -1) return memo[ind][curIndent];
long ans = 0;
if(a[ind] == 'f' && lastFor(ind)) {
ans += dp(ind + 1, curIndent + 1);
} else if(a[ind] == 'f' && !lastFor(ind)) {
ans += dp(ind, curIndent - 1);
ans += dp(ind + 1, curIndent + 1);
// for(int indent = 1; indent <= curIndent + 1; ++indent) {
// ans += dp(ind + 1, indent);
// }
} else if(a[ind] == 's' && lastFor(ind)) {
ans += dp(ind + 1, curIndent);
} else if(a[ind] == 's' && !lastFor(ind)) {
ans += dp(ind + 1, curIndent);
ans += dp(ind, curIndent - 1);
// for(int indent = 0; indent <= curIndent; ++indent) {
// ans += dp(ind + 1, indent);
// }
}
return memo[ind][curIndent] = ans % mod;
}
public void solve(Scanner in, PrintWriter out) {
n = in.nextInt();
a = new char[n];
int forCount = 0;
int[] fc = new int[n + 1];
for(int i = 0; i < n; ++i) {
a[i] = in.next().charAt(0);
if(a[i] == 'f') ++forCount;
fc[i] = forCount;
}
fc[n] = fc[n - 1];
// long time = System.currentTimeMillis();
memo = new long[n][forCount + 1];
for(long[] aa : memo) {
Arrays.fill(aa, -1);
}
for(int i = n; i >= 0; --i) {
for(int indent = fc[i] - 1; indent >= 0; --indent) {
dp(i, indent);
}
}
out.println(dp(0, 0) % mod);
// System.out.println(System.currentTimeMillis() - time);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
new C().solve(in, out);
in.close();
out.close();
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ankur
*/
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();
}
static class TaskC {
long mod = (long) 1e9 + 7;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
char ar[] = new char[n];
for (int i = 0; i < n; i++) {
ar[i] = in.readString().charAt(0);
}
long dp[][] = new long[n + 1][n + 1];
for (int i = 0; i < n; i++) {
dp[n - 1][i] = 1;
}
long prev = n;
for (int i = n - 2; i >= 0; i--) {
if (ar[i] == 'f') {
if (ar[i + 1] == 's') {
for (int j = n - 2; j >= 0; j--) {
dp[i][j] = dp[i + 1][j + 1];
}
} else {
for (int j = n - 2; j >= 0; j--) {
dp[i][j] = dp[i + 1][j + 1];
}
}
} else {
for (int j = n - 1; j >= 0; j--) {
if (prev < 0) {
prev += mod;
}
dp[i][j] = prev;
prev = prev - dp[i + 1][j];
}
}
prev = 0;
for (int j = 0; j < n; j++) {
prev += dp[i][j];
prev = prev % mod;
}
}
out.println(dp[0][0] % mod);
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
//*-*------clare------
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 res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
final int P = (int) 1e9 + 7;
int n;
char[] commands;
int[][] memo;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
commands = new char[n];
memo = new int[n][12345];
for (int i = 0; i < n; i++) {
commands[i] = in.next().charAt(0);
for (int j = 0; j < 12345; j++) {
memo[i][j] = -1;
}
}
out.print(solve(1, 0));
}
int add(int a, int b) {
return ((a % P) + (b % P)) % P;
}
int solve(int i, int indents) {
if (i == n) return 1;
if (memo[i][indents] != -1) return memo[i][indents];
int answer;
if (commands[i - 1] == 'f') {
answer = solve(i + 1, indents + 1);
} else {
if (indents == 0) {
answer = solve(i + 1, indents);
} else {
answer = add(solve(i, indents - 1), solve(i + 1, indents));
}
}
return memo[i][indents] = answer;
}
}
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());
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
static final long MODULO = (long) (1e9 + 7);
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
long[][] dp = new long[n + 100][n + 100];
dp[0][0] = 1;
for (int i = 0; i < n; ++i) {
char current = in.nextCharacter();
if (current == 'f') {
for (int j = 0; j < n; ++j) {
//our only option is to go 1 depth deeper
dp[i + 1][j + 1] += dp[i][j];
dp[i + 1][j + 1] %= MODULO;
}
} else {
long runningSum = 0;
for (int j = n; j >= 0; --j) {
// for each j all preceding depths are possible
// can also implement partial sum to improve
// time complexity to dpeth * n only(affect only if no. of f are less than n s
runningSum += dp[i][j];
runningSum %= MODULO;
dp[i + 1][j] += runningSum;
dp[i + 1][j] %= MODULO;
}
}
}
out.println(dp[n][0]);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public char nextCharacter() {
int c = pread();
while (isSpaceChar(c))
c = pread();
return (char) c;
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
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 Liavontsi Brechka
*/
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();
}
static
@SuppressWarnings("Duplicates")
class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int MAX = 6000;
int MOD = 1000000007;
int n = in.nextInt();
int[][] dp = new int[n][MAX];
dp[0][0] = 1;
char next;
int current;
for (int i = 0; i < n; i++) {
next = in.next().charAt(0);
if (i == n - 1) continue;
current = 0;
for (int j = MAX - 1; j >= 0; j--) {
if (dp[i][j] != 0) {
if (next == 'f') {
if (j < MAX - 1) dp[i + 1][j + 1] = (dp[i + 1][j + 1] + dp[i][j]) % MOD;
} else {
current = (current + dp[i][j]) % MOD;
}
}
if (next == 's') dp[i + 1][j] = current;
}
}
int res = 0;
for (int i = 0; i < MAX; i++) {
res = (res + dp[n - 1][i]) % MOD;
}
out.print(res);
}
}
static class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(readLine());
}
return tokenizer.nextToken();
}
public String readLine() {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class C {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
List<String> commands = IntStream.range(0, n).boxed().map(x -> s.next()).collect(Collectors.toList());
List<Integer> ways = new ArrayList<>();
ways.add(1);
boolean lastWasS = false;
for (String command : commands) {
boolean isS = "s".equals(command);
if (lastWasS) {
for (int i = 1; i < ways.size(); ++i) {
int waysNumber = (ways.get(i-1) + ways.get(i)) % 1_000_000_007;
ways.set(i, waysNumber);
}
}
if (!isS) {
ways.add(0);
}
lastWasS = isS;
}
System.out.println(ways.stream().reduce(0, (a, b) -> (a + b) % 1_000_000_007));
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws IOException
{
// StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
FastScanner sc = new FastScanner();
int dp[][]=new int[6000][6000];
char a[]=new char[6000];
final int n=sc.nextInt();
boolean flag=false;
int cnt=0;
char pre='f';
for(int i=1;i<=n;i++)
{
a[i]=sc.next().charAt(0);
}
dp[1][1]=1;
final int mod=(int)1e9+7;
dp[1][1]=1;
for(int i=2;i<=n;i++)
{
if(a[i-1]=='s')
{
int now=0;
for(int j=5050;j>=1;j--)
{
now=(now+dp[i-1][j])%mod;
dp[i][j]=now;
}
}
else
{
for(int j=5050;j>=1;j--)
{
dp[i][j]=dp[i-1][j-1]%mod;
}
}
}
int ans=0;
for(int i=0;i<=5050;i++)
{
ans+= dp[n][i]%mod;
ans%=mod;
}
out.println(ans%mod);
out.flush();
}
/*
6
f
s
f
s
f
s
*/
static class FastScanner {
BufferedReader br;
StringTokenizer st;
private FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
private boolean hasNextToken()
{
if(st.countTokens()!=StreamTokenizer.TT_EOF)
{
return true;
}
else
return false;
}
private String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
private BigInteger nextBigInteger(){return new BigInteger(next());}
private BigDecimal nextBigDecimal(){return new BigDecimal(next());}
private int nextInt() {return Integer.parseInt(next());}
private long nextLong() {return Long.parseLong(next());}
private double nextDouble() {return Double.parseDouble(next());}
private String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
private int[] nextIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
private long[] nextLongArray(int n){
long[] a = new long[n];
for(int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
private double[] nextDoubleArray(int n){
double[] a = new double[n];
for(int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
private char[][] nextGrid(int n, int m){
char[][] grid = new char[n][m];
for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
return grid;
}
private void sort(int arr[])
{
int cnt[]=new int[(1<<16)+1];
int ys[]=new int[arr.length];
for(int j=0;j<=16;j+=16){
Arrays.fill(cnt,0);
for(int x:arr){cnt[(x>>j&0xFFFF)+1]++;}
for(int i=1;i<cnt.length;i++){cnt[i]+=cnt[i-1];}
for(int x:arr){ys[cnt[x>>j&0xFFFF]++]=x;}
{ final int t[]=arr;arr=ys;ys=t;}
}
if(arr[0]<0||arr[arr.length-1]>=0)return;
int i,j,c;
for(i=arr.length-1,c=0;arr[i]<0;i--,c++){ys[c]=arr[i];}
for(j=arr.length-1;i>=0;i--,j--){arr[j]=arr[i];}
for(i=c-1;i>=0;i--){arr[i]=ys[c-1-i];}
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ShekharN
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
private final int MOD = (int) (1e9 + 7);
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextString();
}
int[] dp = new int[n];
Arrays.parallelSetAll(dp, i -> 0);
dp[0] = 1;
int cnt = 0;
for (int i = 0; i < n; i++) {
if (arr[i].equals("f")) {
cnt++;
continue;
}
calc(dp, n, cnt);
cnt = 0;
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += dp[i];
sum %= MOD;
}
out.println(sum);
}
private void calc(int[] dp, int n, int cnt) {
for (int i = n - 1; i >= 0; i--) {
if (i != n - 1) dp[i] += dp[i + 1];
dp[i] %= MOD;
}
//int[] tmp = new int[n];
int prev = dp[0];
for (int i = 0, y = 0; i < MathUtil.gcdInt(n, cnt); i++) {
//tmp[(i+cnt)%n] = dp[i];
y = i;
prev = dp[i];
do {
int nextId = (y + cnt) % n;
int tmp = dp[nextId];
dp[nextId] = prev;
prev = tmp;
y = nextId;
} while (y != i);
}
//Arrays.parallelSetAll(dp,i->tmp[i]);
}
}
static class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
public String nextString() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
static class MathUtil {
public static int gcdInt(int a, int b) {
if (b == 0) return a;
return gcdInt(b, a % b);
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/*
public class _909C {
}
*/
public class _909C {
int mod = (int) 1e9 + 7;
public void solve() throws FileNotFoundException {
InputStream inputStream = System.in;
InputHelper in = new InputHelper(inputStream);
// actual solution
int n = in.readInteger();
char[] a = new char[n];
for (int i = 0; i < n; i++) {
a[i] = in.read().charAt(0);
}
int[][][] dp = new int[2][n + 1][2];
dp[0][0][0] = dp[0][0][1] = 1;
for (int i = 1; i < n; i++) {
for (int j = n; j >= 0; j--) {
if (a[i - 1] == 's') {
dp[1][j][0] = dp[1][j][1] = dp[0][j][1];
} else {
if (j > 0)
dp[1][j][0] = dp[1][j][1] = dp[0][j - 1][0];
}
}
for (int j = 0; j <= n; j++) {
dp[0][j][0] = dp[1][j][0];
dp[0][j][1] = dp[1][j][1];
dp[1][j][0] = 0;
dp[1][j][1] = 0;
}
for (int j = n - 1; j >= 0; j--) {
dp[0][j][1] += dp[0][j + 1][1];
dp[0][j][1] %= mod;
}
}
System.out.println(dp[0][0][1]);
// end here
}
public static void main(String[] args) throws FileNotFoundException {
(new _909C()).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());
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.*;
public class Main {
static int N;
static int [][] dp;
static int M = (int)(1e9 + 7);
static ArrayList<Integer> l;
static int f(int idx, int b) {
if(idx == l.size())
return 1;
if(dp[idx][b] != -1)
return dp[idx][b];
long ret = f(idx + 1, b + l.get(idx));
if(b > 0)
ret += f(idx, b - 1);
return dp[idx][b] = (int) (ret % M);
}
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner();
N = sc.nextInt();
int [] val = new int[N];
for(int i = 0; i < N; ++i)
if(sc.next().charAt(0) == 's')
val[i] = 0;
else
val[i] = 1;
l = new ArrayList<Integer>();
l.add(val[0]);
for(int i = 1; i < N; ++i)
if(val[i] == val[i - 1] && val[i] == 1) {
int prev = l.get(l.size() - 1);
l.set(l.size() - 1, ++prev);
} else if(val[i - 1] == 0){
l.add(val[i]);
}
// System.out.println(l);
dp = new int[l.size() + 1][N + 1];
for(int i = 0; i <= l.size(); ++i)
Arrays.fill(dp[i], -1);
System.out.println(f(0, 0));
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class PythonIndentiation {
PrintWriter pw = new PrintWriter(System.out);
final static boolean debugmode = true;
public static int k = 7; // for 10^9 + k mods.
public static int STMOD = 1000000000 + k; // 10^9 + k
public static Reader sc = new Reader();
public static void main(String[] args) throws IOException {
int commands = sc.nextInt();
int[][] dp = new int[5000][5000];
int interesting = 0;
String prgm = "";
while (interesting < commands){
byte q = sc.read();
if (q == 115 ){
interesting += 1;
prgm += "s";
}
else if (q == 102){
prgm += "f";
interesting += 1;
}
}
//System.out.println("Program: "+prgm);
dp[0][0] = 1; // line, indentations
for(int line = 1;line<commands;line++){
if(prgm.charAt(line-1) == 'f'){
for(int indent = 1;indent<Math.min(2*line + 1, 5000);indent++){
dp[line][indent] = dp[line-1][indent-1];
}
}
else if(prgm.charAt(line-1) == 's'){
int w = 0;
for(int indent = Math.min(2*line + 1, 4999);indent >= 0;indent--){
w = (w + dp[line-1][indent])% STMOD;
dp[line][indent] = w ;
}
}
}
int q = 0;
for(int i = 0;i<5000;i++){
q = ( q + dp[commands-1][i] ) % STMOD;
}
System.out.println(q);
}
public static String parseIt(int commands) throws IOException{
String c = "";
System.out.println(sc.read());
return c;
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.lang.Math;
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader in;
static PrintStream out;
static StringTokenizer tok;
@SuppressWarnings("empty-statement")
public static void main(String[] args) throws NumberFormatException, IOException, Exception {
in = new BufferedReader(new InputStreamReader(System.in));
//in = new BufferedReader(new FileReader("metro.txt"));
out = System.out;
long mod = (long)1e9 + 7;
int n = nextInt();
long[][] dp = new long[n+1][n+1];
Character[] line = new Character[n+1];
line[0] = 'a';
for (int i = 1; i <= n; i++) {
line[i] = nextToken().charAt(0);
if(line[i-1] == 'f')//for
{
for (int j = 0; j < i; j++) {
dp[i][j+1] = dp[i-1][j];
}
}
else if(line[i-1] == 's')//simple
{
long temp = 0;
for(int j = i; j >=0; j--)
{
temp = (temp + dp[i-1][j]) % mod;
dp[i][j] = temp;
}
}
else dp[i][0] = 1;
}
long total = 0;
for(int j = 0; j <= n; j++)
total = (total + dp[n][j]) % mod;
out.println(total);
}
static String nextToken() throws IOException
{
String line = "";
while(tok == null || !tok.hasMoreTokens()) {
if((line = in.readLine()) != null)
tok = new StringTokenizer(line);
else
return null;
}
return tok.nextToken();
}
static int nextInt() throws NumberFormatException, IOException
{
return Integer.parseInt(nextToken());
}
static long nextLong() throws NumberFormatException, IOException
{
return Long.parseLong(nextToken());
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception {
MyReader reader = new MyReader(System.in);
// MyReader reader = new MyReader(new FileInputStream("input.txt"));
MyWriter writer = new MyWriter(System.out);
new Solution().run(reader, writer);
writer.close();
}
private void run(MyReader reader, MyWriter writer) throws IOException, InterruptedException {
int n = reader.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = reader.nextString().charAt(0);
}
long[][] d = new long[n + 1][n + 1];
d[0][0] = 1;
long mod = 1_000_000_007;
for (int i = 1; i < n; i++) {
for (int j = n - 1; j >= 0; j--) {
if (a[i - 1] == 'f') {
d[i][j + 1] = d[i - 1][j];
} else {
d[i][j] = (d[i - 1][j] + d[i][j + 1]) % mod;
}
}
}
long ans = 0;
for (int i = 0; i <= n; i++) {
ans += d[n - 1][i];
}
writer.print(ans % mod);
}
static class MyReader {
final BufferedInputStream in;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = bufSize;
int k = bufSize;
boolean end = false;
final StringBuilder str = new StringBuilder();
MyReader(InputStream in) {
this.in = new BufferedInputStream(in, bufSize);
}
int nextInt() throws IOException {
return (int) nextLong();
}
int[] nextIntArray(int n) throws IOException {
int[] m = new int[n];
for (int i = 0; i < n; i++) {
m[i] = nextInt();
}
return m;
}
int[][] nextIntMatrix(int n, int m) throws IOException {
int[][] a = new int[n][0];
for (int j = 0; j < n; j++) {
a[j] = nextIntArray(m);
}
return a;
}
long nextLong() throws IOException {
int c;
long x = 0;
boolean sign = true;
while ((c = nextChar()) <= 32) ;
if (c == '-') {
sign = false;
c = nextChar();
}
if (c == '+') {
c = nextChar();
}
while (c >= '0') {
x = x * 10 + (c - '0');
c = nextChar();
}
return sign ? x : -x;
}
long[] nextLongArray(int n) throws IOException {
long[] m = new long[n];
for (int i = 0; i < n; i++) {
m[i] = nextLong();
}
return m;
}
int nextChar() throws IOException {
if (i == k) {
k = in.read(buf, 0, bufSize);
i = 0;
}
return i >= k ? -1 : buf[i++];
}
String nextString() throws IOException {
if (end) {
return null;
}
str.setLength(0);
int c;
while ((c = nextChar()) <= 32 && c != -1) ;
if (c == -1) {
end = true;
return null;
}
while (c > 32) {
str.append((char) c);
c = nextChar();
}
return str.toString();
}
String nextLine() throws IOException {
if (end) {
return null;
}
str.setLength(0);
int c = nextChar();
while (c != '\n' && c != '\r' && c != -1) {
str.append((char) c);
c = nextChar();
}
if (c == -1) {
end = true;
if (str.length() == 0) {
return null;
}
}
if (c == '\r') {
nextChar();
}
return str.toString();
}
char[] nextCharArray() throws IOException {
return nextString().toCharArray();
}
char[][] nextCharMatrix(int n) throws IOException {
char[][] a = new char[n][0];
for (int i = 0; i < n; i++) {
a[i] = nextCharArray();
}
return a;
}
}
static class MyWriter {
final BufferedOutputStream out;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = 0;
final byte c[] = new byte[30];
static final String newLine = System.getProperty("line.separator");
MyWriter(OutputStream out) {
this.out = new BufferedOutputStream(out, bufSize);
}
void print(long x) throws IOException {
int j = 0;
if (i + 30 >= bufSize) {
flush();
}
if (x < 0) {
buf[i++] = (byte) ('-');
x = -x;
}
while (j == 0 || x != 0) {
c[j++] = (byte) (x % 10 + '0');
x /= 10;
}
while (j-- > 0)
buf[i++] = c[j];
}
void print(int[] m) throws IOException {
for (int a : m) {
print(a);
print(' ');
}
}
void print(long[] m) throws IOException {
for (long a : m) {
print(a);
print(' ');
}
}
void print(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
print(s.charAt(i));
}
}
void print(char x) throws IOException {
if (i == bufSize) {
flush();
}
buf[i++] = (byte) x;
}
void print(char[] m) throws IOException {
for (char c : m) {
print(c);
}
}
void println(String s) throws IOException {
print(s);
println();
}
void println() throws IOException {
print(newLine);
}
void flush() throws IOException {
out.write(buf, 0, i);
out.flush();
i = 0;
}
void close() throws IOException {
flush();
out.close();
}
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.*;
public class init {
static class p{
int i;
int c;
public p(int i,int c) {
this.i=i;this.c=c;
// TODO Auto-generated constructor stub
}
}
static int mod=1000000007;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) {
char c=s.next().charAt(0);
if(c=='f')
a[i]=1;
}
int dp[][]=new int[n+1][n+1];
for(int i=0;i<=n;i++) {
for(int j=0;j<=n;j++)
dp[i][j]=-1;
}
System.out.println(ans(dp,1,0,a,n));
}
public static int ans(int dp[][],int i,int j,int a[],int n) {
if(i==n) {
return 1;
}
if(dp[i][j]!=-1) {
return dp[i][j];
}
if(a[i-1]==1) {
int x=ans(dp,i+1,j+1,a,n);
if(x!=-1)
dp[i][j]=x%mod;
}
else {
int x=-1;
if(j!=0)
x=ans(dp,i,j-1,a,n);
int y=ans(dp,i+1,j,a,n);
if(x!=-1)
dp[i][j]=x%mod;
if(y!=-1) {
if(dp[i][j]==-1)
dp[i][j]=y%mod;
else
dp[i][j]+=y%mod;}
}
return dp[i][j];
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.*;
import java.util.*;
public class Codeforces455Div2C {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] sp = br.readLine().split(" ");
int n = Integer.parseInt(sp[0]);
char[] list = new char[n];
for (int i = 0; i < n; i++) {
sp = br.readLine().split(" ");
list[i] = sp[0].charAt(0);
}
int[] list2 = new int[n];
int counter = 0;
for (int i = 0; i < n; i++) {
if (list[i] == 's') {
counter++;
}
else {
list2[counter]++;
}
}
int[][] dp = new int[counter][n-counter+1];
int[][] dpsum = new int[counter][n-counter+1];
int[] count = new int[counter];
count[0] = list2[0];
for (int i = 1; i < counter; i++) {
count[i] = count[i-1] + list2[i];
}
for (int i = 0; i <= count[0]; i++) {
dp[0][i] = 1;
dpsum[0][i] = i+1;
}
for (int i = 1; i < counter; i++) {
for (int j = 0; j <= count[i]; j++) {
dp[i][j] = dpsum[i-1][Math.min(j, count[i-1])];
}
dpsum[i][0] = dp[i][0];
for (int j = 1; j <= count[i]; j++) {
dpsum[i][j] = (dpsum[i][j-1]+dp[i][j])%1000000007;
}
}
System.out.println(dp[counter-1][n-counter]);
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
public class ProblemC {
static long MOD = 1_000_000_007;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
boolean[] isFor = new boolean[n];
for (int a = 0; a < n; a++) {
isFor[a] = input.next().charAt(0) == 'f';
}
long[][] array = new long[n + 1][n + 1];
array[0][0] = 1;
boolean isPreviousFor = false;
for (int idx = 0; idx < n; idx++) {
long heightCache = 0;
for (int height = n-1; height >= 0; height--) {
if (isPreviousFor) {
array[idx + 1][height + 1] += array[idx][height];
array[idx + 1][height + 1] %= MOD;
} else {
heightCache += array[idx][height];
heightCache %= MOD;
array[idx + 1][height] += heightCache;
array[idx + 1][height] %= MOD;
}
}
isPreviousFor = isFor[idx];
}
// System.out.println(Arrays.deepToString(array));
long sum = 0;
for (int height = 0; height <= n; height++) {
sum += array[n][height];
}
System.out.println(sum % MOD);
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.Scanner;
//http://codeforces.com/contest/909/problem/C
public class PythInd {
public static final int MOD = 1000000007;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String[] sTypes = new String[n];
for (int i = 0; i < n; i++) {
sTypes[i] = sc.nextLine();
}
sc.close();
// dp[i][j] = number of ways to have a for loop indented
// j times at the ith position.
int[][] dp = new int[n][n];
dp[0][0] = 1;
for (int i = 0; i < dp.length - 1; i++) {
if (sTypes[i].equals("s")) {
int curSum = 0;
for (int j = i + 1; j >= 0; j--) {
curSum = (dp[i][j] + curSum) % MOD;
dp[i + 1][j] += curSum;
dp[i + 1][j] %= MOD;
}
} else {
for (int j = 1; j <= i + 1; j++) {
dp[i + 1][j] += dp[i][j - 1];
dp[i + 1][j] %= MOD;
}
}
}
int ans = 0;
for (int i = 0; i < dp[0].length; i++) {
ans = (ans + dp[n - 1][i]) % MOD;
}
System.out.println(ans);
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.Optional;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Main main = new Main();
main.solveC();
}
private void solveA() {
Scanner sc = new Scanner(System.in);
String first = sc.next();
String last = sc.next();
String answer = first.substring(0, 1) + last.substring(0, 1);
for (int i = 2; i <= first.length(); i++) {
String current = first.substring(0, i) + last.substring(0, 1);
if (answer.compareTo(current) > 0) {
answer = current;
}
}
System.out.println(answer);
}
private void solveB() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int layer = 0;
for (int i = 1; i <= N; i++) {
int max = N - i + 1;
layer += i < max ? i : max;
}
System.out.println(layer);
}
private void solveC() {
Scanner sc = new Scanner(System.in);
final long MOD_NUM = 1000000007L;
int N = sc.nextInt();
long[] level = new long[N + 2];
level[0] = 1;
sc.nextLine();
String pre = "s";
for (int i = 0; i < N; i++) {
String line = sc.nextLine();
long[] next_level = new long[N + 2];
if (pre.equals("f")) {
for (int j = 1; j < N + 1; j++) {
next_level[j] = level[j - 1];
}
}
if (pre.equals("s")) {
for (int j = N; j >= 0; j--) {
next_level[j] = (next_level[j + 1] + level[j]) % MOD_NUM;
}
}
pre = line;
level = next_level;
}
long answer = 0L;
for (int i = 0; i < N + 1; i++) {
answer = (answer + level[i]) % MOD_NUM;
}
System.out.println(answer);
}
private void solveD() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
System.out.println(N);
}
private void solveE() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
System.out.println(N);
}
private void solveF() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
System.out.println(N);
}
interface Graph {
void link(int from, int to, long cost);
Optional<Long> getCost(int from, int to);
int getVertexNum();
}
interface FlowResolver {
long maxFlow(int from, int to);
}
/**
* グラフの行列による実装
* 接点数の大きいグラフで使うとMLEで死にそう
*/
class ArrayGraph implements Graph {
private Long[][] costArray;
private int vertexNum;
public ArrayGraph(int n) {
costArray = new Long[n][];
for (int i = 0; i < n; i++) {
costArray[i] = new Long[n];
}
vertexNum = n;
}
@Override
public void link(int from, int to, long cost) {
costArray[from][to] = new Long(cost);
}
@Override
public Optional<Long> getCost(int from, int to) {
return Optional.ofNullable(costArray[from][to]);
}
@Override
public int getVertexNum() {
return vertexNum;
}
}
/**
* DFS(深さ優先探索)による実装
* 計算量はO(E*MaxFlow)のはず (E:辺の数, MaxFlow:最大フロー)
*/
class DfsFlowResolver implements FlowResolver {
private Graph graph;
public DfsFlowResolver(Graph graph) {
this.graph = graph;
}
/**
* 最大フロー(最小カット)を求める
* @param from 始点(source)のID
* @param to 終点(target)のID
* @return 最大フロー(最小カット)
*/
public long maxFlow(int from, int to) {
long sum = 0L;
long currentFlow;
do {
currentFlow = flow(from, to, Long.MAX_VALUE / 3, new boolean[graph.getVertexNum()]);
sum += currentFlow;
} while (currentFlow > 0);
return sum;
}
/**
* フローの実行 グラフの更新も行う
* @param from 現在いる節点のID
* @param to 終点(target)のID
* @param current_flow ここまでの流量
* @param passed 既に通った節点か否かを格納した配列
* @return 終点(target)に流した流量/戻りのグラフの流量
*/
private long flow(int from, int to, long current_flow, boolean[] passed) {
passed[from] = true;
if (from == to) {
return current_flow;
}
for (int id = 0; id < graph.getVertexNum(); id++) {
if (passed[id]) {
continue;
}
Optional<Long> cost = graph.getCost(from, id);
if (cost.orElse(0L) > 0) {
long nextFlow = current_flow < cost.get() ? current_flow : cost.get();
long returnFlow = flow(id, to, nextFlow, passed);
if (returnFlow > 0) {
graph.link(from, id, cost.get() - returnFlow);
graph.link(id, from, graph.getCost(id, from).orElse(0L) + returnFlow);
return returnFlow;
}
}
}
return 0L;
}
}
/**
* 1-indexedのBIT配列
*/
class BinaryIndexedTree {
private long[] array;
public BinaryIndexedTree(int size) {
this.array = new long[size + 1];
}
/**
* 指定した要素に値を加算する
* 計算量はO(logN)
* @param index 加算する要素の添字
* @param value 加算する量
*/
public void add(int index, long value) {
for (int i = index; i < array.length; i += (i & -i)) {
array[i] += value;
}
}
/**
* 1〜指定した要素までの和を取得する
* 計算量はO(logN)
* @param index 和の終端
* @return 1〜indexまでの和
*/
public long getSum(int index) {
long sum = 0L;
for (int i = index; i > 0; i -= (i & -i)) {
sum += array[i];
}
return sum;
}
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.*;
public class A{
public static int mod = 1000000007;
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
char s[] = new char[n];
for(int i = 0; i < n; i++)
s[i] = sc.next().charAt(0);
int dp[][] = new int[5001][5001];
int sum[][] = new int[5001][5001];
dp[0][0] = 1;
sum[0][0] = 1;
for(int i = 1; i < n; i++){
for(int j = n - 1; j >= 0; j--){
if(s[i-1] == 'f' && j > 0){
dp[i][j] = dp[i-1][j-1] % mod;
}else if(s[i-1] == 's'){
dp[i][j] = sum[i-1][j] % mod;
}
sum[i][j] = (sum[i][j+1] + dp[i][j]) % mod;
}
}
System.out.println(sum[n-1][0]);
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.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;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
C909 solver = new C909();
solver.solve(1, in, out);
out.close();
}
static class C909 {
int N;
long MOD = 1_000_000_007;
boolean[] type;
long[][] memo;
long dp(int cmd, int dep) {
// safe if we came out of a statement, we can traverse
if (dep < 0) return 0;
if (cmd == N) return 1;
if (memo[cmd][dep] != -1) return memo[cmd][dep];
boolean safe = cmd == 0 ? true : !type[cmd - 1];
int d = type[cmd] ? 1 : 0;
long ways = 0;
if (!safe) {
// we must use this indentation
ways += dp(cmd + 1, dep + d);
ways %= MOD;
} else {
ways += dp(cmd + 1, dep + d);
ways %= MOD;
ways += dp(cmd, dep - 1);
ways %= MOD;
}
return memo[cmd][dep] = ways;
}
public void solve(int testNumber, FastScanner s, PrintWriter out) {
N = s.nextInt();
type = new boolean[N];
for (int i = 0; i < N; i++) {
type[i] = s.next().charAt(0) == 'f';
}
memo = new long[N][N + 1];
for (long[] a : memo)
Arrays.fill(a, -1);
out.println(dp(0, 0));
}
}
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
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++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
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();
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.*;
import java.util.*;
public class Solution {
static MyScanner sc;
private static PrintWriter out;
static long M2 = 1_000_000_000L + 7;
private static HashMap<Long, Long>[] mods;
public static void main(String[] s) throws Exception {
StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append("7 3\n" +
// "1 5 2 6 3 7 4\n" +
// "2 5 3\n" +
// "4 4 1\n" +
// "1 7 3");
//
// Random r = new Random(5);
// stringBuilder.append("100000 5000 ");
// for (int i = 0; i < 100000; i++) {
// stringBuilder.append(" " + (r.nextInt(2000000000) - 1000000000) + " ");
//
// }
// for (int k = 0; k < 5000; k++) {
// stringBuilder.append(" 1 100000 777 ");
// }
if (stringBuilder.length() == 0) {
sc = new MyScanner(System.in);
} else {
sc = new MyScanner(new BufferedReader(new StringReader(stringBuilder.toString())));
}
out = new PrintWriter(new OutputStreamWriter(System.out));
initData();
solve();
out.flush();
}
private static void solve() throws IOException {
int n = sc.nextInt();
boolean[] k = new boolean[n];
for (int r = 0; r < n; r++) {
k[r] = sc.next().charAt(0) == 'f';
}
if (k[n - 1]) {
out.println(0);
return;
}
long[][] res = new long[n + 1][n + 1];
res[0][0] = 1;
for (int t = 0; t < n; t++) {
boolean pl = t != 0 && k[t - 1];
if (pl) {
System.arraycopy(res[t], 0, res[t + 1], 1, n);
} else {
long last = 0;
for (int f = n; f >= 0; f--) {
last += res[t][f];
last %= M2;
res[t + 1][f] = last;
}
}
}
long pp = 0;
for (long kk : res[n]) {
pp += kk;
pp %= M2;
}
out.println(pp);
}
private static void initData() {
}
static char[][] data;
static String cmd;
private static final class STree {
private final Comparator<Integer> comparator;
int[] val1;
int[] from1;
int[] to1;
int[] max1;
public STree(int c, Comparator<Integer> comparator) {
this.comparator = comparator;
int size = Integer.highestOneBit(c);
if (size != c) {
size <<= 1;
}
int rs = size << 1;
val1 = new int[rs];
from1 = new int[rs];
max1 = new int[rs];
to1 = new int[rs];
Arrays.fill(from1, Integer.MAX_VALUE);
for (int r = rs - 1; r > 1; r--) {
if (r >= size) {
from1[r] = r - size;
to1[r] = r - size;
}
from1[r / 2] = Math.min(from1[r / 2], from1[r]);
to1[r / 2] = Math.max(to1[r / 2], to1[r]);
}
}
public int max(int from, int to) {
return max(1, from, to);
}
private int max(int cur, int from, int to) {
if (cur >= val1.length) return -1;
if (from <= from1[cur] && to1[cur] <= to) {
return max1[cur];
}
if (from1[cur] > to || from > to1[cur]) {
return -1;
}
cur <<= 1;
return max0(max(cur, from, to), max(cur + 1, from, to));
}
public void put(int x, int val) {
x += val1.length >> 1;
val1[x] = val;
max1[x] = val;
addToParent(x);
}
private void addToParent(int cur) {
while (cur > 1) {
cur >>= 1;
max1[cur] = max0(max1[cur << 1], max1[1 + (cur << 1)]);
}
}
private int max0(int i, int i1) {
if (i == -1) return i1;
if (i1 == -1) return i;
return comparator.compare(i, i1) > 0 ? i1 : i;
}
}
private static boolean isset(long i, int k) {
return (i & (1 << k)) > 0;
}
private static void solveT() throws IOException {
int t = sc.nextInt();
while (t-- > 0) {
solve();
}
}
private static long gcd(long l, long l1) {
if (l > l1) return gcd(l1, l);
if (l == 0) return l1;
return gcd(l1 % l, l);
}
private static long pow(long a, long b, long m) {
if (b == 0) return 1;
if (b == 1) return a;
long pp = pow(a, b / 2, m);
pp *= pp;
pp %= m;
return (pp * (b % 2 == 0 ? 1 : a)) % m;
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
MyScanner(BufferedReader br) {
this.br = br;
}
public MyScanner(InputStream in) {
this(new BufferedReader(new InputStreamReader(in)));
}
void findToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String next() {
findToken();
return st.nextToken();
}
Integer[] nab(int n) {
Integer[] k = new Integer[n];
for (int i = 0; i < n; i++) {
k[i] = sc.fi();
}
return k;
}
int[] na(int n) {
int[] k = new int[n];
for (int i = 0; i < n; i++) {
k[i] = sc.fi();
}
return k;
}
long[] nl(int n) {
long[] k = new long[n];
for (int i = 0; i < n; i++) {
k[i] = sc.nextLong();
}
return k;
}
int nextInt() {
return Integer.parseInt(next());
}
int fi() {
String t = next();
int cur = 0;
boolean n = t.charAt(0) == '-';
for (int a = n ? 1 : 0; a < t.length(); a++) {
cur = cur * 10 + t.charAt(a) - '0';
}
return n ? -cur : cur;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int[]dp1 = new int[n+1];
int[]dp2 = new int[n+1];
dp1[1] = 1;
int mod = (int) (1e9+7);
char[]instruction = new char[n+1];
instruction[0] = 's';
int[]sum = new int[n+1];
for (int i = 1; i <= n; i++) {
instruction[i] = next().charAt(0);
for (int j = 1; j <= i; j++) {
sum[j] = sum[j-1] + dp1[j];
if (sum[j] >= mod)
sum[j] -= mod;
}
for (int j = 1; j <= i; j++) {
if (instruction[i-1]=='f')
dp2[j] = dp1[j-1];
else {
dp2[j] = sum[i] - sum[j-1];
if (dp2[j] < 0)
dp2[j] += mod;
}
}
for (int j = 1; j <= i; j++) {
dp1[j] = dp2[j];
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
ans += dp1[i];
if (ans >= mod)
ans -= mod;
}
System.out.println(ans);
pw.close();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.*;
import java.text.*;
import java.io.*;
import java.math.*;
public class code5 {
InputStream is;
PrintWriter out;
static long mod=pow(10,9)+7;
static int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
String arr[];
long dp[][];
void solve() throws IOException
{
int n=ni();
arr=new String[n];
for(int i=0;i<n;i++)
arr[i]=ns();
dp=new long[n+1][n+1];
dp[0][0]=1;
for(int i=0;i<n;i++)
{
long next[]=new long[n+1];
for(int j=0;j<=i;j++)
{
if(arr[i].charAt(0)=='s')
{
next[0]+=dp[i][j];
next[j+1]-=dp[i][j];
}else {
next[j+1]+=dp[i][j];
next[j+2]-=dp[i][j];
}
}
long count=0;
for(int j=0;j<n;j++)
{
count+=next[j];
count=(count+mod)%mod;
dp[i+1][j]=count;
}
}
long ans=0;
for(int i=0;i<n;i++)
{
ans+=dp[n-1][i];
ans%=mod;
}
out.print(ans);
}
long rec(int index,int level)
{
if(index>=arr.length-1)
return 1;
if(dp[index][level]!=-1)
return dp[index][level];
dp[index][level]=0;
if(arr[index].charAt(0)=='s')
{
dp[index][level]+=rec(index+1,level);
dp[index][level]%=mod;
if(level>0)
{
dp[index][level]+=rec(index+1,0);
dp[index][level]%=mod;
}
}
else {
dp[index][level]+=rec(index+1,level+1);
dp[index][level]%=mod;
}
return dp[index][level];
}
double a[],b[],p;
int sum(int i)
{
int sum=0;
while(i!=0)
{
if((i%10)%2==1)
sum+=i%10;
i/=10;
}
return sum;
}
ArrayList<Integer> al[];
void take(int n,int m)
{
al=new ArrayList[n];
for(int i=0;i<n;i++)
al[i]=new ArrayList<Integer>();
for(int i=0;i<m;i++)
{
int x=ni()-1;
int y=ni()-1;
al[x].add(y);
al[y].add(x);
}
}
int check(long n)
{
int count=0;
while(n!=0)
{
if(n%10!=0)
break;
n/=10;
count++;
}
return count;
}
public static int count(int x)
{
int num=0;
while(x!=0)
{
x=x&(x-1);
num++;
}
return num;
}
static long d, x, y;
void extendedEuclid(long A, long B) {
if(B == 0) {
d = A;
x = 1;
y = 0;
}
else {
extendedEuclid(B, A%B);
long temp = x;
x = y;
y = temp - (A/B)*y;
}
}
long modInverse(long A,long M) //A and M are coprime
{
extendedEuclid(A,M);
return (x%M+M)%M; //x may be negative
}
public static void mergeSort(int[] arr, int l ,int r){
if((r-l)>=1){
int mid = (l+r)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,r,mid);
}
}
public static void merge(int arr[], int l, int r, int mid){
int n1 = (mid-l+1), n2 = (r-mid);
int left[] = new int[n1];
int right[] = new int[n2];
for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
int i =0, j =0, k = l;
while(i<n1 && j<n2){
if(left[i]>right[j]){
arr[k++] = right[j++];
}
else{
arr[k++] = left[i++];
}
}
while(i<n1) arr[k++] = left[i++];
while(j<n2) arr[k++] = right[j++];
}
public static void mergeSort(long[] arr, int l ,int r){
if((r-l)>=1){
int mid = (l+r)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,r,mid);
}
}
public static void merge(long arr[], int l, int r, int mid){
int n1 = (mid-l+1), n2 = (r-mid);
long left[] = new long[n1];
long right[] = new long[n2];
for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
int i =0, j =0, k = l;
while(i<n1 && j<n2){
if(left[i]>right[j]){
arr[k++] = right[j++];
}
else{
arr[k++] = left[i++];
}
}
while(i<n1) arr[k++] = left[i++];
while(j<n2) arr[k++] = right[j++];
}
static class Pair implements Comparable<Pair>{
int x,y,k;
int i,dir;
long val;
Pair (int x,int y){
this.x=x;
this.y=y;
}
public int compareTo(Pair o) {
if(this.x!=o.x)
return this.x-o.x;
return this.y-o.y;
}
public String toString(){
return x+" "+y+" "+k+" "+i;}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Long(x).hashCode()*31 + new Long(y).hashCode() ;
}
}
public static boolean isPal(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
public static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x,long y){
if(y==0)
return x;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y){
if(y==0)
return x;
return gcd(y,x%y);
}
public static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
public static int abs(int a,int b){
return (int)Math.abs(a-b);
}
public static long abs(long a,long b){
return (long)Math.abs(a-b);
}
public static int max(int a,int b){
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b){
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b){
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b){
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
void run() throws Exception {
is = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
public void run() {
try {
new code5().run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
//new code5().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 long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
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();
}
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.*;
import java.util.*;
/*
TASK: CFC
LANG: JAVA
*/
public class CFC {
static int n;
static int[][] dp;
static boolean[] s;
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in); //new FileInputStream(new File("CFC.in")));
//PrintWriter out = new PrintWriter(new File("CFC.out"));
n = in.nextInt();
if(n == 1){
System.out.println(1);
return;
}
dp = new int[n][n+1];
s = new boolean[n];
for(int i = 0;i <n; i++)s[i] = in.next().equals("s");
for(int j = 0;j < n; j++){
if(s[n-2])dp[n-1][j] = j+1;
else dp[n-1][j] = 1;
}
int suma , sumb;
for(int i = n-2; i >= 0; i--){
if(i == 0 ? true : s[i-1]){
if(s[i]) {
for (int j = 0; j < n; j++) {
dp[i][j] = ((j == 0 ? 0 : dp[i][j - 1]) + dp[i + 1][j]) % 1000000007;
}
}
else{
for(int j = 0;j < n; j++){
dp[i][j] = ((j == 0 ? 0 : dp[i][j-1]) + dp[i+1][j+1]) % 1000000007;
}
}
}
else{
if(s[i]){
for(int j = 0;j < n; j++){
dp[i][j] = dp[i+1][j];
}
}
else{
for(int j = 0;j < n; j++){
dp[i][j] = dp[i+1][j+1];
}
}
}
}
System.out.println(dp[0][0]);
}
private static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
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++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
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 (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class C455C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
ArrayList<Integer> listCount = new ArrayList<Integer>();
listCount.add(1);
boolean justf = false;
int p = 1000000007;
long ans = 0;
for(int x=0; x<n; x++){
String next = sc.nextLine();
if(next.equals("f")){
if(justf){
listCount.add(0);
}
else{
for(int i=1; i<listCount.size(); i++){
int sum = (listCount.get(i-1) + listCount.get(i)) % p;
listCount.set(i, sum);
}
listCount.add(0);
}
justf = true;
}
else{ // "s"
if(justf){
justf = false;
}
else{
for(int i=1; i<listCount.size(); i++){
int sum = (listCount.get(i-1) + listCount.get(i)) % p;
listCount.set(i, sum);
}
}
}
//System.out.println(listCount);
}
for(int i=0; i<listCount.size(); i++){
ans += listCount.get(i);
}
System.out.print((ans % p));
}
}
/*
int n = Integer.parseInt(sc.nextLine());
String[] t = sc.nextLine().split(" ");
int[] list = new int[n];
for(int x=0; x<n; x++){
list[x] = Integer.parseInt(t[x]);
}
String[] dir = sc.nextLine().split(" ");
int a = Integer.parseInt(dir[0]);
int b = Integer.parseInt(dir[1]);
int c = Integer.parseInt(dir[2]);
int d = Integer.parseInt(dir[3]);
int e = Integer.parseInt(dir[4]);
int n = Integer.parseInt(sc.nextLine());
*/ | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
// Write your code here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
char[] seq=new char[n];
for(int i=0;i<n;i++){
seq[i]=s.next().charAt(0);
}
long mod=(long)Math.pow(10,9)+7;
long[][] arr=new long[n][n];
arr[0][0]=1;
for(int i=1;i<n;i++){
if(seq[i-1]=='f'){
for(int j=1;j<n;j++){
arr[i][j]=arr[i-1][j-1];
}
}else{
long sum=0;
for(int j=n-1;j>=0;j--){
sum=(sum+arr[i-1][j])%mod;
arr[i][j]=sum;
}
}
}
long ans=0;
for(int i=0;i<n;i++){
ans=(ans+arr[n-1][i])%mod;
}
System.out.println(ans);
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.*;
public class A{
void solve(){
int n=ni();
s=new char[n+1];
s[0]='.';
for(int i=1;i<=n;i++) s[i]=ns().charAt(0);
dp=new long[5001][5001];
dp[1][0]=1;
long sum[]=new long[n+2];
sum[0]=1;
for(int i=2;i<=n;i++){
for(int j=0;j<=n;j++) {
if (s[i - 1] == 'f') {
if(j-1>=0) dp[i][j]=dp[i-1][j-1];
else dp[i][j]=0;
}else {
dp[i][j]=sum[j];
}
}
for(int j=n;j>=0;j--){
sum[j]=(sum[j+1]+dp[i][j])%M;
}
}
long ans=0;
for(int i=0;i<=n;i++){
ans+=dp[n][i];
if(ans>=M) ans%=M;
}
pw.println(ans);
}
char s[];
long dp[][];
long go(int x,int cnt,int n){
// pw.println(x+" "+cnt);
if(x>n) return 1;
long cc=0;
if(dp[x][cnt]!=-1) return dp[x][cnt];
if(s[x]=='f'){
cc=(cc+go(x+1,cnt+1,n))%M;
}else {
for(int j=cnt;j>=0;j--) cc=(cc+go(x+1,j,n))%M;
if(x==n) cc=(cc-cnt+M)%M;
}
cc%=M;
dp[x][cnt]=cc;
return cc;
}
long M=(long)1e9+7;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new A().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 void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.*;
import java.util.*;
public class utkarsh{
BufferedReader br;
void solve(){
br = new BufferedReader(new InputStreamReader(System.in));
int i, j, n, mod = (int)(1e9 + 7);
n = ni();
char c[] = new char[n];
for(i = 0; i < n; i++) c[i] = ns().charAt(0);
long dp[][] = new long[n][n];
dp[0][0] = 1;
for(i = 1; i < n; i++){
if(c[i-1] == 'f'){
for(j = 0; j < i; j++){
dp[i][j+1] = dp[i-1][j];
}
}else{
for(j = i-1; j >= 0; j--){
dp[i][j] = dp[i-1][j] + dp[i][j+1];
dp[i][j] %= mod;
}
}
}
long ans = 0;
for(long x : dp[n-1]){
ans += x;
ans %= mod;
}
System.out.println(ans);
}
int ni(){
return Integer.parseInt(ns());
}
String ip[];
int len, sz;
String ns(){
if(len >= sz){
try{
ip = br.readLine().split(" ");
len = 0;
sz = ip.length;
}catch(IOException e){
throw new InputMismatchException();
}
if(sz <= 0) return "-1";
}
return ip[len++];
}
public static void main(String[] args){ new utkarsh().solve(); }
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class c {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numbOfStatements = in.nextInt();
long[] dp = new long[numbOfStatements];
dp[0] = 1L;
boolean priorFor = in.next().equals("f");
for(int i=0; i<numbOfStatements-1; i++)
{
String type = in.next();
if (priorFor) {
for(int j=numbOfStatements-1;j>0;j--) {
dp[j] = dp[j-1];
}
dp[0] = 0L;
} else {
long sum = 0;
for(int j = numbOfStatements - 1; j >= 0; --j) {
sum = (sum + dp[j]) % 1000000007;
dp[j] = sum;
}
}
priorFor = type.equals("f");
}
long ans = 0;
for(int j=0; j<numbOfStatements; j++) {
ans = (ans + dp[j]) % 1000000007;
}
System.out.println(ans);
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.TreeMap;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.sqrt;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
import static java.util.Collections.reverse;
import static java.util.Collections.reverseOrder;
import static java.util.Collections.sort;
public class Main {
private FastScanner in;
private PrintWriter out;
private void solve() throws IOException {
solveC();
}
private void solveA() throws IOException {
char[] n = in.next().toCharArray(), s = in.next().toCharArray();
out.print(n[0]);
for (int i = 1; i < n.length && n[i] < s[0]; i++)
out.print(n[i]);
out.print(s[0]);
}
private void solveB() throws IOException {
int n = in.nextInt();
long dp[] = new long[n + 1];
for (int i = 1; i <= n; i++) {
dp[i] = i + (i < 3 ? 0 : dp[i - 2]);
}
out.print(dp[n]);
}
private void solveC() throws IOException {
int n = in.nextInt(), prev = -1;
long sum, mod = (long) 1e9 + 7, p;
long[] deep = new long[n + 10];
deep[0] = 1;
char c;
for (int cur = 0; cur < n; cur++) {
c = in.nextLine().charAt(0);
if (prev + 1 != cur) {
sum = 0;
if (c == 'f') {
for (int i = deep.length - 1; i > 0; i--) {
sum += deep[i - 1];
sum %= mod;
deep[i] = sum;
}
deep[0] = 0;
} else {
for (int i = deep.length - 1; i >= 0; i--) {
sum += deep[i];
sum %= mod;
deep[i] = sum;
}
}
}
if (c != 's') {
if (cur == prev + 1) {
for (int i = deep.length - 1; i > 0; i--) {
deep[i] = deep[i - 1];
}
deep[0] = 0;
}
prev = cur;
}
//out.println(Arrays.toString(deep));
}
long ans = 0;
for (int i = 0; i < deep.length; i++) {
ans += deep[i];
ans %= mod;
}
out.println(ans);
}
private void solveD() throws IOException {
}
private void solveE() throws IOException {
}
class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
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;
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();
}
static class TaskC {
static final int modular = (int) (1e9 + 7);
public void solve(int testNum, InputReader in, PrintWriter out) {
int n = in.nextInt();
int ans = 0;
String[] g = new String[n];
int[][] dp = new int[2][n];
for(int i = 0; i < n; i++) {
g[i] = in.next();
}
if(n == 1) {
out.println(1);
return;
}
dp[0][0] = 1;
for(int i = 1; i < n; i++) {
if(g[i - 1].equals("f")) {
dp[1][0] = 0;
for(int j = 1; j < n; j++) {
dp[1][j] = dp[0][j - 1];
}
}
else {
dp[1][n - 1] = dp[0][n - 1];
for(int j = n - 2; j >= 0; j--) {
dp[1][j] = dp[1][j + 1] + dp[0][j];
dp[1][j] = dp[1][j] % modular;
}
}
for(int j = 0; j < n; j++) {
dp[0][j] = dp[1][j];
}
if(i == n - 1) {
for(int j = 0; j < n; j++) {
ans = ans + dp[1][j];
ans = ans % modular;
}
}
}
out.println(ans);
}
}
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());
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class c {
static boolean seq[];
static long memo[][], mod = (long)1e9 + 7;
static long go(int n, int d) {
long ans = 0;
if(d < 0) return 0;
if(n == seq.length) return 1;
int f = 1;
if(n > 0) f = seq[n-1]?1:0;
if(memo[n][d] != -1) return memo[n][d];
if(f == 0) {
ans += go(n + 1, d + (seq[n]?1:0));
ans %= mod;
ans += go(n, d-1);
ans %= mod;
}
if(f == 1) {
ans += go(n + 1, d + (seq[n]?1:0));
ans %= mod;
}
return memo[n][d] = ans;
}
public static void main(String args[]) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
//BEGIN HERE
int n = in.nextInt();
seq = new boolean[n];
for (int i = 0; i < n; i++ ) {
seq[i] = (in.next().charAt(0) == 'f');
}
memo = new long[n][n+1];
for(int i = 0; i < n; i++) {
Arrays.fill(memo[i], -1);
}
System.out.println(go(0, 0));
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = null;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
if (st == null) {
st = new StringTokenizer(br.readLine());
}
String line = st.nextToken("\n");
st = null;
return line;
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
public static class combinatorics {
static long modInv(long a, long b) {
return 1 < a ? b - modInv(b % a, a) * b / a : 1;
}
static long factorial[], mod;
combinatorics(int n, long MOD) {
mod = MOD;
factorial = new long[n + 1];
factorial[0] = 1;
for (int i = 1; i <= n; i++) {
factorial[i] = i * factorial[i - 1];
factorial[i] %= mod;
}
}
static long nCr(int n, int r) {
if (r > n)
return 0;
return (factorial[n] * modInv((factorial[n - r] * factorial[r]) % mod, mod)) % mod;
}
}
public static class DisjointSet {
int p[], r[], s[];
int numDisjoint;
DisjointSet(int N) {
numDisjoint = N;
r = new int[N];
s = new int[N];
p = new int[N];
for (int i = 0; i < N; i++)
p[i] = i;
}
int findSet(int i) {
return (p[i] == i) ? i : (p[i] = findSet(p[i]));
}
boolean isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
void unionSet(int i, int j) {
if (!isSameSet(i, j)) // if from different set
{
numDisjoint--;
int x = findSet(i), y = findSet(j);
if (r[x] > r[y]) {
p[y] = x; // rank keeps the tree short
s[x] += s[y];
} else {
p[x] = y;
if (r[x] == r[y])
r[y]++;
s[y] += s[x];
}
}
}
int sizeOfSet(int i) {
return s[findSet(i)];
}
};
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
//package round455;
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 C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int mod = 1000000007;
long[] dp = new long[5005];
dp[0] = 1;
for(int i = 0;i < n;i++){
char c = nc();
if(c == 's'){
if(i < n-1){
for(int j = 5003;j >= 0;j--){
dp[j] += dp[j+1];
if(dp[j] >= mod)dp[j] -= mod;
}
}
}else{
for(int j = 5003;j >= 0;j--){
dp[j+1] = dp[j];
}
dp[0] = 0;
}
}
long ans = 0;
for(int i = 0;i < 5005;i++)ans += dp[i];
out.println(ans % mod);
}
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 C().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)); }
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.*;
import java.util.*;
public final class PythonIndentation
{
public static void main(String[] args)
{
new PythonIndentation(System.in, System.out);
}
static class Solver implements Runnable
{
static final int MOD = (int) 1e9 + 7;
int n;
char[] arr;
long[][] dp;
BufferedReader in;
PrintWriter out;
void solve() throws IOException
{
n = Integer.parseInt(in.readLine());
arr = new char[n];
dp = new long[n + 1][n + 1];
for (int i = 0; i < n; i++)
arr[i] = in.readLine().charAt(0);
for (int i = 0; i <= n; i++)
Arrays.fill(dp[i], -1);
dp[0][0] = 1;
if (arr[0] == 's')
out.println(find(1, 0));
else
out.println(find(1, 1));
}
long find(int curr, int backIndents)
{
if (backIndents < 0)
return 0;
if (curr == n)
return 1;
if (dp[curr][backIndents] != -1)
return dp[curr][backIndents];
long ans;
if (arr[curr] == 's')
ans = find(curr + 1, backIndents);
else
ans = find(curr + 1, backIndents + 1);
if (arr[curr - 1] != 'f')
ans = CMath.mod(ans + find(curr, backIndents - 1), MOD);
return dp[curr][backIndents] = ans;
}
public Solver(BufferedReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
@Override public void run()
{
try
{
solve();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
static class CMath
{
static long mod(long number, long mod)
{
return number - (number / mod) * mod;
}
}
private PythonIndentation(InputStream inputStream, OutputStream outputStream)
{
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
PrintWriter out = new PrintWriter(outputStream);
Thread thread = new Thread(null, new Solver(in, out), "PythonIndentation", 1 << 29);
try
{
thread.start();
thread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
out.flush();
out.close();
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
boolean[] isF = new boolean[n];
for (int i = 0; i < n; i++) {
isF[i] = in.readCharacter() == 'f';
}
FenwickTree[] fenwickTrees = new FenwickTree[n + 1];
for (int i = 0; i < fenwickTrees.length; i++) {
fenwickTrees[i] = new FenwickTree(n + 1);
}
fenwickTrees[n].add(0, 1);
for (int idx = n - 1; idx >= 0; idx--) {
for (int indentLevel = 0; indentLevel < n; indentLevel++) {
long fenwickRes;
if (isF[idx]) {
fenwickRes = fenwickTrees[idx + 1].get(indentLevel + 1, indentLevel + 1);
} else {
fenwickRes = fenwickTrees[idx + 1].get(0, indentLevel);
}
fenwickTrees[idx].add(indentLevel, fenwickRes % MiscUtils.MOD7);
}
}
out.printLine(fenwickTrees[0].get(0, 0));
}
}
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 char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
static class MiscUtils {
public static final int MOD7 = (int) (1e9 + 7);
}
static class FenwickTree {
private final long[] value;
public FenwickTree(int size) {
value = new long[size];
}
public long get(int from, int to) {
return get(to) - get(from - 1);
}
private long get(int to) {
to = Math.min(to, value.length - 1);
long result = 0;
while (to >= 0) {
result += value[to];
to = (to & (to + 1)) - 1;
}
return result;
}
public void add(int at, long value) {
while (at < this.value.length) {
this.value[at] += value;
at = at | (at + 1);
}
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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();
}
static class TaskC {
private long MOD = (long) (1e9 + 7);
int[][] dp = new int[5001][5001];
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
ArrayList<Character> commands = new ArrayList<>();
for (int i = 0; i < n; i++) {
char ch = in.next().charAt(0);
commands.add(ch);
}
for (int a[] : dp) Arrays.fill(a, -1);
out.println(count(0, commands, 0));
}
public int count(int index, ArrayList<Character> commands, int deepCount) {
if (deepCount < 0) {
return 0;
}
if (index == commands.size()) {
return 1;
} else {
if (dp[index][deepCount] != -1) return dp[index][deepCount];
long result = 0;
char ch = commands.get(index);
result = count(index, commands, deepCount - 1);
if (ch == 's') {
result += count(index + 1, commands, deepCount);
} else {
result += count(index + 1, commands, deepCount + 1);
result -= count(index + 1, commands, deepCount);
}
if (result >= MOD) {
result -= MOD;
}
if (result < 0) {
result += MOD;
}
return dp[index][deepCount] = (int) result;
}
}
}
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 String next() {
return readString();
}
public int nextInt() {
return readInt();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.*;
import java.util.StringTokenizer;
public class Main {
BufferedReader br;
PrintWriter pw;
StringTokenizer st;
long mod = (long) (1e9 + 7);
public static void main(String[] args) {
(new Main()).run();
}
void solve() throws IOException {
int n = nextInt();
boolean p[] = new boolean[n];
for (int i = 0; i < n; i++) {
String s = nextToken();
if (s.charAt(0) == 'f') p[i] = true;
}
long d[][] = new long[n][n];
d[0][0] = 1;
for (int i = 1; i < n; i++) {
if (p[i - 1]) {
d[i][0] = 0;
for (int j = 1; j < n; j++) {
d[i][j] = d[i - 1][j - 1];
}
} else {
long sum = 0;
for (int j = n - 1; j >= 0; j--) {
sum += d[i - 1][j];
sum %= mod;
d[i][j] = sum;
}
}
}
long sum = 0;
for (int i = 0; i < n; i++) {
sum += d[n - 1][i];
sum %= mod;
}
pw.print(sum);
}
void run() {
try {
// br = new BufferedReader(new FileReader("divljak.in"));
// pw = new PrintWriter(new BufferedWriter(new FileWriter("divljak.out")));
// br = new BufferedReader(new FileReader("input.txt"));
// pw = new PrintWriter(new FileWriter("output.txt"));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
solve();
pw.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
class h {
int ans;
int last;
public h() {
last = -1;
ans = 0;
}
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class CFC {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
final long MOD = 1000L * 1000L * 1000L + 7;
int[] dx = {0, -1, 0, 1};
int[] dy = {1, 0, -1, 0};
void solve() throws IOException {
int n = nextInt();
long[] dp0 = new long[10 + n];
long[] dp1 = new long[10 + n];
long[] pre = new long[10 + n];
dp0[0] = 1;
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = nextString();
}
String s = "s";
for (int i = 0; i < n; i++) {
Arrays.fill(dp1, 0);
if (i == 0) {
dp0[0] = 1;
dp1[0] = 1;
}
else {
if (arr[i - 1].equals(s)) {
for (int j = 0; j <= n + 5; j++) {
dp1[j] = pre[j];
}
}
else {
for (int j = 1; j <= n + 5; j++) {
dp1[j] = dp0[j - 1];
}
}
}
Arrays.fill(pre, 0);
pre[n + 5] = dp1[n + 5];
for (int j = n + 4; j >= 0; j--) {
pre[j] = pre[j + 1] + dp1[j];
pre[j] %= MOD;
}
for (int j = 0; j <= n + 5; j++) {
dp0[j] = dp1[j];
}
}
long res = 0;
for (int j = 0; j <= n + 5; j++) {
res += dp0[j];
res %= MOD;
}
out(res);
}
void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
int gcd(int a, int b) {
while(a != 0 && b != 0) {
int c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
public CFC() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFC();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
static ArrayList<Integer> statements;
static final int MOD = (int) 1e9 + 7;
static int[][] memo;
static int solve(int i, int c) {
if(i == statements.size())
return 1;
if(memo[i][c] != -1)
return memo[i][c];
long ans = solve(i + 1, c + statements.get(i));
if(c > 0)
ans += solve(i, c - 1);
return memo[i][c] = (int) (ans % MOD);
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
statements = new ArrayList<>();
char[] c = new char[n];
for (int i = 0; i < n; i++) {
c[i] = sc.next().charAt(0);
}
if(c[0] == 's')
statements.add(0);
else
statements.add(1);
for (int i = 1; i < n; i++) {
if(c[i - 1] == 'f') {
if(c[i] == 'f')
statements.set(statements.size() - 1, statements.get(statements.size() - 1) + 1);
}else {
if(c[i] == 's')
statements.add(0);
else
statements.add(1);
}
}
memo = new int[statements.size()][n + 1];
for(int[] a : memo)
Arrays.fill(a, -1);
out.println(solve(0, 0));
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws FileNotFoundException {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | quadratic | 909_C. Python Indentation | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ShekharN
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
private final int MOD = (int) (1e9 + 7);
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextString();
}
int[] dp = new int[n];
Arrays.parallelSetAll(dp, i -> 0);
dp[0] = 1;
int cnt = 0;
for (int i = 0; i < n; i++) {
if (arr[i].equals("f")) {
cnt++;
continue;
}
calc(dp, n, cnt);
cnt = 0;
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += dp[i];
sum %= MOD;
}
out.println(sum);
}
private void calc(int[] dp, int n, int cnt) {
for (int i = n - 1; i >= 0; i--) {
if (i != n - 1) dp[i] += dp[i + 1];
dp[i] %= MOD;
}
int[] tmp = new int[n];
for (int i = 0; i < n; i++) {
tmp[(i + cnt) % n] = dp[i];
}
Arrays.parallelSetAll(dp, i -> tmp[i]);
}
}
static class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
public String nextString() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
}
| quadratic | 909_C. Python Indentation | CODEFORCES |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.