src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringlengths 6
50
| from
stringclasses 1
value |
---|---|---|---|
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
String[] response = {"even", "odd"};
int n = in.nextInt();
int[] arr = in.nextIntArray(0, n);
int swaps = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) swaps = (swaps + 1) % 2;
}
}
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int l = in.nextInt(), r = in.nextInt(), combinaisons = ((r - l) * (r - l + 1)) / 2;
if (combinaisons % 2 == 1) {
swaps ^= 1;
}
out.println(response[swaps]);
}
}
}
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());
}
public int[] nextIntArray(int offset, int length) {
int[] arr = new int[offset + length];
for (int i = offset; i < offset + length; i++) {
arr[i] = nextInt();
}
return arr;
}
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.io.*;
import java.util.*;
import java.util.function.Consumer;
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();
int[] data = sc.na(n);
boolean ev = true;
for (int t = 0; t < n - 1; t++) {
for (int x = t + 1; x < n; x++) {
if (data[t] > data[x]) {
ev = !ev;
}
}
}
int m = sc.nextInt();
for (int i = 0; i < m; i++) {
int dd = -sc.nextInt() + sc.nextInt();
int dm = (dd + 1) * dd / 2;
if (dm % 2 == 1) {
ev = !ev;
}
out.println(ev ? "even" : "odd");
}
}
private static void initData() {
}
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 | 911_D. Inversion Counting | CODEFORCES |
import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;
public class USACO {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
StringTokenizer st = new StringTokenizer(reader.readLine()," ");
int[] perm = new int[n];
int count=0;
for (int i=0;i<n;i++) {
perm[i]=Integer.parseInt(st.nextToken());
for (int j=0;j<i;j++) {
if (perm[j]>perm[i]) {
count++;
}
}
}
count=count%2;
int m = Integer.parseInt(reader.readLine());
for (int i=0;i<m;i++) {
StringTokenizer st2 = new StringTokenizer(reader.readLine()," ");
int a = Integer.parseInt(st2.nextToken());
int b = Integer.parseInt(st2.nextToken());
if ((b-a+1)%4==2||(b-a+1)%4==3) {
count++;
count=count%2;
}
if(count%2==0) {
System.out.println("even");
} else {
System.out.println("odd");
}
}
}
} | quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
public class D {
int N,M;
int[] a,l,r;
private void solve() {
N = nextInt();
a = new int[N];
for(int i = 0;i < N;i++) {
a[i] = nextInt();
}
M = nextInt();
l = new int[M];
r = new int[M];
for(int i = 0;i < M;i++) {
l[i] = nextInt();
r[i] = nextInt();
}
int count = 0;
for(int i = 0;i < N - 1;i++) {
for(int j = i + 1;j < N;j++) if (a[i] > a[j]) {
count++;
}
}
for(int i = 0;i < M;i++) {
count += (r[i] - l[i] + 1) * (r[i] - l[i]) / 2;
count %= 2;
out.println(count == 0 ? "even" : "odd");
}
}
public static void main(String[] args) {
out.flush();
new D().solve();
out.close();
}
/* Input */
private static final InputStream in = System.in;
private static final PrintWriter out = new PrintWriter(System.out);
private final byte[] buffer = new byte[2048];
private int p = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (p < buflen)
return true;
p = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0)
return false;
return true;
}
public boolean hasNext() {
while (hasNextByte() && !isPrint(buffer[p])) {
p++;
}
return hasNextByte();
}
private boolean isPrint(int ch) {
if (ch >= '!' && ch <= '~')
return true;
return false;
}
private int nextByte() {
if (!hasNextByte())
return -1;
return buffer[p++];
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = -1;
while (isPrint((b = nextByte()))) {
sb.appendCodePoint(b);
}
return sb.toString();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class D {
public static void main(String[] args) throws Exception {
new D().run();
}
int[] BIT;
public void run() throws Exception {
FastScanner f = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = f.nextInt();
int[] arr = new int[n];
BIT = new int[n+10];
int inv = 0;
for(int i = 0; i < n; i++) {
arr[i] = f.nextInt();
inv ^= (i-query(arr[i])) & 1;
add(arr[i]);
}
int k = f.nextInt();
while(k-->0) {
int diff = -f.nextInt()+f.nextInt()+1;
inv ^= (diff*(diff-1)/2) & 1;
out.println(inv == 1 ? "odd" : "even");
}
out.flush();
}
public int query(int i) {
i++;
int res = 0;
while(i > 0) {
res += BIT[i];
i -= i & -i;
}
return res;
}
public void add(int i) {
i++;
while(i < BIT.length) {
BIT[i]++;
i += i & -i;
}
}
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 | 911_D. Inversion Counting | 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.FileReader;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileNotFoundException;
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int[] arr = new int[n + 1];
for (int i = 1; i <= n; i++) {
arr[i] = in.nextInt();
}
int inversions = 0;
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
if (arr[i] > arr[j])
inversions++;
}
}
inversions %= 2;
int q = in.nextInt();
for (int i = 0; i < q; i++) {
int l = in.nextInt(), r = in.nextInt();
int d = r - l + 1;
d = d * (d - 1) / 2;
if ((d & 1) == 1) inversions ^= 1;
out.println((inversions & 1) == 1 ? "odd" : "even");
}
}
}
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 | 911_D. Inversion Counting | CODEFORCES |
/*
* Author Ayub Subhaniya
* Institute DA-IICT
*/
import java.io.*;
import java.math.*;
import java.util.*;
public class A
{
InputStream in;
PrintWriter out;
void solve()
{
int n=ni();
int a[]=na(n);
int INV=0;
for (int i=0;i<n;i++)
for (int j=i+1;j<n;j++)
if (a[i]>a[j])
INV++;
boolean even=INV%2==0;
int q=ni();
while (q-->0)
{
int l=ni();
int r=ni();
int len=r-l+1;
len=(len-1)*(len)/2;
if (len%2==1)
even=!even;
if (even)
out.println("even");
else
out.println("odd");
}
}
int MAX = (int)1e5;
long factorial[];
void findfactorial()
{
factorial = new long[MAX + 1];
factorial[0] = 1;
for (int i = 1; i < MAX + 1; i++)
{
factorial[i] = mul(i,factorial[i - 1]);
}
}
long mod=(long)1e9+7;
long add(long a,long b)
{
long x=(a+b);
while(x>=mod) x-=mod;
return x;
}
long sub(long a,long b)
{
long x=(a-b);
while(x<0) x+=mod;
return x;
}
long mul(long a,long b)
{
a%=mod;
b%=mod;
long x=(a*b);
return x%mod;
}
int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
int min(int a,int b)
{
if(a>b)
return b;
else
return a;
}
long max(long a,long b)
{
if(a>b)
return a;
else
return b;
}
long min(long a,long b)
{
if(a>b)
return b;
else
return a;
}
void run() throws Exception
{
String INPUT = "C:/Users/ayubs/Desktop/input.txt";
in = oj ? System.in : new FileInputStream(INPUT);
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 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 = in.read(inbuf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean inSpaceChar(int c)
{
return !(c >= 33 && c <= 126);
}
private int skip()
{
int b;
while ((b = readByte()) != -1 && inSpaceChar(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 (!(inSpaceChar(b)))
{ // when nextLine, (inSpaceChar(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 && !(inSpaceChar(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 | 911_D. Inversion Counting | CODEFORCES |
import java.util.Scanner;
public class D {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; ++i) {
a[i] = in.nextInt();
}
int ans = 0;
for(int i = 0; i < n; ++i) {
for(int j = i+1; j < n; ++j) {
if(a[i] > a[j]) ans++;
}
}
int m = in.nextInt();
for(int i = 0; i < m; ++i) {
int l = in.nextInt();
int r = in.nextInt();
int size = r-l + 1;
int x = size * size - size;
x = x >> 1;
ans = ans^x;
if(ans%2 == 0) System.out.println("even");
else System.out.println("odd");
}
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
/*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
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();
int[] arr = nextIntArr(n);
int cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
cnt++;
}
}
}
int m = nextInt();
boolean[] vis = new boolean[n];
for (int i = 0; i < m; i++) {
int l = nextInt() - 1;
int r = nextInt() - 1;
int len = r - l + 1;
if (len * (len - 1) / 2 % 2 != 0) {
cnt++;
}
if (cnt % 2 != 0) {
outln("odd");
}
else {
outln("even");
}
}
}
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;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long 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 CFA() 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 CFA();
}
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 | 911_D. Inversion Counting | 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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static
@SuppressWarnings("Duplicates")
class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int m = in.nextInt();
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) count = (count + 1) % 2;
}
}
StringBuilder res = new StringBuilder();
int l, r;
while (m-- > 0) {
l = in.nextInt() - 1;
r = in.nextInt() - 1;
count = count ^ (((r - l + 1) * (r - l) / 2) % 2);
res.append(count == 1 ? "odd" : "even").append('\n');
}
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[] nextIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; ++i) {
array[i] = nextInt();
}
return array;
}
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 | 911_D. Inversion Counting | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
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 Wolfgang Beyer
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.readIntArray(n);
long count = 0;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (a[j] > a[i]) count++;
}
}
boolean even = count % 2 == 0 ? true : false;
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int left = in.nextInt();
int right = in.nextInt();
int diff = right - left;
if ((diff % 4 == 1) || (diff % 4 == 2)) {
even = !even;
}
if (even) {
out.println("even");
} else {
out.println("odd");
}
}
}
}
static class InputReader {
private static BufferedReader in;
private static StringTokenizer tok;
public InputReader(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] readIntArray(int n) {
int[] ar = new int[n];
for (int i = 0; i < n; i++) {
ar[i] = nextInt();
}
return ar;
}
public String next() {
try {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
//tok = new StringTokenizer(in.readLine(), ", \t\n\r\f"); //adds commas as delimeter
}
} catch (IOException ex) {
System.err.println("An IOException was caught :" + ex.getMessage());
}
return tok.nextToken();
}
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args){
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt();
int[] a = new int[n+1];
for(int i = 1; i <= n; i++) a[i] = scan.nextInt();
BIT bit = new BIT(n);
int p = 0;
for(int i = 1; i <= n; i++) {
p ^= bit.atOrAbove(a[i])&1;
bit.add(a[i], 1);
}
int m = scan.nextInt();
for(int i = 0; i < m; i++) {
int l = scan.nextInt(), r = scan.nextInt();
int s = r-l+1;
int in = s*(s-1)/2;
if((in&1) == 1) p ^= 1;
out.println(p==0?"even":"odd");
}
out.close();
}
static class BIT {
int[] a;
int n;
public BIT(int n) {
this.n = n;
a = new int[n+1];
}
public void add(int i, int val) {
while(i <= n) {
a[i] += val;
i += i & -i;
}
}
public int sum(int j)
{
int res = 0;
for(int i = j; i >= 1; i -= (i & -i)) res += a[i];
return res;
}
public int sum(int i, int j) {
return sum(j)-sum(i-1);
}
public int atOrAbove(int index) {
int sub = 0;
if (index > 0) sub = sum(index-1);
return sum(n) - sub;
}
}
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 | 911_D. Inversion Counting | CODEFORCES |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
* @author pttrung
*/
public class D_Edu_Round_35 {
public static long MOD = 1000000007;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int[] data = new int[n];
for (int i = 0; i < n; i++) {
data[i] = in.nextInt();
}
FT tree = new FT(n + 1);
int result = 0;
for (int i = n - 1; i >= 0; i--) {
tree.update(data[i], 1);
result += tree.get(data[i] - 1);
result %= 2;
}
int q = in.nextInt();
int[] tmp = new int[n];
for (int i = 0; i < q; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
int total = r - l + 1;
total = total * (total - 1) / 2;
total %= 2;
result += total;
result %= 2;
if (result % 2 == 0) {
out.println("even");
} else {
out.println("odd");
}
}
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
int[] data;
FT(int n) {
data = new int[n];
}
public void update(int index, int value) {
while (index < data.length) {
data[index] += value;
data[index] %= 2;
index += (index & (-index));
}
}
public int get(int index) {
int result = 0;
while (index > 0) {
result += data[index];
result %= 2;
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.io.*;
import java.util.*;
public class Codeforces911D {
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]);
int[] a = new int[n];
sp = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(sp[i]);
}
int inversions = 0;
for (int i = 0; i < n-1; i++) {
for (int j = i+1; j < n; j++) {
if (a[i] > a[j]) {
inversions++;
}
}
}
inversions = inversions%2;
sp = br.readLine().split(" ");
int m = Integer.parseInt(sp[0]);
for (int i = 0; i < m; i++) {
sp = br.readLine().split(" ");
int l = Integer.parseInt(sp[0]);
int r = Integer.parseInt(sp[1]);
if ((r-l+1)%4 == 2 || (r-l+1)%4 == 3) {
inversions = 1-inversions;
}
if (inversions == 1) {
System.out.println("odd");
}
else {
System.out.println("even");
}
}
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int ar[] = in.nextIntArray(n);
long dp[][] = new long[n][n];
long ct = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (ar[i] > ar[j]) {
dp[i][j]++;
ct++;
}
}
}
for (int i = n - 2; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
dp[i][j] += dp[i + 1][j];
}
}
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
long val = (r - l + 1);
long estimated = (val * (val - 1)) / 2;
long change = estimated - dp[l][r];
//System.out.println(ct);
ct = ct - dp[l][r];
dp[l][r] = change;
ct += dp[l][r];
if (ct % 2 == 0) {
out.println("even");
} else {
out.println("odd");
}
// System.out.println(ct);
}
}
}
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 int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
public class D {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), sum = 0;
int [] a = new int[n+1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
for (int i = 1; i <= n; ++i)
for (int j = i + 1; j <= n; ++j)
sum += a[i] > a[j] ? 1 : 0;
int m = in.nextInt();
sum &= 1;
for (int i = 1; i <= m; i++) {
int l = in.nextInt(), r = in.nextInt();
if (((r - l + 1) / 2) % 2 == 1)
sum ^= 1;
System.out.println(sum == 1 ? "odd" : "even");
}
}
} | quadratic | 911_D. Inversion Counting | CODEFORCES |
import javafx.util.Pair;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
int chet = 0;
for (int i = 0; i < n; i++) {
arr[i]=scanner.nextInt();
for (int j = 0; j < i; j++) {
if (arr[j]>arr[i]) chet^=1;
}
}
n = scanner.nextInt();
for (int i = 0; i < n; i++) {
int l = scanner.nextInt();
int r = scanner.nextInt();
if ((((r-l+1)/2)&1)!=0){
chet^=1;
}
if (chet==1){
System.out.println("odd");
}else{
System.out.println("even");
}
}
}
} | quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
public double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;}
}
// |----| /\ | | ----- |
// | / / \ | | | |
// |--/ /----\ |----| | |
// | \ / \ | | | |
// | \ / \ | | ----- -------
public static void main(String[] args)throws IOException
{
Reader sc=new Reader();
PrintWriter out=new PrintWriter(System.out);
int n=sc.i();
int arr[]=sc.arr(n);
int count=0;
for(int i=0;i<n;i++)for(int j=i+1;j<n;j++)if(arr[j]<arr[i])count++;
count%=2;
int q=sc.i();
while(q-->0)
{
int a=sc.i();
int b=sc.i();
long len=((long)(b-a+1)*(b-a))/2;
if(len%2==1)count^=1;
if(count==0)out.println("even");
else out.println("odd");
}
out.flush();
}
} | quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.util.*;
public class inversions {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] values = new int[N];
for(int i=0;i<N;i++){
values[i] = sc.nextInt();
}
int query = sc.nextInt();
int[][] tasks = new int[query][2];
for(int i=0;i<query;i++){
tasks[i][0] = sc.nextInt();
tasks[i][1] = sc.nextInt();
}
int startinversions = 0;
for(int i=1;i<values.length;i++){
for(int j=i-1;j>=0;j--){
if(values[i]<values[j]){
startinversions++;
}
}
}
int value = startinversions%2;
for(int[] task : tasks){
int n = task[1]-task[0];
if(n*(n+1)/2 % 2 != 0){
value = (value+1)%2;
}
if(value==1){
System.out.println("odd");
}
else{
System.out.println("even");
}
}
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
public class lc1 implements Runnable{
public void run() {
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t = 1;
while(t-- > 0) {
int n = s.nextInt();
int[] a = new int[n + 1];
for(int i = 1; i <= n; i++)
a[i] = s.nextInt();
int curr = 0;
for(int i = 1; i <= n; i++)
for(int j = i + 1; j <= n; j++)
if(a[i] > a[j])
curr++;
curr = curr % 2;
int m = s.nextInt();
while(m-- > 0) {
int l = s.nextInt();
int r = s.nextInt();
int fact = (r - l) % 4;
if(fact == 1 || fact == 2)
curr = 1 - curr;
if(curr % 2 == 0)
w.println("even");
else
w.println("odd");
}
}
w.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public 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);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new lc1(),"lc1",1<<26).start();
}
} | quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int inv=0;
int []a=new int [n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
for(int j=0;j<n;j++)
for(int i=j+1;i<n;i++)
if(a[j]>a[i])
inv=1-inv;
int m=sc.nextInt();
StringBuilder sb=new StringBuilder();
while(m-->0)
{
int l=sc.nextInt();
int r=sc.nextInt();
int s=r-l+1;
if(s*(s-1)/2%2==1)
inv=1-inv;
if(inv==1)
sb.append("odd\n");
else
sb.append("even\n");
}
System.out.print(sb);
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
import sun.reflect.generics.tree.Tree;
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception{
IO io = new IO(null,null);
int n = io.getNextInt(),ans = 0;
int [] A = new int[n];
for (int i = 0;i < n;i++) {
A[i] = io.getNextInt();
for (int j = 0;j < i;j++)
ans ^= (A[j] > A[i]) ? 1 : 0;
}
String [] word = {"even","odd"};
int m = io.getNextInt();
for (int i = 0;i < m;i++) {
int l = io.getNextInt(),r = io.getNextInt();
int len = r - l + 1;
long tot = len*(len - 1L)/2;
ans ^= tot & 1;
io.println(word[ans]);
}
io.close();
}
}
class IO{
private BufferedReader br;
private StringTokenizer st;
private PrintWriter writer;
private String inputFile,outputFile;
public boolean hasMore() throws IOException{
if(st != null && st.hasMoreTokens()) return true;
if(br != null && br.ready()) return true;
return false;
}
public String getNext() throws FileNotFoundException, IOException{
while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String getNextLine() throws FileNotFoundException, IOException{
return br.readLine().trim();
}
public int getNextInt() throws FileNotFoundException, IOException{
return Integer.parseInt(getNext());
}
public long getNextLong() throws FileNotFoundException, IOException{
return Long.parseLong(getNext());
}
public void print(double x,int num_digits) throws IOException{
writer.printf("%." + num_digits + "f" ,x);
}
public void println(double x,int num_digits) throws IOException{
writer.printf("%." + num_digits + "f\n" ,x);
}
public void print(Object o) throws IOException{
writer.print(o.toString());
}
public void println(Object o) throws IOException{
writer.println(o.toString());
}
public IO(String x,String y) throws FileNotFoundException, IOException{
inputFile = x;
outputFile = y;
if(x != null) br = new BufferedReader(new FileReader(inputFile));
else br = new BufferedReader(new InputStreamReader(System.in));
if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
else writer = new PrintWriter(new OutputStreamWriter(System.out));
}
protected void close() throws IOException{
br.close();
writer.close();
}
public void outputArr(Object [] A) throws IOException{
int L = A.length;
for (int i = 0;i < L;i++) {
if(i > 0) writer.print(" ");
writer.print(A[i]);
}
writer.print("\n");
}
}
| quadratic | 911_D. Inversion Counting | 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 = reader.nextIntArray(n);
boolean b = false;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
b = !b;
}
}
}
int m = reader.nextInt();
for (int i = 0; i < m; i++) {
int l = reader.nextInt();
int r = reader.nextInt();
int d = r - l + 1;
if (d * (d - 1) / 2 % 2 == 1) {
b = !b;
}
writer.println(b ? "odd" : "even");
}
}
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 | 911_D. Inversion Counting | 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 D {
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[]a = new int[n+1];
for (int i = 1; i <= n; i++) {
a[i] = nextInt();
}
int inv = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j < i; j++) {
if (a[j] > a[i])
inv++;
}
}
int m = nextInt();
boolean odd = inv % 2==1;
for (int i = 0; i < m; i++) {
int left = nextInt();
int right = nextInt();
long k = right-left+1;
if (k*(k-1)/2 % 2==1)
odd = !odd;
if (odd)
pw.println("odd");
else
pw.println("even");
}
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 | 911_D. Inversion Counting | 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.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class d {
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();
int perm[] = new int[n];
for(int i = 0; i < n; i++) {
perm[i] = in.nextInt();
}
int q = in.nextInt();
int inv[] = new int[n];
inv[0] = 0;
for(int i = 1; i < n; i++) {
inv[i] = inv[i-1];
for(int j = i - 1; j >= 0; j--) {
if(perm[i] < perm[j]) inv[i]++;
}
}
boolean parity = inv[n-1] % 2 == 0;
for(int i = 0; i < q; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() -1;
if(l == r) {
System.out.println(parity?"even":"odd");
continue;
}
int s = r - l + 1;
s = s * (s-1)/ 2;
if(s % 2 != 0) {
parity = !parity;
}
System.out.println(parity?"even":"odd");
}
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 | 911_D. Inversion Counting | 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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int inv = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (a[j] > a[i]) {
inv++;
}
}
}
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int l = in.nextInt();
int r = in.nextInt();
int s = (r - l + 1) * (r - l) / 2;
inv = (inv + s) % 2;
out.println(inv % 2 == 0 ? "even" : "odd");
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String next() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
/*
* UMANG PANCHAL
* DAIICT
*/
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main
{
static LinkedList<Integer> adj[];
static ArrayList<Integer> adj1[];
static int[] color,visited1;
static boolean b[],visited[],possible;
static int level[];
static Map<Integer,HashSet<Integer>> s;
static int totalnodes,colored;
static int count[];
static long sum[];
static int nodes;
static double ans=0;
static long[] as=new long[10001];
static long c1=0,c2=0;
static int[] a,d,k;
static int max=100000000;
static long MOD = (long)1e9 + 7,sm=0,m=Long.MIN_VALUE;
static boolean[] prime=new boolean[1000005];
static int[] levl;
static int[] eat;
static int price[];
static int size[],res[],par[];
static int result=0;
// --------------------My Code Starts Here----------------------
public static void main(String[] args) throws IOException
{
in=new InputReader(System.in);
w=new PrintWriter(System.out);
int n=ni();
int[] a=na(n);
int ans=0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[j]<a[i])
ans++;
}
}
int m=ni();
ans=ans%2;
while(m-->0)
{
int l=ni(),r=ni();
int range=r-l+1;
range=range*(range-1)/2;
range=range%2;
ans=(ans+range)%2;
if(ans==1)
w.println("odd");
else
w.println("even");
}
w.close();
}
public static long nCrModp(long n, long r, long p)
{
long[] C=new long[(int)r+1];
C[0] = 1;
for (long i = 1; i <= n; i++)
{
for (long j = Math.min(i, r); j > 0; j--)
C[(int)j] = (C[(int)j] + C[(int)(j-1)])%p;
}
return C[(int)r];
}
public static long nCr(long n, long r)
{
long x=1;
for(long i=n;i>=n-r+1;i--)
x=((x)*(i));
for(long i=r;i>=1;i--)
x=((x)/(i));
return x%MOD;
}
public static long nCrModpDP(long n, long r, long p)
{
long[] C=new long[(int)r+1];
C[0] = 1;
for (long i = 1; i <= n; i++)
{
for (int j = (int)Math.min(i, r); j > 0; j--)
C[j] = (C[j] + C[j-1])%p;
}
return C[(int)r];
}
public static long nCrModpLucas(long n,long r, long p)
{
if (r==0)
return 1;
long ni = n%p, ri = r%p;
return (nCrModpLucas(n/p,r/p, p) * nCrModpDP(ni,ri, p)) % p;
}
public static void buildgraph(int n){
adj=new LinkedList[n+1];
visited=new boolean[n+1];
levl=new int[n+1];
par=new int[n+1];
for(int i=0;i<=n;i++){
adj[i]=new LinkedList<Integer>();
}
}
public static int getSum(long BITree[], int index)
{
int sum = 0;
while (index > 0)
{
sum += BITree[index];
index -= index & (-index);
}
return sum;
}
public static long[] updateBIT(long BITree[], int n, int index, int val)
{
while (index <= n)
{
BITree[index] += val;
index += index & (-index);
}
return BITree;
}
public static boolean isPrime(int n)
{
// Corner cases
if (n <= 1) return false;
if (n <= 3) return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n%2 == 0 || n%3 == 0)
return false;
for (int i=5; i*i<=n; i=i+6)
if (n%i == 0 || n%(i+2) == 0)
return false;
return true;
}
// --------------------My Code Ends Here------------------------
public static String ns()
{
return in.nextLine();
}
public static int ni()
{
return in.nextInt();
}
public static long nl()
{
return in.nextLong();
}
public static int[] na(int n)
{
a=new int[n];
for(int i=0;i<n;i++)
a[i]=ni();
return a;
}
public static void sieveOfEratosthenes()
{
int n=prime.length;
for(int i=0;i<n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
if(prime[p] == true)
{
for(int i = p*2; i <n; i += p)
prime[i] = false;
}
}
}
public static boolean printDivisors(long n)
{
long ans=0;
for (int i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
if (n/i == i)
ans++;
else
{
ans=ans+2;
}
}
if(ans>3)
break;
}
if(ans==3)
return true;
else
return false;
}
public static void dfs(int i)
{
visited[i]=true;
for(int j:adj[i])
{
if(!visited[j])
{
dfs(j);
nodes++;
}
}
}
public static String rev(String s)
{
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long lcm(long a, long b)
{
return a * (b / gcd(a, b));
}
static long gcd(long a, long b)
{
while (b > 0)
{
long temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
static InputReader in;
static PrintWriter w;
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 String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
}
while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
}
while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
} | quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.io.*;
import java.util.StringTokenizer;
public class D911 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
int[] num = new int[n];
for (int i = 0; i < n; i++) {
num[i] = Integer.parseInt(st.nextToken());
}
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (num[i] < num[j]) {
count++;
}
}
}
boolean ans = count % 2 == 0;
for (int m = Integer.parseInt(br.readLine()); m-- > 0; ) {
st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
if (((r - l + 1) / 2) % 2 != 0) {
ans = !ans;
}
out.println(ans ? "even" : "odd");
}
out.close();
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.util.*;
import java.io.*;
public class D {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
boolean even = true;
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
for (int j = 0; j < i; j++) {
if (a[j] > a[i]) {
even = !even;
}
}
}
int m = in.nextInt();
for (int i = 0; i < m; i++) {
if ((1 - in.nextInt() + in.nextInt()) / 2 % 2 == 1) {
even = !even;
}
if (even)
out.println("even");
else
out.println("odd");
}
finish();
}
public static void finish() {
out.close();
in.close();
System.exit(0);
}
static class InputReader implements Iterator<String>, Closeable {
// Fast input reader. Based on Kattio.java from open.kattis.com
// but has method names to match Scanner
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
public InputReader(InputStream i) {
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasNext() {
return peekToken() != null;
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public String next() {
return nextToken();
}
public String nextLine() {
try {
line = r.readLine();
} catch (IOException e) {
line = null;
}
token = null;
st = null;
return line;
}
public void close() {
try {
r.close();
} catch (IOException e) {
}
}
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
} | quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.Map.Entry;
public class Template {
String fileName = "";
long INF = Long.MAX_VALUE / 3;
int MODULO = 1000*1000*1000+7;
long[] fenwik;
int BORDER = 1000*1000+100;
void solve() throws IOException {
int n = readInt();
int[] a = new int[n];
for(int i=0; i<n; ++i){
a[i] = readInt();
}
fenwik = new long[BORDER];
long ans = 0;
for(int i=n-1;i>=0;--i){
ans+=sumFenwik(a[i]);
incFenwik(a[i],1);
}
boolean even = ans % 2 == 0;
int m = readInt();
for(int i=0; i<m; ++i){
int l = readInt();
int r = readInt();
if(((r-l+1)/2)%2==1){
even = !even;
}
out.println(even?"even":"odd");
}
}
void incFenwik(int i, int delta){
for(;i<BORDER;i = i|(i+1)){
fenwik[i]+=delta;
}
}
long sumFenwik(int r){
long sum = 0;
for(;r>=0;r = (r&(r+1))-1){
sum+=fenwik[r];
}
return sum;
}
int gcd(int a, int b){
return b == 0 ? a : gcd(b, a%b);
}
long binPow(long a, long b, long m) {
if (b == 0) {
return 1;
}
if (b % 2 == 1) {
return ((a % m) * (binPow(a, b - 1, m) % m)) % m;
} else {
long c = binPow(a, b / 2, m);
return (c * c) % m;
}
}
class Fenwik {
long[] t;
int length;
Fenwik(int[] a) {
length = a.length + 100;
t = new long[length];
for (int i = 0; i < a.length; ++i) {
inc(i, a[i]);
}
}
void inc(int ind, int delta) {
for (; ind < length; ind = ind | (ind + 1)) {
t[ind] += delta;
}
}
long getSum(int r) {
long sum = 0;
for (; r >= 0; r = (r & (r + 1)) - 1) {
sum += t[r];
}
return sum;
}
}
class SegmentTree {
int[] t;
SegmentTree(int[] a) {
int n = a.length - 1;
t = new int[n * 4];
build(a, 1, 1, n);
}
void build(int[] a, int v, int tl, int tr) {
if (tl == tr) {
t[v] = a[tl];
return;
}
int mid = (tr + tl) / 2;
build(a, 2 * v, tl, mid);
build(a, 2 * v + 1, mid + 1, tr);
t[v] = Math.max(t[2 * v], t[2 * v + 1]);
}
void update(int v, int tl, int tr, int pos, int value) {
if (tl == tr) {
t[v] = value;
return;
}
int mid = (tl + tr) / 2;
if (pos <= mid) {
update(2 * v, tl, mid, pos, value);
} else {
update(2 * v + 1, mid + 1, tr, pos, value);
}
t[v] = Math.max(t[2 * v], t[2 * v + 1]);
}
int getMax(int v, int tl, int tr, int l, int r) {
if (l > r) {
return -1000 * 1000;
}
if (tl == tr) {
return t[v];
}
if (l == tl && r == tr) {
return t[v];
}
int mid = (tl + tr) / 2;
int max1 = getMax(2 * v, tl, mid, l, Math.min(mid, r));
int max2 = getMax(2 * v + 1, mid + 1, tr, Math.max(mid + 1, l), r);
return Math.max(max1, max2);
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
new Template().run();
}
void run() throws NumberFormatException, IOException {
solve();
out.close();
};
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
String delim = " ";
Random rnd = new Random();
Template() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
if (fileName.isEmpty()) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader(fileName + ".in"));
out = new PrintWriter(fileName + ".out");
}
}
tok = new StringTokenizer("");
}
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) {
return null;
}
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt() throws NumberFormatException, IOException {
return Integer.parseInt(readString());
}
long readLong() throws NumberFormatException, IOException {
return Long.parseLong(readString());
}
double readDouble() throws NumberFormatException, IOException {
return Double.parseDouble(readString());
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.util.*;
import java.io.*;
public class CF911D {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] array = new int[n];
for(int i = 0; i < n; i++){
array[i] = sc.nextInt();
}
int count = 0;
for(int i = 0; i < array.length; i++){
for(int j = i+1; j < array.length; j++){
if(array[i] > array[j]){
count++;
}
}
}
count%=2;
int q = sc.nextInt();
for(int i = 0; i < q; i++){
int l = sc.nextInt();
int r = sc.nextInt();
int sz = r - l + 1;
count += (sz*(sz-1))/2;
count %= 2;
if(count == 1)
System.out.println("odd");
else
System.out.println("even");
}
}
} | quadratic | 911_D. Inversion Counting | CODEFORCES |
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
int[] A=new int[n];
String[] s=br.readLine().split(" ");
for(int i=0;i<n;i++){
A[i]=Integer.parseInt(s[i]);
}
/*int[][] nck=new int[2000][2000];
for(int i=0;i<=n;i++){
for(int j=0;j<=n;j++){
nck[i][j]=0;
}
}
for(int i=0;i<=n;i++){
nck[i][0]=1;
for(int j=1;j<=i;j++){
nck[i][j]=nck[i-1][j]+nck[i-1][j-1];
nck[i][j]%=2;
}
}*/
int inv=0;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(A[i]>A[j]){
inv++;
}
}
}
StringBuilder sb=new StringBuilder("");
int m=Integer.parseInt(br.readLine());
for(int i=0;i<m;i++){
s=br.readLine().split(" ");
int li=Integer.parseInt(s[0]);
int ri=Integer.parseInt(s[1]);
int tot=ri-li+1;
inv=inv+tot*(tot-1)/2;
if(inv%2==0){
sb.append("even\n");
}
else{
sb.append("odd\n");
}
}
System.out.print(sb);
}
} | quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.util.*;
import java.io.*;
import java.util.Queue;
import java.util.LinkedList;
import java.math.*;
public class Sample implements Runnable
{
public static void solve()
{
int n=i();
int[] a=new int[n];
for(int i=0;i<n;i++)a[i]=i();
int temp=0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[j]<a[i])temp++;
}
}
boolean even=(temp%2==0)?true:false;
int m=i();
while(m-->0)
{
int l=i(); int r=i();
long tt=(long)(Math.floor(r-l+1)/2);
if(tt%2==1)
{
if(even)
{
out.println("odd");
even=false;
}
else
{
out.println("even");
even=true;
}
}else
{
if(even)
{
out.println("even");
}
else
{
out.println("odd");
}
}
}
}
public void run()
{
solve();
out.close();
}
public static void main(String[] args) throws IOException
{
new Thread(null, new Sample(), "whatever", 1<<26).start();
}
abstract static class Pair implements Comparable<Pair>
{
long a;
int b;
Pair(){}
Pair(long a,int b)
{
this.a=a;
this.b=b;
}
public int compareTo(Pair x)
{
return Long.compare(x.a,this.a);
}
}
////////////////////////////////////////////////////// Merge Sort ////////////////////////////////////////////////////////////////////////
static class Merge
{
public static void sort(long inputArr[])
{
int length = inputArr.length;
doMergeSort(inputArr,0, length - 1);
}
private static void doMergeSort(long[] 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(long[]array,int lowerIndex, int middle, int higherIndex)
{
long[] temp=new long[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++;
}
}
}
/////////////////////////////////////////////////////////// Methods ////////////////////////////////////////////////////////////////////////
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 int gcd(int a,int b){return (a==0)?b:gcd(b%a,a);}
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;
}
boolean findSum(int set[], int n, long sum)
{
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
if (set[n-1] > sum)
return findSum(set, n-1, sum);
return findSum(set, n-1, sum) ||findSum(set, n-1, sum-set[n-1]);
}
public static long modPow(long base, long exp, long mod)
{
base = base % mod;
long result = 1;
while (exp > 0)
{
if (exp % 2 == 1)
{
result = (result * base) % mod;
}
base = (base * base) % mod;
exp = exp >> 1;
}
return result;
}
static long[] fac;
static long[] inv;
static long mod=(long)1e9+7;
public static void cal()
{
fac = new long[1000005];
inv = new long[1000005];
fac[0] = 1;
inv[0] = 1;
for (int i = 1; i <= 1000000; i++)
{
fac[i] = (fac[i - 1] * i) % mod;
inv[i] = (inv[i - 1] * modPow(i, mod - 2, mod)) % mod;
}
}
public static long ncr(int n, int r)
{
return (((fac[n] * inv[r]) % mod) * inv[n - r]) % mod;
}
////////////////////////////////////////// Input Reader ////////////////////////////////////////////////////////////////////////////////////////////////////
static InputReader sc = new InputReader(System.in);
static PrintWriter out= new PrintWriter(System.out);
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 | 911_D. Inversion Counting | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.io.InputStream;
public class BuildIn {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
public static void solve(InputReader in, PrintWriter out) throws IOException
{
int n = in.nextInt();
int[] list = new int[n];
for(int i = 0; i < n; i++)
{
list[i]=in.nextInt();
}
int count = 0;
for(int i = 0; i < n-1; i++)
{
for(int j = i+1; j < n; j++)
{
if(list[j]<list[i])
{
count++;
}
}
}
boolean sta = true;
if(count%2==1) sta = false;
int m = in.nextInt();
for(int i = 0; i <m; i++)
{
int a = in.nextInt();
int b = in.nextInt();
if((b-a)%4==2) sta = !sta;
if((b-a)%4==1) sta = !sta;
if(sta) out.println("even");
else out.println("odd");
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.util.Scanner;
public class TaskD {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
int m = s.nextInt();
int inv = 0;
// count inversions
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
inv++;
}
}
}
boolean odd = (inv % 2 == 1);
for (int i = 0; i < m; i++) {
int l = s.nextInt();
int r = s.nextInt() + 1; // r excluding, l including
int num = (r - l)*(r - l - 1)/2;
if (num % 2 == 1) {
odd = !odd;
}
System.out.println((odd) ? "odd" : "even");
}
}
}
| quadratic | 911_D. Inversion Counting | CODEFORCES |
import java.util.*;
public class vas2 {
public static void main( String[] args ) {
Scanner in = new Scanner( System.in );
int n = in.nextInt();
String st = in.next();
int[] a = new int[n];
for ( int i = 0; i < n; i++ )
a[i] = st.charAt( i ) - 48;
boolean c = false;
for ( int i = 1; !c && i < n; i++ ) {
int s = 0;
for ( int j = 0; j < i; j++ )
s += a[j];
int t = 0;
for ( int j = i; j < n; j++ ) {
t += a[j];
if ( t > s )
if ( t - a[j] != s )
break;
else
t = a[j];
}
if ( t == s )
c = true;
}
System.out.println( c ? "YES" : "NO" );
}
}
| quadratic | 1030_C. Vasya and Golden Ticket | CODEFORCES |
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.*;
public class Main{
static ArrayList a[]=new ArrayList[200001];
static int Count(int a[][],int n) {
dsu d=new dsu(n);
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(a[i][j]==0) {
d.union(i, j);
}
}
}
int cnt=0;
boolean chk[]=new boolean [n];
for(int i=0;i<n;i++) {
int p=d.root(i);
if(!chk[p]) {
chk[p]=true;
cnt++;
}
}
return cnt;
}
public void solve () {
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n=in.nextInt();
int a=in.nextInt();
int b=in.nextInt();
if(a==1 || b==1) {
int ans[][]=new int [n][n];
int temp=(a==1)?b:a;
for(int i=1;i<=n-temp;i++) {
ans[i][i-1]=1;
ans[i-1][i]=1;
}
int freq=Count(ans,n);
if(freq!=1) {
pw.println("NO");
}
else {
pw.println("YES");
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(i==j) {
pw.print(0);
}
else
pw.print((ans[i][j]+((temp==b)?1:0))%2);
}
pw.println();
}
}
}
else {
pw.print("NO");
}
pw.flush();
pw.close();
}
public static void main(String[] args) throws Exception {
new Thread(null,new Runnable() {
public void run() {
new Main().solve();
}
},"1",1<<26).start();
}
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static long mod = 1000000007;
public static int d;
public static int p;
public static int q;
public void extended(int a,int b) {
if(b==0) {
d=a;
p=1;
q=0;
}
else
{
extended(b,a%b);
int temp=p;
p=q;
q=temp-(a/b)*q;
}
}
public static long[] shuffle(long[] a,Random gen)
{
int n = a.length;
for(int i=0;i<n;i++)
{
int ind = gen.nextInt(n-i)+i;
long temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
return a;
}
public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
public static HashSet<Integer> primeFactorization(int n)
{
HashSet<Integer> a =new HashSet<Integer>();
for(int i=2;i*i<=n;i++)
{
while(n%i==0)
{
a.add(i);
n/=i;
}
}
if(n!=1)
a.add(n);
return a;
}
public static void sieve(boolean[] isPrime,int n)
{
for(int i=1;i<n;i++)
isPrime[i] = true;
isPrime[0] = false;
isPrime[1] = false;
for(int i=2;i*i<n;i++)
{
if(isPrime[i] == true)
{
for(int j=(2*i);j<n;j+=i)
isPrime[j] = false;
}
}
}
public static int GCD(int a,int b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
static class pair implements Comparable<pair>
{
Integer x;
Long y;
pair(int x,long y)
{
this.x=x;
this.y=y;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString()
{
return x+" "+y;
}
public boolean equals(Object o)
{
if (o instanceof pair)
{
pair p = (pair)o;
return p.x == x && p.y == y ;
}
return false;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode();
}
}
}
class pair implements Comparable<pair>
{
Integer x;
Long y;
pair(int x,long y)
{
this.x=x;
this.y=y;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString()
{
return x+" "+y;
}
public boolean equals(Object o)
{
if (o instanceof pair)
{
pair p = (pair)o;
return p.x == x && p.y == y ;
}
return false;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode();
}
}
class dsu{
int parent[];
dsu(int n){
parent=new int[n+1];
for(int i=0;i<=n;i++)
{
parent[i]=i;
}
}
int root(int n) {
while(parent[n]!=n)
{
parent[n]=parent[parent[n]];
n=parent[n];
}
return n;
}
void union(int _a,int _b) {
int p_a=root(_a);
int p_b=root(_b);
parent[p_a]=p_b;
}
boolean find(int a,int b) {
if(root(a)==root(b))
return true;
else
return false;
}
}
| quadratic | 990_D. Graph And Its Complement | CODEFORCES |
/**
* @author derrick20
*/
import java.io.*;
import java.util.*;
public class SameSumBlocks {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
int[] pre = new int[N + 1];
for (int i = 1; i <= N; i++) {
pre[i] = pre[i - 1] + sc.nextInt();
}
// var sumMap = new HashMap<Integer, ArrayList<Pair>>();
var sums = new ArrayList<Pair>();
for (int i = 1; i <= N; i++) {
for (int j = i; j <= N; j++) {
int sum = pre[j] - pre[i - 1];
// sumMap.computeIfAbsent(sum, val -> new ArrayList<>()).add(new Pair(i, j, sum));
sums.add(new Pair(i, j, sum));
}
}
Collections.sort(sums, (p1, p2) -> p1.sum - p2.sum != 0 ? p1.sum - p2.sum : p1.r - p2.r);
var ans = new ArrayList<Pair>();
int i = 0;
while (i < sums.size()) {
int j = i;
var group = new ArrayList(List.of(sums.get(i)));
int last = sums.get(i).r;
while (j + 1 < sums.size() && sums.get(j + 1).sum == sums.get(j).sum) {
if (sums.get(j + 1).l > last) {
group.add(sums.get(j + 1));
last = sums.get(j + 1).r;
}
j++;
}
// System.out.println(group);
if (group.size() > ans.size()) {
ans = group;
}
i = j + 1;
}
out.println(ans.size());
for (Pair p : ans) {
out.println(p);
}
out.close();
}
static class Pair {
int l, r, sum;
public Pair(int ll, int rr, int ss) {
l = ll; r = rr; sum = ss;
}
public String toString() {
return l + " " + r;
}
}
static class FastScanner {
private int BS = 1<<16;
private char NC = (char)0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt=1;
boolean neg = false;
if(c==NC)c=getChar();
for(;(c<'0' || c>'9'); c = getChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=getChar()) {
res = (res<<3)+(res<<1)+c-'0';
cnt*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/cnt;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=getChar();
while(c>32) {
res.append(c);
c=getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=getChar();
while(c!='\n') {
res.append(c);
c=getChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=getChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.IntStream;
public class Main {
private static InputReader reader = new InputReader(System.in);
private static PrintWriter writer = new PrintWriter(System.out);
public static void main(String[] args) {
int n = readInt();
long[] a = readLongArray(n);
HashMap<Long, List<Block>> blocks = new HashMap<>();
for (int j = 0; j < n; j++) {
long sum = 0;
for (int i = j; i >= 0; i--) {
sum += a[i];
if (!blocks.containsKey(sum))
blocks.put(sum, new LinkedList<>());
List<Block> blockList = blocks.get(sum);
if (blockList.size() > 0 && blockList.get(blockList.size() - 1).r == j) continue;
blockList.add(new Block(i, j));
}
}
List<Block> bestBlocks = new LinkedList<>();
for(long sum : blocks.keySet()) {
List<Block> blockList = blocks.get(sum);
List<Block> curBest = new LinkedList<>();
int lastR = -1;
for(Block block : blockList) {
if (block.l > lastR) {
curBest.add(block);
lastR = block.r;
}
}
if (curBest.size() > bestBlocks.size()) {
bestBlocks = curBest;
}
}
writer.println(bestBlocks.size());
for(Block block : bestBlocks) {
writer.printf("%d %d\n", block.l + 1, block.r + 1);
}
writer.flush();
}
private static int readInt() {
return reader.nextInt();
}
private static long readLong() {
return Long.parseLong(reader.next());
}
private static int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
private static long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
private static void reverseIntArray(int[] array) {
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
}
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());
}
}
private static class Block {
int l, r;
Block(int l, int r) {
this.l = l;
this.r = r;
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
// package codeforce.Training1900;
import java.io.PrintWriter;
import java.util.*;
//https://codeforces.com/problemset/problem/1141/F2
public class SameSumBlocks {
// MUST SEE BEFORE SUBMISSION
// check whether int part would overflow or not, especially when it is a * b!!!!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
// int t = sc.nextInt();
int t = 1;
for (int i = 0; i < t; i++) {
solve(sc, pw);
}
pw.close();
}
static void solve(Scanner in, PrintWriter out){
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
Map<Long, List<int[]>> mp = new HashMap<>();
long[] pre = new long[n + 1];
for (int i = 1; i <= n; i++) {
pre[i] = pre[i - 1] + arr[i - 1];
}
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
long sz = pre[j + 1] - pre[i];
if (!mp.containsKey(sz)) mp.put(sz, new ArrayList<>());
mp.get(sz).add(new int[]{i, j});
}
}
int max = 0;
List<int[]> ans = new ArrayList<>();
for(List<int[]> ls : mp.values()){
Collections.sort(ls, (a, b) -> {
if (a[1] == b[1]) return b[0] - a[0];
return a[1] - b[1];
});
List<int[]> tt = new ArrayList<>();
int cnt = 0;
int pr = -1;
for (int i = 0; i < ls.size(); i++) {
int[] get = ls.get(i);
if (get[0] <= pr) continue;
cnt++;
tt.add(get);
pr = get[1];
}
if (max < cnt){
ans = tt;
max = cnt;
}
}
out.println(max);
for(int[] v : ans){
out.println((v[0] + 1) + " " + (v[1] + 1));
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | 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.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author revanth
*/
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);
F2SameSumBlocksHard solver = new F2SameSumBlocksHard();
solver.solve(1, in, out);
out.close();
}
static class F2SameSumBlocksHard {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
long[] a = in.nextLongArray(n);
HashMap<Long, ArrayList<Pair>> hm = new HashMap<>();
long sum;
for (int j = 0; j < n; j++) {
sum = 0;
for (int i = j; i >= 0; i--) {
sum += a[i];
if (!hm.containsKey(sum))
hm.put(sum, new ArrayList<>());
hm.get(sum).add(new Pair(i + 1, j + 1));
}
}
ArrayList<Pair> al1 = new ArrayList<>();
ArrayList<Pair> al2 = new ArrayList<>();
int prev;
for (ArrayList<Pair> al : hm.values()) {
prev = 0;
al1.clear();
for (Pair p : al) {
if (p.x > prev) {
al1.add(p);
prev = p.y;
}
}
if (al1.size() > al2.size())
al2 = new ArrayList<>(al1);
}
out.println(al2.size());
for (Pair p : al2)
out.println(p.x + " " + p.y);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private InputReader.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 long[] nextLongArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class Pair implements Comparable<Pair> {
public int x;
public int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == this)
return true;
if (!(obj instanceof Pair))
return false;
Pair o = (Pair) obj;
return o.x == this.x && o.y == this.y;
}
public int hashCode() {
return this.x + this.y;
}
public int compareTo(Pair p) {
if (x == p.x)
return Integer.compare(y, p.y);
return Integer.compare(x, p.x);
}
}
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 println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.InputMismatchException;
public class F547 {
public static void main(String[] args) {
FastScanner in = new FastScanner(System.in);
int N = in.nextInt();
int[] arr = new int[N];
for(int i = 0; i < N; i++)
arr[i] = in.nextInt();
long[] sum = new long[arr.length + 1];
for(int i = 1; i < sum.length; i++)
sum[i] = sum[i-1] + arr[i-1];
HashMap<Long, ArrayList<Pair>> map = new HashMap<>();
for(int i = 0; i < sum.length; i++) {
for(int j = i+1; j < sum.length; j++) {
long diff = sum[j] - sum[i];
if(!map.containsKey(diff))
map.put(diff, new ArrayList<>());
ArrayList<Pair> list = map.get(diff);
list.add(new Pair(i, j));
}
}
for(long key : map.keySet()) {
ArrayList<Pair> list1 = map.get(key);
Collections.sort(list1);
ArrayList<Pair> list2 = new ArrayList<>();
int end = 0;
for(Pair p : list1) {
if(end <= p.a) {
list2.add(p);
end = p.b;
}
}
map.put(key, list2);
}
long maxKey = -1;
int max = -1;
for(long key : map.keySet()) {
if(map.get(key).size() > max) {
max = map.get(key).size();
maxKey = key;
}
}
ArrayList<Pair> list = map.get(maxKey);
StringBuilder sb = new StringBuilder();
sb.append(list.size());
sb.append("\n");
for(Pair p : list) {
sb.append((1 + p.a) + " " + p.b);
sb.append("\n");
}
System.out.println(sb.toString());
}
static class Pair implements Comparable<Pair> {
int a, b;
public Pair(int x, int y) {
a = x;
b = y;
}
public int compareTo(Pair other) {
if(b != other.b) {
return b - other.b;
}
return other.a - a;
}
public String toString() {
return "(" + a + ", " + b + ")";
}
}
/**
* Source: Matt Fontaine
*/
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int chars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (chars == -1)
throw new InputMismatchException();
if (curChar >= chars) {
curChar = 0;
try {
chars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (chars <= 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();
}
}
}
/*
7
4 1 2 2 1 5 3
outputCopy
3
7 7
2 3
4 5
inputCopy
11
-5 -4 -3 -2 -1 0 1 2 3 4 5
outputCopy
2
3 4
1 1
inputCopy
4
1 1 1 1
outputCopy
4
4 4
1 1
2 2
3 3
*/ | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.Scanner;
import java.util.Vector;
import java.util.HashMap;
import java.util.Comparator;
public class F2{
static class Pair{
int l;
int r;
Pair(int l, int r){
this.l = l;
this.r = r;
}
public String toString(){
return "(" + l + ", " + r + ")";
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n+1];
for(int i = 1;i<=n;++i){
a[i] = in.nextInt();
}
HashMap<Integer, Vector<Pair>> map = new HashMap<>();
for(int i = 1;i<=n;++i){
int sum = 0;
for(int j = i;j<=n;++j){
sum+=a[j];
if(!map.containsKey(sum))
map.put(sum,new Vector<>());
map.get(sum).add(new Pair(i,j));
}
}
Vector<Pair> an = null;
for(Integer key : map.keySet()){
Vector<Pair> vec = map.get(key);
Vector<Pair> ans = new Vector<>();
ans.add(vec.get(0));
int size = 1;
for(int i = 1;i<vec.size();++i){
if(ans.get(size-1).r > vec.get(i).r)
ans.set(size-1,vec.get(i));
else if(ans.get(size-1).r < vec.get(i).l){
ans.add(vec.get(i));
size++;
}
}
if(an == null || an.size() < size) an = ans;
}
StringBuilder res = new StringBuilder().append(an.size() + "\n");
for(int i = 0;i<an.size();++i)
res.append(an.get(i).l + " " + an.get(i).r + "\n");
System.out.println(res);
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.regex.*;
import java.util.stream.LongStream;
public class Main{
static ArrayList a[]=new ArrayList[5000001];
static Vector<pair>schedule_it(ArrayList<pair> v) {
Vector<pair >ans=new Vector<>();
Collections.sort(v, new Comparator<pair>() {
public int compare(pair p1,pair p2) {
if(p1.y<p2.y)
return -1;
if(p1.y>p2.y)
return 1;
if(p1.x<p2.x)
return -1;
if(p1.x>p2.x)
return 1;
return 0;
}
});
int end=-1;
for(int i=0;i<v.size();i++) {
pair p=v.get(i);
if(p.x>end) {
ans.add(p);
end=p.y;
}
}
return ans;
}
public static void main(String[] args)
{
InputReader in=new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n=in.nextInt();
long arr[]=new long[n];
for(int i=0;i<n;i++) {
arr[i]=in.nextLong();
}
HashMap<Long,Integer>hm=new HashMap<>();
int id=0;
for(int i=0;i<n;i++) {
long sum=0;
for(int j=i;j<n;j++) {
sum+=arr[j];
if(!hm.containsKey(sum)) {
hm.put(sum, id++);
a[id-1]=new ArrayList<pair>();
}
a[hm.get(sum)].add(new pair(i,j));
}
}
Vector<pair>fi=new Vector<>();
for(int i=0;i<id;i++) {
Vector<pair> v=schedule_it(a[i]);
if(v.size()>fi.size()) {
fi=v;
}
}
pw.println(fi.size());
for(int i=0;i<fi.size();i++) {
pw.println((fi.get(i).x+1)+" "+(fi.get(i).y+1));
}
pw.flush();
pw.close();
}
private static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
static class tri implements Comparable<tri> {
int p, c, l;
tri(int p, int c, int l) {
this.p = p;
this.c = c;
this.l = l;
}
public int compareTo(tri o) {
return Integer.compare(l, o.l);
}
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static long mod = 1000000007;
public static int d;
public static int p;
public static int q;
public static int[] suffle(int[] a,Random gen)
{
int n = a.length;
for(int i=0;i<n;i++)
{
int ind = gen.nextInt(n-i)+i;
int temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
return a;
}
public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
/* public static long primeFactorization(long n)
{
HashSet<Integer> a =new HashSet<Integer>();
long cnt=0;
for(int i=2;i*i<=n;i++)
{
while(a%i==0)
{
a.add(i);
a/=i;
}
}
if(a!=1)
cnt++;
//a.add(n);
return cnt;
}*/
public static void sieve(boolean[] isPrime,int n)
{
for(int i=1;i<n;i++)
isPrime[i] = true;
isPrime[0] = false;
isPrime[1] = false;
for(int i=2;i*i<n;i++)
{
if(isPrime[i] == true)
{
for(int j=(2*i);j<n;j+=i)
isPrime[j] = false;
}
}
}
public static int GCD(int a,int b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static long GCD(long a,long b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static void extendedEuclid(int A,int B)
{
if(B==0)
{
d = A;
p = 1 ;
q = 0;
}
else
{
extendedEuclid(B, A%B);
int temp = p;
p = q;
q = temp - (A/B)*q;
}
}
public static long LCM(long a,long b)
{
return (a*b)/GCD(a,b);
}
public static int LCM(int a,int b)
{
return (a*b)/GCD(a,b);
}
public static int binaryExponentiation(int x,int n)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static long binaryExponentiation(long x,long n)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static int modularExponentiation(int x,int n,int M)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x%M*x)%M;
n=n/2;
}
return result;
}
public static long modularExponentiation(long x,long n,long M)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result%M * x%M)%M;
x=(x%M * x%M)%M;
n=n/2;
}
return result;
}
public static long modInverse(int A,int M)
{
return modularExponentiation(A,M-2,M);
}
public static long modInverse(long A,long M)
{
return modularExponentiation(A,M-2,M);
}
public static boolean isPrime(int n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n%2 == 0 || n%3 == 0)
return false;
for (int i=5; i*i<=n; i=i+6)
{
if (n%i == 0 || n%(i+2) == 0)
return false;
}
return true;
}
public static long[] shuffle(long[] a, Random gen){
for(int i = 0, n = a.length;i < n;i++){
int ind = gen.nextInt(n-i)+i;
long d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
static class pair implements Comparable<pair>{
Integer x;
Integer y;
pair(int l,int id){
this.x=l;
this.y=id;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString(){
return (x+" "+y);
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
public class Codeforces {
static long MOD = 1_000_000_007L;
static void main2() throws Exception {
int n = ni();
int[] arr = nia(n);
Map<Integer, List<Pair<Integer, Integer>>> map = new HashMap<>();
for(int r = 0; r < n; r++) {
int sum = 0;
for(int l = r; l >= 0; l--) {
sum += arr[l];
if(!map.containsKey(sum)) map.put(sum, new ArrayList<Pair<Integer, Integer>>());
map.get(sum).add(new Pair<Integer, Integer>(l + 1, r + 1));
}
}
int bestSum = Integer.MIN_VALUE;
int bestSumCount = -1;
for(Map.Entry<Integer, List<Pair<Integer, Integer>>> entry : map.entrySet()) {
int count = 0;
int r = -1;
for(Pair<Integer, Integer> pair : entry.getValue()) {
if(r < pair.first) {
count++;
r = pair.second;
}
}
if(count > bestSumCount) {
bestSumCount = count;
bestSum = entry.getKey();
}
}
//got best sum
println(bestSumCount);
int r = -1;
for(Pair<Integer, Integer> pair : map.get(bestSum)) {
if(r < pair.first) {
println(pair.first + " " + pair.second);
r = pair.second;
}
}
}
// ____________________________________________________________________________
//| |
//| /$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$$$$$ /$$$$$$ |
//| |_ $$_/ /$$__ $$ /$$__ $$ | $$ /$$__ $$ /$$__ $$ |
//| | $$ | $$ \ $$ | $$ \__//$$$$$$ /$$ /$$| $$ \__/| $$ \__/ |
//| | $$ | $$ | $$ | $$$$$$|_ $$_/ | $$ | $$| $$$$ | $$$$ |
//| | $$ | $$ | $$ \____ $$ | $$ | $$ | $$| $$_/ | $$_/ |
//| | $$ | $$ | $$ /$$ \ $$ | $$ /$$| $$ | $$| $$ | $$ |
//| /$$$$$$| $$$$$$/ | $$$$$$/ | $$$$/| $$$$$$/| $$ | $$ |
//| |______/ \______/ \______/ \___/ \______/ |__/ |__/ |
//|____________________________________________________________________________|
private static byte[] scannerByteBuffer = new byte[1024]; // Buffer of Bytes
private static int scannerIndex;
private static InputStream scannerIn;
private static int scannerTotal;
private static BufferedWriter printerBW;
private static boolean DEBUG = false;
private static int next() throws IOException { // Scan method used to scan buf
if (scannerTotal < 0)
throw new InputMismatchException();
if (scannerIndex >= scannerTotal) {
scannerIndex = 0;
scannerTotal = scannerIn.read(scannerByteBuffer);
if (scannerTotal <= 0)
return -1;
}
return scannerByteBuffer[scannerIndex++];
}
static int ni() throws IOException {
int integer = 0;
int n = next();
while (isWhiteSpace(n)) // Removing startPointing whitespaces
n = next();
int neg = 1;
if (n == '-') { // If Negative Sign encounters
neg = -1;
n = next();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = next();
} else
throw new InputMismatchException();
}
return neg * integer;
}
static long nl() throws IOException {
long integer = 0;
int n = next();
while (isWhiteSpace(n)) // Removing startPointing whitespaces
n = next();
int neg = 1;
if (n == '-') { // If Negative Sign encounters
neg = -1;
n = next();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = next();
} else
throw new InputMismatchException();
}
return neg * integer;
}
static String line() throws IOException {
StringBuilder sb = new StringBuilder();
int n = next();
while (isWhiteSpace(n))
n = next();
while (!isNewLine(n)) {
sb.append((char) n);
n = next();
}
return sb.toString();
}
private static boolean isNewLine(int n) {
return n == '\n' || n == '\r' || n == -1;
}
private static boolean isWhiteSpace(int n) {
return n == ' ' || isNewLine(n) || n == '\t';
}
static int[] nia(int n) throws Exception {
if (n < 0)
throw new Exception("Array size should be non negative");
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = ni();
return array;
}
static int[][] n2dia(int r, int c) throws Exception {
if (r < 0 || c < 0)
throw new Exception("Array size should be non negative");
int[][] array = new int[r][c];
for (int i = 0; i < r; i++)
array[i] = nia(c);
return array;
}
static long[] nla(int n) throws Exception {
if (n < 0)
throw new Exception("Array size should be non negative");
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nl();
return array;
}
static float[] nfa(int n) throws Exception {
if (n < 0)
throw new Exception("Array size should be non negative");
float[] array = new float[n];
for (int i = 0; i < n; i++)
array[i] = nl();
return array;
}
static double[] nda(int n) throws Exception {
if (n < 0)
throw new Exception("Array size should be non negative");
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nl();
return array;
}
static <T> void print(T ... str) {
try {
for(T ele : str)
printerBW.append(ele.toString());
if (DEBUG)
flush();
} catch (IOException e) {
System.out.println(e.toString());
}
}
static <T> void println(T ... str) {
if(str.length == 0) {
print('\n');
return;
}
for(T ele : str)
print(ele, '\n');
}
static void flush() throws IOException {
printerBW.flush();
}
static void close() {
try {
printerBW.close();
} catch (IOException e) {
System.out.println(e.toString());
}
}
public static void main(String[] args) throws Exception {
long startPointTime = System.currentTimeMillis();
scannerIn = System.in;
printerBW = new BufferedWriter(new OutputStreamWriter(System.out));
if (args.length > 0 && args[0].equalsIgnoreCase("debug")
|| args.length > 1 && args[1].equalsIgnoreCase("debug"))
DEBUG = true;
main2();
long endTime = System.currentTimeMillis();
float totalProgramTime = endTime - startPointTime;
if (args.length > 0 && args[0].equalsIgnoreCase("time") || args.length > 1 && args[1].equalsIgnoreCase("time"))
print("Execution time is " + totalProgramTime + " (" + (totalProgramTime / 1000) + "s)");
close();
}
static class Pair <L, R> {
L first;
R second;
Pair(L first, R second) {
this.first = first;
this.second = second;
}
public boolean equals(Object p2) {
if (p2 instanceof Pair) {
return ((Pair) p2).first.equals(first) && ((Pair) p2).second.equals(second);
}
return false;
}
public String toString() {
return "(first=" + first.toString() + ",second=" + second.toString() + ")";
}
}
static class DisjointSet {
int[] arr;
int[] size;
DisjointSet(int n) {
arr = new int[n + 1];
size = new int[n + 1];
makeSet();
}
void makeSet() {
for (int i = 1; i < arr.length; i++) {
arr[i] = i;
size[i] = 1;
}
}
void union(int i, int j) {
if (i == j)
return;
if (i > j) {
i ^= j;
j ^= i;
i ^= j;
}
i = find(i);
j = find(j);
if (i == j)
return;
arr[j] = arr[i];
size[i] += size[j];
size[j] = size[i];
}
int find(int i) {
if (arr[i] != i) {
arr[i] = find(arr[i]);
size[i] = size[arr[i]];
}
return arr[i];
}
int getSize(int i) {
i = find(i);
return size[i];
}
public String toString() {
return Arrays.toString(arr);
}
}
static boolean isSqrt(double a) {
double sr = Math.sqrt(a);
return ((sr - Math.floor(sr)) == 0);
}
static long abs(long a) {
return Math.abs(a);
}
static int min(int ... arr) {
int min = Integer.MAX_VALUE;
for (int var : arr)
min = Math.min(min, var);
return min;
}
static long min(long ... arr) {
long min = Long.MAX_VALUE;
for (long var : arr)
min = Math.min(min, var);
return min;
}
static int max(int... arr) {
int max = Integer.MIN_VALUE;
for (int var : arr)
max = Math.max(max, var);
return max;
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
new Main().go();
}
PrintWriter out;
Reader in;
BufferedReader br;
Main() throws IOException {
try {
//br = new BufferedReader( new FileReader("input.txt") );
//in = new Reader("input.txt");
in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
}
catch (Exception e) {
//br = new BufferedReader( new InputStreamReader( System.in ) );
in = new Reader();
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
}
}
void go() throws Exception {
//int t = in.nextInt();
int t = 1;
while (t > 0) {
solve();
t--;
}
out.flush();
out.close();
}
int inf = 2000000000;
int mod = 1000000007;
double eps = 0.000000001;
int n;
int m;
ArrayList<Integer>[] g;
int[] a;
void solve() throws IOException {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
HashMap<Integer, ArrayList<Pair>> segs = new HashMap<>();
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += a[j];
if (!segs.containsKey(sum))
segs.put(sum, new ArrayList<>());
segs.get(sum).add(new Pair(i, j));
}
}
int max = 0;
ArrayList<Pair> ans = new ArrayList<>();
for (Integer k : segs.keySet()) {
ArrayList<Pair> list = segs.get(k);
ArrayList<Pair> blocks = new ArrayList<>();
Collections.reverse(list);
int prev = inf;
for (Pair p : list) {
int l = p.a;
int r = p.b;
if (r < prev) {
blocks.add(p);
prev = l;
}
}
if (blocks.size() > max) {
ans = blocks;
max = blocks.size();
}
}
out.println(ans.size());
for (Pair p : ans)
out.println((p.a+1)+" "+(p.b+1));
}
class Pair implements Comparable<Pair>{
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair p) {
if (a != p.a)
return Integer.compare(a, p.a);
else
return Integer.compare(b, p.b);
}
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
static class InputReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public InputReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public InputReader(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 | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class default_dst {
public static void main(String[] args) {
in = new FastReader();
int n=ni();
int[] arr=takeIntegerArrayInput(n);
HashMap<Long,ArrayList<pair>> hm=new HashMap<>();
int max_size=0;
long S=-1;
for (int i=0;i<arr.length;i++){
long sum=0;
for (int j=i;j>=0;j--){
sum+=arr[j];
if (!hm.containsKey(sum)){
hm.put(sum,new ArrayList<>());
}
if (hm.get(sum).size()==0||hm.get(sum).get(hm.get(sum).size()-1).y<j){
hm.get(sum).add(new pair(j,i));
}
if (hm.get(sum).size()>max_size){
max_size=hm.get(sum).size();
S=sum;
}
}
}
System.out.println(max_size);
StringBuilder sb=new StringBuilder();
for (int i=0;i<hm.get(S).size();i++){
sb.append(hm.get(S).get(i)).append("\n");
}
System.out.print(sb.toString());
}
static class pair{
int x;
int y;
pair(int x,int y){
this.x=x;
this.y=y;
}
@Override
public String toString(){
return (this.x+1)+" "+(this.y+1);
}
}
public static long binarySearch(long low, long high) {
while (high - low > 1) {
long mid = (high - low)/2 + low;
//System.out.println(mid);
if (works(mid)) {
high = mid;
} else {
low = mid;
}
}
return (works(low) ? low : high);
}
static long fast_exp_with_mod(long base, long exp) {
long MOD=1000000000+7;
long res=1;
while(exp>0) {
if(exp%2==1) res=(res*base)%MOD;
base=(base*base)%MOD;
exp/=2;
}
return res%MOD;
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class my_no{
long num;
long denom;
@Override
public String toString() {
if (denom<0){
this.num=-this.num;
this.denom=-this.denom;
}
if (num==0)return "0";
return (num+"/"+denom);
}
my_no(int no){
this.num=no;
this.denom=1;
}
my_no(long num,long denom){
this.num=num;
this.denom=denom;
}
my_no multiply(my_no obj){
long num1=obj.num;
long denom1=obj.denom;
long n=num1*num;
long d=denom1*denom;
long gcd=gcd(n,d);
n/=gcd;
d/=gcd;
return new my_no(n,d);
}
// my_no multiply(my_no obj){
// long num1=obj.num;
// long denom1=obj.denom;
// long num2=this.num;
// long denom2=this.denom;
//
// }
my_no multiply(int no){
long n=num*no;
long d=denom;
long gcd=gcd(n,d);
n/=gcd;
d/=gcd;
return new my_no(n,d);
}
}
static void memset(int[][] arr,int val){
for (int i=0;i<arr.length;i++){
for (int j=0;j<arr[i].length;j++){
arr[i][j]=val;
}
}
}
static void memset(int[] arr,int val){
for (int i=0;i<arr.length;i++){
arr[i]=val;
}
}
static void memset(long[][] arr,long val){
for (int i=0;i<arr.length;i++){
for (int j=0;j<arr[i].length;j++){
arr[i][j]=val;
}
}
}
static void memset(long[] arr,long val){
for (int i=0;i<arr.length;i++){
arr[i]=val;
}
}
static private boolean works(long test){
return true;
}
static void reverse(char[] arr ,int i,int j){
if (i==j)
return;
while (i<j){
char temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
++i;
--j;
}
}
static int[] takeIntegerArrayInput(int no){
int[] arr=new int[no];
for (int i=0;i<no;++i){
arr[i]=ni();
}
return arr;
}
static long fast_Multiply(long no , long pow){
long result=1;
while (pow>0){
if ((pow&1)==1){
result=result*no;
}
no=no*no;
pow>>=1;
}
return result;
}
static long[] takeLongArrayInput(int no){
long[] arr=new long[no];
for (int i=0;i<no;++i){
arr[i]=ni();
}
return arr;
}
static final long MOD = (long)1e9+7;
static FastReader in;
static void p(Object o){
System.out.print(o);
}
static void pn(Object o){
System.out.println(o);
}
static String n(){
return in.next();
}
static String nln(){
return in.nextLine();
}
static int ni(){
return Integer.parseInt(in.next());
}
static int[] ia(int N){
int[] a = new int[N];
for(int i = 0; i<N; i++)a[i] = ni();
return a;
}
static long[] la(int N){
long[] a = new long[N];
for(int i = 0; i<N; i++)a[i] = nl();
return a;
}
static long nl(){
return Long.parseLong(in.next());
}
static double nd(){
return Double.parseDouble(in.next());
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
}
static void println(String[] arr){
for (int i=0;i<arr.length;++i){
System.out.println(arr[i]);
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Reader in = new Reader();
int n = in.nextInt();
int[] a = in.na(n);
HashMap<Long, ArrayList<Pair>> v = new HashMap<>();
for(int i = 0; i<n; i++) {
long s = 0;
for(int j = i; j<n; j++) {
s+=a[j];
Pair p = new Pair(i+1, j+1);
if(v.containsKey(s)) {
v.get(s).add(p);
}else {
ArrayList<Pair> xd = new ArrayList<>();
xd.add(p);
v.put(s,xd);
}
}
}
ArrayList<Pair> ans = new ArrayList<>();
for(Entry<Long,ArrayList<Pair>> e : v.entrySet()) {
ArrayList<Pair> pairs = e.getValue();
Collections.sort(pairs);
Stack<Pair> st = new Stack<>();
for(int i = 0; i<pairs.size(); i++) {
Pair cur = pairs.get(i);
if(st.isEmpty()||st.peek().r<cur.l) {
st.push(cur);
}else if(st.peek().r>cur.r) {
st.pop();
st.push(cur);
}
if(st.size()>ans.size()) ans = new ArrayList<>(st);
}
}
System.out.println(ans.size());
for(Pair p : ans)
System.out.println(p.l +" "+p.r);
}
static class Pair implements Comparable<Pair>{
int l,r;
public Pair(int l, int r) {
this.l = l;
this.r = r;
}
@Override
public int compareTo(Pair o) {
return this.l - o.l;
}
}
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public String[] nS(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = next();
return a;
}
public int nextInt() {
if (st == null || !st.hasMoreTokens())
try {
readLine();
} catch (Exception e) {
}
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
if (st == null || !st.hasMoreTokens())
try {
readLine();
} catch (Exception e) {
}
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
if (st == null || !st.hasMoreTokens())
try {
readLine();
} catch (Exception e) {
}
return Long.parseLong(st.nextToken());
}
public String next() {
if (st == null || !st.hasMoreTokens())
try {
readLine();
} catch (Exception e) {
}
return st.nextToken();
}
public static void readLine() {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
}
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.*;
public class Solution{
static class Node implements Comparable<Node>{
int sum;
int l;
int r;
Node next;
int nb;
Node ini;
boolean not;
public Node(int sum,int l,int r){
this.sum = sum;
this.l = l;
this.r = r;
nb = 0;
not = false;
ini = null;
}
@Override
public int compareTo(Node node){
if(sum-node.sum!=0) return sum-node.sum;
else if(l-node.l!=0) return l-node.l;
else return r - node.r;
}
}
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(st.nextToken());
TreeSet<Node> ts = new TreeSet<Node>();
st = new StringTokenizer(br.readLine());
int[] a = new int[n+1];
for(int i=1;i<=n;i++) a[i] = Integer.parseInt(st.nextToken());
int[] s = new int[n+1];
for(int i=1;i<=n;i++) s[i] = s[i-1] + a[i];
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++){
ts.add(new Node(s[j]-s[i-1],i,j));
}
}
int minvalue = -2000*(int)Math.pow(10,5);
int maxvalue = 2000*(int)Math.pow(10,5);
ts.add(new Node(minvalue,0,0));
ts.add(new Node(maxvalue,0,0));
//System.out.println(minvalue);
Node node = ts.higher(ts.first());
int sum = 0;
int max = 0;
Node m = null;
while(node.sum!=maxvalue){
sum = node.sum;
while(node.sum==sum){
node = ts.higher(node);
}
Node var = ts.lower(node);
// System.out.println(sum+" "+var.sum);
max = 0;
while(var.sum==sum){
Node next = ts.higher(new Node(sum,var.r+1,0));
if(max>1+next.nb){
var.nb = max;
var.ini = m;
}
else if(next.ini==null){
var.nb = 1 + next.nb;
var.next = next;
if(max<var.nb){
max = var.nb;
m = var;
}
}else{
var.nb = 1 + next.nb;
var.next = next.ini;
if(max<var.nb){
max = var.nb;
m = var;
}
}
var = ts.lower(var);
//System.out.println(sum+" "+var.sum);
}
}
int k = 0;
Node best = new Node(minvalue,0,0);
//var = new Node(minvalue,0,0);
for(Node var:ts){
if(k<var.nb){
k = var.nb;
best = var;
if(var.ini!=null) best = var.ini;
}
}
if(k==0) System.out.println("erreur");
else{
out.println(k);
sum = best.sum;
while(best.sum==sum){
out.println(best.l+" "+best.r);
best = best.next;
}
}
out.flush();
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Set;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Washoum
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
inputClass in = new inputClass(inputStream);
PrintWriter out = new PrintWriter(outputStream);
F2SameSumBlocksHard solver = new F2SameSumBlocksHard();
solver.solve(1, in, out);
out.close();
}
static class F2SameSumBlocksHard {
public void solve(int testNumber, inputClass sc, PrintWriter out) {
int n = sc.nextInt();
int[] tab = new int[n];
int[] s = new int[n];
for (int i = 0; i < n; i++) {
tab[i] = sc.nextInt();
if (i > 0)
s[i] = s[i - 1] + tab[i];
else
s[0] = tab[0];
}
HashMap<Integer, F2SameSumBlocksHard.Pair> sums = new HashMap<>();
F2SameSumBlocksHard.Pair p;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j > 0) {
if (sums.get(s[i] - s[j - 1]) != null) {
if (sums.get(s[i] - s[j - 1]).last < j) {
sums.get(s[i] - s[j - 1]).sum++;
sums.get(s[i] - s[j - 1]).last = i;
}
} else {
p = new F2SameSumBlocksHard.Pair();
p.sum = 1;
p.last = i;
sums.put(s[i] - s[j - 1], p);
}
} else {
if (sums.get(s[i]) != null) {
if (sums.get(s[i]).last < j) {
sums.get(s[i]).sum++;
sums.get(s[i]).last = i;
}
} else {
p = new F2SameSumBlocksHard.Pair();
p.sum = 1;
p.last = i;
sums.put(s[i], p);
}
}
}
}
Iterator<Map.Entry<Integer, F2SameSumBlocksHard.Pair>> it = sums.entrySet().iterator();
Map.Entry<Integer, F2SameSumBlocksHard.Pair> t;
int maxsum = 0;
int cnt = 0;
while (it.hasNext()) {
t = it.next();
if (t.getValue().sum > cnt) {
maxsum = t.getKey();
cnt = t.getValue().sum;
}
}
out.println(cnt);
int start = 0;
for (int i = 0; i < n; i++) {
for (int j = start; j <= i; j++) {
if (j > 0) {
if (s[i] - s[j - 1] == maxsum) {
out.println((j + 1) + " " + (i + 1));
start = i + 1;
break;
}
} else {
if (s[i] == maxsum) {
out.println((j + 1) + " " + (i + 1));
start = i + 1;
break;
}
}
}
}
}
static class Pair {
int sum;
int last;
}
}
static class inputClass {
BufferedReader br;
StringTokenizer st;
public inputClass(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
public class A {
String filename = "";
final int INF = 1_000_000_000;
void solve() {
int n = readInt();
int[] a = new int[n];
for(int i = 0;i<n;i++){
a[i] = readInt();
}
Map<Integer, Integer>[] maps = new Map[n];
Map<Integer, Integer> sums = new HashMap();
for(int i = 0;i<n;i++){
maps[i] = new HashMap<>();
}
for(int i = 0;i<n;i++){
int summ = 0;
for(int j = i;j<n;j++){
summ += a[j];
if(!maps[i].containsKey(summ)) maps[i].put(summ, j);
int x = sums.getOrDefault(summ, 0);
sums.put(summ, x + 1);
}
}
int max = 0;
int goodSumm = 0;
for(int summ : sums.keySet()){
if(sums.get(summ) <= max) continue;
int right = -1;
int ans = 0;
for(int j = 0;j<n;j++){
if(!maps[j].containsKey(summ)) continue;
int end = maps[j].get(summ);
if(right == -1){
right = end;
ans++;
continue;
}
if(j > right){
right = end;
ans++;
continue;
}
if(end < right){
right = end;
}
}
if(max < ans){
max = ans;
goodSumm = summ;
}
}
int left = -1;
int right = -1;
List<Integer> ans = new ArrayList<>();
for(int j = 0;j<n;j++){
if(!maps[j].containsKey(goodSumm)) continue;
int start = j;
int end = maps[j].get(goodSumm);
if(right == -1){
left = j;
right = end;
continue;
}
if(start > right){
ans.add(left + 1);
ans.add(right + 1);
left = start;
right = end;
continue;
}
if(end < right){
left = start;
right = end;
}
}
ans.add(left + 1);
ans.add(right + 1);
out.println(max);
for(int i = 0;i<ans.size();i+=2){
out.println(ans.get(i) + " " + ans.get(i + 1));
}
}
public static void main(String[] args) throws FileNotFoundException {
new A().run();
}
void run() throws FileNotFoundException {
init();
solve();
out.close();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
if(!filename.equals("")) {
in = new BufferedReader(new FileReader(new File(filename + ".in")));
out = new PrintWriter(new File(filename + ".out"));
return;
}
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
String readLine(){
try{
return in.readLine();
}catch (Exception e){
throw new RuntimeException(e);
}
}
String readString(){
while(!tok.hasMoreTokens()){
String nextLine = readLine();
if(nextLine == null) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt(){
return Integer.parseInt(readString());
}
long readLong(){
return Long.parseLong(readString());
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class F11141 {
static class Solver {
ArrayList<int[]> ranges[];
HashMap<Long, Integer> hm = new HashMap<>();
int id(long s) {
if (!hm.containsKey(s))
hm.put(s, hm.size());
return hm.get(s);
}
// max disjoint range set in ranges[r]
int[] memo;
int go(int r) {
memo[N] = 0;
int last = N;
for(int[] a : ranges[r]) {
while(a[0] < last) {
memo[last - 1] = memo[last];
last--;
}
memo[a[0]] = Math.max(memo[a[0]], Math.max(memo[a[0]], 1 + memo[a[1] + 1]));
last = a[0];
}
return memo[last];
}
ArrayDeque<int[]> ans = new ArrayDeque<>();
void go2(int r) {
memo[N] = 0;
int last = N;
int minAt[] = new int[N], oo = 987654321;
Arrays.fill(minAt, oo);
for(int[] a : ranges[r]) {
minAt[a[0]] = Math.min(minAt[a[0]], a[1] - a[0]);
while(a[0] < last) {
memo[last - 1] = memo[last];
last--;
}
memo[a[0]] = Math.max(memo[a[0]], Math.max(memo[a[0]], 1 + memo[a[1] + 1]));
last = a[0];
}
while(0 < last) {
memo[last - 1] = memo[last];
last--;
}
int k = 0;
for(; k < N;) {
if(minAt[k] == oo || memo[k] != 1 + memo[k + minAt[k] + 1]) k++;
else {
ans.push(new int[] {k, k + minAt[k]});
k += minAt[k] + 1;
}
}
}
@SuppressWarnings("unchecked")
Solver() {
ranges = new ArrayList[2250001];
for (int i = 0; i < ranges.length; i++)
ranges[i] = new ArrayList<>();
}
int N, LID;
long[] a;
void solve(Scanner s, PrintWriter out) {
N = s.nextInt();
a = new long[N + 1];
for (int i = 1; i <= N; i++)
a[i] = s.nextLong() + a[i - 1];
for (int i = N; i >= 1; i--)
for (int j = i; j <= N; j++) {
int x = id(a[j] - a[i - 1]);
ranges[x].add(new int[] { i - 1, j - 1 });
}
int best = 0, bid = -1;
memo = new int[N + 1];
Arrays.sort(ranges, (a, b) -> b.size() - a.size());
for(int i = 0; i < ranges.length; i++, LID++) {
if(ranges[i].size() <= best) break;
int ans = go(i);
if(ans > best) {
best = ans;
bid = i;
}
}
// backtrack on bid
out.println(best);
go2(bid);
while(!ans.isEmpty()) {
int[] c = ans.pop();
out.println(++c[0] + " " + ++c[1]);
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver solver = new Solver();
solver.solve(s, out);
out.close();
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class ProblemF {
private static boolean debug = false;
private static int N;
private static int[] A;
private static void solveProblem(InputStream instr) throws Exception {
InputReader sc = new InputReader(instr);
int testCount = 1;
if (debug) {
testCount = sc.nextInt();
}
for (int t = 1; t <= testCount; t++) {
printDebug("------ " + t + " ------");
N = sc.nextInt();
A = readInts(sc, N);
Object result = solveTestCase();
System.out.println(result);
}
}
private static Object solveTestCase() {
int sum[] = new int[N];
sum[0] = A[0];
for (int i = 1; i < N; i++) {
sum[i] = sum[i - 1] + A[i];
}
TreeMap<Integer, List<int[]>> map = new TreeMap<>();
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
int groupSum = sum[j] - (i == 0 ? 0 : sum[i - 1]);
map.putIfAbsent(groupSum, new ArrayList<>());
map.get(groupSum).add(new int[]{i, j});
}
}
int max = -1;
List<int[]> maxAnswer = null;
for (Map.Entry<Integer, List<int[]>> entry : map.entrySet()) {
List<int[]> values = entry.getValue();
if (values.size() <= max) {
continue;
}
List<int[]> curr = findMax(values);
if (curr.size() > max) {
max = curr.size();
maxAnswer = curr;
}
}
List<String> answer = new ArrayList<>();
for (int[] value : maxAnswer) {
answer.add((value[0] + 1) + " " + (value[1] + 1));
}
return max + "\n" + joinValues(answer, "\n");
}
private static List<int[]> findMax(List<int[]> values) {
values.sort(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1] - o2[1];
}
});
List<int[]> answer = new ArrayList<>();
int right = -1;
for (int i = 0; i < values.size(); i++) {
int[] value = values.get(i);
if (value[0] > right) {
answer.add(value);
right = value[1];
}
}
return answer;
}
private static int[] readInts(InputReader sc, int N) throws Exception {
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = sc.nextInt();
}
return arr;
}
private static String joinValues(List<? extends Object> list, String delim) {
return list.stream().map(Object::toString).collect(Collectors.joining(delim));
}
private static String joinValues(int[] arr, String delim) {
List<Object> list = new ArrayList<>();
for (Object value : arr) {
list.add(value);
}
return list.stream().map(Object::toString).collect(Collectors.joining(delim));
}
public static void printDebug(Object str) {
if (debug) {
System.out.println("DEBUG: " + str);
}
}
private static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int Chars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws Exception {
if (curChar >= Chars) {
curChar = 0;
Chars = stream.read(buf);
if (Chars <= 0)
return -1;
}
return buf[curChar++];
}
public final int nextInt() throws Exception {
return (int)nextLong();
}
public final long nextLong() throws Exception {
int c = read();
while (isSpaceChar(c)) {
c = read();
if (c == -1)
throw new IOException();
}
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 final int[] nextIntBrray(int size) throws Exception {
int[] arr = new int[size];
for (int i = 0; i < size; i++)
arr[i] = nextInt();
return arr;
}
public final String next() throws Exception {
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();
}
public final String nextLine() throws Exception {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.append((char)c);
c = read();
} while (c != '\n' && c != -1);
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static void main(String[] args) throws Exception {
long currTime = System.currentTimeMillis();
if (debug) {
solveProblem(new FileInputStream(new File("input.in")));
System.out.println("Time: " + (System.currentTimeMillis() - currTime));
} else {
solveProblem(System.in);
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x1141F
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
HashMap<Long, ArrayList<Integer>> map = new HashMap<Long, ArrayList<Integer>>();
for(int r=0; r < N; r++)
{
long sum = 0L;
for(int i=r; i >= 0; i--)
{
sum += arr[i];
if(!map.containsKey(sum))
map.put(sum, new ArrayList<Integer>());
map.get(sum).add(i);
map.get(sum).add(r);
}
}
ArrayList<Integer> res = new ArrayList<Integer>();
for(long key: map.keySet())
{
ArrayList<Integer> ls = map.get(key);
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(ls.get(0));
temp.add(ls.get(1));
int r = ls.get(1);
for(int i=2; i < ls.size(); i+=2)
if(r < ls.get(i))
{
r = ls.get(i+1);
temp.add(ls.get(i));
temp.add(ls.get(i+1));
}
if(res.size() < temp.size())
res = temp;
}
System.out.println(res.size()/2);
StringBuilder sb = new StringBuilder();
for(int i=0; i < res.size(); i+=2)
{
sb.append((1+res.get(i))+" "+(1+res.get(i+1)));
sb.append("\n");
}
System.out.print(sb);
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
public class Main {
public static class node implements Comparable<node> {
int l,r;
node(){}
node(int l,int r) {
this.l=l;
this.r=r;
}
@Override
public int compareTo(node rhs) {
return r-rhs.r;
}
}
public static void main(String[] args) throws IOException {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
StringTokenizer sa=new StringTokenizer(in.readLine());
int n=Integer.parseInt(sa.nextToken());
sa=new StringTokenizer(in.readLine());
int[] a=new int[n];
TreeMap<Integer,ArrayList<node>> mp=new TreeMap();
for (int i=0;i<n;++i) a[i]=Integer.parseInt(sa.nextToken());
ArrayList<node> ans=new ArrayList<node>();
for (int i=0;i<n;++i) {
int tmp=0;
for (int j=i;j<n;++j) {
tmp+=a[j];
if (!mp.containsKey(tmp)) {
ArrayList<node> t=new ArrayList();
t.add(new node(i,j));
mp.put(tmp,t);
} else {
ArrayList<node> t=mp.get(tmp);
int left=0,right=t.size()-1,res=t.size();
while (left<=right) {
int mid=(left+right)>>1;
if (t.get(mid).r>=i) {
res=mid;
right=mid-1;
} else left=mid+1;
}
if (res==t.size()) t.add(new node(i,j));
else if (t.get(res).r>j) t.set(res,new node(i,j));
}
if (mp.get(tmp).size()>ans.size()) ans=mp.get(tmp);
}
}
out.println(ans.size());
for (int i=0;i<ans.size();++i)
out.printf("%d %d\n",ans.get(i).l+1,ans.get(i).r+1);
out.flush();
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.*;
import java.math.*;
public class Main{
static HashMap<Integer,ArrayList<seg>> ma;
static class seg{
seg(int a,int b){
l=a;r=b;
}
int l,r;
}
static int n,sum,dex;
static int arr[]=new int[1600];
public static void main(String argas[]){
Scanner cin=new Scanner(System.in);
ma=new HashMap();
n=cin.nextInt();
for(int i=1;i<=n;i++){
arr[i]=cin.nextInt();
sum=0;
for(int j=i;j>0;j--){
sum+=arr[j];
if(ma.containsKey(sum)) ma.get(sum).add(new seg(j,i));
else {
ma.put(sum, new ArrayList<seg>());
ma.get(sum).add(new seg(j,i));
}
}
}
int ans=0,te;
ArrayList<seg> best=new ArrayList(),now,temp;
Iterator it=ma.entrySet().iterator();
while(it.hasNext()){
now=new ArrayList();
te=0;
Map.Entry entry=(Map.Entry) it.next();
temp=(ArrayList<seg>) entry.getValue();
dex=0;
for(int i=0;i<temp.size();i++){
if(temp.get(i).l>dex){
dex=temp.get(i).r;
te++;
now.add(new seg(temp.get(i).l,temp.get(i).r));
}
}
if(te>ans){
ans=te;
best=now;
}
}
System.out.println(ans);
for(int i=0;i<best.size();i++){
System.out.println(best.get(i).l+" "+best.get(i).r);
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
//package com.example.programming;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Test {
static class Pair {
int f,s;
public Pair(int x, int y) {f = x; s = y;}
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] s = br.readLine().split(" ");
int[] arr = new int[n];
for(int i = 0; i<n; i++) arr[i] = Integer.parseInt(s[i]);
HashMap<Integer, ArrayList<Pair>> map = new HashMap<>();
for(int i = 0; i<n; i++) {
int sum = 0;
for(int j = i; j>=0; j--) {
sum += arr[j];
ArrayList<Pair> list = map.get(sum);
if(list == null) {
list = new ArrayList<>();
map.put(sum, list);
}
list.add(new Pair(j, i));
}
}
Iterator it = map.entrySet().iterator();
ArrayList<Pair> ans = new ArrayList<>();
for(;it.hasNext();){
Map.Entry<Integer, ArrayList<Pair>> entry = (Map.Entry<Integer, ArrayList<Pair>>)it.next();
ArrayList<Pair> list = entry.getValue();
ArrayList<Pair> pre = new ArrayList<>();
int r = -1;
for(Pair p : list) {
if(p.f > r) {
pre.add(p);
r = p.s;
}
}
if(ans.size()<pre.size()) ans = pre;
}
StringBuilder sb = new StringBuilder();
sb.append(ans.size()).append('\n');
for(Pair p : ans) {
sb.append(p.f+1).append(' ').append(p.s+1).append('\n');
}
System.out.print(sb);
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
/**
* @author derrick20
*/
import java.io.*;
import java.util.*;
public class SameSumBlocks {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
int[] pre = new int[N + 1];
for (int i = 1; i <= N; i++) {
pre[i] = pre[i - 1] + sc.nextInt();
}
var sumMap = new HashMap<Integer, ArrayList<Pair>>();
for (int i = 1; i <= N; i++) {
for (int j = i; j <= N; j++) {
int sum = pre[j] - pre[i - 1];
sumMap.computeIfAbsent(sum, val -> new ArrayList<>()).add(new Pair(i, j));
}
}
var ans = new ArrayList<Pair>();
for (var list : sumMap.values()) {
Collections.sort(list, Comparator.comparingInt(p -> p.r));
// greedily schedule the intervals
int last = 0;
var group = new ArrayList<Pair>();
for (Pair p : list) {
if (p.l > last) {
group.add(p);
last = p.r;
}
}
if (group.size() > ans.size()) {
ans = group;
}
}
out.println(ans.size());
for (Pair p : ans) {
out.println(p);
}
out.close();
}
static class Pair {
int l, r;
public Pair(int ll, int rr) {
l = ll; r = rr;
}
public String toString() {
return l + " " + r;
}
}
static class FastScanner {
private int BS = 1<<16;
private char NC = (char)0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt=1;
boolean neg = false;
if(c==NC)c=getChar();
for(;(c<'0' || c>'9'); c = getChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=getChar()) {
res = (res<<3)+(res<<1)+c-'0';
cnt*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/cnt;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=getChar();
while(c>32) {
res.append(c);
c=getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=getChar();
while(c!='\n') {
res.append(c);
c=getChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=getChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import javafx.util.Pair;
public class Solve6 {
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
new Solve6().solve(pw);
pw.flush();
pw.close();
}
public void solve(PrintWriter pw) throws IOException {
FastReader sc = new FastReader();
int n = sc.nextInt();
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = sc.nextInt();
}
HashMap<Integer, LinkedList<Pair<Integer, Integer>>> h = new HashMap();
for (int i = 1; i <= n; i++) {
int s = 0;
for (int j = i; j >= 1; j--) {
s += a[j];
LinkedList<Pair<Integer, Integer>> l;
if (!h.containsKey(s)) {
l = new LinkedList();
} else {
l = h.get(s);
}
l.add(new Pair(j, i));
h.put(s, l);
}
}
int max = 0, index = 0;
for (Map.Entry<Integer, LinkedList<Pair<Integer, Integer>>> entrySet : h.entrySet()) {
int i = 0, size = 0;
for (Pair<Integer, Integer> pair : entrySet.getValue()) {
if (pair.getKey() > i) {
i = pair.getValue();
size++;
}
}
if (size > max) {
max = size;
index = entrySet.getKey();
}
}
pw.println(max);
int i = 0;
for (Pair<Integer, Integer> pair : h.get(index)) {
if (pair.getKey() > i) {
pw.println(pair.getKey() + " " + pair.getValue());
i = pair.getValue();
}
}
}
static class FastReader {
StringTokenizer st;
BufferedReader br;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public boolean hasNext() throws IOException {
String s = br.readLine();
if (s == null || s.isEmpty()) {
return false;
}
st = new StringTokenizer(s);
return true;
}
public String next() throws IOException {
if (st == null || !st.hasMoreTokens()) {
String s = br.readLine();
if (s.isEmpty()) {
return null;
}
st = new StringTokenizer(s);
}
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main {
private static class Interval implements Comparable<Interval> {
public int start , end;
public Interval(int start , int end) {
this.start = start;
this.end = end;
}
@Override
public int compareTo(Interval interval) {
return this.end - interval.end;
}
}
private static int getTotal(List<Interval> list) {
int ans = 0 , i , n = list.size();
for (i = 0;i < n;i ++) {
int end = list.get(i).end;
while (i < n && list.get(i).start <= end) {
i ++;
}
i --;
ans ++;
}
return ans;
}
private static void solve(List<Interval> list) {
List<int[]> ans = new ArrayList<>();
int i , n = list.size();
for (i = 0;i < n;i ++) {
int start = list.get(i).start , end = list.get(i).end;
while (i < n && list.get(i).start <= end) {
i ++;
}
i --;
ans.add(new int[] {start , end});
}
System.out.println(ans.size());
for (int[] array : ans) {
System.out.println(array[0] + " " + array[1]);
}
}
private static long[] a = new long[2000];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Map<Long , List<Interval>> map = new HashMap<>();
int i , j , n = scan.nextInt() , max = 0;
long ans = 0;
for (i = 1;i <= n;i ++) {
a[i] = scan.nextLong();
}
for (i = 1;i <= n;i ++) {
long sum = 0;
for (j = i;j <= n;j ++) {
sum += a[j];
if (!map.containsKey(sum)) {
map.put(sum , new ArrayList<>());
}
map.get(sum).add(new Interval(i , j));
}
}
for (List<Interval> list : map.values()) {
Collections.sort(list);
}
for (Map.Entry<Long , List<Interval>> entry : map.entrySet()) {
int total = getTotal(entry.getValue());
if (total > max) {
max = total;
ans = entry.getKey();
}
}
solve(map.get(ans));
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author beginner1010
*/
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);
TaskF2 solver = new TaskF2();
solver.solve(1, in, out);
out.close();
}
static class TaskF2 {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
HashMap<Integer, Integer> lastIndex = new HashMap<>();
HashMap<Integer, Integer> maxSize = new HashMap<>();
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += a[j];
if (maxSize.containsKey(sum) == false) {
maxSize.put(sum, 0);
}
int curMaxSize = maxSize.get(sum);
int curLastIndex = curMaxSize == 0 ? -1 : lastIndex.get(sum);
if (curMaxSize == 0 || curLastIndex < i) {
curMaxSize++;
curLastIndex = j;
} else if (curLastIndex >= j) {
curLastIndex = j;
}
maxSize.put(sum, curMaxSize);
lastIndex.put(sum, curLastIndex);
}
}
int bestSum = -1;
int bestSize = -1;
for (int sum : maxSize.keySet()) {
if (maxSize.get(sum) > bestSize) {
bestSize = maxSize.get(sum);
bestSum = sum;
}
}
ArrayList<Interval> best = new ArrayList<>();
lastIndex = new HashMap<>();
maxSize = new HashMap<>();
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += a[j];
if (sum != bestSum)
continue; // consider only bestSums
if (maxSize.containsKey(sum) == false) {
maxSize.put(sum, 0);
}
int curMaxSize = maxSize.get(sum);
int curLastIndex = curMaxSize == 0 ? -1 : lastIndex.get(sum);
if (curMaxSize == 0 || curLastIndex < i) {
curMaxSize++;
curLastIndex = j;
best.add(new Interval(i, j));
} else if (curLastIndex >= j) {
curLastIndex = j;
best.set(best.size() - 1, new Interval(i, j));
}
maxSize.put(sum, curMaxSize);
lastIndex.put(sum, curLastIndex);
}
}
out.println(bestSize);
for (Interval i : best) {
out.println((i.l + 1) + " " + (i.r + 1));
}
}
class Interval {
int l;
int r;
Interval(int l, int r) {
this.l = l;
this.r = r;
}
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isWhitespace(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 (!isWhitespace(c));
return res * sgn;
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.Map.Entry;
import java.io.BufferedReader;
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);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Map<Integer, List<Range>> rgs = new HashMap<Integer, List<Range>>();
for (int i = 0; i < n; i++) {
int s = 0;
for (int j = i; j < n; j++) {
s += a[j];
if (rgs.get(s) == null) {
rgs.put(s, new ArrayList<Range>());
}
rgs.get(s).add(new Range(i, j));
}
}
Iterator it = rgs.entrySet().iterator();
List<Range> ans = new ArrayList<Range>();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
int sum = (int) pair.getKey();
Object[] intermediate = ((List<Object[]>) pair.getValue()).toArray();
Range[] ranges = new Range[intermediate.length];
for (int i = 0; i < intermediate.length; i++) {
ranges[i] = (Range) intermediate[i];
}
Arrays.sort(ranges);
List<Range> cand = new ArrayList<Range>();
for (Range r : ranges) {
if (cand.size() == 0) {
cand.add(r);
continue;
}
if (cand.get(cand.size() - 1).j < r.i) {
cand.add(r);
} else {
if (cand.get(cand.size() - 1).j > r.j) {
cand.remove(cand.size() - 1);
cand.add(r);
}
}
}
if (cand.size() > ans.size()) {
ans = cand;
}
}
out.println(ans.size());
for (Range r : ans) {
out.println((r.i + 1) + " " + (r.j + 1));
}
}
public class Range implements Comparable {
public int i;
public int j;
public Range(int i, int j) {
this.i = i;
this.j = j;
}
public int compareTo(Object o) {
Range t = (Range) o;
if (this.i == t.i) {
if (this.j < t.j) return 1;
else return 0;
}
if (this.i < t.i) return 1;
return 0;
}
}
}
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 | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main {
static final long MOD = 1_000_000_007, INF = 1_000_000_000_000_000_000L;
static final int INf = 1_000_000_000;
static FastReader reader;
static PrintWriter writer;
public static void main(String[] args) {
Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000);
t.start();
}
static class O implements Runnable {
public void run() {
try {
magic();
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
static class FastReader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[1000000];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
static void magic() throws IOException {
reader = new FastReader();
writer = new PrintWriter(System.out, true);
Map<Integer, ArrayList<Pair>> map = new HashMap<>();
int n = reader.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;++i) {
arr[i] = reader.nextInt();
}
for(int i=0;i<n;++i) {
int sum = 0;
for(int j=i;j<n;++j) {
sum+=arr[j];
ArrayList<Pair> list = map.get(sum);
if(list==null) {
list = new ArrayList<>();
}
list.add(new Pair(i+1,j+1));
map.put(sum, list);
}
}
int ans = 0,at = -1;
for(int e : map.keySet()) {
ArrayList<Pair> list = map.get(e);
Collections.sort(list);
// writer.println("Pairs having sum: "+e);
// for(Pair p : list) {
// writer.print(p);
// writer.print(" ");
// }
// writer.println();
int ispe = 0;
int len = list.size();
for(int i=0;i<len;++i) {
ispe++;
int r = list.get(i).y;
while(i+1<len && list.get(i+1).x<=r) {
i++;
}
}
if(ans<ispe) {
ans = ispe;
at = e;
}
}
writer.println(ans);
ArrayList<Pair> list = map.get(at);
Collections.sort(list);
int len = list.size();
for(int i=0;i<len;++i) {
writer.println(list.get(i).x+" "+list.get(i).y);
int r = list.get(i).y;
while(i+1<len && list.get(i+1).x<=r) {
i++;
}
}
}
static class Pair implements Comparable<Pair> {
int x,y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair other) {
if(this.y!=other.y) {
return this.y - other.y;
}
return this.x - other.x;
}
public String toString() {
return "{" + x + "," + y + "}";
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class F11141 {
static class Solver {
ArrayList<int[]> ranges[];
HashMap<Long, Integer> hm = new HashMap<>();
int id(long s) {
if (!hm.containsKey(s))
hm.put(s, hm.size());
return hm.get(s);
}
// max disjoint range set in ranges[r]
int[] memo;
int go(int r) {
memo[N] = 0;
int last = N;
for(int[] a : ranges[r]) {
while(a[0] < last) {
memo[last - 1] = memo[last];
last--;
}
memo[a[0]] = Math.max(memo[a[0]], Math.max(memo[a[0]], 1 + memo[a[1] + 1]));
last = a[0];
}
while(0 < last) {
memo[last - 1] = memo[last];
last--;
}
return memo[0];
}
ArrayDeque<int[]> ans = new ArrayDeque<>();
void go2(int r) {
memo[N] = 0;
int last = N;
int minAt[] = new int[N], oo = 987654321;
Arrays.fill(minAt, oo);
for(int[] a : ranges[r]) {
minAt[a[0]] = Math.min(minAt[a[0]], a[1] - a[0]);
while(a[0] < last) {
memo[last - 1] = memo[last];
last--;
}
memo[a[0]] = Math.max(memo[a[0]], Math.max(memo[a[0]], 1 + memo[a[1] + 1]));
last = a[0];
}
while(0 < last) {
memo[last - 1] = memo[last];
last--;
}
int k = 0;
for(; k < N;) {
if(minAt[k] == oo || memo[k] != 1 + memo[k + minAt[k] + 1]) k++;
else {
ans.push(new int[] {k, k + minAt[k]});
k += minAt[k] + 1;
}
}
}
@SuppressWarnings("unchecked")
Solver() {
ranges = new ArrayList[2250001];
for (int i = 0; i < ranges.length; i++)
ranges[i] = new ArrayList<>();
}
int N, LID;
long[] a;
void solve(Scanner s, PrintWriter out) {
N = s.nextInt();
a = new long[N + 1];
for (int i = 1; i <= N; i++)
a[i] = s.nextLong() + a[i - 1];
for (int i = N; i >= 1; i--)
for (int j = i; j <= N; j++) {
int x = id(a[j] - a[i - 1]);
ranges[x].add(new int[] { i - 1, j - 1 });
}
int best = 0, bid = -1;
memo = new int[N + 1];
Arrays.sort(ranges, (a, b) -> b.size() - a.size());
for(int i = 0; i < ranges.length; i++, LID++) {
if(ranges[i].size() <= best) break;
int ans = go(i);
if(ans > best) {
best = ans;
bid = i;
}
}
// backtrack on bid
out.println(best);
go2(bid);
while(!ans.isEmpty()) {
int[] c = ans.pop();
out.println(++c[0] + " " + ++c[1]);
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver solver = new Solver();
solver.solve(s, out);
out.close();
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main {
private static class Interval implements Comparable<Interval> {
public int start , end;
public Interval(int start , int end) {
this.start = start;
this.end = end;
}
@Override
public int compareTo(Interval interval) {
return this.end - interval.end;
}
}
private static int getTotal(List<Interval> list) {
int ans = 0 , i , n = list.size();
for (i = 0;i < n;i ++) {
int end = list.get(i).end;
while (i < n && list.get(i).start <= end) {
i ++;
}
i --;
ans ++;
}
return ans;
}
private static void solve(List<Interval> list) {
List<int[]> ans = new ArrayList<>();
int i , n = list.size();
for (i = 0;i < n;i ++) {
int start = list.get(i).start , end = list.get(i).end;
while (i < n && list.get(i).start <= end) {
i ++;
}
i --;
ans.add(new int[] {start , end});
}
System.out.println(ans.size());
for (int[] array : ans) {
System.out.println(array[0] + " " + array[1]);
}
}
private static long[] a = new long[2000];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Map<Long , List<Interval>> map = new HashMap<>();
int i , j , n = scan.nextInt() , max = 0;
long ans = 0;
for (i = 1;i <= n;i ++) {
a[i] = scan.nextLong();
}
for (i = 1;i <= n;i ++) {
long sum = 0;
for (j = i;j <= n;j ++) {
sum += a[j];
if (!map.containsKey(sum)) {
map.put(sum , new ArrayList<>());
}
map.get(sum).add(new Interval(i , j));
}
}
for (List<Interval> list : map.values()) {
Collections.sort(list);
}
for (Map.Entry<Long , List<Interval>> entry : map.entrySet()) {
int total = getTotal(entry.getValue());
if (total > max) {
max = total;
ans = entry.getKey();
}
}
solve(map.get(ans));
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.*;
import java.io.*;
import java.text.*;
//Solution Credits: Taranpreet Singh
public class Main{
//SOLUTION BEGIN
//Code not meant for understanding, proceed with caution
void pre() throws Exception{}
void solve(int TC) throws Exception{
int n = ni();
int[] a = new int[n];
for(int i = 0; i< n; i++)a[i] = ni();
HashMap<Long, ArrayList<int[]>> map = new HashMap<>();
for(int i = 0; i< n; i++){
long sum = 0;
for(int j = i; j< n; j++){
sum+=a[j];
if(!map.containsKey(sum))map.put(sum, new ArrayList<>());
map.get(sum).add(new int[]{i+1, j+1});
}
}
int[][] ans = new int[n][];int cur = 0;
int[][] tmp = new int[n][];int tc;
for(Map.Entry<Long, ArrayList<int[]>> e: map.entrySet()){
int prev = 0;
ArrayList<int[]> li = e.getValue();
Collections.sort(li, new Comparator<int[]>(){
public int compare(int[] i1, int[] i2){
if(i1[1]!=i2[1])return Integer.compare(i1[1], i2[1]);
return Integer.compare(i1[0], i1[0]);
}
});
tc = 0;
for(int[] p:li){
if(p[0]>prev){
tmp[tc++] = new int[]{p[0],p[1]};
prev = p[1];
}
}
if(tc>cur){
cur = tc;
for(int i = 0; i< tc; i++)ans[i] = new int[]{tmp[i][0], tmp[i][1]};
}
}
pn(cur);
for(int i = 0; i< cur; i++)pn(ans[i][0]+" "+ans[i][1]);
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
long mod = (long)1e9+7, IINF = (long)1e18;
final int INF = (int)1e9, MX = (int)2e3+1;
DecimalFormat df = new DecimalFormat("0.00000000000");
double PI = 3.1415926535897932384626433832792884197169399375105820974944, eps = 1e-8;
static boolean multipleTC = false, memory = false;
FastReader in;PrintWriter out;
void run() throws Exception{
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC)?ni():1;
//Solution Credits: Taranpreet Singh
pre();for(int t = 1; t<= T; t++)solve(t);
out.flush();
out.close();
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new Main().run();
}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str = "";
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class ProblemF {
private static boolean debug = false;
private static int N;
private static int[] A;
private static void solveProblem(InputStream instr) throws Exception {
InputReader sc = new InputReader(instr);
int testCount = 1;
if (debug) {
testCount = sc.nextInt();
}
for (int t = 1; t <= testCount; t++) {
printDebug("------ " + t + " ------");
N = sc.nextInt();
A = readInts(sc, N);
Object result = solveTestCase();
System.out.println(result);
}
}
private static Object solveTestCase() {
int sum[] = new int[N];
sum[0] = A[0];
for (int i = 1; i < N; i++) {
sum[i] = sum[i - 1] + A[i];
}
Map<Integer, List<int[]>> map = new HashMap<>();
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
int groupSum = sum[j] - (i == 0 ? 0 : sum[i - 1]);
map.putIfAbsent(groupSum, new ArrayList<>());
map.get(groupSum).add(new int[]{i, j});
}
}
int max = -1;
List<int[]> maxAnswer = null;
for (Map.Entry<Integer, List<int[]>> entry : map.entrySet()) {
List<int[]> values = entry.getValue();
if (values.size() <= max) {
continue;
}
List<int[]> curr = findMax(values);
if (curr.size() > max) {
max = curr.size();
maxAnswer = curr;
}
}
List<String> answer = new ArrayList<>();
for (int[] value : maxAnswer) {
answer.add((value[0] + 1) + " " + (value[1] + 1));
}
return max + "\n" + joinValues(answer, "\n");
}
private static List<int[]> findMax(List<int[]> values) {
values.sort(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1] - o2[1];
}
});
List<int[]> answer = new ArrayList<>();
int right = -1;
for (int i = 0; i < values.size(); i++) {
int[] value = values.get(i);
if (value[0] > right) {
answer.add(value);
right = value[1];
}
}
return answer;
}
private static int[] readInts(InputReader sc, int N) throws Exception {
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = sc.nextInt();
}
return arr;
}
private static String joinValues(List<? extends Object> list, String delim) {
return list.stream().map(Object::toString).collect(Collectors.joining(delim));
}
private static String joinValues(int[] arr, String delim) {
List<Object> list = new ArrayList<>();
for (Object value : arr) {
list.add(value);
}
return list.stream().map(Object::toString).collect(Collectors.joining(delim));
}
public static void printDebug(Object str) {
if (debug) {
System.out.println("DEBUG: " + str);
}
}
private static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int Chars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws Exception {
if (curChar >= Chars) {
curChar = 0;
Chars = stream.read(buf);
if (Chars <= 0)
return -1;
}
return buf[curChar++];
}
public final int nextInt() throws Exception {
return (int)nextLong();
}
public final long nextLong() throws Exception {
int c = read();
while (isSpaceChar(c)) {
c = read();
if (c == -1)
throw new IOException();
}
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 final int[] nextIntBrray(int size) throws Exception {
int[] arr = new int[size];
for (int i = 0; i < size; i++)
arr[i] = nextInt();
return arr;
}
public final String next() throws Exception {
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();
}
public final String nextLine() throws Exception {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.append((char)c);
c = read();
} while (c != '\n' && c != -1);
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static void main(String[] args) throws Exception {
long currTime = System.currentTimeMillis();
if (debug) {
solveProblem(new FileInputStream(new File("input.in")));
System.out.println("Time: " + (System.currentTimeMillis() - currTime));
} else {
solveProblem(System.in);
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
// Author: aman_robotics
//package math_codet;
import java.io.*;
import java.util.*;
public class lets_do {
FastReader in;
PrintWriter out;
Helper_class h;
final long mod = 1000000009;
final int MAXN = 1000005;
final int lgN = 20;
final long INF = (long)1e18;
final long MAX_Ai = (long)1e12;
public static void main(String[] args) throws java.lang.Exception{
new lets_do().run();
}
void run() throws Exception{
in=new FastReader(System.in);
out = new PrintWriter(System.out);
h = new Helper_class();
int t = 1;
while(t--> 0)
solve();
out.flush();
out.close();
}
void solve(){
int n = h.ni();
long[] arr = new long[n];
int i = 0, j = 0;
for(i = 0; i < n; i++)
arr[i] = h.nl();
HashMap<Long, Integer> hmap = new HashMap<Long, Integer>();
int cnt = 0;
for(i = 0; i < n; i++){
long sum = 0;
for(j = i; j < n; j++){
sum += arr[j];
Integer x = hmap.get(sum);
if(x == null)
hmap.put(sum, cnt++);
}
}
TreeSet<Pair>[] tset = new TreeSet[cnt];
for(i = 0; i < cnt; i++)
tset[i] = new TreeSet<Pair>(com);
for(i = 0; i < n; i++){
long sum = 0;
for(j = i; j < n; j++){
sum += arr[j];
tset[hmap.get(sum)].add(new Pair(i, j));
}
}
int max = 0;
int ind = -1;
int max_x = 0, max_y = 0;
for(i = 0; i < cnt; i++){
int curr_y = tset[i].first().y;
int cnt1 = 1;
for(Pair yo : tset[i]){
if(yo.x > curr_y) {
cnt1++;
curr_y = yo.y;
}
}
if(max < cnt1) {
max = cnt1;
ind = i;
}
}
h.pn(max);
Pair hola_yee = new Pair(tset[ind].first().x, tset[ind].first().y);
h.pn((tset[ind].first().x + 1) +" "+(tset[ind].first().y + 1));
int curr_y = tset[ind].first().y;
for(Pair yo : tset[ind]){
if(yo.x > curr_y) {
curr_y = yo.y;
h.pn((yo.x + 1) +" "+(yo.y + 1));
}
}
}
static final Comparator<Pair> com=new Comparator<Pair>(){
public int compare(Pair a, Pair b){
if(Integer.compare(a.y, b.y) != 0)
return Integer.compare(a.y, b.y);
else
return Integer.compare(a.x, b.x);
}
};
class Pair{
int x;
int y;
Pair(int p, int q){
x = p;
y = q;
}
}
class Edge{
int u , v;
long wt;
Edge(int a, int b, long w){
u = a;
v = b;
wt = w;
}
int other(int x) {
return u ^ v ^ x;
}
}
class Helper_class{
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bitcount(long n){return (n==0)?0:(1+bitcount(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n(){return in.next();}
String nln(){return in.nextLine();}
int ni(){return Integer.parseInt(in.next());}
long nl(){return Long.parseLong(in.next());}
double nd(){return Double.parseDouble(in.next());}
long mul(long a,long b){
if(a>=mod)a%=mod;
if(b>=mod)b%=mod;
a*=b;
if(a>=mod)a%=mod;
return a;
}
long modPow(long a, long p){
long o = 1;
while(p>0){
if((p&1)==1)o = mul(o,a);
a = mul(a,a);
p>>=1;
}
return o;
}
long add(long a, long b){
if(a>=mod)a%=mod;
if(b>=mod)b%=mod;
if(b<0)b+=mod;
a+=b;
if(a>=mod)a-=mod;
return a;
}
}
class FastReader{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public void skip(int x) {
while (x-- > 0)
read();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextString() {
return next();
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean hasNext() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value != -1;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main
{
HashMap<Integer,Pair> map;
int n,a[];
private void solve()throws IOException
{
n=nextInt();
a=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=nextInt();
map=new HashMap<>();
for(int i=1;i<=n;i++)
{
int sum=0;
for(int j=i;j>=1;j--)
{
sum+=a[j];
if(!map.containsKey(sum))
map.put(sum,new Pair(i,1));
else
{
Pair p=map.get(sum);
if(p.pos<j)
map.put(sum,new Pair(i,p.cnt+1));
}
}
}
int sum=0,ans=0;
for(int i:map.keySet())
if(map.get(i).cnt>ans)
{
ans=map.get(i).cnt;
sum=i;
}
out.println(ans);
ArrayList<String> list=new ArrayList<>();
for(int i=1,prev=0;i<=n;i++)
{
int s=0;
for(int j=i;j>=1;j--)
{
s+=a[j];
if(s==sum && j>prev)
{
list.add(j+" "+i);
prev=i;
}
}
}
for(String s:list)
out.println(s);
}
class Pair{
int pos,cnt;
Pair(int a,int b){
pos=a;
cnt=b;
}
}
///////////////////////////////////////////////////////////
public void run()throws IOException
{
br=new BufferedReader(new InputStreamReader(System.in));
st=null;
out=new PrintWriter(System.out);
solve();
br.close();
out.close();
}
public static void main(String args[])throws IOException{
new Main().run();
}
BufferedReader br;
StringTokenizer st;
PrintWriter out;
String nextToken()throws IOException{
while(st==null || !st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine()throws IOException{
return br.readLine();
}
int nextInt()throws IOException{
return Integer.parseInt(nextToken());
}
long nextLong()throws IOException{
return Long.parseLong(nextToken());
}
double nextDouble()throws IOException{
return Double.parseDouble(nextToken());
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
public class B implements Runnable {
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int n = scn.nextInt();
int[] arr = scn.nextIntArray(n);
int[][] a = new int[n * (n + 1) / 2][];
int[] need = new int[a.length];
int pos = 0;
for (int l = 0; l < n; l++) {
int sum = 0;
for (int r = l; r < n; r++) {
sum += arr[r];
a[pos] = new int[] { l, r, sum };
need[pos++] = sum;
}
}
need = scn.uniq(need);
int[][][] list = new int[need.length][][];
int[] size = new int[list.length];
for (int i = 0; i < pos; i++) {
size[Arrays.binarySearch(need, a[i][2])]++;
}
for (int i = 0; i < list.length; i++) {
list[i] = new int[size[i]][];
}
for (int i = 0; i < pos; i++) {
int ind = Arrays.binarySearch(need, a[i][2]);
list[ind][--size[ind]] = new int[] { a[i][0], a[i][1] };
}
int ind = -1, max = 0;
for (int i = 0; i < list.length; i++) {
if(list[i].length == 0) {
continue;
}
Arrays.sort(list[i], (o1, o2) -> o1[1] - o2[1]);
int count = 1, last = list[i][0][1];
for(int j = 1; j < list[i].length; j++) {
if(list[i][j][0] > last) {
count++;
last = list[i][j][1];
}
}
if (count > max) {
max = count;
ind = i;
}
}
out.println(max);
int last = list[ind][0][1];
out.println((list[ind][0][0] + 1) + " " + (list[ind][0][1] + 1));
for(int i = 1; i < list[ind].length; i++) {
if(list[ind][i][0] > last) {
out.println((list[ind][i][0] + 1) + " " + (list[ind][i][1] + 1));
last = list[ind][i][1];
}
}
}
public void run() {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
scn = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) {
new Thread(null, new B(), "Main", 1 << 26).start();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
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++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
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();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
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);
}
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 * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
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 * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
return arr;
}
int[] uniq(int[] arr) {
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
int[] reverse(int[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class SolutionArch2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.valueOf(scanner.nextLine());
String s = scanner.nextLine();
int[] arr = Arrays.stream(s.split(" "))
.mapToInt(Integer::valueOf)
.toArray();
int[] prefixSum = new int[n + 1];
for (int i = 0; i < n; i++) {
prefixSum[i + 1] = prefixSum[i] + arr[i];
}
Map<Integer, List<int[]>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int subarraySum = prefixSum[j + 1] - prefixSum[i];
map.putIfAbsent(subarraySum, new ArrayList<>());
int l = i + 1, r = j + 1;
map.get(subarraySum).add(new int[]{l, r});
}
}
List<int[]> resultPairs = new ArrayList<>();
for (Map.Entry<Integer, List<int[]>> e : map.entrySet()) {
List<int[]> result = new ArrayList<>();
int[] curr = new int[2];
List<int[]> pairs = e.getValue();
Collections.sort(pairs, Comparator.<int[]>comparingInt(a -> a[1]));
for (int[] next : pairs) {
if (next[0] > curr[1]) {
result.add(next);
curr = next;
}
}
if (resultPairs.size() < result.size()) {
resultPairs = result;
}
}
printResult(resultPairs);
}
private static void printResult(List<int[]> list) {
StringBuilder sb = new StringBuilder();
sb.append(list.size()).append("\n");
for (int[] pair : list) {
sb.append(pair[0]).append(" ").append(pair[1]).append("\n");
}
System.out.print(sb);
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.Point;
public final class Solution {
BufferedReader br;
StringTokenizer st;
{
st = null;
br = new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args) throws Exception {
new Solution().run();
}
void run() throws Exception {
int n = ni();
int[] a = new int[n];
for(int i=0; i<n; i++) a[i] = ni();
for(int i=1; i<n; i++) a[i] += a[i-1];
HashMap<Integer, List<Point>> map = new HashMap<>();
for(int i=0; i<n; i++) {
for(int j=i; j<n; j++) {
int sum = getSum(a, i, j);
if(!map.containsKey(sum)) map.put(sum, new ArrayList<>());
map.get(sum).add(new Point(i+1, j+1));
}
}
for(int key : map.keySet()) {
Collections.sort(map.get(key), new Comparator<Point>() {
@Override
public int compare(Point p1, Point p2) {
if(p1.x == p2.x) return p1.y - p2.y;
return p1.x - p2.x;
}
});
}
Stack<Point> stack = new Stack<>();
for(int key : map.keySet()) {
Stack<Point> st = getPairs(map.get(key));
if(st.size() > stack.size()) stack = st;
}
pl(stack.size());
while(!stack.isEmpty()) {
Point p = stack.pop();
pl(p.x + " " + p.y);
}
}
Stack<Point> getPairs(List<Point> list) {
Stack<Point> stack = new Stack<>();
stack.push(list.get(0));
for(int i=1; i<list.size(); i++) {
Point p = list.get(i);
if(p.x >= stack.peek().x && p.x <= stack.peek().y) {
Point p2 = stack.pop();
if(p2.y < p.y) {
stack.push(p2);
} else {
stack.push(p );
}
} else {
stack.push(p);
}
}
return stack;
}
int getSum(int[] a, int l, int r) {
return (l == 0) ? a[r] : a[r] - a[l-1];
}
class Node {
HashSet<Integer> adj;
public Node() {
adj = new HashSet<>();
}
}
// I/O
String nt() throws Exception {
if(st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine(), " ");
}
return st.nextToken();
}
int ni() throws Exception {
return Integer.parseInt(nt());
}
long nl() throws Exception {
return Long.parseLong(nt());
}
void p(Object o) {
System.out.print(o);
}
void pl(Object o) {
System.out.println(o);
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;
public class P1141F {
static BufferedReader br;
static BufferedWriter bw;
static StringTokenizer st;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
int[] a = new int[n];
int[][] b = new int[n][n];
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; ++i) {
a[i] = Integer.parseInt(st.nextToken());
int r = i;
b[r][r] = a[r];
if (!map.containsKey(b[r][r]))
map.put(b[r][r], new ArrayList<Integer>());
for(int l = 0; l < r; ++l) {
b[l][r] = b[l][r-1] + a[r];
if (!map.containsKey(b[l][r]))
map.put(b[l][r], new ArrayList<Integer>());
}
}
for(int r = 0; r < n; ++r) {
for(int l = 0; l <= r; ++l) {
int sum = b[l][r];
ArrayList<Integer> intervals = map.get(sum);
int last_r = -1;
if(!intervals.isEmpty())
last_r = intervals.get(intervals.size()-1);
if(l > last_r) {
intervals.add(l);
intervals.add(r);
}
}
}
//int best_sum = -1;
ArrayList<Integer> best_intervals = new ArrayList<Integer>();
for(Map.Entry<Integer, ArrayList<Integer>> entry : map.entrySet()) {
//int sum = entry.getKey();
ArrayList<Integer> intervals = entry.getValue();
if(intervals.size() > best_intervals.size()) {
best_intervals = intervals;
}
}
bw.write(best_intervals.size()/2 + "\n");
for(int i = 0; i < best_intervals.size(); i += 2) {
bw.write((best_intervals.get(i)+1) + " " + (best_intervals.get(i+1)+1) + "\n");
}
br.close();
bw.close();
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
//package sept;
import java.io.*;
import java.util.*;
public class TimePass implements Runnable {
InputStream is;
PrintWriter out;
String INPUT = "";
//boolean debug=false;
boolean debug=true;
static long mod=998244353;
static long mod2=1000000007;
void solve() throws IOException
{
int n=ni();
int[] a=na(n);
long[] sum=new long[n];
sum[0]=a[0];
for(int i=1;i<n;i++)sum[i]=sum[i-1]+a[i];
HashMap<Long,ArrayList<Pair>> map=new HashMap<>();
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
long curr=sum[j]-(i>0?sum[i-1]:0);
if(map.containsKey(curr))
{
map.get(curr).add(new Pair(i+1,j+1));
}
else
{
ArrayList<Pair> list=new ArrayList<>();
list.add(new Pair(i+1,j+1));
map.put(curr,list);
}
}
}
int max=0;
long maxSum=0;
for(long key:map.keySet())
{
ArrayList<Pair> list=map.get(key);
list.sort(new Comparator<Pair>(){
public int compare(Pair p1,Pair p2)
{
return p1.b-p2.b;
}
});
int prevl=0;
int cnt=0;
for(Pair pr:list)
{
if(pr.a>prevl)
{
cnt++;
prevl=pr.b;
}
}
if(max<cnt)
{
max=cnt;
maxSum=key;
}
}
int prevl=0;
ArrayList<Pair> list=map.get(maxSum);
ArrayList<Pair> ans=new ArrayList<>();
for(Pair pr:list)
{
if(pr.a>prevl)
{
//cnt++;
ans.add(pr);
//out.println(pr.a+" "+pr.b);
prevl=pr.b;
}
}
out.println(ans.size());
for(Pair pr:ans)
{
out.println(pr.a+" "+pr.b);
}
}
static long fnc(int a,int b)
{
return a+(long)1000000007*b;
}
static Pair[][] packU(int n,int[] from,Pair[] to)
{
Pair[][] g=new Pair[n][];
int[] p=new int[n];
for(int f:from)
{
p[f]++;
}
int m=from.length;
for(int i=0;i<n;i++)
{
g[i]=new Pair[p[i]];
}
for(int i=0;i<m;i++)
{
g[from[i]][--p[from[i]]]=to[i];
}
return g;
}
static int[][] packD(int n,int[] from,int[] to)
{
int[][] g=new int[n][];
int[] p=new int[n];
for(int f:from)
{
p[f]++;
}
int m=from.length;
for(int i=0;i<n;i++)
{
g[i]=new int[p[i]];
}
for(int i=0;i<m;i++)
{
g[from[i]][--p[from[i]]]=to[i];
}
return g;
}
static class Pair
{
int a,b,c;
public Pair(int a,int b
//,int c
)
{
this.a=a;
this.b=b;
//this.c=c;
}
}
static long lcm(int a,int b)
{
long val=a;
val*=b;
return (val/gcd(a,b));
}
static long gcd(long a,long b)
{
if(a==0)return b;
return gcd(b%a,a);
}
static int pow(int a, int b, int p)
{
long ans = 1, base = a;
while (b!=0)
{
if ((b & 1)!=0)
{
ans *= base;
ans%= p;
}
base *= base;
base%= p;
b >>= 1;
}
return (int)ans;
}
static int inv(int x, int p)
{
return pow(x, p - 2, p);
}
public static long[] radixSort(long[] f){ return radixSort(f, f.length); }
public static long[] radixSort(long[] f, int n)
{
long[] to = new long[n];
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(int)(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[(int)(f[i]&0xffff)]++] = f[i];
long[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>16&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>16&0xffff)]++] = f[i];
long[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>32&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>32&0xffff)]++] = f[i];
long[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(int)(f[i]>>>48&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[(int)(f[i]>>>48&0xffff)]++] = f[i];
long[] d = f; f = to;to = d;
}
return f;
}
public void run()
{
if(debug)oj=true;
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
try {
solve();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception {new Thread(null,new TimePass(),"Main",1<<26).start();}
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 | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
arr[0] = sc.nextInt();
for (int i = 1; i < n; i++) {
arr[i] = arr[i - 1] + sc.nextInt();
}
HashMap<Integer, List<Pair>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
if (map.containsKey(arr[i])) map.get(arr[i]).add(new Pair(0, i));
else {
List<Pair> l = new ArrayList<>();
l.add(new Pair(0, i));
map.put(arr[i], l);
}
for (int j = 1; j <= i; j++) {
int ss = arr[i] - arr[j - 1];
if (map.containsKey(ss)) map.get(ss).add(new Pair(j, i));
else {
List<Pair> l = new ArrayList<>();
l.add(new Pair(j, i));
map.put(ss, l);
}
}
}
List<Pair> el = null;
for (List<Pair> value : map.values()) {
value.sort(Comparator.comparingInt(Pair::getStart));
ArrayList<Pair> ps = new ArrayList<>();
Pair last = value.get(0);
for (int i = 1; i < value.size(); i++) {
if (last.getEnd() < value.get(i).getStart()) {
ps.add(last);
last = value.get(i);
}
else if (last.getEnd() > value.get(i).getEnd()) last = value.get(i);
}
ps.add(last);
if (el == null) el = ps;
else if (ps.size() > el.size()) el = ps;
}
System.out.println(el.size());
for (Pair pair : el) {
System.out.println((pair.getStart() + 1) + " " + (pair.getEnd() + 1));
}
}
}
class Pair {
private final int start;
private final int end;
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
public Pair(int start, int end) {
this.start = start;
this.end = end;
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main{
class Node implements Comparable<Node>{
int l;
int r;
public Node(int l,int r){
this.l=l;
this.r=r;
}
public int compareTo(Node c){
int t=Integer.compare(this.r,c.r);
if(t!=0) return t;
t=Integer.compare(this.l,c.l);
return t;
}
}
void solve() {
int n=ni();
int a[]=new int[n+1];
long pref[]=new long[n+1];
for(int i=1;i<=n;i++){
a[i]=ni();
pref[i]=pref[i-1]+a[i];
}
PriorityQueue<Long> q=new PriorityQueue<>();
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++) q.offer(pref[j]-pref[i-1]);
}
int sz=1;
while(!q.isEmpty()){
long val=q.poll();
if(!mp.containsKey(val)){
mp.put(val,sz++);
}
}
vec=new Node[sz][];
int size[]=new int[sz];
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++) size[mp.get(pref[j]-pref[i-1])]++;
}
for(int i=1;i<sz;i++) vec[i]=new Node[size[i]];
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++) {
int idx=mp.get(pref[j]-pref[i-1]);
vec[idx][--size[idx]]=new Node(i,j);
}
}
for(int i=1;i<sz;i++) Arrays.sort(vec[i]);
for(int i=1;i<sz;i++){
solve(vec[i]);
}
pw.println(ans.size());
for(Node p : ans) pw.println(p.l+" "+p.r);
}
HashMap<Long,Integer> mp=new HashMap<>();
Node vec[][];
int cnt=0;
ArrayList<Node> ans=new ArrayList<>();
void solve(Node [] v){
int n=v.length;
if(n==0) return;
int dp[]=new int[n+1];
int prev[]=new int[n+1];
int mx[]=new int[n+1];
int mxid[]=new int[n+1];
for(int i=1;i<=n;i++){
Node p=v[i-1];
dp[i]=dp[i-1];
prev[i]=-1;
int l=1,r=i-1;
int idx=0;
while(l<=r){
int mid=(l+r)>>1;
if(v[mid-1].r<p.l){
idx=mid;
l=mid+1;
}else r=mid-1;
}
if(1+mx[idx]>dp[i]){
dp[i]=1+mx[idx];
prev[i]=mxid[idx];
}
mx[i]=mx[i-1];
mxid[i]=mxid[i-1];
if(dp[i]>mx[i]){
mx[i]=dp[i];
mxid[i]=i;
}
}
if (dp[n] > cnt){
cnt=dp[n];
ans.clear();
int id=n;
while(id>0){
if(dp[id]==dp[id-1]){
id--;
continue;
}
ans.add(new Node(v[id-1].l,v[id-1].r));
id=prev[id];
}
}
}
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 Main().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 (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | 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.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Comparator;
import java.util.Collections;
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);
Task547F solver = new Task547F();
solver.solve(1, in, out);
out.close();
}
static class Task547F {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
long arr[] = in.nextLongArray(n);
long cur = 0;
int i, j;
Map<Long, List<Pair>> hm = new HashMap<>();
for (i = 0; i < n; i++) {
cur = 0;
for (j = i; j < n; j++) {
cur += arr[j];
if (!hm.containsKey(cur)) {
List<Pair> al = new LinkedList<>();
al.add(new Pair(i + 1, j + 1));
hm.put(cur, al);
} else {
List<Pair> al = hm.get(cur);
al.add(new Pair(i + 1, j + 1));
hm.put(cur, al);
}
}
}
//out.println(hm);
long max = arr[0];
int msize = 0;
for (long key : hm.keySet()) {
List<Pair> al = hm.get(key);
if (al.size() < hm.get(max).size())
continue;
Collections.sort(al, new Comparator<Pair>() {
public int compare(Pair o1, Pair o2) {
if (o1.b != o2.b)
return o1.b - o2.b;
return o1.a - o2.a;
}
});
//out.println(al);
List<Pair> all = new LinkedList<>();
int prev = -1;
for (Pair p : al) {
if (p.a > prev) {
all.add(p);
prev = p.b;
}
}
//out.println(all);
hm.put(key, all);
//out.println(all.size());
if (all.size() > msize) {
//out.println("ca" + msize + " " + all.size());
msize = all.size();
max = key;
}
}
//out.println(hm);
List<Pair> al = hm.get(max);
out.println(al.size());
for (Pair p : al) {
out.println(p.a + " " + p.b);
}
}
class Pair {
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
public String toString() {
return "(" + a + ", " + b + ")";
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
public class Soln {
public static int[] io(int n) {
int[] d = new int[n];
for (int i=0;i<n;i++) d[i] = f.nextInt();
return d;
}
public static int binlog( int bits ){
int log = 0;
if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; }
if( bits >= 256 ) { bits >>>= 8; log += 8; }
if( bits >= 16 ) { bits >>>= 4; log += 4; }
if( bits >= 4 ) { bits >>>= 2; log += 2; }
return log + ( bits >>> 1 );
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static final long mod = (long)Math.pow(10, 9) + 7;
static FastReader f=new FastReader();
public static void main (String[] args) throws IOException{
int n = f.nextInt();
int[] a = io(n);
HashMap<Integer,ArrayList<ivl>> hm = new HashMap<>();
for (int i=0;i<n;i++) {
int sum = 0;
for (int j=i;j<n;j++) {
sum+=a[j];
if (hm.get(sum)==null) hm.put(sum,new ArrayList<ivl>());
hm.get(sum).add(new ivl(i,j));
}
}
HashSet<ivl> hs = new HashSet<ivl>();
for (ArrayList<ivl> arr : hm.values()) {
Collections.sort(arr,new comp());
HashSet<ivl> temp = new HashSet<ivl>();
temp.add(arr.get(0));
int lastr = arr.get(0).r;
int num = 1;
for (ivl curr:arr) {
if (curr.l>lastr) {
lastr = curr.r;
num++;
temp.add(curr);
}
}
if (temp.size()>hs.size()) hs = temp;
}
System.out.println(hs.size());
for (ivl curr:hs) {
System.out.println((curr.l+1)+" "+(curr.r+1));
}
}
static class ivl{
int l,r;
ivl(int l,int r){
this.l=l;this.r=r;
}
}
static class comp implements Comparator<ivl>{
public int compare(ivl a,ivl b) {
if (a.r - b.r == 0) return a.l-b.l;
return a.r-b.r;
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class F{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static class Pair
{
int l;
int r;
Pair(int l,int r)
{
this.l = l;
this.r = r;
}
}
public static void main(String[] args)
{
OutputStream outputStream = System.out;
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(outputStream);
int n = sc.nextInt();
int a[] = new int[n];
Pair pr;
HashMap<Long,ArrayList> hm = new HashMap<>();
ArrayList<Pair> ar;
for(int i = 0; i < n; i++)
{
a[i] = sc.nextInt();
}
long sum = 0;
for(int r = 0; r < n; r++)
{
sum = 0;
for(int l = r; l >= 0; l--)
{
sum += a[l];
if(!hm.containsKey(sum))
{
ar = new ArrayList<>();
ar.add(new Pair(l,r));
hm.put(sum,ar);
}
else
{
ar = hm.get(sum);
ar.add(new Pair(l,r));
hm.put(sum,ar);
}
}
}
int count = 0;
int maxCount = 0;
long maxSum = 0;
for(Map.Entry<Long,ArrayList> entry:hm.entrySet())
{
sum = entry.getKey();
ar = entry.getValue();
count = 0;
int r = -1;
for(int i = 0; i < ar.size(); i++)
{
if(ar.get(i).l > r)
{
count++;
r = ar.get(i).r;
}
}
if(count > maxCount)
{
maxCount = count;
maxSum = sum;
}
}
ar = hm.get(maxSum);
out.println(maxCount);
//out.println((ar.get(0).l+1)+" "+(ar.get(0).r+1));
int r = -1;
for(int i = 0; i < ar.size(); i++)
{
if(ar.get(i).l > r)
{
out.println((ar.get(i).l+1) +" "+(ar.get(i).r+1));
r = ar.get(i).r;
}
}
out.close();
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.PrintWriter;
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt();
int a[]=new int[n];
for (int i = 0; i <n ; i++) {
a[i]=sc.nextInt();
}
HashMap<Integer,ArrayList<Node>> h=new HashMap<>();
for (int i = 0; i <n ; i++) {
int sum=0;
for (int j = i; j <n ; j++) {
sum+=a[j];
if(h.containsKey(sum)){
h.get(sum).add(new Node(i,j));
}
else{
ArrayList<Node> temp=new ArrayList<>();
temp.add(new Node(i,j));
h.put(sum,temp);
}
}
}
long ans=0;
ArrayList<Integer> ansList=new ArrayList<>();
for(int x:h.keySet()){
Collections.sort(h.get(x), new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return Integer.compare(o1.r,o2.r);
}
});
ArrayList<Node> l=h.get(x);
//out.println(l);
ArrayList<Integer> temp=new ArrayList<>();
int lasty=Integer.MIN_VALUE;
for (int i = 0; i <l.size() ; i++) {
if(l.get(i).l>lasty){
lasty=l.get(i).r;
temp.add(l.get(i).l);
temp.add(l.get(i).r);
}
}
if(ans<temp.size()){
ansList=temp;
ans=ansList.size();
}
}
out.println(ans/2);
for (int i = 0; i <ansList.size() ; i++) {
out.print((ansList.get(i)+1)+" ");
i++;
out.println((ansList.get(i)+1)+" ");
}
out.close();
}
static class Node{
int l,r;
public Node(int a,int b){
l=a;
r=b;
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1141f2_2 {
public static void main(String[] args) throws IOException {
int n = ri(), a[] = ria(n), pre[] = new int[n + 1];
for (int i = 0; i < n; ++i) {
pre[i + 1] = pre[i] + a[i];
}
Map<Integer, List<p>> sums = new HashMap<>();
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= i; ++j) {
sums.computeIfAbsent(pre[i + 1] - pre[j], k -> new ArrayList<>()).add(new p(j, i));
}
}
int k = 0;
List<p> ans = new ArrayList<>();
for (int key : sums.keySet()) {
List<p> segs = sums.get(key);
segs.sort((x, y) -> x.b == y.b ? x.a - y.a : x.b - y.b);
int last = -1, cnt = 0;
for (int i = 0, end = segs.size(); i < end; ++i) {
if (segs.get(i).a > last) {
++cnt;
last = segs.get(i).b;
}
}
if (cnt > k) {
k = cnt;
ans = segs;
}
}
prln(k);
int last = -1;
for (int i = 0, end = ans.size(); i < end; ++i) {
if (ans.get(i).a > last) {
prln(ans.get(i).a + 1, ans.get(i).b + 1);
last = ans.get(i).b;
}
}
close();
}
static class p {
int a, b;
p(int a_, int b_) {
a = a_;
b = b_;
}
@Override
public String toString() {
return "Pair{" + "a = " + a + ", b = " + b + '}';
}
public boolean asymmetricEquals(Object o) {
p p = (p) o;
return a == p.a && b == p.b;
}
public boolean symmetricEquals(Object o) {
p p = (p) o;
return a == p.a && b == p.b || a == p.b && b == p.a;
}
@Override
public boolean equals(Object o) {
return asymmetricEquals(o);
}
public int asymmetricHashCode() {
return Objects.hash(a, b);
}
public int symmetricHashCode() {
return Objects.hash(a, b) + Objects.hash(b, a);
}
@Override
public int hashCode() {
return asymmetricHashCode();
}
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// graph util
static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static void pryesno(boolean b) {prln(b ? "yes" : "no");};
static void pryn(boolean b) {prln(b ? "Yes" : "No");}
static void prYN(boolean b) {prln(b ? "YES" : "NO");}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author beginner1010
*/
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);
TaskF2 solver = new TaskF2();
solver.solve(1, in, out);
out.close();
}
static class TaskF2 {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
HashMap<Long, ArrayList<Interval>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
long sum = 0;
for (int j = i; j < n; j++) {
sum += a[j];
if (map.containsKey(sum) == false) {
map.put(sum, new ArrayList<>());
}
ArrayList<Interval> arr = map.get(sum);
if (arr.isEmpty() || arr.get(arr.size() - 1).r < i) {
arr.add(new Interval(i, j));
} else if (arr.get(arr.size() - 1).r >= j) {
arr.set(arr.size() - 1, new Interval(i, j));
}
}
}
ArrayList<Interval> best = new ArrayList<>();
for (ArrayList<Interval> arr : map.values()) {
if (best.size() < arr.size()) {
best = arr;
}
}
out.println(best.size());
for (Interval i : best) {
out.println((i.l + 1) + " " + (i.r + 1));
}
}
class Interval {
int l;
int r;
Interval(int l, int r) {
this.l = l;
this.r = r;
}
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isWhitespace(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 (!isWhitespace(c));
return res * sgn;
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.*;
public class Main {
public static class node implements Comparable<node>{
int l,r;
node(){}
node(int l,int r) {
this.l=l;
this.r=r;
}
@Override
public int compareTo(node rhs) {
return r-rhs.r;
}
}
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int x[] = new int[a];
for(int n=0;n<a;n++){
x[n] = in.nextInt();
}
int max = 1;
int t = 0;
HashMap<Integer, ArrayList<node>> map = new HashMap<Integer, ArrayList<node>>();
for(int n=0;n<a;n++){
int num = 0;
for(int m=n;m<a;m++){
num += x[m];
node node = new node(n, m);
if(!map.containsKey(num)){
ArrayList<node> list = new ArrayList<node>();
list.add(node);
map.put(num, list);
if(max == 1)t = num;
}
else{
ArrayList<node> list = map.get(num);
int left = 0;
int right = list.size()-1;
int res = list.size();
while(left <= right){
int mid = (left + right) >> 1;
//System.out.println(mid +" "+ left +" " +right);
if(list.get(mid).r >= n){
res = mid;
right = mid - 1;
}
else{
left = mid + 1;
}
}
if(res == list.size()){
list.add(node);
if(max < res+1){
max = res+1;
t = num;
}
}
else if(list.get(res).r>m){
list.set(res, node);
if(max < res){
max = list.size();
t = num;
}
}
}
}
}
System.out.println(max);
for(int n=0;n<max;n++){
System.out.println((map.get(t).get(n).l+1)+" "+(map.get(t).get(n).r+1));
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
public class Q3 {
static class Pair {
int a;
int b;
Pair(int p, int q) {
a = p;
b = q;
}
}
public static void main(String[] args) {
InputReader in = new InputReader();
int N = in.nextInt();
int arr[] = new int[N];
for (int i = 0; i < N; i++)
arr[i] = in.nextInt();
HashMap<Integer, ArrayList<Pair>> name = new HashMap<>();
for (int i = 0; i < N; i++) {
int sum = 0;
for (int j = i; j < N; j++) {
sum += arr[j];
if (name.get(sum) == null)
name.put(sum, new ArrayList());
name.get(sum).add(new Pair(i+1, j+1));
}
}
HashSet<Pair> ans = new HashSet<>();
for (ArrayList<Pair> n : name.values()) {
Collections.sort(n, new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if (Integer.compare(o1.b, o2.b) == 0)
return Integer.compare(o1.a, o2.a);
return Integer.compare(o1.b, o2.b);
}
});
HashSet<Pair> temp = new HashSet<>();
temp.add(n.get(0));
int num = 1;
int r = n.get(0).b;
for (int i = 1; i < n.size(); i++) {
if (n.get(i).a > r) {
num++;
r = n.get(i).b;
temp.add(n.get(i));
}
}
if (num > ans.size())
ans = temp;
}
System.out.println(ans.size());
for (Pair val : ans)
System.out.println(val.a + " " + val.b);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
return arr;
}
public InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public InputReader(InputStream stream) {
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 char nextChar() {
return next().charAt(0);
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArr(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextInt();
}
return arr;
}
public Integer[] nextIntegerArr(int n) {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = new Integer(this.nextInt());
return arr;
}
public int[][] next2DIntArr(int n, int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = this.nextInt();
}
}
return arr;
}
public int[] nextSortedIntArr(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextInt();
}
Arrays.sort(arr);
return arr;
}
public long[] nextLongArr(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextLong();
}
return arr;
}
public char[] nextCharArr(int n) {
char[] arr = new char[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextChar();
}
return arr;
}
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static int[] uwiSieve(int n) {
if (n <= 32) {
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int i = 0; i < primes.length; i++) {
if (n < primes[i]) {
return Arrays.copyOf(primes, i);
}
}
return primes;
}
int u = n + 32;
double lu = Math.log(u);
int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];
ret[0] = 2;
int pos = 1;
int[] isp = new int[(n + 1) / 32 / 2 + 1];
int sup = (n + 1) / 32 / 2 + 1;
int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int tp : tprimes) {
ret[pos++] = tp;
int[] ptn = new int[tp];
for (int i = (tp - 3) / 2; i < tp << 5; i += tp)
ptn[i >> 5] |= 1 << (i & 31);
for (int i = 0; i < tp; i++) {
for (int j = i; j < sup; j += tp)
isp[j] |= ptn[i];
}
}
// 3,5,7
// 2x+3=n
int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17,
9, 6, 16, 5, 15, 14};
int h = n / 2;
for (int i = 0; i < sup; i++) {
for (int j = ~isp[i]; j != 0; j &= j - 1) {
int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];
int p = 2 * pp + 3;
if (p > n)
break;
ret[pos++] = p;
for (int q = pp; q <= h; q += p)
isp[q >> 5] |= 1 << (q & 31);
}
}
return Arrays.copyOf(ret, pos);
}
public static int[] radixSort(int[] f) {
return radixSort(f, f.length);
}
public static int[] radixSort(int[] f, int n) {
int[] to = new int[n];
{
int[] b = new int[65537];
for (int i = 0; i < n; i++) b[1 + (f[i] & 0xffff)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < n; i++) to[b[f[i] & 0xffff]++] = f[i];
int[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < n; i++) b[1 + (f[i] >>> 16)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < n; i++) to[b[f[i] >>> 16]++] = f[i];
int[] d = f;
f = to;
to = d;
}
return f;
}
}
}
// for(Map.Entry<Integer,Integer> Test: map.entrySet()){
// int Key=Test.getKey();
// int val=Test.getValue();
// }
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
/*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static final long MOD = 1000L * 1000L * 1000L + 7;
private static final int[] dx = {0, -1, 0, 1};
private static final int[] dy = {1, 0, -1, 0};
private static final String yes = "Yes";
private static final String no = "No";
int n;
int[] arr;
class Segment {
int start;
int end;
public Segment(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public String toString() {
return start + " " + end;
}
}
Map<Integer, List<Segment>> hm = new HashMap<>();
void solve() throws IOException {
n = nextInt();
arr = nextIntArr(n);
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
if (!hm.containsKey(sum)) {
hm.put(sum, new ArrayList<>());
}
hm.get(sum).add(new Segment(i, j));
}
}
int max = -1;
int idx = -1;
for (Map.Entry<Integer, List<Segment>> entry : hm.entrySet()) {
int key = entry.getKey();
List<Segment> values = entry.getValue();
Collections.sort(values, new Comparator<Segment>() {
@Override
public int compare(Segment o1, Segment o2) {
return Integer.compare(o1.end, o2.end);
}
});
int cnt = findSeg(values).size();
if (cnt > max) {
max = cnt;
idx = key;
}
}
List<Segment> res = findSeg(hm.get(idx));
outln(res.size());
for (int i = 0; i < res.size(); i++) {
outln((1 + res.get(i).start) + " " + (1 + res.get(i).end));
}
}
List<Segment> findSeg(List<Segment> input) {
List<Segment> res = new ArrayList<>();
int bound = -1;
for (int i = 0; i < input.size(); i++) {
if (input.get(i).start > bound) {
res.add(input.get(i));
bound = input.get(i).end;
}
}
return 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;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long 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);
}
private void formatPrint(double val) {
outln(String.format("%.9f%n", val));
}
public CFA() 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 CFA();
}
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 | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
// package CF1141;
import java.io.*;
import java.util.*;
public class CF1141F1 {
static FastReader s;
static PrintWriter out;
static String INPUT = "7\n" +
"4 1 2 2 1 5 3\n";
public static void main(String[] args) {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
s = new FastReader(oj);
int n = s.nextInt();
int[] arr = s.nextIntArray(n);
int[] sum = new int[n];
sum[0] = arr[0];
for (int i = 1; i < n; i++) {
sum[i] = sum[i - 1] + arr[i];
}
// int max = Integer.MIN_VALUE;
HashMap<Integer, ArrayList<pair>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if(i == 0) {
ArrayList<pair> list = map.getOrDefault(sum[j], new ArrayList<>());
list.add(new pair(i, j));
map.put(sum[j], list);
} else {
ArrayList<pair> list = map.getOrDefault(sum[j] - sum[i - 1], new ArrayList<>());
list.add(new pair(i, j));
map.put(sum[j] - sum[i - 1], list);
}
}
}
ArrayList<Integer> keys = new ArrayList<>(map.keySet());
ArrayList<pair> ans = null;
for (int curr : keys) {
ArrayList<pair> list = map.get(curr);
Collections.sort(list);
ArrayList<pair> smallAns = new ArrayList<>();
smallAns.add(list.get(0));
for (int k = 1; k < list.size(); k++) {
if(list.get(k).start > smallAns.get(smallAns.size() - 1).finish) {
smallAns.add(list.get(k));
}
}
if(ans == null) {
ans = smallAns;
} else {
if(ans.size() < smallAns.size()) {
ans = smallAns;
}
}
}
// out.println(ans.size() + "\n" + ans);
//
// out.println(map);
//
// out.println(Arrays.toString(sum));
StringBuilder ans1 = new StringBuilder();
ans1.append(ans.size() + "\n");
for (pair p : ans) {
ans1.append((p.start + 1) + " " + (p.finish + 1));
ans1.append("\n");
}
out.println(ans1);
if (!oj) {
System.out.println(Arrays.deepToString(new Object[]{System.currentTimeMillis() - time + " ms"}));
}
out.flush();
}
private static class pair implements Comparable<pair>{
int start;
int finish;
public pair(int start, int finish) {
this.start = start;
this.finish = finish;
}
@Override
public int compareTo(pair o) {
return Integer.compare(this.finish, o.finish);
}
@Override
public String toString() {
return this.start + " " + this.finish;
}
}
private static class Matrix {
static long[][] I;
static long mod = 1000000007;
public static long[][] exp(long[][] M, long n) {
if (n <= 0) {
I = new long[M.length][M.length];
for (int i = 0; i < M.length; i++) {
I[i][i] = 1L;
}
return I;
}
if (n == 1) return M;
long[][] res = exp(M, n / 2);
res = mult(res, res);
if (n % 2 == 0) return res;
return mult(res, M);
}
public static long[][] mult(long[][] p, long[][] q) {
long[][] r = new long[p.length][q[0].length];
for (int i = 0; i < p.length; i++)
for (int j = 0; j < q[0].length; j++)
for (int k = 0; k < q.length; k++) {
r[i][j] += p[i][k] * q[k][j];
r[i][j] %= mod;
}
return r;
}
}
private static class Maths {
static ArrayList<Long> printDivisors(long n) {
// Note that this loop runs till square root
ArrayList<Long> list = new ArrayList<>();
for (long i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
if (n / i == i) {
list.add(i);
} else {
list.add(i);
list.add(n / i);
}
}
}
return list;
}
// GCD - Using Euclid theorem.
private static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
// Extended euclidean algorithm
// Used to solve equations of the form ax + by = gcd(a,b)
// return array [d, a, b] such that d = gcd(p, q), ap + bq = d
static long[] extendedEuclidean(long p, long q) {
if (q == 0)
return new long[]{p, 1, 0};
long[] vals = extendedEuclidean(q, p % q);
long d = vals[0];
long a = vals[2];
long b = vals[1] - (p / q) * vals[2];
return new long[]{d, a, b};
}
// X ^ y mod p
static long power(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
// Returns modulo inverse of a
// with respect to m using extended
// Euclid Algorithm. Refer below post for details:
// https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
static long inv(long a, long m) {
long m0 = m, t, q;
long x0 = 0, x1 = 1;
if (m == 1)
return 0;
// Apply extended Euclid Algorithm
while (a > 1) {
q = a / m;
t = m;
m = a % m;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
// Make x1 positive
if (x1 < 0)
x1 += m0;
return x1;
}
// k is size of num[] and rem[].
// Returns the smallest number
// x such that:
// x % num[0] = rem[0],
// x % num[1] = rem[1],
// ..................
// x % num[k-2] = rem[k-1]
// Assumption: Numbers in num[] are pairwise
// coprime (gcd for every pair is 1)
static long findMinX(long num[], long rem[], long k) {
int prod = 1;
for (int i = 0; i < k; i++)
prod *= num[i];
int result = 0;
for (int i = 0; i < k; i++) {
long pp = prod / num[i];
result += rem[i] * inv(pp, num[i]) * pp;
}
return result % prod;
}
}
private static class BS {
// Binary search
private static int binarySearch(int[] arr, int ele) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == ele) {
return mid;
} else if (ele < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
// First occurence using binary search
private static int binarySearchFirstOccurence(int[] arr, int ele) {
int low = 0;
int high = arr.length - 1;
int ans = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == ele) {
ans = mid;
high = mid - 1;
} else if (ele < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
// Last occurenece using binary search
private static int binarySearchLastOccurence(int[] arr, int ele) {
int low = 0;
int high = arr.length - 1;
int ans = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == ele) {
ans = mid;
low = mid + 1;
} else if (ele < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
}
private static class arrays {
// Merge sort
static void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int[n1];
int R[] = new int[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
static void sort(int arr[], int l, int r) {
if (l < r) {
int m = (l + r) / 2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
static void sort(int[] arr) {
sort(arr, 0, arr.length - 1);
}
}
private static class UnionFindDisjointSet {
int[] parent;
int[] size;
int n;
int size1;
public UnionFindDisjointSet(int n) {
this.n = n;
this.parent = new int[n];
this.size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
for (int i = 0; i < n; i++) {
size[i] = 1;
}
this.size1 = n;
}
private int numDisjointSets() {
System.out.println(size1);
return size1;
}
private boolean find(int a, int b) {
int rootA = root(a);
int rootB = root(b);
if (rootA == rootB) {
return true;
}
return false;
}
private int root(int b) {
if (parent[b] != b) {
return parent[b] = root(parent[b]);
}
return b;
}
private void union(int a, int b) {
int rootA = root(a);
int rootB = root(b);
if (rootA == rootB) {
return;
}
if (size[rootA] < size[rootB]) {
parent[rootA] = parent[rootB];
size[rootB] += size[rootA];
} else {
parent[rootB] = parent[rootA];
size[rootA] += size[rootB];
}
size1--;
System.out.println(Arrays.toString(parent));
}
}
private static class SegTree {
int[] st;
int[] arr;
public SegTree(int[] arr) {
this.arr = arr;
int size = (int) Math.ceil(Math.log(arr.length) / Math.log(2));
st = new int[(int) ((2 * Math.pow(2, size)) - 1)];
buildSegmentTree(1, 0, arr.length - 1);
}
//**********JUST CALL THE CONSTRUCTOR, THIS FUNCTION WILL BE CALLED AUTOMATICALLY******
private void buildSegmentTree(int index, int L, int R) {
if (L == R) {
st[index] = arr[L];
return;
}
buildSegmentTree(index * 2, L, (L + R) / 2);
buildSegmentTree(index * 2 + 1, (L + R) / 2 + 1, R);
// Replace this line if you want to change the function of the Segment tree.
st[index] = Math.min(st[index * 2], st[index * 2 + 1]);
}
//***********We have to use this function **************
private int Query(int queL, int queR) {
return Query1(1, 0, arr.length - 1, queL, queR);
}
//This is a helper function.
//************* DO NOT USE THIS ****************
private int Query1(int index, int segL, int segR, int queL, int queR) {
if (queL > segR || queR < segL) {
return -1;
}
if (queL <= segL && queR >= segR) {
return st[index];
}
int ans1 = Query1(index * 2, segL, (segL + segR) / 2, queL, queR);
int ans2 = Query1(index * 2 + 1, (segL + segR) / 2 + 1, segR, queL, queR);
if (ans1 == -1) {
return ans2;
}
if (ans2 == -1) {
return ans1;
}
// Segment tree implemented for range minimum query. Change the below line to change the function.
return Math.min(ans1, ans2);
}
private void update(int idx, int val) {
update1(1, 0, arr.length - 1, idx, val);
}
private void update1(int node, int queL, int queR, int idx, int val) {
// idx - index to be updated in the array
// node - index to be updated in the seg tree
if (queL == queR) {
// Leaf node
arr[idx] += val;
st[node] += val;
} else {
int mid = (queL + queR) / 2;
if (queL <= idx && idx <= mid) {
// If idx is in the left child, recurse on the left child
update1(2 * node, queL, mid, idx, val);
} else {
// if idx is in the right child, recurse on the right child
update1(2 * node + 1, mid + 1, queR, idx, val);
}
// Internal node will have the min of both of its children
st[node] = Math.min(st[2 * node], st[2 * node + 1]);
}
}
}
private static class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
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++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
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();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
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);
}
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 * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
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 * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
return arr;
}
int[] uniq(int[] arr) {
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
//package codeforces_464_div2;
import java.util.*;
import java.util.stream.Collectors;
public class F {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
int[][] sub = new int[n][n];
for (int i = 0; i < n; i++) {
sub[i][i] = arr[i];
for (int j = i + 1; j < n; j++) {
sub[i][j] = sub[i][j - 1] + arr[j];
}
}
HashMap<Integer, List<P>> hm = new HashMap<>();
/*for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (hm.containsKey(sub[i][j])) {
hm.get(sub[i][j]).add(new P(i, j));
} else {
List<P> temp = new ArrayList<>();
temp.add(new P(i, j));
hm.put(sub[i][j], temp);
}
}
}*/
for(int stop=0; stop<n; stop++) {
for(int start=0; start<=stop; start++) {
if (hm.containsKey(sub[start][stop])) {
hm.get(sub[start][stop]).add(new P(start, stop));
} else {
List<P> temp = new ArrayList<>();
temp.add(new P(start, stop));
hm.put(sub[start][stop], temp);
}
}
}
int ans = Integer.MIN_VALUE;
/*for(Map.Entry it : hm.entrySet()) {
int or = overlap(it.getValue());
ans = Math.max(ans, or);
}*/
List<P> ansList = null;
for (List<P> it : hm.values()) {
int or = overlap(it);
if(or>ans) {
ans = or;
ansList = it;
}
}
List<P> processedList = extractOverlapping(ansList);
System.out.println(ans);
for(int i=0; i<processedList.size(); i++) {
int A = processedList.get(i).a + 1;
int B = processedList.get(i).b + 1;
System.out.println(A + " " + B);
}
}
public static int overlap(List<P> listOfPair) {
/*List<P> sortedList = listOfPair.stream()
.sorted((pair1, pair2) -> pair1.getB().compareTo(pair2.getB()))
.collect(Collectors.toList());*/
List<P> sortedList = listOfPair;
int cnt = 0;
int end = sortedList.get(0).b;
for (int i = 1; i < sortedList.size(); i++) {
if (sortedList.get(i).a <= end) {
cnt++;
} else {
end = sortedList.get(i).b;
}
}
return sortedList.size() - cnt;
}
public static List<P> extractOverlapping(List<P> ansList) {
List<P> sortedList = ansList.stream()
.sorted((pair1, pair2) -> pair1.getB().compareTo(pair2.getB()))
.collect(Collectors.toList());
List<P> finalList = new ArrayList<>();
finalList.add(sortedList.get(0));
int end = sortedList.get(0).b;
for (int i = 1; i < sortedList.size(); i++) {
if (sortedList.get(i).a <= end) {
continue;
} else {
finalList.add(sortedList.get(i));
end = sortedList.get(i).b;
}
}
return finalList;
}
}
class P implements Comparable<P> {
Integer a;
Integer b;
public P(int a, int b) {
this.a = a;
this.b = b;
}
public Integer getA() {
return a;
}
public Integer getB() {
return b;
}
@Override
public int compareTo(P that) {
return this.b.compareTo(that.b);
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[])
{
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int T=1;
while(T-->0)
{
int n=input.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=input.nextInt();
}
HashMap<Integer,ArrayList<Pair>> map=new HashMap<>();
for(int i=0;i<n;i++)
{
int sum=0;
for(int j=i;j<n;j++)
{
sum+=a[j];
if(map.containsKey(sum))
{
map.get(sum).add(new Pair(i,j));
}
else
{
map.put(sum,new ArrayList<>());
map.get(sum).add(new Pair(i,j));
}
}
}
int max=Integer.MIN_VALUE;
Iterator it=map.entrySet().iterator();
ArrayList<Pair> setBlocks=new ArrayList<>();
while(it.hasNext())
{
Map.Entry e=(Map.Entry)it.next();
ArrayList<Pair> list=(ArrayList)e.getValue();
Collections.sort(list, new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if(o1.l==o2.l)
{
return o1.r-o2.r;
}
else
{
return o1.l-o2.l;
}
}
});
Pair1 sufMin[]=new Pair1[list.size()];
TreeSet<Pair> set=new TreeSet<>(new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if(o1.l==o2.l)
{
return o1.r-o2.r;
}
else
{
return o1.l-o2.l;
}
}
});
int min=Integer.MAX_VALUE;
int index=-1;
for(int j=list.size()-1;j>=0;j--)
{
if(min>=list.get(j).r)
{
min=list.get(j).r;
index=j;
}
sufMin[j]=new Pair1(min,index);
set.add(new Pair(list.get(j).l,j));
}
int count=0;
int j=0;
ArrayList<Pair> blocks=new ArrayList<>();
while(j<list.size())
{
int m=sufMin[j].min;
int ind=sufMin[j].index;
blocks.add(list.get(ind));
count++;
Pair p=new Pair(m+1,0);
if(set.ceiling(p)==null)
{
break;
}
else
{
Pair p1=set.ceiling(p);
j=p1.r;
}
}
if(max<count)
{
max=count;
setBlocks=blocks;
}
}
out.println(max);
for(int i=0;i<setBlocks.size();i++)
{
out.println((setBlocks.get(i).l+1)+" "+(setBlocks.get(i).r+1));
}
}
out.close();
}
public static class Pair1
{
int min,index;
Pair1(int min,int index)
{
this.min=min;
this.index=index;
}
}
public static class Pair
{
int l,r;
Pair(int l,int r)
{
this.l=l;
this.r=r;
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
//package codeforces;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class SameSumBlocksHard {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in .nextInt();
long[] a = new long[n + 1];
long[] sum = new long[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
sum[i] = sum[i - 1] + a[i];
}
Map<Long, List<int[]>> map = new HashMap<>();
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
long x = sum[j] - sum[i - 1];
List<int[]> list = map.get(x);
if (list == null) {
list = new ArrayList<>();
map.put(x, list);
}
list.add(new int[] {i, j});
}
}
List<int[]> ans = new ArrayList<>();
for (Map.Entry<Long, List<int[]>> entry : map.entrySet()) {
List<int[]> list = entry.getValue();
List<int[]> tmp = new ArrayList<>();
calc(list, tmp);
if (tmp.size() > ans.size()) {
ans.clear();
ans.addAll(tmp);
}
}
System.out.println(ans.size());
for (int[] pair : ans) {
System.out.println(pair[0] + " " + pair[1]);
}
in.close();
}
static void calc(List<int[]> list, List<int[]> tmp) {
Collections.sort(list, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[1] < o2[1]) {
return -1;
} else if (o1[1] > o2[1]) {
return 1;
} else {
return 0;
}
}
});
int last = -1;
for (int[] p : list) {
if (last == -1) {
last = p[1];
tmp.add(p);
} else if (p[0] > last) {
last = p[1];
tmp.add(p);
}
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.util.Collections;
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);
F1BlokiRavnoiSummiProstayaRedakciya solver = new F1BlokiRavnoiSummiProstayaRedakciya();
solver.solve(1, in, out);
out.close();
}
static class F1BlokiRavnoiSummiProstayaRedakciya
{
InputReader in;
Map<Long, List<F1BlokiRavnoiSummiProstayaRedakciya.Block>> sums;
public void solve(int testNumber, InputReader in, PrintWriter out)
{
this.in = in;
int n = ni();
long[] a = nla(n);
sums = new HashMap<>();
for (int i = 0; i < n; i++)
{
long sum = 0;
for (int j = i; j < n; j++)
{
sum += a[j];
sums.computeIfAbsent(sum, k -> new ArrayList<>()).add(
new F1BlokiRavnoiSummiProstayaRedakciya.Block(i, j, sum));
}
}
for (Map.Entry<Long, List<F1BlokiRavnoiSummiProstayaRedakciya.Block>> e : sums.entrySet())
{
Collections.sort(e.getValue());
}
List<F1BlokiRavnoiSummiProstayaRedakciya.Block> res = Collections.emptyList();
for (Map.Entry<Long, List<F1BlokiRavnoiSummiProstayaRedakciya.Block>> e : sums.entrySet())
{
List<F1BlokiRavnoiSummiProstayaRedakciya.Block> blocks = e.getValue();
List<F1BlokiRavnoiSummiProstayaRedakciya.Block> updated = new ArrayList<>();
if (blocks.size() <= res.size())
continue;
for (F1BlokiRavnoiSummiProstayaRedakciya.Block next : blocks)
{
if (updated.size() == 0)
updated.add(next);
else
{
F1BlokiRavnoiSummiProstayaRedakciya.Block prev = updated.get(updated.size() - 1);
if (next.l > prev.r)
updated.add(next);
}
}
if (updated.size() > res.size())
res = updated;
}
StringBuilder resS = new StringBuilder();
resS.append(res.size()).append('\n');
for (F1BlokiRavnoiSummiProstayaRedakciya.Block block : res)
resS.append(block.l + 1).append(' ').append(block.r + 1).append('\n');
out.println(resS);
}
private long[] nla(int size)
{
return in.nextLongArray(size);
}
private int ni()
{
return in.nextInt();
}
static class Block implements Comparable<F1BlokiRavnoiSummiProstayaRedakciya.Block>
{
int l;
int r;
long sum;
public Block(int l, int r, long sum)
{
this.l = l;
this.r = r;
this.sum = sum;
}
public int compareTo(F1BlokiRavnoiSummiProstayaRedakciya.Block o)
{
int res = Integer.compare(r, o.r);
if (res == 0)
res = Integer.compare(l, o.l);
return res;
}
}
}
static class InputReader
{
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream in)
{
reader = new BufferedReader(new InputStreamReader(in));
}
public long[] nextLongArray(int size)
{
long[] array = new long[size];
for (int i = 0; i < size; ++i)
{
array[i] = nextLong();
}
return array;
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(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 | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeMap;
public class Main extends PrintWriter {
static BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
// static Scanner s=new Scanner(System.in);
Main () { super(System.out); }
public static void main(String[] args) throws IOException{
Main d1=new Main ();d1.main();d1.flush();
}
void main() throws IOException {
BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
StringBuffer sb = new StringBuffer();
StringBuffer sb1 = new StringBuffer();
PrintWriter out = new PrintWriter(System.out);
int t=1;
// t=i(s()[0]);
while(t-->0) {
//dp[i]=a[i]+max(dp[j]) S.T. j<i and h[j]<h[i];
String[] s1 = s();
int n = i(s1[0]);
long[] a=new long[n];
arr(a,n);
HashMap<Long,Integer>[] dp=new HashMap[n];
long[] presum=new long[n];
for(int i=0;i<n;i++){
if(i==0){
presum[i]=a[i];
}else{
presum[i]=a[i]+presum[i-1];
}
}HashMap<Long,TreeMap<Integer,Long> > tm=new HashMap<>();int ans=0;long maxsum=0;
for(int i=0;i<n;i++){
dp[i]=new HashMap<>();
for(int j=-1;j<i;j++){
long sum=0;
if(j==-1) sum=presum[i];else sum=presum[i]-presum[j];
// if(sum==5&&i==5) System.out.println(tm.get(sum).floorKey(4));
if(tm.containsKey(sum)&&tm.get(sum).floorKey(j)!=null){
dp[i].put(sum,Math.max(dp[i].getOrDefault(sum,0),dp[tm.get(sum).floorKey(j)].getOrDefault(sum,0)+1));
if(dp[i].get(sum)>ans){
maxsum=sum;
}
ans=Math.max(ans,dp[i].get(sum));
}else if(dp[i].containsKey(sum)==false){
if(dp[i].getOrDefault(sum,0)<1) dp[i].put(sum,1);
if(dp[i].get(sum)>ans){
maxsum=sum;
}
ans=Math.max(ans,1);
}
long val=dp[i].getOrDefault(sum,0);
// if(tm.containsKey(sum)&&tm.get(sum).floorKey(i-1)!=null){
if(!tm.containsKey(sum)||tm.get(sum).floorKey(i-1)==null||dp[tm.get(sum).floorKey(i-1)].getOrDefault(sum,0)<val) {
// val = Math.max(val, dp[tm.get(sum).floorKey(i - 1)].getOrDefault(sum, 0));
TreeMap<Integer, Long> tt = new TreeMap<>();
tt.put(i, val);
tm.put(sum, tt);
}
// }
}
}int cnt=0;int last=-1;
for(int i=0;i<n;i++){
for(int j=i-1;j>=-1;j--){
long sum=0;
if(j==-1) sum=presum[i];
else sum=presum[i]-presum[j];
if(dp[i].getOrDefault(maxsum,0)>cnt&&maxsum==sum){
sb.append(j+2+" "+(i+1)+"\n");cnt++;
break;
}
}
} System.out.println(ans);
// System.out.println(dp[5].get(5L)+" "+dp[4].get(5L));
System.out.println(sb);
}
}
// System.out.println(sb);
long[] st;
void buildtree(int i,int s,int e,long[] a){
if(s==e){
st[i]=a[s];
return;
}
int mid=(s+e)/2;
buildtree(2*i,s,mid,a);
buildtree(2*i+1,mid+1,e,a);
st[i]=Math.min(st[2*i],st[2*(i)+1]);
}
long query(int i,int s,int e,int qs,int qe){
if(qs>e||qe<s) return Integer.MIN_VALUE;
if(s>=qs&&e<=qe) return st[i];
int mid=(s+e)/2;
long l=query(2*i,s,mid,qs,qe);
long r=query(2*i+1,mid+1,e,qs,qe);
return Math.max(l,r);
}
void pointupdate(int i,int s,int e,int qi,long [] a){
if(s==e){
st[i]=a[s];return;
}
int mid=(s+e)/2;
if(qi<=mid) pointupdate(2*i,s,mid,qi,a);
else pointupdate(2*(i)+1,mid+1,e,qi,a);
st[i]=Math.max(st[2*i],st[2*i+1]);
}
public void arr(long[] a,int n) throws IOException{
// BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
String[] s2=s();
for(int i=0;i<n;i++){
a[i]=i(s2[i]);
}
}
public void sort(int[] a,int l,int h){
if(l==h) return;
int mid=(l+h)/2;
sort(a,l,mid);
sort(a,mid+1,h);
merge(a,l,(l+h)/2,h);
}
void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int[n1];
int R[] = new int[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static String[] s() throws IOException {
return s.readLine().trim().split("\\s+");
}
static int i(String ss) {
return Integer.parseInt(ss);
}
static long l(String ss) {
return Long.parseLong(ss);
}
}
class Student {
long a;int b;int c;
public Student(int a,int b) {
this.a=a;this.c=c;this.b=b;
}
}
class Pair {
int a,b,c;
public Pair(int a,int b){
this.a=a;this.b=b;this.c=c;}
}
class Sortbyroll implements Comparator<Student> {
public int compare(Student a, Student b){
if(a.b==b.b) return (int)b.a-(int)a.a;
return a.b-b.b;}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//package Round547;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
/**
*
* @author Hemant Dhanuka
*/
public class F1 {
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main(String[] args) throws IOException {
// Scanner s=new Scanner(System.in);
Reader s=new Reader();
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=s.nextInt();
}
Map<Long,PriorityQueue<Node>> map=new HashMap();
for(int i=0;i<n;i++){
long sum=0;
for(int j=i;j<n;j++){
sum=sum+a[j];
PriorityQueue<Node> pq=map.get(sum);
if(pq==null){
pq=new PriorityQueue();
map.put(sum, pq);
}
pq.add(new Node(i,j));
}
}
Set<Long> keys=map.keySet();
Iterator<Long> itr=keys.iterator();
int max=0;
int solbackDp[]=null;
Node solA[]=new Node[0];
while(itr.hasNext()){
Long sum=itr.next();
PriorityQueue<Node> pq1=map.get(sum);
//Node rangelist[]=new Node[pq1.size()+1];
ArrayList<Node> rangelist=new ArrayList<>();
rangelist.add(new Node(-1, -1));
//int count=1;
//rangelist[0]=new Node(-1,-1);
Node last=rangelist.get(0);
while(!pq1.isEmpty()){
Node n1=pq1.poll();
if(n1.l!=last.l){
rangelist.add(n1);
last=n1;
}
}
int backTrack[]=new int[rangelist.size()];
int dp[]=new int[rangelist.size()];
Arrays.fill(dp, -1);
int ans=fun(0,dp,rangelist,backTrack);
if(ans>max){
max=ans;
solA=rangelist.toArray(solA);
solbackDp=backTrack;
}
}
System.out.println(max);
int pos=0;
while(solbackDp[pos]!=-1){
pos=solbackDp[pos];
System.out.println((solA[pos].l+1)+" "+(solA[pos].r+1));
}
}
static int fun(int pos, int[] dp, ArrayList<Node> rangeList, int[] bactTrack){
if(pos==rangeList.size()-1){
bactTrack[pos]=-1;
return 0;
}
if(dp[pos]!=-1){
return dp[pos];
}
int i=pos+1;
int maxAns=0;
int nextPos=-1;
for(;i<=rangeList.size()-1;i++){
if(rangeList.get(i).l>rangeList.get(pos).r){
int tempAns=1+fun(i, dp,rangeList, bactTrack);
if(tempAns>maxAns){
maxAns=tempAns;
nextPos=i;
}
}
}
dp[pos]=maxAns;
bactTrack[pos]=nextPos;
return maxAns;
}
static class Node implements Comparable<Node>{
int l;
int r;
public Node(int l, int r) {
this.l = l;
this.r = r;
}
@Override
public int compareTo(Node o2) {
if(this.l!=o2.l){
return this.l-o2.l;
} else{
return this.r-o2.r;
}
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.*;
import java.io.*;
public class Solution1{
static class Node{
int start,end;
Node(int start, int end){
this.start=start;
this.end=end;
}
public String toString(){
return start+" "+end;
}
}
public static void sameSumBlock(int a[],int n){
HashMap<Long,ArrayList<Node>> map=new HashMap<>();
long sum;
for(int i=0;i<n;i++){
sum=0;
for(int j=i;j<n;j++){
sum+=a[j];
if(!map.containsKey(sum))
map.put(sum,new ArrayList<>());
map.get(sum).add( new Node(i+1, j+1) );
}
}
//for(Map.Entry<Long,ArrayList<Node>> pair: map.entrySet())
//System.out.println(pair.getKey()+" "+pair.getValue());
int max=0; LinkedList<Node> list=new LinkedList<>();
for(Map.Entry<Long,ArrayList<Node>> pair: map.entrySet()){
ArrayList<Node> arr=pair.getValue();
Collections.sort(arr, (Node x, Node y)->{ return x.end-y.end; });
int count=0,end=0;
LinkedList<Node> temp=new LinkedList<>();
for(Node item: arr){
if(end<item.start){
end=item.end;
count+=1;
temp.add(new Node(item.start, item.end));
}
}
if(count>max){
max=count;
list=temp;
}
}
System.out.println(max);
for(Node item: list)
System.out.println(item.start+" "+item.end);
}
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=in.nextInt();
sameSumBlock(a,n);
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class F11141 {
static class Solver {
ArrayList<int[]> ranges[];
HashMap<Long, Integer> hm = new HashMap<>();
int id(long s) {
if (!hm.containsKey(s))
hm.put(s, hm.size());
return hm.get(s);
}
// max disjoint range set in ranges[r]
int[] memo;
int go(int r) {
memo[N] = 0;
int last = N;
for(int[] a : ranges[r]) {
while(a[0] < last) {
memo[last - 1] = memo[last];
last--;
}
memo[a[0]] = Math.max(memo[a[0]], Math.max(memo[a[0]], 1 + memo[a[1] + 1]));
last = a[0];
}
while(0 < last) {
memo[last - 1] = memo[last];
last--;
}
return memo[0];
}
ArrayDeque<int[]> ans = new ArrayDeque<>();
void go2(int r) {
memo[N] = 0;
int last = N;
int minAt[] = new int[N], oo = 987654321;
Arrays.fill(minAt, oo);
for(int[] a : ranges[r]) {
minAt[a[0]] = Math.min(minAt[a[0]], a[1] - a[0]);
while(a[0] < last) {
memo[last - 1] = memo[last];
last--;
}
memo[a[0]] = Math.max(memo[a[0]], Math.max(memo[a[0]], 1 + memo[a[1] + 1]));
last = a[0];
}
while(0 < last) {
memo[last - 1] = memo[last];
last--;
}
int k = 0;
for(; k < N;) {
if(minAt[k] == oo || memo[k] != 1 + memo[k + minAt[k] + 1]) k++;
else {
ans.push(new int[] {k, k + minAt[k]});
k += minAt[k] + 1;
}
}
}
@SuppressWarnings("unchecked")
Solver() {
ranges = new ArrayList[2250001];
for (int i = 0; i < ranges.length; i++)
ranges[i] = new ArrayList<>();
}
int N, LID;
long[] a;
void solve(Scanner s, PrintWriter out) {
N = s.nextInt();
a = new long[N + 1];
for (int i = 1; i <= N; i++)
a[i] = s.nextLong() + a[i - 1];
for (int i = N; i >= 1; i--)
for (int j = i; j <= N; j++) {
int x = id(a[j] - a[i - 1]);
ranges[x].add(new int[] { i - 1, j - 1 });
}
int best = 0, bid = -1;
memo = new int[N + 1];
// Arrays.sort(ranges, (a, b) -> b.size() - a.size());
for(int i = 0; i < ranges.length; i++, LID++) {
if(ranges[i].size() <= best) continue;
int ans = go(i);
if(ans > best) {
best = ans;
bid = i;
}
}
// backtrack on bid
out.println(best);
go2(bid);
while(!ans.isEmpty()) {
int[] c = ans.pop();
out.println(++c[0] + " " + ++c[1]);
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver solver = new Solver();
solver.solve(s, out);
out.close();
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author beginner1010
*/
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);
TaskF2 solver = new TaskF2();
solver.solve(1, in, out);
out.close();
}
static class TaskF2 {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
HashMap<Integer, ArrayList<Interval>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += a[j];
if (map.containsKey(sum) == false) {
map.put(sum, new ArrayList<>());
}
ArrayList<Interval> arr = map.get(sum);
if (arr.isEmpty() || arr.get(arr.size() - 1).r < i) {
arr.add(new Interval(i, j));
} else if (arr.get(arr.size() - 1).r >= j) {
arr.set(arr.size() - 1, new Interval(i, j));
}
}
}
ArrayList<Interval> best = new ArrayList<>();
for (ArrayList<Interval> arr : map.values()) {
if (best.size() < arr.size()) {
best = arr;
}
}
out.println(best.size());
for (Interval i : best) {
out.println((i.l + 1) + " " + (i.r + 1));
}
}
class Interval {
int l;
int r;
Interval(int l, int r) {
this.l = l;
this.r = r;
}
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isWhitespace(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 (!isWhitespace(c));
return res * sgn;
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Vector;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Stack;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author beginner1010
*/
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);
TaskF2 solver = new TaskF2();
solver.solve(1, in, out);
out.close();
}
static class TaskF2 {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
HashMap<Integer, Stack<Interval>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += a[j];
if (map.containsKey(sum) == false) {
map.put(sum, new Stack<>());
}
Stack<Interval> stack = map.get(sum);
if (stack.isEmpty() || stack.get(stack.size() - 1).r < i) {
stack.push(new Interval(i, j));
} else if (stack.get(stack.size() - 1).r >= j) {
stack.pop();
stack.push(new Interval(i, j));
}
}
}
Stack<Interval> best = new Stack<>();
for (Stack<Interval> stack : map.values()) {
if (best.size() < stack.size()) {
best = stack;
}
}
out.println(best.size());
for (Interval i : best) {
out.println((i.l + 1) + " " + (i.r + 1));
}
}
class Interval {
int l;
int r;
Interval(int l, int r) {
this.l = l;
this.r = r;
}
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isWhitespace(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 (!isWhitespace(c));
return res * sgn;
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
InputReader in = new InputReader(inputStream);
// for(int i=4;i<=4;i++) {
// InputStream uinputStream = new FileInputStream("shortcut.in");
// String f = i+".in";
// InputStream uinputStream = new FileInputStream(f);
// InputReader in = new InputReader(uinputStream);
// PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("shortcut.out")));
Task t = new Task();
t.solve(in, out);
out.close();
// }
}
static class Task {
public void solve(InputReader in, PrintWriter out) throws IOException {
int n = in.nextInt();
int arr[] = in.readIntArray(n);
int v[][] = new int[n][n];
int c=0;
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
for(int i=0;i<n;i++) {
for(int j=i;j<n;j++) {
v[i][j] = arr[j];
if(j>i) v[i][j] += v[i][j-1];
if(!mp.containsKey(v[i][j])) mp.put(v[i][j], c++);
}
}
ArrayList<seg>[] all = new ArrayList[c];
for(int i=0;i<c;i++) all[i] = new ArrayList<seg>();
for(int i=0;i<n;i++) {
for(int j=i;j<n;j++) {
int idx = mp.get(v[i][j]);
all[idx].add(new seg(i,j,v[i][j]));
}
}
for(int i=0;i<c;i++) Collections.sort(all[i]);
int max = Integer.MIN_VALUE;
int val = -1;
for(int i=0;i<c;i++) {
if(all[i].size()==0) continue;
int num=1;
int p=0;int q=p+1;
while(q<all[i].size()) {
if(all[i].get(q).s>all[i].get(p).e) {
p=q;
num++;
}
q++;
}
if(num>max) {
max=num;
val = i;
}
}
out.println(max);
StringBuilder sb = new StringBuilder();
int p=0;int q=p+1;
sb.append(all[val].get(0).toString());
while(q<all[val].size()) {
if(all[val].get(q).s>all[val].get(p).e) {
sb.append(all[val].get(q).toString());
p=q;
}
q++;
}
out.println(sb.toString());
}
public class seg implements Comparable<seg>{
int s; int e; int val;
public seg(int a, int b, int c) {
s=a;e=b;val=c;
}
@Override
public int compareTo(seg t) {
if(this.e==t.e) return this.s-t.s;
return this.e-t.e;
}
public String toString() {
return (s+1)+" "+(e+1)+"\n";
}
}
public int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
}
static class ArrayUtils {
static final long seed = System.nanoTime();
static final Random rand = new Random(seed);
public static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void shuffle(int[] a) {
for (int i = 0; i < a.length; i++) {
int j = rand.nextInt(i + 1);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
static class BIT{
int arr[];
int n;
public BIT(int a) {
n=a;
arr = new int[n];
}
int sum(int p) {
int s=0;
while(p>0) {
s+=arr[p];
p-=p&(-p);
}
return s;
}
void add(int p, int v) {
while(p<n) {
arr[p]+=v;
p+=p&(-p);
}
}
}
static class DSU{
int[] arr;
int[] sz;
public DSU(int n) {
arr = new int[n];
sz = new int[n];
for(int i=0;i<n;i++) arr[i] = i;
Arrays.fill(sz, 1);
}
public int find(int a) {
if(arr[a]!=a) arr[a] = find(arr[a]);
return arr[a];
}
public void union(int a, int b) {
int x = find(a);
int y = find(b);
if(x==y) return;
arr[x] = y;
sz[y] += sz[x];
}
public int size(int x) {
return sz[find(x)];
}
}
static class MinHeap<Key> implements Iterable<Key> {
private int maxN;
private int n;
private int[] pq;
private int[] qp;
private Key[] keys;
private Comparator<Key> comparator;
public MinHeap(int capacity){
if (capacity < 0) throw new IllegalArgumentException();
this.maxN = capacity;
n=0;
pq = new int[maxN+1];
qp = new int[maxN+1];
keys = (Key[]) new Object[capacity+1];
Arrays.fill(qp, -1);
}
public MinHeap(int capacity, Comparator<Key> c){
if (capacity < 0) throw new IllegalArgumentException();
this.maxN = capacity;
n=0;
pq = new int[maxN+1];
qp = new int[maxN+1];
keys = (Key[]) new Object[capacity+1];
Arrays.fill(qp, -1);
comparator = c;
}
public boolean isEmpty() { return n==0; }
public int size() { return n; }
public boolean contains(int i) {
if (i < 0 || i >= maxN) throw new IllegalArgumentException();
return qp[i] != -1;
}
public int peekIdx() {
if (n == 0) throw new NoSuchElementException("Priority queue underflow");
return pq[1];
}
public Key peek(){
if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
return keys[pq[1]];
}
public int poll(){
if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
int min = pq[1];
exch(1,n--);
down(1);
assert min==pq[n+1];
qp[min] = -1;
keys[min] = null;
pq[n+1] = -1;
return min;
}
public void update(int i, Key key) {
if (i < 0 || i >= maxN) throw new IllegalArgumentException();
if (!contains(i)) {
this.add(i, key);
}else {
keys[i] = key;
up(qp[i]);
down(qp[i]);
}
}
private void add(int i, Key x){
if (i < 0 || i >= maxN) throw new IllegalArgumentException();
if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue");
n++;
qp[i] = n;
pq[n] = i;
keys[i] = x;
up(n);
}
private void up(int k){
while(k>1&&less(k,k/2)){
exch(k,k/2);
k/=2;
}
}
private void down(int k){
while(2*k<=n){
int j=2*k;
if(j<n&&less(j+1,j)) j++;
if(less(k,j)) break;
exch(k,j);
k=j;
}
}
public boolean less(int i, int j){
if (comparator == null) {
return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0;
}
else {
return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0;
}
}
public void exch(int i, int j){
int swap = pq[i];
pq[i] = pq[j];
pq[j] = swap;
qp[pq[i]] = i;
qp[pq[j]] = j;
}
@Override
public Iterator<Key> iterator() {
// TODO Auto-generated method stub
return null;
}
}
private static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int zcurChar;
private int znumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (znumChars == -1)
throw new InputMismatchException();
if (zcurChar >= znumChars)
{
zcurChar = 0;
try
{
znumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (znumChars <= 0)
return -1;
}
return buf[zcurChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return nextString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public int[] readIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
static class Dumper {
static void print_int_arr(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_char_arr(char[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_double_arr(double[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_2d_arr(int[][] arr, int x, int y) {
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("---------------------");
}
static void print_2d_arr(boolean[][] arr, int x, int y) {
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("---------------------");
}
static void print(Object o) {
System.out.println(o.toString());
}
static void getc() {
System.out.println("here");
}
}
} | quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.BufferedInputStream;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.FilterInputStream;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Comparator;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jenish
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
F2SameSumBlocksHard solver = new F2SameSumBlocksHard();
solver.solve(1, in, out);
out.close();
}
static class F2SameSumBlocksHard {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
long arr[] = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = in.scanLong();
}
HashMap<Long, ArrayList<pair>> hm = new HashMap<>();
for (int i = 0; i < n; i++) {
long sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
if (hm.containsKey(sum)) {
hm.get(sum).add(new pair(i + 1, j + 1));
} else {
hm.put(sum, new ArrayList<>());
hm.get(sum).add(new pair(i + 1, j + 1));
}
}
}
long maxi_sum = -1;
long sum = 0;
for (Map.Entry<Long, ArrayList<pair>> k : hm.entrySet()) {
Collections.sort(k.getValue(), new Comparator<pair>() {
public int compare(pair o1, pair o2) {
return o1.r - o2.r;
}
});
int count = k.getValue().size() > 0 ? 1 : 0;
int index = 0;
for (int i = 1; i < k.getValue().size(); i++) {
if (k.getValue().get(i).l > k.getValue().get(index).r) {
count++;
index = i;
}
}
if (count > maxi_sum) {
maxi_sum = count;
sum = k.getKey();
}
}
out.println(maxi_sum);
ArrayList<pair> tt = hm.get(sum);
Collections.sort(tt, new Comparator<pair>() {
public int compare(pair o1, pair o2) {
return o1.r - o2.r;
}
});
out.println(tt.size() > 0 ? (tt.get(0).l + " " + tt.get(0).r) : (" "));
int index = 0;
for (int i = 1; i < tt.size(); i++) {
if (tt.get(i).l > tt.get(index).r) {
out.println(tt.get(i).l + " " + tt.get(i).r);
index = i;
}
}
}
class pair {
int l;
int r;
public pair(int l, int r) {
this.l = l;
this.r = r;
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() {
long I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.util.*;
import java.lang.*;
import java.io.*;
import java.awt.*;
// U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................
//JUst keep faith in ur strengths ..................................................
// ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219
// odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4
// FOR ANY ODD NO N : N,N-1,N-2
//ALL ARE PAIRWISE COPRIME
//THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS
// two consecutive odds are always coprime to each other
// two consecutive even have always gcd = 2 ;
// Rectangle r = new Rectangle(int x , int y,int widht,int height)
//Creates a rect. with bottom left cordinates as (x, y) and top right as ((x+width),(y+height))
//BY DEFAULT Priority Queue is MIN in nature in java
//to use as max , just push with negative sign and change sign after removal
// We can make a sieve of max size 1e7 .(no time or space issue)
// In 1e7 starting nos we have about 66*1e4 prime nos
public class Main
{
// static int[] arr = new int[100002] ;
// static int[] dp = new int[100002] ;
static PrintWriter out;
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}
String next(){
while(st==null || !st.hasMoreElements()){
try{
st= new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try{
str=br.readLine();
}
catch(IOException e){
e.printStackTrace();
}
return str;
}
}
////////////////////////////////////////////////////////////////////////////////////
public static int countDigit(long n)
{
return (int)Math.floor(Math.log10(n) + 1);
}
/////////////////////////////////////////////////////////////////////////////////////////
public static int sumOfDigits(long n)
{
if( n< 0)return -1 ;
int sum = 0;
while( n > 0)
{
sum = sum + (int)( n %10) ;
n /= 10 ;
}
return sum ;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
public static long arraySum(int[] arr , int start , int end)
{
long ans = 0 ;
for(int i = start ; i <= end ; i++)ans += arr[i] ;
return ans ;
}
/////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public static void swapArray(int[] arr , int start , int end)
{
while(start < end)
{
int temp = arr[start] ;
arr[start] = arr[end];
arr[end] = temp;
start++ ;end-- ;
}
}
//////////////////////////////////////////////////////////////////////////////////
static long factorial(long a)
{
if(a== 0L || a==1L)return 1L ;
return a*factorial(a-1L) ;
}
///////////////////////////////////////////////////////////////////////////////
public static int[][] rotate(int[][] input){
int n =input.length;
int m = input[0].length ;
int[][] output = new int [m][n];
for (int i=0; i<n; i++)
for (int j=0;j<m; j++)
output [j][n-1-i] = input[i][j];
return output;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// ////////////////////////////////////////////////
public static boolean isPowerOfTwo(long n)
{
if(n==0)
return false;
if(((n ) & (n-1)) == 0 ) return true ;
else return false ;
}
/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
public static String reverse(String input)
{
StringBuilder str = new StringBuilder("") ;
for(int i =input.length()-1 ; i >= 0 ; i-- )
{
str.append(input.charAt(i));
}
return str.toString() ;
}
///////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
public static boolean isPossibleTriangle(int a ,int b , int c)
{
if( a + b > c && c+b > a && a +c > b)return true ;
else return false ;
}
////////////////////////////////////////////////////////////////////////////////////////////
static long xnor(long num1, long num2) {
if (num1 < num2) {
long temp = num1;
num1 = num2;
num2 = temp;
}
num1 = togglebit(num1);
return num1 ^ num2;
}
static long togglebit(long n) {
if (n == 0)
return 1;
long i = n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return i ^ n;
}
///////////////////////////////////////////////////////////////////////////////////////////////
public static int xorOfFirstN(int n)
{
if( n % 4 ==0)return n ;
else if( n % 4 == 1)return 1 ;
else if( n % 4 == 2)return n+1 ;
else return 0 ;
}
//////////////////////////////////////////////////////////////////////////////////////////////
public static int gcd(int a, int b )
{
if(b==0)return a ;
else return gcd(b,a%b) ;
}
public static long gcd(long a, long b )
{
if(b==0)return a ;
else return gcd(b,a%b) ;
}
////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a, int b ,int c , int d )
{
int temp = lcm(a,b , c) ;
int ans = lcm(temp ,d ) ;
return ans ;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a, int b ,int c )
{
int temp = lcm(a,b) ;
int ans = lcm(temp ,c) ;
return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a , int b )
{
int gc = gcd(a,b);
return (a/gc)*b ;
}
public static long lcm(long a , long b )
{
long gc = gcd(a,b);
return (a/gc)*b;
}
///////////////////////////////////////////////////////////////////////////////////////////
static boolean isPrime(long n)
{
if(n==1)
{
return false ;
}
boolean ans = true ;
for(long i = 2L; i*i <= n ;i++)
{
if(n% i ==0)
{
ans = false ;break ;
}
}
return ans ;
}
static boolean isPrime(int n)
{
if(n==1)
{
return false ;
}
boolean ans = true ;
for(int i = 2; i*i <= n ;i++)
{
if(n% i ==0)
{
ans = false ;break ;
}
}
return ans ;
}
///////////////////////////////////////////////////////////////////////////
static int sieve = 1000000 ;
static boolean[] prime = new boolean[sieve + 1] ;
public static void sieveOfEratosthenes()
{
// FALSE == prime
// TRUE == COMPOSITE
// FALSE== 1
// time complexity = 0(NlogLogN)== o(N)
// gives prime nos bw 1 to N
for(int i = 4; i<= sieve ; i++)
{
prime[i] = true ;
i++ ;
}
for(int p = 3; p*p <= sieve; p++)
{
if(prime[p] == false)
{
for(int i = p*p; i <= sieve; i += p)
prime[i] = true;
}
p++ ;
}
}
///////////////////////////////////////////////////////////////////////////////////
public static void sortD(int[] arr , int s , int e)
{
sort(arr ,s , e) ;
int i =s ; int j = e ;
while( i < j)
{
int temp = arr[i] ;
arr[i] =arr[j] ;
arr[j] = temp ;
i++ ; j-- ;
}
return ;
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long countSubarraysSumToK(long[] arr ,long sum )
{
HashMap<Long,Long> map = new HashMap<>() ;
int n = arr.length ;
long prefixsum = 0 ;
long count = 0L ;
for(int i = 0; i < n ; i++)
{
prefixsum = prefixsum + arr[i] ;
if(sum == prefixsum)count = count+1 ;
if(map.containsKey(prefixsum -sum))
{
count = count + map.get(prefixsum -sum) ;
}
if(map.containsKey(prefixsum ))
{
map.put(prefixsum , map.get(prefixsum) +1 );
}
else{
map.put(prefixsum , 1L );
}
}
return count ;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// KMP ALGORITHM : TIME COMPL:O(N+M)
// FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING
//RETURN THE ARRAYLIST OF INDEXES
// IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING
public static ArrayList<Integer> kmpAlgorithm(String str , String pat)
{
ArrayList<Integer> list =new ArrayList<>();
int n = str.length() ;
int m = pat.length() ;
String q = pat + "#" + str ;
int[] lps =new int[n+m+1] ;
longestPefixSuffix(lps, q,(n+m+1)) ;
for(int i =m+1 ; i < (n+m+1) ; i++ )
{
if(lps[i] == m)
{
list.add(i-2*m) ;
}
}
return list ;
}
public static void longestPefixSuffix(int[] lps ,String str , int n)
{
lps[0] = 0 ;
for(int i = 1 ; i<= n-1; i++)
{
int l = lps[i-1] ;
while( l > 0 && str.charAt(i) != str.charAt(l))
{
l = lps[l-1] ;
}
if(str.charAt(i) == str.charAt(l))
{
l++ ;
}
lps[i] = l ;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n
// TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1
// or n and the no will be coprime in nature
//time : O(n*(log(logn)))
public static void eulerTotientFunction(int[] arr ,int n )
{
for(int i = 1; i <= n ;i++)arr[i] =i ;
for(int i= 2 ; i<= n ;i++)
{
if(arr[i] == i)
{
arr[i] =i-1 ;
for(int j =2*i ; j<= n ; j+= i )
{
arr[j] = (arr[j]*(i-1))/i ;
}
}
}
return ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long nCr(int n,int k)
{
long ans=1L;
k=k>n-k?n-k:k;
int j=1;
for(;j<=k;j++,n--)
{
if(n%j==0)
{
ans*=n/j;
}else
if(ans%j==0)
{
ans=ans/j*n;
}else
{
ans=(ans*n)/j;
}
}
return ans;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static ArrayList<Integer> allFactors(int n)
{
ArrayList<Integer> list = new ArrayList<>() ;
for(int i = 1; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)
{
list.add(i) ;
}
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
public static ArrayList<Long> allFactors(long n)
{
ArrayList<Long> list = new ArrayList<>() ;
for(long i = 1L; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)
{
list.add(i) ;
}
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static final int MAXN = 1000001;
static int spf[] = new int[MAXN];
static void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
spf[i] = i;
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
if (spf[i] == i)
{
for (int j=i*i; j<MAXN; j+=i)
if (spf[j]==j)
spf[j] = i;
}
}
}
static ArrayList<Integer> getPrimeFactorization(int x)
{
ArrayList<Integer> ret = new ArrayList<Integer>();
while (x != 1)
{
ret.add(spf[x]);
x = x / spf[x];
}
return ret;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
public static void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void sort(long arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void merge(long arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long[n1];
long R[] = new long[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long knapsack(int[] weight,long value[],int maxWeight){
int n= value.length ;
//dp[i] stores the profit with KnapSack capacity "i"
long []dp = new long[maxWeight+1];
//initially profit with 0 to W KnapSack capacity is 0
Arrays.fill(dp, 0);
// iterate through all items
for(int i=0; i < n; i++)
//traverse dp array from right to left
for(int j = maxWeight; j >= weight[i]; j--)
dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]);
/*above line finds out maximum of dp[j](excluding ith element value)
and val[i] + dp[j-wt[i]] (including ith element value and the
profit with "KnapSack capacity - ith element weight") */
return dp[maxWeight];
}
///////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
// to return max sum of any subarray in given array
public static long kadanesAlgorithm(long[] arr)
{
if(arr.length == 0)return 0 ;
long[] dp = new long[arr.length] ;
dp[0] = arr[0] ;
long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0)
{
dp[i] = dp[i-1] + arr[i] ;
}
else{
dp[i] = arr[i] ;
}
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long kadanesAlgorithm(int[] arr)
{
if(arr.length == 0)return 0 ;
long[] dp = new long[arr.length] ;
dp[0] = arr[0] ;
long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0)
{
dp[i] = dp[i-1] + arr[i] ;
}
else{
dp[i] = arr[i] ;
}
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
///////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
//TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING
// JUST CALL generatePermutation( str, start, end) start :inclusive ,end : exclusive
//Function for swapping the characters at position I with character at position j
public static String swapString(String a, int i, int j) {
char[] b =a.toCharArray();
char ch;
ch = b[i];
b[i] = b[j];
b[j] = ch;
return String.valueOf(b);
}
//Function for generating different permutations of the string
public static void generatePermutation(String str, int start, int end)
{
//Prints the permutations
if (start == end-1)
System.out.println(str);
else
{
for (int i = start; i < end; i++)
{
//Swapping the string by fixing a character
str = swapString(str,start,i);
//Recursively calling function generatePermutation() for rest of the characters
generatePermutation(str,start+1,end);
//Backtracking and swapping the characters again.
str = swapString(str,start,i);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
public static long factMod(long n, long mod) {
if (n <= 1) return 1;
long ans = 1;
for (int i = 1; i <= n; i++) {
ans = (ans * i) % mod;
}
return ans;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static long power(int a ,int b)
{
//time comp : o(logn)
long x = (long)(a) ;
long n = (long)(b) ;
if(n==0)return 1 ;
if(n==1)return x;
long ans =1L ;
while(n>0)
{
if(n % 2 ==1)
{
ans = ans *x ;
}
n = n/2L ;
x = x*x ;
}
return ans ;
}
public static long power(long a ,long b)
{
//time comp : o(logn)
long x = (a) ;
long n = (b) ;
if(n==0)return 1L ;
if(n==1)return x;
long ans =1L ;
while(n>0)
{
if(n % 2 ==1)
{
ans = ans *x ;
}
n = n/2L ;
x = x*x ;
}
return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
public static long powerMod(long x, long n, long mod) {
//time comp : o(logn)
if(n==0)return 1L ;
if(n==1)return x;
long ans = 1;
while (n > 0) {
if (n % 2 == 1) ans = (ans * x) % mod;
x = (x * x) % mod;
n /= 2;
}
return ans;
}
//////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/*
lowerBound - finds largest element equal or less than value paased
upperBound - finds smallest element equal or more than value passed
if not present return -1;
*/
public static long lowerBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static int lowerBound(int[] arr,int k)
{
int ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static long upperBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
public static int upperBound(int[] arr,int k)
{
int ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
//////////////////////////////////////////////////////////////////////////////////////////
public static void printArray(int[] arr , int si ,int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
}
public static void printArrayln(int[] arr , int si ,int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
out.println() ;
}
public static void printLArray(long[] arr , int si , int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
}
public static void printLArrayln(long[] arr , int si , int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
out.println() ;
}
public static void printtwodArray(int[][] ans)
{
for(int i = 0; i< ans.length ; i++)
{
for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" ");
out.println() ;
}
out.println() ;
}
static long modPow(long a, long x, long p) {
//calculates a^x mod p in logarithmic time.
a = a % p ;
if(a == 0)return 0L ;
long res = 1L;
while(x > 0) {
if( x % 2 != 0) {
res = (res * a) % p;
}
a = (a * a) % p;
x =x/2;
}
return res;
}
static long modInverse(long a, long p) {
//calculates the modular multiplicative of a mod p.
//(assuming p is prime).
return modPow(a, p-2, p);
}
static long[] factorial = new long[1000001] ;
static void modfac(long mod)
{
factorial[0]=1L ; factorial[1]=1L ;
for(int i = 2; i<= 1000000 ;i++)
{
factorial[i] = factorial[i-1] *(long)(i) ;
factorial[i] = factorial[i] % mod ;
}
}
static long modBinomial(long n, long r, long p) {
// calculates C(n,r) mod p (assuming p is prime).
if(n < r) return 0L ;
long num = factorial[(int)(n)] ;
long den = (factorial[(int)(r)]*factorial[(int)(n-r)]) % p ;
long ans = num*(modInverse(den,p)) ;
ans = ans % p ;
return ans ;
}
static void update(int val , long[] bit ,int n)
{
for( ; val <= n ; val += (val &(-val)) )
{
bit[val]++ ;
}
}
static long query(int val , long[] bit , int n)
{
long ans = 0L;
for( ; val >=1 ; val-=(val&(-val)) )ans += bit[val];
return ans ;
}
static int countSetBits(long n)
{
int count = 0;
while (n > 0) {
n = (n) & (n - 1L);
count++;
}
return count;
}
static int abs(int x)
{
if(x < 0)x = -1*x ;
return x ;
}
static long abs(long x)
{
if(x < 0)x = -1L*x ;
return x ;
}
////////////////////////////////////////////////////////////////////////////////////////////////
static void p(int val)
{
out.print(val) ;
}
static void p()
{
out.print(" ") ;
}
static void pln(int val)
{
out.println(val) ;
}
static void pln()
{
out.println() ;
}
static void p(long val)
{
out.print(val) ;
}
static void pln(long val)
{
out.println(val) ;
}
////////////////////////////////////////////////////////////////////////////////////////////
// calculate total no of nos greater than or equal to key in sorted array arr
static int bs(int[] arr, int s ,int e ,int key)
{
if( s> e)return 0 ;
int mid = (s+e)/2 ;
if(arr[mid] <key)
{
return bs(arr ,mid+1,e , key) ;
}
else{
return bs(arr ,s ,mid-1, key) + e-mid+1;
}
}
// static ArrayList<Integer>[] adj ;
// static int mod= 1000000007 ;
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
public static void solve()
{
FastReader scn = new FastReader() ;
//Scanner scn = new Scanner(System.in);
//int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ;
// product of first 11 prime nos is greater than 10 ^ 12;
//sieve() ;
//ArrayList<Integer> arr[] = new ArrayList[n] ;
ArrayList<Integer> list = new ArrayList<>() ;
ArrayList<Long> lista = new ArrayList<>() ;
ArrayList<Long> listb = new ArrayList<>() ;
// ArrayList<Integer> lista = new ArrayList<>() ;
// ArrayList<Integer> listb = new ArrayList<>() ;
//ArrayList<String> lists = new ArrayList<>() ;
HashMap<Integer,ArrayList<Pair>> map = new HashMap<>() ;
//HashMap<Long,Long> map = new HashMap<>() ;
HashMap<Integer,Integer> mapx = new HashMap<>() ;
HashMap<Integer,Integer> mapy = new HashMap<>() ;
//HashMap<String,Integer> maps = new HashMap<>() ;
//HashMap<Integer,Boolean> mapb = new HashMap<>() ;
//HashMap<Point,Integer> point = new HashMap<>() ;
Set<Integer> set = new HashSet<>() ;
Set<Integer> setx = new HashSet<>() ;
Set<Integer> sety = new HashSet<>() ;
StringBuilder sb =new StringBuilder("") ;
//Collections.sort(list);
//if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ;
//else map.put(arr[i],1) ;
// if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ;
// else map.put(temp,1) ;
//int bit =Integer.bitCount(n);
// gives total no of set bits in n;
// Arrays.sort(arr, new Comparator<Pair>() {
// @Override
// public int compare(Pair a, Pair b) {
// if (a.first != b.first) {
// return a.first - b.first; // for increasing order of first
// }
// return a.second - b.second ; //if first is same then sort on second basis
// }
// });
int testcase = 1;
//testcase = scn.nextInt() ;
for(int testcases =1 ; testcases <= testcase ;testcases++)
{
//if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ;
//if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ;
//adj = new ArrayList[n] ;
// for(int i = 0; i< n; i++)
// {
// adj[i] = new ArrayList<Integer>();
// }
// long n = scn.nextLong() ;
//String s = scn.next() ;
int n= scn.nextInt() ;
int[] arr= new int[n] ;
for(int i=0; i < n;i++)
{
arr[i]= scn.nextInt();
}
for(int r= 0 ; r < n ;r++)
{
int sum = 0 ;
for(int l =r ;l>= 0 ;l--)
{
sum = sum + arr[l] ;
if(map.containsKey(sum))
{
map.get(sum).add(new Pair(l,r)) ;
}
else{
map.put(sum,new ArrayList<Pair>());
map.get(sum).add(new Pair(l,r)) ;
}
}
}
ArrayList<Pair> ans = null ;
int bestcount = 0 ;
for(int x : map.keySet())
{
ArrayList<Pair> curr = map.get(x) ;
ArrayList<Pair> now = new ArrayList<Pair>() ;
int r=-1 ;
int count = 0 ;
for(Pair seg : curr)
{
if(seg.first > r)
{
count++ ;
now.add(seg) ;
r= seg.second ;
}
}
if(count > bestcount)
{
ans = now ;
bestcount = count ;
}
}
pln(bestcount) ;
if(bestcount >0)
{
for(Pair x : ans)
{
out.println((x.first+1) +" " +( x.second+1)) ;
}
}
//out.println(ans) ;
//out.println(ans+" "+in) ;
//out.println("Case #" + testcases + ": " + ans ) ;
//out.println("@") ;
set.clear() ;
sb.delete(0 , sb.length()) ;
list.clear() ;lista.clear() ;listb.clear() ;
map.clear() ;
mapx.clear() ;
mapy.clear() ;
setx.clear() ;sety.clear() ;
} // test case end loop
out.flush() ;
} // solve fn ends
public static void main (String[] args) throws java.lang.Exception
{
solve() ;
}
}
class Pair
{
int first ;
int second ;
public Pair(int l , int r)
{
first = l ;second = r ;
}
@Override
public String toString() {
String ans = "" ;
ans += this.first ;
ans += " ";
ans += this.second ;
return ans ;
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | CODEFORCES |
import java.io.*;
import java.util.*;
import java.awt.Point;
public class CF_1141F2 {
public static void main(String args[]) throws Exception {
BufferedScanner in = new BufferedScanner(new InputStreamReader(System.in));
PrintStream out = new PrintStream(new BufferedOutputStream(System.out));
int n = in.nextInt();
int[] arr = in.nextN(n);
HashMap<Integer, ArrayList<Point>> lp = new HashMap<>();
for (int i = 0; i < n; i++) {
int curr = 0;
for (int j = i; j >= 0; j--) {
curr += arr[j];
if (!lp.containsKey(curr)) lp.put(curr, new ArrayList<>());
lp.get(curr).add(new Point(j, i));
}
}
ArrayList<Point> retPs = new ArrayList<>();
for (ArrayList<Point> ps : lp.values()) {
Collections.sort(ps, (a, b) -> a.y - b.y);
ArrayList<Point> currPs = new ArrayList<>();
for (int i = 0; i < ps.size(); ) {
Point curr = ps.get(i);
currPs.add(curr);
while (i < ps.size() && ps.get(i).x <= curr.y) i++;
}
if(currPs.size() > retPs.size()) retPs = currPs;
}
out.println(retPs.size());
for (Point p : retPs) out.println((p.x + 1) + " " + (p.y + 1));
out.close();
in.close();
}
static class BufferedScanner {
private BufferedReader in;
private StringTokenizer st;
BufferedScanner(Reader in) throws IOException {
this.in = new BufferedReader(in);
st = new StringTokenizer(this.in.readLine());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
int[] nextN(int n) throws IOException {
int[] ret = new int[n];
for (int i = 0; i < n; i++) ret[i] = this.nextInt();
return ret;
}
long[] nextNL(int n) throws IOException {
long[] ret = new long[n];
for (int i = 0; i < n; i++) ret[i] = this.nextLong();
return ret;
}
String next() throws IOException {
if (!st.hasMoreElements()) st = new StringTokenizer(in.readLine());
return st.nextToken();
}
void close() throws IOException {
in.close();
}
}
}
| quadratic | 1141_F2. Same Sum Blocks (Hard) | 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.