src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
import static java.lang.Integer.compare; import static java.util.Comparator.comparingInt; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; public class SameSumBlocks { public static void main(String[] args) { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String[] numbersAsString = input.lines() .skip(1) .findFirst() .get() .split(" "); int[] numbers = Arrays.stream(numbersAsString).mapToInt(Integer::parseInt).toArray(); List<PairOfInt> sameSumBlocks = findSameSumBlocks(numbers); System.out.println(sameSumBlocks.size()); sameSumBlocks.forEach(System.out::println); } static List<PairOfInt> findSameSumBlocks(int[] numbers) { List<List<PairOfInt>> potentials = buildPotentialsSum(numbers); List<List<PairOfInt>> sortedPairList = potentials.stream() .filter(p -> p.size() > 0) .sorted((l1, l2) -> compare(l2.size(), l1.size())) .collect(Collectors.toList()); List<PairOfInt> max = new ArrayList<>(); max.add(PairOfInt.of(1, 1)); for (int i = 0; i < sortedPairList.size(); i++) { List<PairOfInt> result = sortedPairList.get(i); result.sort(comparingInt(p -> p.b)); List<PairOfInt> maxDisjoint = maxDisjointPair(result); if (maxDisjoint.size() > max.size()) { max = maxDisjoint; if (i + 1 < sortedPairList.size() && maxDisjoint.size() >= sortedPairList.get(i + 1).size()) { return maxDisjoint; } } } return max; } public static List<PairOfInt> maxDisjointPair(List<PairOfInt> result) { if (result.size() == 0) return result; boolean over = false; while (!over) { int i; for (i = 1; i < result.size(); i++) { if (result.get(i).a <= result.get(i - 1).b) { result.remove(result.get(i)); break; } } if (i == result.size()) { over = true; } } return result; } private static List<List<PairOfInt>> buildPotentialsSum(int[] numbers) { Map<Integer, List<PairOfInt>> result = new HashMap<>(); for (int i = 0; i < numbers.length; i++) { int blockSum = 0; for (int j = i; j < numbers.length; j++) { blockSum += numbers[j]; final int tmpi = i, tmpj = j; result.compute(blockSum, (k, l) -> { if (l == null) { l = new ArrayList<>(); } l.add(PairOfInt.of(tmpi + 1, tmpj + 1)); return l; }); if(blockSum == 0) { break; } } } return new ArrayList<>(result.values()); } public static class PairOfInt { final int a, b; public static PairOfInt of(int a, int b) { return new PairOfInt(a, b); } private PairOfInt(int a, int b) { this.a = a; this.b = b; } @Override public String toString() { return a + " " + b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairOfInt pairOfInt = (PairOfInt) o; return a == pairOfInt.a && b == pairOfInt.b; } @Override public int hashCode() { return Objects.hash(a, b); } } }
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.util.List; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author prakharjain */ 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); long[] p = in.calculatePrefixSum(a); Map<Long, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { long sum = 0; for (int j = i; j < n; j++) { sum += a[j]; map.merge(sum, 1, (x, y) -> x + y); } } List<sum> sums = new ArrayList<>(); for (long sum : map.keySet()) { sums.add(new sum(sum, map.get(sum))); } sums.sort((x, y) -> y.c - x.c); int ans = -1; int[] fca = null; long mxsum = -1; for (int i = 0; i < sums.size(); i++) { sum cs = sums.get(i); long sum = cs.sum; long c = cs.c; if (c < ans) { continue; } Map<Long, Integer> lm = new HashMap<>(); int[] ca = new int[n]; lm.put(0l, -1); for (int j = 0; j < n; j++) { long val = p[j]; if (j > 0) { ca[j] = ca[j - 1]; } long req = val - sum; if (lm.containsKey(req)) { int li = lm.get(req); if (li == -1) ca[j] = Math.max(1, ca[j]); else ca[j] = Math.max(1 + ca[li], ca[j]); } lm.put(val, j); } if (ca[n - 1] > ans) { ans = ca[n - 1]; mxsum = sum; fca = ca; } } List<Integer> al = new ArrayList<>(); long sum = 0; for (int i = n - 1; i >= 0; i--) { if (i > 0 && fca[i] != fca[i - 1]) { sum = 0; al.add(i + 1); do { sum += a[i]; i--; } while (i >= 0 && sum != mxsum); i++; al.add(i + 1); } else if (i == 0) { if (a[i] == mxsum) { al.add(i + 1); al.add(i + 1); } } } out.println(al.size() / 2); for (int i = al.size() - 1; i >= 0; i -= 2) { out.println(al.get(i) + " " + al.get(i - 1)); } } class sum { long sum; int c; public sum(long sum, int c) { this.sum = sum; this.c = c; } } } 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 static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; ++i) array[i] = nextLong(); return array; } public long[] calculatePrefixSum(long[] a) { int n = a.length; long[] prefixSum = new long[n]; prefixSum[0] = a[0]; for (int i = 1; i < n; i++) { prefixSum[i] = prefixSum[i - 1] + a[i]; } return prefixSum; } 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.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.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(); List<Range> ranges = rgs.get(sum); 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.*; public class Solution { public static void main(String[] args) { class Pair { int start; int end; public Pair(int start, int end) { this.start = start; this.end = end; } } 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 maxLen = 0; int key = -1; HashMap<Integer, List<Pair>> ans = new HashMap<>(); for (int i=0; i<n; i++){ int currSum = 0; for (int j=i; j>=0; j--){ currSum = currSum + array[j]; if (!ans.containsKey(currSum)){ ans.put(currSum, new ArrayList<>()); } List<Pair> pairs = ans.get(currSum); if (pairs.size() == 0 || pairs.get(pairs.size()-1).end <= j){ pairs.add(new Pair(j+1, i+1)); } if (pairs.size() > maxLen){ maxLen = pairs.size(); key = currSum; } } } System.out.println(maxLen); for (Pair pair : ans.get(key)){ System.out.println(pair.start + " " + pair.end); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.InputMismatchException; import java.util.List; public class Q6 { public static void main(String[] args) { InputReader s = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t = 1; // t = s.nextInt(); nexttest: while (t-- > 0) { int n = s.nextInt(); int a[] = s.nextIntArray(n); HashMap<Integer, List<Pair>> sets = new HashMap<>(); int pre[] = new int[n + 1]; for (int i = 1; i <= n; i++) { pre[i] = a[i - 1] + pre[i - 1]; } for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { final Integer key = pre[j] - pre[i - 1]; if (!sets.containsKey(key)) { sets.put(key, new ArrayList<>()); } sets.get(key).add(new Pair(i, j)); } } // System.out.println(sets); int ans = 0; List<Pair> answer = new ArrayList<>(); int[] ansNextPos = new int[1]; boolean[] ansTaken = new boolean[1]; for (List<Pair> intervals : sets.values()) { Collections.sort(intervals); int[] nextPos = new int[intervals.size()]; boolean[] taken = new boolean[intervals.size()]; int[] dp = new int[intervals.size()]; dp[intervals.size() - 1] = 1; taken[intervals.size() - 1] = true; nextPos[intervals.size() - 1] = -1; for (int i = intervals.size() - 2; i >= 0; i--) { dp[i] = dp[i + 1]; taken[i] = false; nextPos[i] = i + 1; int ll = i + 1; int rr = intervals.size(); while (ll < rr) { int mid = ll + rr; mid /= 2; if (intervals.get(mid).x > intervals.get(i).y) { rr = mid; } else { ll = mid + 1; } } if (ll < intervals.size()) { if (dp[i] < 1 + dp[ll]) { dp[i] = Math.max(dp[i], 1 + dp[ll]); taken[i] = true; nextPos[i] = ll; } } } if (dp[0] > ans) { ans = dp[0]; answer = intervals; ansNextPos = nextPos; ansTaken = taken; } } out.println(ans); int cur = 0; while (cur != -1) { if (ansTaken[cur]) { out.println(answer.get(cur)); } cur = ansNextPos[cur]; } } out.close(); } static class Pair implements Comparable<Pair> { int x; int y; @Override public String toString() { return x + " " + y; } public Pair(final int x, final int y) { this.x = x; this.y = y; } @Override public int compareTo(final Pair o) { return this.x - o.x; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, 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 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); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
// Don't place your source in a package import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(System.out); int T=1; for(int t=0;t<T;t++){ int n=Int(); int A[]=new int[n]; for(int i=0;i<n;i++){ A[i]=Int(); } Solution sol=new Solution(); sol.solution(out,A); } out.flush(); } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution{ public void solution(PrintWriter out,int A[]){ Map<Integer,List<int[]>>f=new HashMap<>(); List<int[]>res=new ArrayList<>(); for(int i=0;i<A.length;i++){ int sum=0; for(int j=i;j<A.length;j++){ sum+=A[j]; if(!f.containsKey(sum))f.put(sum,new ArrayList<>()); List<int[]>list=f.get(sum); list.add(new int[]{i,j}); } } for(Integer key:f.keySet()){ List<int[]>list=f.get(key); Collections.sort(list,(a,b)->{ return a[1]-b[1]; }); int pre[]=new int[list.size()]; Arrays.fill(pre,-1); int dp[][]=new int[list.size()][2]; dp[0][0]=1; dp[0][1]=0; for(int i=1;i<list.size();i++){ int pair[]=list.get(i); int l=0,r=i-1; int pos=-1; while(l<=r){ int mid=l+(r-l)/2; if(list.get(mid)[1]<pair[0]){ pos=mid; l=mid+1; } else{ r=mid-1; } } if(pos!=-1){ int mx=1+dp[pos][0]; if(mx>=dp[i-1][0]){ dp[i][0]=mx; dp[i][1]=i; pre[i]=dp[pos][1]; } else{ dp[i][0]=dp[i-1][0]; dp[i][1]=dp[i-1][1]; } } else{ dp[i][0]=dp[i-1][0]; dp[i][1]=dp[i-1][1]; } } int n=list.size(); if(dp[n-1][0]>res.size()){ res=new ArrayList<>(); int j=dp[n-1][1]; while(j!=-1){ res.add(list.get(j)); j=pre[j]; } } } out.println(res.size()); for(int p[]:res){ out.println((p[0]+1)+" "+(p[1]+1)); } } } /* ;\ |' \ _ ; : ; / `-. /: : | | ,-.`-. ,': : | \ : `. `. ,'-. : | \ ; ; `-.__,' `-.| \ ; ; ::: ,::'`:. `. \ `-. : ` :. `. \ \ \ , ; ,: (\ \ :., :. ,'o)): ` `-. ,/,' ;' ,::"'`.`---' `. `-._ ,/ : ; '" `;' ,--`. ;/ :; ; ,:' ( ,:) ,.,:. ; ,:., ,-._ `. \""'/ '::' `:'` ,'( \`._____.-'"' ;, ; `. `. `._`-. \\ ;:. ;: `-._`-.\ \`. '`:. : |' `. `\ ) \ -hrr- ` ;: | `--\__,' '` ,' ,-' free bug dog */
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import javax.print.attribute.standard.PrinterMessageFromOperator; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws Exception { new Main().run();} // int[] h,ne,to,wt; // int ct = 0; // int n; // void graph(int n,int m){ // h = new int[n]; // Arrays.fill(h,-1); //// sccno = new int[n]; //// dfn = new int[n]; //// low = new int[n]; //// iscut = new boolean[n]; // ne = new int[2*m]; // to = new int[2*m]; // wt = new int[2*m]; // ct = 0; // } // void add(int u,int v,int w){ // to[ct] = v; // ne[ct] = h[u]; // wt[ct] = w; // h[u] = ct++; // } // // int color[],dfn[],low[],stack[] = new int[1000000],cnt[]; // int sccno[]; // boolean iscut[]; // int time = 0,top = 0; // int scc_cnt = 0; // // // 有向图的强连通分量 // void tarjan(int u) { // low[u] = dfn[u]= ++time; // stack[top++] = u; // for(int i=h[u];i!=-1;i=ne[i]) { // int v = to[i]; // if(dfn[v]==0) { // tarjan(v); // low[u]=Math.min(low[u],low[v]); // } else if(sccno[v]==0) { // // dfn>0 but sccno==0, means it's in current stack // low[u]=Math.min(low[u],low[v]); // } // } // // if(dfn[u]==low[u]) { // sccno[u] = ++scc_cnt; // while(stack[top-1]!=u) { // sccno[stack[top-1]] = scc_cnt; // --top; // } // --top; // } // } // // //缩点, topology sort // int[] h1,to1,ne1; // int ct1 = 0; // void point(){ // for(int i=0;i<n;i++) { // if(dfn[i]==0) tarjan(i);//有可能图不连通,所以要循环判断。 // } // // 入度 // int du[] = new int[scc_cnt+1]; // h1 = new int[scc_cnt+1]; // Arrays.fill(h1, -1); // to1 = new int[scc_cnt*scc_cnt]; // ne1 = new int[scc_cnt*scc_cnt]; // // scc_cnt 个点 // // for(int i=1;i<=n;i++) { // for(int j=h[i]; j!=-1; j=ne[j]) { // int y = to[j]; // if(sccno[i] != sccno[y]) { // // add(sccno[i],sccno[y]); // 建新图 // to1[ct1] = sccno[y]; // ne1[ct1] = h[sccno[i]]; // h[sccno[i]] = ct1++; // du[sccno[y]]++; //存入度 // } // } // } // // int q[] = new int[100000]; // int end = 0; // int st = 0; // for(int i=1;i<=scc_cnt;++i){ // if(du[i]==0){ // q[end++] = i; // } // } // // int dp[] = new int[scc_cnt+1]; // while(st<end){ // int cur = q[st++]; // for(int i=h1[cur];i!=-1;i=ne1[i]){ // int y = to[i]; // // dp[y] += dp[cur]; // if(--du[y]==0){ // q[end++] = y; // } // } // } // } // // // // // int fa[]; // int faw[]; // // int dep = -1; // int pt = 0; // void go(int rt,int f,int dd){ // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = f;p++; // while(p>0) { // int cur = stk[p - 1]; // int fp = fk[p - 1]; // int ll = lk[p - 1]; // p--; // // // if (ll > dep) { // dep = ll; // pt = cur; // } // for (int i = h[cur]; i != -1; i = ne[i]) { // int v = to[i]; // if (fp == v) continue; // // stk[p] = v; // lk[p] = ll + wt[i]; // fk[p] = cur; // p++; // } // } // } // int pt1 = -1; // void go1(int rt,int f,int dd){ // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = f;p++; // while(p>0) { // int cur = stk[p - 1]; // int fp = fk[p - 1]; // int ll = lk[p - 1]; // p--; // // // if (ll > dep) { // dep = ll; // pt1 = cur; // } // // fa[cur] = fp; // for (int i = h[cur]; i != -1; i = ne[i]) { // int v = to[i]; // if (v == fp) continue; // faw[v] = wt[i]; // stk[p] = v; // lk[p] = ll + wt[i]; // fk[p] = cur; // p++; // } // } // } // // int r = 0; // int stk[] = new int[301]; // int fk[] = new int[301]; // int lk[] = new int[301]; // void ddfs(int rt,int t1,int t2,int t3,int l){ // // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = t3;p++; // while(p>0){ // int cur = stk[p-1]; // int fp = fk[p-1]; // int ll = lk[p-1]; // p--; // r = Math.max(r,ll); // for(int i=h[cur];i!=-1;i=ne[i]){ // int v = to[i]; // if(v==t1||v==t2||v==fp) continue; // stk[p] = v; // lk[p] = ll+wt[i]; // fk[p] = cur;p++; // } // } // // // // } static long mul(long a, long b, long p) { long res=0,base=a; while(b>0) { if((b&1L)>0) res=(res+base)%p; base=(base+base)%p; b>>=1; } return res; } static long mod_pow(long k,long n,long p){ long res = 1L; long temp = k; while(n!=0L){ if((n&1L)==1L){ res = (res*temp)%p; } temp = (temp*temp)%p; n = n>>1L; } return res%p; } int ct = 0; int f[] =new int[200001]; int b[] =new int[200001]; int str[] =new int[200001]; void go(int rt,List<Integer> g[]){ str[ct] = rt; f[rt] = ct; for(int cd:g[rt]){ ct++; go(cd,g); } b[rt] = ct; } int add =0; void go(int rt,int sd,int k,List<Integer> g[],int n){ if(add>n) { return; } Queue<Integer> q =new LinkedList<>(); q.offer(rt); for(int i=1;i<=sd;++i){ int sz =q.size(); if(sz==0) break; int f = (i==1?2:1); while(sz-->0){ int cur = q.poll(); for(int j=0;j<k-f;++j){ q.offer(add); g[cur].add(add);add++; if(add==n+1){ return; } } } } } void solve() { int n = ni(); long s[] = new long[n+1]; for(int i=0;i<n;++i){ s[i+1] = s[i] + ni(); } Map<Long,List<int[]>> mp = new HashMap<>(); for(int i=0;i<n;++i) { for (int j = i; j>=0; --j) { long v = s[i+1]-s[j]; if(!mp.containsKey(v)){ mp.put(v, new ArrayList<>()); } mp.get(v).add(new int[]{j,i}); } } int all = 0;long vv = -1; for(long v:mp.keySet()){ List<int[]> r = mp.get(v); int sz = r.size();int c = 0; int ri = -2000000000; for(int j=0;j<sz;++j){ if(r.get(j)[0]>ri){ ri = r.get(j)[1];c++; } } if(c>all){ all = c; vv = v; } } println(all); List<int[]> r = mp.get(vv); int sz = r.size();int c = 0; int ri = -2000000000; for(int j=0;j<sz;++j){ if(r.get(j)[0]>ri){ ri = r.get(j)[1];println((1+r.get(j)[0])+" "+(1+r.get(j)[1])); } } //N , M , K , a , b , c , d . 其中N , M是矩阵的行列数;K 是上锁的房间数目,(a, b)是起始位置,(c, d)是出口位置 // int n = ni(); // int m = ni(); // int k = ni(); // int a = ni(); // int b = ni(); // int c = ni(); // int d = ni(); // // // char cc[][] = nm(n,m); // char keys[][] = new char[n][m]; // // char ky = 'a'; // for(int i=0;i<k;++i){ // int x = ni(); // int y = ni(); // keys[x][y] = ky; // ky++; // } // int f1[] = {a,b,0}; // // int dd[][] = {{0,1},{0,-1},{1,0},{-1,0}}; // // Queue<int[]> q = new LinkedList<>(); // q.offer(f1); // int ts = 1; // // boolean vis[][][] = new boolean[n][m][33]; // // while(q.size()>0){ // int sz = q.size(); // while(sz-->0) { // int cur[] = q.poll(); // vis[cur[0]][cur[1]][cur[2]] = true; // // int x = cur[0]; // int y = cur[1]; // // for (int u[] : dd) { // int lx = x + u[0]; // int ly = y + u[1]; // if (lx >= 0 && ly >= 0 && lx < n && ly < m && (cc[lx][ly] != '#')&&!vis[lx][ly][cur[2]]){ // char ck =cc[lx][ly]; // if(ck=='.'){ // if(lx==c&&ly==d){ // println(ts); return; // } // if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') { // int cao = cur[2] | (1 << (keys[lx][ly] - 'a')); // q.offer(new int[]{lx, ly, cao}); // vis[lx][ly][cao] = true; // }else { // // q.offer(new int[]{lx, ly, cur[2]}); // } // // }else if(ck>='A'&&ck<='Z'){ // int g = 1<<(ck-'A'); // if((g&cur[2])>0){ // if(lx==c&&ly==d){ // println(ts); return; // } // if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') { // // int cao = cur[2] | (1 << (keys[lx][ly] - 'a')); // q.offer(new int[]{lx, ly, cao}); // vis[lx][ly][cao] = true;; // }else { // // q.offer(new int[]{lx, ly, cur[2]}); // } // } // } // } // } // // } // ts++; // } // println(-1); // int n = ni(); // // HashSet<String> st = new HashSet<>(); // HashMap<String,Integer> mp = new HashMap<>(); // // // for(int i=0;i<n;++i){ // String s = ns(); // int id= 1; // if(mp.containsKey(s)){ // int u = mp.get(s); // id = u; // // } // // if(st.contains(s)) { // // while (true) { // String ts = s + id; // if (!st.contains(ts)) { // s = ts; // break; // } // id++; // } // mp.put(s,id+1); // }else{ // mp.put(s,1); // } // println(s); // st.add(s); // // } // int t = ni(); // // for(int i=0;i<t;++i){ // int n = ni(); // long w[] = nal(n); // // Map<Long,Long> mp = new HashMap<>(); // PriorityQueue<long[]> q =new PriorityQueue<>((xx,xy)->{return Long.compare(xx[0],xy[0]);}); // // for(int j=0;j<n;++j){ // q.offer(new long[]{w[j],0}); // mp.put(w[j],mp.getOrDefault(w[j],0L)+1L); // } // // while(q.size()>=2){ // long f[] = q.poll(); // long y1 = f[1]; // if(y1==0){ // y1 = mp.get(f[0]); // if(y1==1){ // mp.remove(f[0]); // }else{ // mp.put(f[0],y1-1); // } // } // long g[] = q.poll(); // long y2 = g[1]; // if(y2==0){ // y2 = mp.get(g[0]); // if(y2==1){ // mp.remove(g[0]); // }else{ // mp.put(g[0],y2-1); // } // } // q.offer(new long[]{f[0]+g[0],2L*y1*y2}); // // } // long r[] = q.poll(); // println(r[1]); // // // // // } // int o= 9*8*7*6; // println(o); // int t = ni(); // for(int i=0;i<t;++i){ // long a = nl(); // int k = ni(); // if(k==1){ // println(a); // continue; // } // // int f = (int)(a%10L); // int s = 1; // int j = 0; // for(;j<30;j+=2){ // int u = f-j; // if(u<0){ // u = 10+u; // } // s = u*s; // s = s%10; // if(s==k){ // break; // } // } // // if(s==k) { // println(a - j - 2); // }else{ // println(-1); // } // // // // // } // int m = ni(); // h = new int[n]; // to = new int[2*(n-1)]; // ne = new int[2*(n-1)]; // wt = new int[2*(n-1)]; // // for(int i=0;i<n-1;++i){ // int u = ni()-1; // int v = ni()-1; // // } // long a[] = nal(n); // int n = ni(); // int k = ni(); // t1 = new long[200002]; // // int p[][] = new int[n][3]; // // for(int i=0;i<n;++i){ // p[i][0] = ni(); // p[i][1] = ni(); // p[i][2] = i+1; // } // Arrays.sort(p, new Comparator<int[]>() { // @Override // public int compare(int[] x, int[] y) { // if(x[1]!=y[1]){ // return Integer.compare(x[1],y[1]); // } // return Integer.compare(y[0], x[0]); // } // }); // // for(int i=0;i<n;++i){ // int ck = p[i][0]; // // } } // int []h,to,ne,wt; long t1[]; // long t2[]; void update(long[] t,int i,long v){ for(;i<t.length;i+=(i&-i)){ t[i] += v; } } long get(long[] t,int i){ long s = 0; for(;i>0;i-=(i&-i)){ s += t[i]; } return s; } int equal_bigger(long t[],long v){ int s=0,p=0; for(int i=Integer.numberOfTrailingZeros(Integer.highestOneBit(t.length));i>=0;--i) { if(p+(1<<i)< t.length && s + t[p+(1<<i)] < v){ v -= t[p+(1<<i)]; p |= 1<<i; } } return p+1; } static class S{ int l = 0; int r = 0 ; long le = 0; long ri = 0; long tot = 0; long all = 0; public S(int l,int r) { this.l = l; this.r = r; } } static S a[]; static int[] o; static void init(int[] f){ o = f; int len = o.length; a = new S[len*4]; build(1,0,len-1); } static void build(int num,int l,int r){ S cur = new S(l,r); if(l==r){ a[num] = cur; return; }else{ int m = (l+r)>>1; int le = num<<1; int ri = le|1; build(le, l,m); build(ri, m+1,r); a[num] = cur; pushup(num, le, ri); } } // static int query(int num,int l,int r){ // // if(a[num].l>=l&&a[num].r<=r){ // return a[num].tot; // }else{ // int m = (a[num].l+a[num].r)>>1; // int le = num<<1; // int ri = le|1; // pushdown(num, le, ri); // int ma = 1; // int mi = 100000001; // if(l<=m) { // int r1 = query(le, l, r); // ma = ma*r1; // // } // if(r>m){ // int r2 = query(ri, l, r); // ma = ma*r2; // } // return ma; // } // } static long dd = 10007; static void update(int num,int l,long v){ if(a[num].l==a[num].r){ a[num].le = v%dd; a[num].ri = v%dd; a[num].all = v%dd; a[num].tot = v%dd; }else{ int m = (a[num].l+a[num].r)>>1; int le = num<<1; int ri = le|1; pushdown(num, le, ri); if(l<=m){ update(le,l,v); } if(l>m){ update(ri,l,v); } pushup(num,le,ri); } } static void pushup(int num,int le,int ri){ a[num].all = (a[le].all*a[ri].all)%dd; a[num].le = (a[le].le + a[le].all*a[ri].le)%dd; a[num].ri = (a[ri].ri + a[ri].all*a[le].ri)%dd; a[num].tot = (a[le].tot + a[ri].tot + a[le].ri*a[ri].le)%dd; //a[num].res[1] = Math.min(a[le].res[1],a[ri].res[1]); } static void pushdown(int num,int le,int ri){ } int gcd(int a,int b){ return b==0?a: gcd(b,a%b);} InputStream is;PrintWriter out; void run() throws Exception {is = System.in;out = new PrintWriter(System.out);solve();out.flush();} private byte[] inbuf = new byte[2]; 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 char ncc() {int b;while((b = readByte()) != -1 && !(b >= 32 && b <= 126));return (char)b;} 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 String nline() {int b = skip();StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b);b = readByte(); } return sb.toString();} private char[][] nm(int n, int m) {char[][] a = new char[n][];for (int i = 0; i < n; i++) a[i] = ns(m);return a;} private int[] na(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = ni();return a;} private long[] nal(int n) { long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nl();return a;} private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')){}; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') num = (num << 3) + (num << 1) + (b - '0'); else return minus ? -num : num; b = readByte();}} private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')){}; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') num = num * 10 + (b - '0'); else return minus ? -num : num; b = readByte();}} void print(Object obj){out.print(obj);} void println(Object obj){out.println(obj);} void println(){out.println();} }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; public class MyClass { static class Pair implements Comparable<Pair>{ int x,y; Pair(int x,int y){ this.x=x; this.y=y; } public int compareTo(Pair p){ return Integer.compare(this.y,p.y); } } public static void main(String args[]) { Scanner in =new Scanner(System.in); HashMap<Long,ArrayList<Pair>> hm=new HashMap<Long,ArrayList<Pair>>(); int n=in.nextInt(); int a[]=new int[n]; long sum[]=new long[n]; long s=0; for(int i=0;i<n;i++){ a[i]=in.nextInt(); s+=a[i]; sum[i]=s; } for(int i=0;i<n;i++){ for(int j=i;j<n;j++){ long x=sum[j]-sum[i]+a[i]; ArrayList<Pair> temp=new ArrayList<Pair>(); if(hm.containsKey(x)) { temp=hm.get(x); } temp.add(new Pair(i+1,j+1)); hm.put(x,temp); } } ArrayList<Pair> ans=new ArrayList<Pair>(); for(Map.Entry em:hm.entrySet()){ ArrayList<Pair> array=hm.get(em.getKey()); Collections.sort(array); int prev=0; ArrayList<Pair> temp=new ArrayList<Pair>(); for(int i=0;i<array.size();i++){ if(array.get(i).x>prev){ temp.add(new Pair(array.get(i).x,array.get(i).y)); prev=array.get(i).y; } } // System.out.println(temp.size()); if(temp.size()>ans.size()){ ans=(ArrayList<Pair>)temp.clone(); } } long g=-5; System.out.println(ans.size()); for(int i=0;i<ans.size();i++){ System.out.println(ans.get(i).x+" "+ans.get(i).y); } } }
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.InputMismatchException; import java.util.HashMap; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author MaxHeap */ 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); F1SameSumBlocksEasy solver = new F1SameSumBlocksEasy(); solver.solve(1, in, out); out.close(); } static class F1SameSumBlocksEasy { Map<Long, List<IntPair>> sums = new HashMap<>(); public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long[] arr = in.nextLongArray(n); long[] pref = ArrayUtils.prefixSum(arr); for (int i = 0; i < n; ++i) { for (int j = i; j >= 0; --j) { long sum = pref[i + 1] - pref[j]; if (sums.containsKey(sum)) { sums.get(sum).add(Factories.makeIntPair(j, i)); } else { List<IntPair> pairs = new ArrayList<>(); pairs.add(Factories.makeIntPair(j, i)); sums.put(sum, pairs); } } } int best = 0; List<IntPair> res = new ArrayList<>(); for (long sum : sums.keySet()) { List<IntPair> pairs = sums.get(sum); List<IntPair> temp = new ArrayList<>(); int last = -1; for (IntPair cur : pairs) { if (cur.first > last) { last = cur.second; temp.add(cur); } } if (temp.size() > best) { best = temp.size(); res = temp; } } out.println(best); for (IntPair pair : res) { out.println((pair.first + 1) + " " + (pair.second + 1)); } } } static class ArrayUtils { public static long[] prefixSum(long[] arr) { long[] acc = new long[arr.length + 1]; for (int i = 1; i <= arr.length; ++i) { acc[i] = acc[i - 1] + arr[i - 1]; } return acc; } } static interface FastIO { } static final class Factories { private Factories() { } public static IntPair makeIntPair(int first, int second) { return new IntPair(first, second); } } static class IntPair implements Comparable<IntPair> { public int first; public int second; public IntPair() { first = second = 0; } public IntPair(int first, int second) { this.first = first; this.second = second; } public int compareTo(IntPair a) { if (first == a.first) { return Integer.compare(second, a.second); } return Integer.compare(first, a.first); } public String toString() { return "<" + first + ", " + second + ">"; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntPair a = (IntPair) o; if (first != a.first) { return false; } return second == a.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } } static class InputReader implements FastIO { private InputStream stream; private static final int DEFAULT_BUFFER_SIZE = 1 << 16; private static final int EOF = -1; private byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (this.numChars == EOF) { throw new UnknownError(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException ex) { throw new InputMismatchException(); } if (this.numChars <= 0) { return EOF; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public long nextLong() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } long res = 0; while (c >= 48 && c <= 57) { res *= 10L; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == EOF; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.*; import java.util.*; public class B{ static long []sum; static int n; public static void main(String[] args) throws IOException { Scanner sc=new Scanner(); PrintWriter out=new PrintWriter(System.out); n=sc.nextInt(); sum=new long [n+1]; for(int i=1;i<=n;i++) sum[i]=sc.nextInt()+sum[i-1]; HashMap<Long,Integer> map=new HashMap(); ArrayList<int []>[]adj=new ArrayList[n*n+10]; for(int i=0;i<adj.length;i++) adj[i]=new ArrayList(); for(int r=1;r<=n;r++) for(int l=1;l<=n;l++) { if(r<l) continue; long x=sum[r]-sum[l-1]; map.put(x, map.getOrDefault(x, map.size())); adj[map.get(x)].add(new int [] {l,r}); } int ans=0; int bestIdx=0; for(int idx=0;idx<adj.length;idx++) { ArrayList<int[]>list=adj[idx]; if(list.isEmpty()) continue; int curr=1; int R=list.get(0)[1]; for(int i=1;i<list.size();i++) { int []tmp=list.get(i); if(tmp[0]>R) { R=tmp[1]; curr++; } } if(curr>=ans) { ans=curr; bestIdx=idx; } } out.println(ans); ArrayList<int[]>list=adj[bestIdx]; int R=list.get(0)[1]; out.println(list.get(0)[0]+" "+R); for(int i=1;i<list.size();i++) { int []tmp=list.get(i); if(tmp[0]>R) { R=tmp[1]; out.println(tmp[0]+" "+tmp[1]); } } out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(){ br=new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException{ br=new BufferedReader(new FileReader(fileName)); } String next() 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(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { static final long mod=(int)1e9+7; public static void main(String[] args) throws Exception { FastReader in=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int n=in.nextInt(); int[] arr=new int[n+1]; for(int i=1;i<=n;i++) arr[i]=in.nextInt(); Map<Integer,TreeMap<Integer,Integer>> map=new HashMap(); for(int i=1;i<=n;i++) { int sum=0; for(int j=i;j<=n;j++) { sum+=arr[j]; if(map.containsKey(sum)) { TreeMap<Integer,Integer> t=map.get(sum); // System.out.println(t+" "+sum); Map.Entry<Integer,Integer> e=t.lastEntry(); if(e.getKey()>j) { t.remove(e.getKey()); t.put(j,i); map.put(sum,t); } else if(e.getKey()<i) { t.put(j,i); map.put(sum,t); } } else { TreeMap<Integer,Integer> t=new TreeMap(); t.put(j,i); map.put(sum,t); } } } int ans=0,size=0; for(Map.Entry<Integer,TreeMap<Integer,Integer>> e:map.entrySet()) { if(e.getValue().size()>size) { ans=e.getKey(); size=e.getValue().size(); } } pw.println(size); for(Map.Entry e:map.get(ans).entrySet()) pw.println(e.getValue()+" "+e.getKey()); pw.flush(); } } class pair { int f,s; } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if(st==null || !st.hasMoreElements()) { 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()); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; import java.io.*; import java.util.regex.*; public class Codeforces{ static class MyScanner{ BufferedReader br; StringTokenizer st; MyScanner(FileReader fileReader){ br = new BufferedReader(fileReader); } MyScanner(){ br = new BufferedReader(new InputStreamReader(System.in)); } String nn(){ while(st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } char nc(){ return nn().charAt(0); } int ni(){ return Integer.parseInt(nn()); } long nl(){ return Long.parseLong(nn()); } double nd(){ return Double.parseDouble(nn()); } int[] niArr0(int n){ int[] ar = new int[n]; for(int i = 0; i < n; i++) ar[i] = ni(); return ar; } int[] niArr1(int n){ int[] ar = new int[n + 1]; for(int i = 1; i <= n; i++) ar[i] = ni(); return ar; } long[] nlArr0(int n){ long[] ar = new long[n]; for(int i = 0; i < n; i++) ar[i] = nl(); return ar; } } public static <T> void mprintln(T ... ar){ for(T i: ar) out.print(i + " "); out.println(); } private static PrintWriter out; public static void main(String[] args) throws FileNotFoundException{ // Input from file // File inputFile = new File("JavaFile.txt"); // File outputFile = new File("JavaOutputFile.txt"); // FileReader fileReader = new FileReader(inputFile); // Here it ends MyScanner sc = new MyScanner(); // MyScanner sc = new MyScanner(fileReader); out = new PrintWriter(new BufferedOutputStream(System.out)); // Output to console // out = new PrintWriter(new PrintStream(outputFile)); // Output to file getAns(sc); out.close(); } private static void getAns(MyScanner sc){ int n = sc.ni(); long[] ar = sc.nlArr0(n); HashMap<Long, ArrayList<int[]>> map = new HashMap(); for(int i = 0; i < n; i++){ long cur = 0; for(int j = i; j >= 0; j--){ cur += ar[j]; if(!map.containsKey(cur)) map.put(cur, new ArrayList()); map.get(cur).add(new int[]{j + 1, i + 1}); } } // System.out.println(map); Set<Long> set = map.keySet(); // System.out.println(set); ArrayList<int[]> ans = new ArrayList(); for(Long l: set){ ArrayList<int[]> cur = new ArrayList(); int right = -1; for(int[] arc: map.get(l)) if(arc[0] > right){ right = arc[1]; cur.add(arc); } if(cur.size() > ans.size()) ans = cur; } out.println(ans.size()); for(int[] arc: ans) mprintln(arc[0], arc[1]); } }
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()); 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 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)); } } } int res=0; for (Entry<Integer,ArrayList<node>> entry:mp.entrySet()) res=Math.max(res,entry.getValue().size()); out.println(res); for (Entry<Integer,ArrayList<node>> entry:mp.entrySet()) if (entry.getValue().size()==res) { ArrayList<node> tmp=entry.getValue(); for (int i=0;i<tmp.size();++i) out.printf("%d %d\n",tmp.get(i).l+1,tmp.get(i).r+1); out.flush(); return; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.HashMap; import java.util.Scanner; public class Main{ int[] ints; int[] prefix; public static void main(String[] args) { new Main().run(); } public void run() { Scanner file = new Scanner(System.in); int N = file.nextInt(); ints = new int[N]; for(int i = 0;i<N;i++) ints[i] = file.nextInt(); prefix = new int[N]; prefix[0] = ints[0]; for(int i =1;i<prefix.length;i++) prefix[i] = prefix[i-1]+ints[i]; HashMap<Integer,Integer> ending = new HashMap<>();//ending for each sum HashMap<Integer,Integer> amount = new HashMap<>();//k for each sum for(int end = 0;end<prefix.length;end++) { for(int start = 0;start<=end;start++) { int sum = sum(start,end); if(!ending.containsKey(sum)) ending.put(sum, -1); if(!amount.containsKey(sum)) amount.put(sum,0); if(ending.get(sum)<start) { amount.put(sum,amount.get(sum)+1); ending.put(sum,end); } } } int max = 0; int maxnum = -1; for(int x:amount.keySet()) { if(amount.get(x)>max) { max = amount.get(x); maxnum = x; } } System.out.println(max); HashMap<Integer,Integer> occurrence = new HashMap<Integer,Integer>(); occurrence.put(0,0); for(int i = 0;i<prefix.length;i++) { if(occurrence.containsKey(prefix[i]-maxnum)) { System.out.println(occurrence.get(prefix[i]-maxnum)+1+" "+(i+1)); occurrence.clear(); } occurrence.put(prefix[i],i+1); } } public int sum(int L, int R) { return prefix[R] - prefix[L] + ints[L]; } }
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]; var ansMap = new HashMap<Integer, ArrayDeque<Pair>>(); for (int j = 1; j <= N; j++) { pre[j] = pre[j - 1] + sc.nextInt(); for (int i = j; i >= 1; i--) { int sum = pre[j] - pre[i - 1]; /** we can actually perform the greedy scheduling as we read in the information! Because we are sweeping with an increasing right pointer, the moment a sum is found with this right endpoint, we can greedily place it into the schedule for a given sum "bucket", (if it's disjoint. Otherwise, we would be replacing one OR MORE previous intervals, which would only decrease or keep the same size, while reducing our future accessibility for adding intervals!) */ if (!ansMap.containsKey(sum) || ansMap.get(sum).getLast().r < i) { var dq = ansMap.computeIfAbsent(sum, val -> new ArrayDeque<>()); dq.add(new Pair(i, j, sum)); } } } var ans = new ArrayDeque<Pair>(); for (var group : ansMap.values()) { 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, 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.util.*; public class F2 { private static int n; private static int[] a; private static Collection<Segment> answer; public static void main(String[] args) { in(); solution(); out(); } private static void in() { Scanner in = new Scanner(System.in); n = in.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } } private static void solution() { HashMap<Long, LinkedList<Segment>> segments = new HashMap<>(); for (int i = 0; i < n; i++) { long sum = 0; for (int j = i; j < n; j++) { sum += a[j]; if (segments.containsKey(sum)) { segments.get(sum).add(new Segment(i, j)); } else { LinkedList<Segment> toPut = new LinkedList<>(); toPut.add(new Segment(i, j)); segments.put(sum, toPut); } } } answer = null; for (Map.Entry<Long, LinkedList<Segment>> sums : segments.entrySet()) { LinkedList<Segment> currentSegments = sums.getValue(); Collections.sort(currentSegments); LinkedList<Segment> segmentsWithoutCrossing = new LinkedList<>(); for (Segment segment : currentSegments) { if ( segmentsWithoutCrossing.isEmpty() || !segmentsWithoutCrossing.getLast().isCrossingToNextSegment(segment)) { segmentsWithoutCrossing.add(segment); } else if (segmentsWithoutCrossing.getLast().getR() > segment.getR()) { segmentsWithoutCrossing.removeLast(); segmentsWithoutCrossing.add(segment); } } answer = segmentsWithoutCrossing.size() > (answer != null ? answer.size() : 0) ? segmentsWithoutCrossing : answer; } } private static void out() { System.out.println(answer.size()); for (Segment segment : answer) { System.out.println( (segment.getL() + 1) + " " + (segment.getR() + 1)); } } } class Segment implements Comparable<Segment>{ private int l, r; Segment(int l, int r) { this.l = l; this.r = r; } int getL() { return l; } int getR() { return r; } @Override public int compareTo(Segment segment) { if (l == segment.l && r == segment.r) { return 0; } return l != segment.l ? l - segment.l : r - segment.r; } boolean isCrossingToNextSegment(Segment segment) { if (l == segment.l || r == segment.r) { return true; } else if (l < segment.l) { return r >= segment.l; } else if (r > segment.r) { return l <= segment.r; } else { return true; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class F1141 { private static class Interval { public int l; public int r; public Interval(int l,int r) { this.l = l; this.r = r; } } public static void main(String[] args) throws IOException { // BufferedReader br = new BufferedReader(new FileReader("F:/books/input.txt")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int n = Integer.parseInt(s); long[] a = new long[n]; String[] as = br.readLine().split(" "); for(int i=0;i<n;i++) { a[i] = Long.parseLong(as[i]); } StringBuffer sb = solve(a,n); System.out.println(sb.toString()); } private static StringBuffer solve(long[] a, int n) { StringBuffer ret = new StringBuffer(""); Map<Long,List<Interval>> mp = new HashMap<Long,List<Interval>>(); long max = 0,maxId = -1; for(int i=n-1;i>=0;i--) { long s=0; long prev = 1; for(int j=i;j<n;j++) { s+=a[j]; // System.out.println(i+","+j); Interval inter = new Interval(i,j); // if(prev==1 || prev==-1) { List<Interval> ints = mp.get(s); if(ints==null) ints = new ArrayList<Interval>(); if(ints.size()==0 || ints.get(0).l>j) { ints.add(0,inter); } if(ints.size()>max) { max = ints.size(); maxId = s; } mp.put(s, ints); // } if(j<n-1) prev = a[j+1]-a[j]; } } List<Interval> l = mp.get(maxId); ret.append(l.size()+ "\n"); for(Interval inter : l) { ret.append((inter.l+1) + " " + (inter.r+1) + "\n"); } return ret; } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import javax.print.attribute.standard.PrinterMessageFromOperator; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws Exception { new Main().run();} // int[] h,ne,to,wt; // int ct = 0; // int n; // void graph(int n,int m){ // h = new int[n]; // Arrays.fill(h,-1); //// sccno = new int[n]; //// dfn = new int[n]; //// low = new int[n]; //// iscut = new boolean[n]; // ne = new int[2*m]; // to = new int[2*m]; // wt = new int[2*m]; // ct = 0; // } // void add(int u,int v,int w){ // to[ct] = v; // ne[ct] = h[u]; // wt[ct] = w; // h[u] = ct++; // } // // int color[],dfn[],low[],stack[] = new int[1000000],cnt[]; // int sccno[]; // boolean iscut[]; // int time = 0,top = 0; // int scc_cnt = 0; // // // 有向图的强连通分量 // void tarjan(int u) { // low[u] = dfn[u]= ++time; // stack[top++] = u; // for(int i=h[u];i!=-1;i=ne[i]) { // int v = to[i]; // if(dfn[v]==0) { // tarjan(v); // low[u]=Math.min(low[u],low[v]); // } else if(sccno[v]==0) { // // dfn>0 but sccno==0, means it's in current stack // low[u]=Math.min(low[u],low[v]); // } // } // // if(dfn[u]==low[u]) { // sccno[u] = ++scc_cnt; // while(stack[top-1]!=u) { // sccno[stack[top-1]] = scc_cnt; // --top; // } // --top; // } // } // // //缩点, topology sort // int[] h1,to1,ne1; // int ct1 = 0; // void point(){ // for(int i=0;i<n;i++) { // if(dfn[i]==0) tarjan(i);//有可能图不连通,所以要循环判断。 // } // // 入度 // int du[] = new int[scc_cnt+1]; // h1 = new int[scc_cnt+1]; // Arrays.fill(h1, -1); // to1 = new int[scc_cnt*scc_cnt]; // ne1 = new int[scc_cnt*scc_cnt]; // // scc_cnt 个点 // // for(int i=1;i<=n;i++) { // for(int j=h[i]; j!=-1; j=ne[j]) { // int y = to[j]; // if(sccno[i] != sccno[y]) { // // add(sccno[i],sccno[y]); // 建新图 // to1[ct1] = sccno[y]; // ne1[ct1] = h[sccno[i]]; // h[sccno[i]] = ct1++; // du[sccno[y]]++; //存入度 // } // } // } // // int q[] = new int[100000]; // int end = 0; // int st = 0; // for(int i=1;i<=scc_cnt;++i){ // if(du[i]==0){ // q[end++] = i; // } // } // // int dp[] = new int[scc_cnt+1]; // while(st<end){ // int cur = q[st++]; // for(int i=h1[cur];i!=-1;i=ne1[i]){ // int y = to[i]; // // dp[y] += dp[cur]; // if(--du[y]==0){ // q[end++] = y; // } // } // } // } // // // // // int fa[]; // int faw[]; // // int dep = -1; // int pt = 0; // void go(int rt,int f,int dd){ // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = f;p++; // while(p>0) { // int cur = stk[p - 1]; // int fp = fk[p - 1]; // int ll = lk[p - 1]; // p--; // // // if (ll > dep) { // dep = ll; // pt = cur; // } // for (int i = h[cur]; i != -1; i = ne[i]) { // int v = to[i]; // if (fp == v) continue; // // stk[p] = v; // lk[p] = ll + wt[i]; // fk[p] = cur; // p++; // } // } // } // int pt1 = -1; // void go1(int rt,int f,int dd){ // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = f;p++; // while(p>0) { // int cur = stk[p - 1]; // int fp = fk[p - 1]; // int ll = lk[p - 1]; // p--; // // // if (ll > dep) { // dep = ll; // pt1 = cur; // } // // fa[cur] = fp; // for (int i = h[cur]; i != -1; i = ne[i]) { // int v = to[i]; // if (v == fp) continue; // faw[v] = wt[i]; // stk[p] = v; // lk[p] = ll + wt[i]; // fk[p] = cur; // p++; // } // } // } // // int r = 0; // int stk[] = new int[301]; // int fk[] = new int[301]; // int lk[] = new int[301]; // void ddfs(int rt,int t1,int t2,int t3,int l){ // // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = t3;p++; // while(p>0){ // int cur = stk[p-1]; // int fp = fk[p-1]; // int ll = lk[p-1]; // p--; // r = Math.max(r,ll); // for(int i=h[cur];i!=-1;i=ne[i]){ // int v = to[i]; // if(v==t1||v==t2||v==fp) continue; // stk[p] = v; // lk[p] = ll+wt[i]; // fk[p] = cur;p++; // } // } // // // // } static long mul(long a, long b, long p) { long res=0,base=a; while(b>0) { if((b&1L)>0) res=(res+base)%p; base=(base+base)%p; b>>=1; } return res; } static long mod_pow(long k,long n,long p){ long res = 1L; long temp = k; while(n!=0L){ if((n&1L)==1L){ res = (res*temp)%p; } temp = (temp*temp)%p; n = n>>1L; } return res%p; } int ct = 0; int f[] =new int[200001]; int b[] =new int[200001]; int str[] =new int[200001]; void go(int rt,List<Integer> g[]){ str[ct] = rt; f[rt] = ct; for(int cd:g[rt]){ ct++; go(cd,g); } b[rt] = ct; } int add =0; void go(int rt,int sd,int k,List<Integer> g[],int n){ if(add>n) { return; } Queue<Integer> q =new LinkedList<>(); q.offer(rt); for(int i=1;i<=sd;++i){ int sz =q.size(); if(sz==0) break; int f = (i==1?2:1); while(sz-->0){ int cur = q.poll(); for(int j=0;j<k-f;++j){ q.offer(add); g[cur].add(add);add++; if(add==n+1){ return; } } } } } void solve() { int n = ni(); int s[] = new int[n+1]; for(int i=0;i<n;++i){ s[i+1] = s[i] + ni(); } Map<Integer,List<int[]>> mp = new HashMap<>(); for(int i=0;i<n;++i) { for (int j = i; j>=0; --j) { int v = s[i+1]-s[j]; if(!mp.containsKey(v)){ mp.put(v, new ArrayList<>()); } mp.get(v).add(new int[]{j+1,i+1}); } } int all = 0;int vv = -1; for(int v:mp.keySet()){ List<int[]> r = mp.get(v); ;int c = 0; int ri = -2000000000; for(int [] fk : r){ if(fk[0]>ri){ ri = fk[1];c++; } } if(c>all){ all = c; vv = v; } } println(all); List<int[]> r = mp.get(vv); int ri = -2000000000; for(int fk[]:r){ if(fk[0]>ri){ ri = fk[1];println((fk[0])+" "+(fk[1])); } } //N , M , K , a , b , c , d . 其中N , M是矩阵的行列数;K 是上锁的房间数目,(a, b)是起始位置,(c, d)是出口位置 // int n = ni(); // int m = ni(); // int k = ni(); // int a = ni(); // int b = ni(); // int c = ni(); // int d = ni(); // // // char cc[][] = nm(n,m); // char keys[][] = new char[n][m]; // // char ky = 'a'; // for(int i=0;i<k;++i){ // int x = ni(); // int y = ni(); // keys[x][y] = ky; // ky++; // } // int f1[] = {a,b,0}; // // int dd[][] = {{0,1},{0,-1},{1,0},{-1,0}}; // // Queue<int[]> q = new LinkedList<>(); // q.offer(f1); // int ts = 1; // // boolean vis[][][] = new boolean[n][m][33]; // // while(q.size()>0){ // int sz = q.size(); // while(sz-->0) { // int cur[] = q.poll(); // vis[cur[0]][cur[1]][cur[2]] = true; // // int x = cur[0]; // int y = cur[1]; // // for (int u[] : dd) { // int lx = x + u[0]; // int ly = y + u[1]; // if (lx >= 0 && ly >= 0 && lx < n && ly < m && (cc[lx][ly] != '#')&&!vis[lx][ly][cur[2]]){ // char ck =cc[lx][ly]; // if(ck=='.'){ // if(lx==c&&ly==d){ // println(ts); return; // } // if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') { // int cao = cur[2] | (1 << (keys[lx][ly] - 'a')); // q.offer(new int[]{lx, ly, cao}); // vis[lx][ly][cao] = true; // }else { // // q.offer(new int[]{lx, ly, cur[2]}); // } // // }else if(ck>='A'&&ck<='Z'){ // int g = 1<<(ck-'A'); // if((g&cur[2])>0){ // if(lx==c&&ly==d){ // println(ts); return; // } // if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') { // // int cao = cur[2] | (1 << (keys[lx][ly] - 'a')); // q.offer(new int[]{lx, ly, cao}); // vis[lx][ly][cao] = true;; // }else { // // q.offer(new int[]{lx, ly, cur[2]}); // } // } // } // } // } // // } // ts++; // } // println(-1); // int n = ni(); // // HashSet<String> st = new HashSet<>(); // HashMap<String,Integer> mp = new HashMap<>(); // // // for(int i=0;i<n;++i){ // String s = ns(); // int id= 1; // if(mp.containsKey(s)){ // int u = mp.get(s); // id = u; // // } // // if(st.contains(s)) { // // while (true) { // String ts = s + id; // if (!st.contains(ts)) { // s = ts; // break; // } // id++; // } // mp.put(s,id+1); // }else{ // mp.put(s,1); // } // println(s); // st.add(s); // // } // int t = ni(); // // for(int i=0;i<t;++i){ // int n = ni(); // long w[] = nal(n); // // Map<Long,Long> mp = new HashMap<>(); // PriorityQueue<long[]> q =new PriorityQueue<>((xx,xy)->{return Long.compare(xx[0],xy[0]);}); // // for(int j=0;j<n;++j){ // q.offer(new long[]{w[j],0}); // mp.put(w[j],mp.getOrDefault(w[j],0L)+1L); // } // // while(q.size()>=2){ // long f[] = q.poll(); // long y1 = f[1]; // if(y1==0){ // y1 = mp.get(f[0]); // if(y1==1){ // mp.remove(f[0]); // }else{ // mp.put(f[0],y1-1); // } // } // long g[] = q.poll(); // long y2 = g[1]; // if(y2==0){ // y2 = mp.get(g[0]); // if(y2==1){ // mp.remove(g[0]); // }else{ // mp.put(g[0],y2-1); // } // } // q.offer(new long[]{f[0]+g[0],2L*y1*y2}); // // } // long r[] = q.poll(); // println(r[1]); // // // // // } // int o= 9*8*7*6; // println(o); // int t = ni(); // for(int i=0;i<t;++i){ // long a = nl(); // int k = ni(); // if(k==1){ // println(a); // continue; // } // // int f = (int)(a%10L); // int s = 1; // int j = 0; // for(;j<30;j+=2){ // int u = f-j; // if(u<0){ // u = 10+u; // } // s = u*s; // s = s%10; // if(s==k){ // break; // } // } // // if(s==k) { // println(a - j - 2); // }else{ // println(-1); // } // // // // // } // int m = ni(); // h = new int[n]; // to = new int[2*(n-1)]; // ne = new int[2*(n-1)]; // wt = new int[2*(n-1)]; // // for(int i=0;i<n-1;++i){ // int u = ni()-1; // int v = ni()-1; // // } // long a[] = nal(n); // int n = ni(); // int k = ni(); // t1 = new long[200002]; // // int p[][] = new int[n][3]; // // for(int i=0;i<n;++i){ // p[i][0] = ni(); // p[i][1] = ni(); // p[i][2] = i+1; // } // Arrays.sort(p, new Comparator<int[]>() { // @Override // public int compare(int[] x, int[] y) { // if(x[1]!=y[1]){ // return Integer.compare(x[1],y[1]); // } // return Integer.compare(y[0], x[0]); // } // }); // // for(int i=0;i<n;++i){ // int ck = p[i][0]; // // } } // int []h,to,ne,wt; long t1[]; // long t2[]; void update(long[] t,int i,long v){ for(;i<t.length;i+=(i&-i)){ t[i] += v; } } long get(long[] t,int i){ long s = 0; for(;i>0;i-=(i&-i)){ s += t[i]; } return s; } int equal_bigger(long t[],long v){ int s=0,p=0; for(int i=Integer.numberOfTrailingZeros(Integer.highestOneBit(t.length));i>=0;--i) { if(p+(1<<i)< t.length && s + t[p+(1<<i)] < v){ v -= t[p+(1<<i)]; p |= 1<<i; } } return p+1; } static class S{ int l = 0; int r = 0 ; long le = 0; long ri = 0; long tot = 0; long all = 0; public S(int l,int r) { this.l = l; this.r = r; } } static S a[]; static int[] o; static void init(int[] f){ o = f; int len = o.length; a = new S[len*4]; build(1,0,len-1); } static void build(int num,int l,int r){ S cur = new S(l,r); if(l==r){ a[num] = cur; return; }else{ int m = (l+r)>>1; int le = num<<1; int ri = le|1; build(le, l,m); build(ri, m+1,r); a[num] = cur; pushup(num, le, ri); } } // static int query(int num,int l,int r){ // // if(a[num].l>=l&&a[num].r<=r){ // return a[num].tot; // }else{ // int m = (a[num].l+a[num].r)>>1; // int le = num<<1; // int ri = le|1; // pushdown(num, le, ri); // int ma = 1; // int mi = 100000001; // if(l<=m) { // int r1 = query(le, l, r); // ma = ma*r1; // // } // if(r>m){ // int r2 = query(ri, l, r); // ma = ma*r2; // } // return ma; // } // } static long dd = 10007; static void update(int num,int l,long v){ if(a[num].l==a[num].r){ a[num].le = v%dd; a[num].ri = v%dd; a[num].all = v%dd; a[num].tot = v%dd; }else{ int m = (a[num].l+a[num].r)>>1; int le = num<<1; int ri = le|1; pushdown(num, le, ri); if(l<=m){ update(le,l,v); } if(l>m){ update(ri,l,v); } pushup(num,le,ri); } } static void pushup(int num,int le,int ri){ a[num].all = (a[le].all*a[ri].all)%dd; a[num].le = (a[le].le + a[le].all*a[ri].le)%dd; a[num].ri = (a[ri].ri + a[ri].all*a[le].ri)%dd; a[num].tot = (a[le].tot + a[ri].tot + a[le].ri*a[ri].le)%dd; //a[num].res[1] = Math.min(a[le].res[1],a[ri].res[1]); } static void pushdown(int num,int le,int ri){ } int gcd(int a,int b){ return b==0?a: gcd(b,a%b);} InputStream is;PrintWriter out; void run() throws Exception {is = System.in;out = new PrintWriter(System.out);solve();out.flush();} private byte[] inbuf = new byte[2]; 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 char ncc() {int b;while((b = readByte()) != -1 && !(b >= 32 && b <= 126));return (char)b;} 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 String nline() {int b = skip();StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b);b = readByte(); } return sb.toString();} private char[][] nm(int n, int m) {char[][] a = new char[n][];for (int i = 0; i < n; i++) a[i] = ns(m);return a;} private int[] na(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = ni();return a;} private long[] nal(int n) { long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nl();return a;} private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')){}; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') num = (num << 3) + (num << 1) + (b - '0'); else return minus ? -num : num; b = readByte();}} private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')){}; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') num = num * 10 + (b - '0'); else return minus ? -num : num; b = readByte();}} void print(Object obj){out.print(obj);} void println(Object obj){out.println(obj);} void println(){out.println();} }
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.util.List; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author prakharjain */ 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); long[] p = in.calculatePrefixSum(a); Map<Long, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { long sum = 0; for (int j = i; j < n; j++) { sum += a[j]; map.merge(sum, 1, (x, y) -> x + y); } } List<sum> sums = new ArrayList<>(); for (long sum : map.keySet()) { sums.add(new sum(sum, map.get(sum))); } sums.sort((x, y) -> y.c - x.c); int ans = -1; int[] fca = null; long mxsum = -1; for (int i = 0; i < sums.size(); i++) { sum cs = sums.get(i); long sum = cs.sum; long c = cs.c; if (c < ans) { continue; } Map<Long, Integer> lm = new HashMap<>(); int[] ca = new int[n]; lm.put(0l, -1); for (int j = 0; j < n; j++) { long val = p[j]; if (j > 0) { ca[j] = ca[j - 1]; } long req = val - sum; if (lm.containsKey(req)) { int li = lm.get(req); if (li == -1) ca[j] = Math.max(1, ca[j]); else ca[j] = Math.max(1 + ca[li], ca[j]); } lm.put(val, j); } if (ca[n - 1] > ans) { ans = ca[n - 1]; mxsum = sum; fca = ca; } } List<Integer> al = new ArrayList<>(); long sum = 0; for (int i = n - 1; i >= 0; i--) { if (i > 0 && fca[i] != fca[i - 1]) { sum = 0; al.add(i + 1); do { sum += a[i]; i--; } while (i >= 0 && sum != mxsum); i++; al.add(i + 1); } else if (i == 0) { if (a[i] == mxsum) { al.add(i + 1); al.add(i + 1); } } } out.println(al.size() / 2); for (int i = al.size() - 1; i >= 0; i -= 2) { out.println(al.get(i) + " " + al.get(i - 1)); } } class sum { long sum; int c; public sum(long sum, int c) { this.sum = sum; this.c = c; } } } 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 static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; ++i) array[i] = nextLong(); return array; } public long[] calculatePrefixSum(long[] a) { int n = a.length; long[] prefixSum = new long[n]; prefixSum[0] = a[0]; for (int i = 1; i < n; i++) { prefixSum[i] = prefixSum[i - 1] + a[i]; } return prefixSum; } 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.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<>(); 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.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=998244353; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } void work() { int n=in.nextInt(); int[] A=new int[n]; for(int i=0;i<n;i++)A[i]=in.nextInt(); HashMap<Integer,Integer> map=new HashMap<>(); HashMap<Integer,ArrayList<int[]>> rec=new HashMap<>(); for(int i=0;i<n;i++) { for(int j=i,cur=0;j>=0;j--) { cur+=A[j]; if(map.get(cur)==null) { map.put(cur,i); rec.put(cur,new ArrayList<>()); rec.get(cur).add(new int[] {j,i}); }else if(map.get(cur)<j) { map.put(cur,i); rec.get(cur).add(new int[] {j,i}); } } } ArrayList<int[]> ret=null; for(ArrayList<int[]> list:rec.values()) { if(ret==null||ret.size()<list.size()) { ret=list; } } out.println(ret.size()); for(int[] r:ret) { out.println((r[0]+1)+" "+(r[1]+1)); } } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); long[] a = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = Long.parseLong(st.nextToken()); } long[] sum = new long[n]; sum[0] = a[0]; for (int i = 1; i < sum.length; i++) { sum[i] = sum[i - 1] + a[i]; } solve(a, sum); } private static void solve(long[] a, long[] sum) { int n = a.length; Map<Long, List<Pair>> map = new HashMap<>(); for (int j = 0; j < sum.length; j++) { for (int i = 0; i <= j; i++) { long k = getSum(sum, i, j); if (map.containsKey(k)) { map.get(k).add(new Pair(i, j)); } else { List<Pair> arr = new ArrayList<>(); arr.add(new Pair(i, j)); map.put(k, arr); } } } int max = -1; List<Pair> ans = null; for (Map.Entry<Long, List<Pair>> entry : map.entrySet()) { List<Pair> pairs = entry.getValue(); int prev = -1; int count = 0; List<Pair> temp = new ArrayList<Pair>(); for (Pair p : pairs) { if (p.x > prev) { prev = p.y; temp.add(p); count++; } } if (count > max) { ans = temp; max = count; } } if (max != -1) { System.out.println(ans.size()); for (Pair p : ans) { System.out.println((p.x + 1) + " " + (p.y + 1)); } } } private static long getSum(long[] sum, int l, int r) { if (l == 0) { return sum[r]; } return sum[r] - sum[l - 1]; } } class Pair { int x; int y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int hashCode() { int h = 171 << 4; h = h * x; h = h * y; return h; } @Override public boolean equals(Object o) { if (o instanceof Pair) { Pair other = (Pair) o; return this.x == other.x && this.y == other.y; } return false; } @Override public String toString() { return "Pair [x=" + x + ", y=" + y + "]"; } }
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>>(); // var sums = new ArrayList<Pair>(); Pair[] sums = new Pair[N * (N + 1) / 2]; int k = 0; 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[k++] = new Pair(i, j, sum); } } Arrays.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 < k) { var group = new ArrayList<Pair>(); int last = 0; int j = i; while (j < k && sums[j].sum == sums[i].sum) { if (sums[j].l > last) { group.add(sums[j]); last = sums[j].r; } j++; } // System.out.println(group); if (group.size() > ans.size()) { ans = group; } i = j; } 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.BufferedOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class Task { public static void solve() throws Exception { int n = nextInt(); int[] S = new int[n]; for(int i=0;i<n;i++) { S[i] = nextInt(); if(i > 0) { S[i] += S[i-1]; } } Map<Integer, List<L>> map = new HashMap<>(); for(int j=0;j<n;j++) { for(int i=j;i>=0;i--) { int sum = S[j]; if(i > 0) { sum -= S[i-1]; } L l = new L(); l.a = i; l.b = j; List<L> list = map.get(sum); if(list == null) { list = new ArrayList<>(); map.put(sum, list); } list.add(l); } } List<L> longest = null; for(Integer sum: map.keySet()) { List<L> list = map.get(sum); Collections.sort(list); List<L> list2 = new ArrayList<>(list.size()); int from = list.get(0).a; for(L l: list) { if(l.a >= from) { list2.add(l); from = l.b + 1; } } if(longest == null || longest.size() < list2.size()) { longest = list2; } } println(longest.size()); for(int i=0;i<longest.size();i++) { L l = longest.get(i); println((l.a+1) + " " + (l.b+1)); } } private static class L implements Comparable<L>{ int a; int b; @Override public int compareTo(L l2) { return Integer.valueOf(b).compareTo(l2.b); } } public static void main(String[] args) throws Exception { try { fastReader = new FastReader(System.in); systemOut = new BufferedOutputStream(System.out); solve(); } finally { systemOut.close(); } } private static FastReader fastReader = null; private static BufferedOutputStream systemOut = null; public static void print(Object obj) { print(obj.toString()); } public static void print(String str) { try { systemOut.write(str.getBytes("utf-8")); } catch (Exception ex) { throw new RuntimeException(ex); } } public static void println(Object obj) { println(obj.toString()); } public static void println(String str) { try { print(str); systemOut.write('\n'); } catch (Exception ex) { throw new RuntimeException(ex); } } public static String next() { return fastReader.readNextToken(false); } public static String nextLine() { return fastReader.readNextToken(true); } public static int nextInt() { return Integer.parseInt(fastReader.readNextToken(false)); } public static long nextLong() { return Long.parseLong(fastReader.readNextToken(false)); } public static double nextDouble() { return Double.parseDouble(fastReader.readNextToken(false)); } static class FastReader { private byte[] buf = new byte[65536]; private int ind = 0; private int maxInd = -1; private InputStream is = null; private boolean eof = false; private boolean lastCharRead = false; public FastReader(InputStream is) { this.is = is; } public String readNextToken(boolean endOfLine) { try { StringBuilder sb = new StringBuilder(); boolean found = false; while (true) { if (lastCharRead) { return null; } else if (ind > maxInd) { if (eof) { lastCharRead = true; } else { fillBuffer(); } } byte b = '\n'; if (!lastCharRead) { b = buf[ind++]; } if (b == '\r') { // ignore } else if ((b == '\n' && endOfLine) || (Character.isWhitespace(b) && !endOfLine)) { if (found) { break; } } else { sb.append((char) b); found = true; } } return sb.toString(); } catch (Exception ex) { throw new RuntimeException(ex); } } private void fillBuffer() { try { int read = is.read(buf, 0, buf.length); if (read < buf.length) { eof = true; } ind = 0; maxInd = read - 1; } catch (Exception ex) { throw new RuntimeException(ex); } } } public static class LST { public long[][] set; public int n; public LST(int n) { this.n = n; int d = 1; for (int m = n; m > 1; m >>>= 6, d++) ; set = new long[d][]; for (int i = 0, m = n >>> 6; i < d; i++, m >>>= 6) { set[i] = new long[m + 1]; } } // [0,r) public LST setRange(int r) { for (int i = 0; i < set.length; i++, r = r + 63 >>> 6) { for (int j = 0; j < r >>> 6; j++) { set[i][j] = -1L; } if ((r & 63) != 0) set[i][r >>> 6] |= (1L << r) - 1; } return this; } // [0,r) public LST unsetRange(int r) { if (r >= 0) { for (int i = 0; i < set.length; i++, r = r + 63 >>> 6) { for (int j = 0; j < r + 63 >>> 6; j++) { set[i][j] = 0; } if ((r & 63) != 0) set[i][r >>> 6] &= ~((1L << r) - 1); } } return this; } public LST set(int pos) { if (pos >= 0 && pos < n) { for (int i = 0; i < set.length; i++, pos >>>= 6) { set[i][pos >>> 6] |= 1L << pos; } } return this; } public LST unset(int pos) { if (pos >= 0 && pos < n) { for (int i = 0; i < set.length && (i == 0 || set[i - 1][pos] == 0L); i++, pos >>>= 6) { set[i][pos >>> 6] &= ~(1L << pos); } } return this; } public boolean get(int pos) { return pos >= 0 && pos < n && set[0][pos >>> 6] << ~pos < 0; } public LST toggle(int pos) { return get(pos) ? unset(pos) : set(pos); } public int prev(int pos) { for (int i = 0; i < set.length && pos >= 0; i++, pos >>>= 6, pos--) { int pre = prev(set[i][pos >>> 6], pos & 63); if (pre != -1) { pos = pos >>> 6 << 6 | pre; while (i > 0) pos = pos << 6 | 63 - Long.numberOfLeadingZeros(set[--i][pos]); return pos; } } return -1; } public int next(int pos) { for (int i = 0; i < set.length && pos >>> 6 < set[i].length; i++, pos >>>= 6, pos++) { int nex = next(set[i][pos >>> 6], pos & 63); if (nex != -1) { pos = pos >>> 6 << 6 | nex; while (i > 0) pos = pos << 6 | Long.numberOfTrailingZeros(set[--i][pos]); return pos; } } return -1; } private static int prev(long set, int n) { long h = set << ~n; if (h == 0L) return -1; return -Long.numberOfLeadingZeros(h) + n; } private static int next(long set, int n) { long h = set >>> n; if (h == 0L) return -1; return Long.numberOfTrailingZeros(h) + n; } @Override public String toString() { List<Integer> list = new ArrayList<Integer>(); for (int pos = next(0); pos != -1; pos = next(pos + 1)) { list.add(pos); } return list.toString(); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; public class TaskF { 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(); } int[] prefixSum = new int[n + 1]; prefixSum[0] = 0; for (int i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + a[i]; } Map<Integer, List<Segment>> sumToSegments = new HashMap<>(); for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { int sum = prefixSum[j] - prefixSum[i - 1]; sumToSegments .computeIfAbsent(sum, $ -> new ArrayList<>()) .add(Segment.make(i, j)); } } List<Segment> bestSegments = null; for (int sum : sumToSegments.keySet()) { List<Segment> segments = sumToSegments.get(sum); int size = segments.size(); int[] f = new int[size]; int[] next = new int[size]; boolean[] take = new boolean[size]; f[size - 1] = 1; next[size - 1] = -1; take[size - 1] = true; int bestStartIndex = size - 1; for (int i = size - 2; i >= 0; i--) { int nextIndex; if (segments.get(i).q >= segments.get(size - 1).p) { nextIndex = -1; } else { int L = i + 1; int R = size - 1; while (L < R) { int M = (L + R) / 2; if (segments.get(i).q >= segments.get(M).p) { /* intersection */ L = M + 1; } else { R = M; } } nextIndex = L; } f[i] = 1 + ((nextIndex == -1) ? 0 : f[nextIndex]); next[i] = nextIndex; take[i] = true; if (f[i + 1] > f[i]) { take[i] = false; f[i] = f[i + 1]; next[i] = i + 1; } if (bestStartIndex == -1 || f[i] > f[bestStartIndex]) { bestStartIndex = i; } } // recover segment set List<Segment> maxForSum = new ArrayList<>(); int index = bestStartIndex; do { if (take[index]) { maxForSum.add(segments.get(index)); } index = next[index]; } while (index != -1); if (bestSegments == null || maxForSum.size() > bestSegments.size()) { bestSegments = maxForSum; } } System.out.println(bestSegments.size()); for (Segment segment : bestSegments) { System.out.printf("%s %s%n", segment.p, segment.q); } in.close(); } private static class Segment { public final int p; public final int q; private Segment(int p, int q) { this.p = p; this.q = q; } public static Segment make(int p, int q) { return new Segment(p, q); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; public class Main { /*********************************************Constants******************************************/ static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static long mod=(long)1e9+7; static long mod1=998244353; static boolean sieve[]; static ArrayList<Integer> primes; static ArrayList<Long> factorial; static HashSet<Integer> graph[]; /****************************************Solutions Begins*****************************************/ public static void main (String[] args) throws Exception { String st[]=br.readLine().split(" "); int n=Integer.parseInt(st[0]); long input[]=new long[n]; st=br.readLine().split(" "); for(int i=0;i<n;i++){ input[i]=Long.parseLong(st[i]); } HashMap<Long,ArrayList<Pair>> map=new HashMap<>(); long pref[]=new long[n+1]; pref[1]=input[0]; for(int i=1;i<n;i++){ pref[i+1]=pref[i]+input[i]; } for(int i=0;i<n;i++){ for(int j=i;j<n;j++){ long sum=pref[j+1]-pref[i]; if(!map.containsKey(sum)){ ArrayList<Pair> list=new ArrayList<>(); list.add(new Pair(i,j)); map.put(sum,list); } else{ ArrayList<Pair> list=map.get(sum); list.add(new Pair(i,j)); } } } ArrayList<Pair> ans=new ArrayList<>(); // debug(map); for(long keys:map.keySet()){ ArrayList<Pair> list=map.get(keys); Collections.sort(list,new PairComp()); int nn=list.size(); for(int j=0;j<=0;j++){ ArrayList<Pair> cur=new ArrayList<>(); cur.add(list.get(j)); int lim=list.get(j).v; int i=j; while(i<nn){ if(list.get(i).u<=lim){ i++; } else{ cur.add(list.get(i)); lim=list.get(i).v; i++; } } if(ans.size()<cur.size()){ ans=cur; } } } out.println(ans.size()); for(Pair p:ans){ out.println(++p.u+" "+ ++p.v); } /****************************************Solutions Ends**************************************************/ out.flush(); out.close(); } /****************************************Template Begins************************************************/ /***************************************Precision Printing**********************************************/ static void printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.00000000000000000"); out.println(ft.format(d)); } /******************************************Graph*********************************************************/ static void Makegraph(int n){ graph=new HashSet[n]; for(int i=0;i<n;i++){ graph[i]=new HashSet<>(); } } static void addEdge(int a,int b){ graph[a].add(b); } /*********************************************PAIR********************************************************/ static class PairComp implements Comparator<Pair>{ public int compare(Pair p1,Pair p2){ if(p1.v>p2.v){ return 1; } else if(p1.v<p2.v){ return -1; } else{ return p1.u-p2.u; } } } static class Pair implements Comparable<Pair> { int u; int v; int index=-1; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } static class PairCompL implements Comparator<Pairl>{ public int compare(Pairl p1,Pairl p2){ if(p1.v>p2.v){ return -1; } else if(p1.v<p2.v){ return 1; } else{ return 0; } } } static class Pairl implements Comparable<Pair> { long u; long v; int index=-1; public Pairl(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*****************************************DEBUG***********************************************************/ public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } /************************************MODULAR EXPONENTIATION***********************************************/ static long modulo(long a,long b,long c) { long x=1; long y=a; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } /********************************************GCD**********************************************************/ static long gcd(long x, long y) { if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0) { r = a % b; a = b; b = r; } return r; } /******************************************SIEVE**********************************************************/ static void sieveMake(int n){ sieve=new boolean[n]; Arrays.fill(sieve,true); sieve[0]=false; sieve[1]=false; for(int i=2;i*i<n;i++){ if(sieve[i]){ for(int j=i*i;j<n;j+=i){ sieve[j]=false; } } } primes=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(sieve[i]){ primes.add(i); } } } /********************************************End***********************************************************/ }
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.List; import java.util.StringTokenizer; import java.util.HashMap; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); F2BlokiRavnoiSummiUslozhnennayaRedakciya solver = new F2BlokiRavnoiSummiUslozhnennayaRedakciya(); solver.solve(1, in, out); out.close(); } static class F2BlokiRavnoiSummiUslozhnennayaRedakciya { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] sum = new int[n]; int prev = 0; for (int i = 0; i < n; i++) { sum[i] = in.nextInt() + prev; prev = sum[i]; } HashMap<Integer, List<Pair<Integer, Integer>>> blocks = new HashMap<>(); int max = 0; int maxS = 0; for (int i = 0; i < n; i++) { for (int h = i; h >= 0; h--) { int s = sum[i]; if (h > 0) { s -= sum[h - 1]; } blocks.putIfAbsent(s, new ArrayList<>()); List<Pair<Integer, Integer>> l = blocks.get(s); if (l.isEmpty() || l.get(l.size() - 1).sc < h) { l.add(new Pair<>(h, i)); } if (l.size() > max) { max = l.size(); maxS = s; } } } out.println(max); for (int i = 0; i < max; i++) { out.println(String.format("%d %d", blocks.get(maxS).get(i).fs + 1, blocks.get(maxS).get(i).sc + 1)); } } } 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()); } } static class Pair<T, K> { T fs; K sc; public Pair(T fs, K sc) { this.fs = fs; this.sc = sc; } } }
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
//package com.example.programming; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Scanner; public class CodeforcesProblems { static class Pair { public Pair(int key, int val) { this.key = key; this.val = val; } int key; int val; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //String[] strings = br.readLine().split(" "); int n = Integer.parseInt(br.readLine()); String[] strings = br.readLine().split(" "); int[] arr = new int[n]; for(int i = 0; i<n; i++) { arr[i] = Integer.parseInt(strings[i]); } HashMap<Integer, ArrayList<Pair>> segments = new HashMap<>(); for(int r = 0; r<arr.length; r++) { int sum = 0; for(int l = r; l>=0; l--) { sum += arr[l]; ArrayList<Pair> pairs = segments.get(sum); if(pairs == null) { pairs = new ArrayList<>(); segments.put(sum, pairs); } pairs.add(new Pair(l, r)); } } int res = 0; ArrayList<Pair> result = new ArrayList<>(); for(ArrayList<Pair> pairs: segments.values()) { ArrayList<Pair> temp = new ArrayList<>(); int count = 0; int r = -1; for(Pair p : pairs) { if(p.key>r) { count++; temp.add(p); r = p.val; } } if(count>res) { res = count; result = temp; } } System.out.println(res); StringBuilder sb = new StringBuilder(); for(Pair p : result){ sb.append(p.key+1).append(' ').append(p.val+1).append('\n'); } System.out.print(sb); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import javax.print.attribute.standard.PrinterMessageFromOperator; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws Exception { new Main().run();} // int[] h,ne,to,wt; // int ct = 0; // int n; // void graph(int n,int m){ // h = new int[n]; // Arrays.fill(h,-1); //// sccno = new int[n]; //// dfn = new int[n]; //// low = new int[n]; //// iscut = new boolean[n]; // ne = new int[2*m]; // to = new int[2*m]; // wt = new int[2*m]; // ct = 0; // } // void add(int u,int v,int w){ // to[ct] = v; // ne[ct] = h[u]; // wt[ct] = w; // h[u] = ct++; // } // // int color[],dfn[],low[],stack[] = new int[1000000],cnt[]; // int sccno[]; // boolean iscut[]; // int time = 0,top = 0; // int scc_cnt = 0; // // // 有向图的强连通分量 // void tarjan(int u) { // low[u] = dfn[u]= ++time; // stack[top++] = u; // for(int i=h[u];i!=-1;i=ne[i]) { // int v = to[i]; // if(dfn[v]==0) { // tarjan(v); // low[u]=Math.min(low[u],low[v]); // } else if(sccno[v]==0) { // // dfn>0 but sccno==0, means it's in current stack // low[u]=Math.min(low[u],low[v]); // } // } // // if(dfn[u]==low[u]) { // sccno[u] = ++scc_cnt; // while(stack[top-1]!=u) { // sccno[stack[top-1]] = scc_cnt; // --top; // } // --top; // } // } // // //缩点, topology sort // int[] h1,to1,ne1; // int ct1 = 0; // void point(){ // for(int i=0;i<n;i++) { // if(dfn[i]==0) tarjan(i);//有可能图不连通,所以要循环判断。 // } // // 入度 // int du[] = new int[scc_cnt+1]; // h1 = new int[scc_cnt+1]; // Arrays.fill(h1, -1); // to1 = new int[scc_cnt*scc_cnt]; // ne1 = new int[scc_cnt*scc_cnt]; // // scc_cnt 个点 // // for(int i=1;i<=n;i++) { // for(int j=h[i]; j!=-1; j=ne[j]) { // int y = to[j]; // if(sccno[i] != sccno[y]) { // // add(sccno[i],sccno[y]); // 建新图 // to1[ct1] = sccno[y]; // ne1[ct1] = h[sccno[i]]; // h[sccno[i]] = ct1++; // du[sccno[y]]++; //存入度 // } // } // } // // int q[] = new int[100000]; // int end = 0; // int st = 0; // for(int i=1;i<=scc_cnt;++i){ // if(du[i]==0){ // q[end++] = i; // } // } // // int dp[] = new int[scc_cnt+1]; // while(st<end){ // int cur = q[st++]; // for(int i=h1[cur];i!=-1;i=ne1[i]){ // int y = to[i]; // // dp[y] += dp[cur]; // if(--du[y]==0){ // q[end++] = y; // } // } // } // } // // // // // int fa[]; // int faw[]; // // int dep = -1; // int pt = 0; // void go(int rt,int f,int dd){ // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = f;p++; // while(p>0) { // int cur = stk[p - 1]; // int fp = fk[p - 1]; // int ll = lk[p - 1]; // p--; // // // if (ll > dep) { // dep = ll; // pt = cur; // } // for (int i = h[cur]; i != -1; i = ne[i]) { // int v = to[i]; // if (fp == v) continue; // // stk[p] = v; // lk[p] = ll + wt[i]; // fk[p] = cur; // p++; // } // } // } // int pt1 = -1; // void go1(int rt,int f,int dd){ // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = f;p++; // while(p>0) { // int cur = stk[p - 1]; // int fp = fk[p - 1]; // int ll = lk[p - 1]; // p--; // // // if (ll > dep) { // dep = ll; // pt1 = cur; // } // // fa[cur] = fp; // for (int i = h[cur]; i != -1; i = ne[i]) { // int v = to[i]; // if (v == fp) continue; // faw[v] = wt[i]; // stk[p] = v; // lk[p] = ll + wt[i]; // fk[p] = cur; // p++; // } // } // } // // int r = 0; // int stk[] = new int[301]; // int fk[] = new int[301]; // int lk[] = new int[301]; // void ddfs(int rt,int t1,int t2,int t3,int l){ // // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = t3;p++; // while(p>0){ // int cur = stk[p-1]; // int fp = fk[p-1]; // int ll = lk[p-1]; // p--; // r = Math.max(r,ll); // for(int i=h[cur];i!=-1;i=ne[i]){ // int v = to[i]; // if(v==t1||v==t2||v==fp) continue; // stk[p] = v; // lk[p] = ll+wt[i]; // fk[p] = cur;p++; // } // } // // // // } static long mul(long a, long b, long p) { long res=0,base=a; while(b>0) { if((b&1L)>0) res=(res+base)%p; base=(base+base)%p; b>>=1; } return res; } static long mod_pow(long k,long n,long p){ long res = 1L; long temp = k; while(n!=0L){ if((n&1L)==1L){ res = (res*temp)%p; } temp = (temp*temp)%p; n = n>>1L; } return res%p; } int ct = 0; int f[] =new int[200001]; int b[] =new int[200001]; int str[] =new int[200001]; void go(int rt,List<Integer> g[]){ str[ct] = rt; f[rt] = ct; for(int cd:g[rt]){ ct++; go(cd,g); } b[rt] = ct; } int add =0; void go(int rt,int sd,int k,List<Integer> g[],int n){ if(add>n) { return; } Queue<Integer> q =new LinkedList<>(); q.offer(rt); for(int i=1;i<=sd;++i){ int sz =q.size(); if(sz==0) break; int f = (i==1?2:1); while(sz-->0){ int cur = q.poll(); for(int j=0;j<k-f;++j){ q.offer(add); g[cur].add(add);add++; if(add==n+1){ return; } } } } } void solve() { int n = ni(); int s[] = new int[n+1]; for(int i=0;i<n;++i){ s[i+1] = s[i] + ni(); } Map<Integer,List<int[]>> mp = new HashMap<>(); for(int i=0;i<n;++i) { for (int j = i; j>=0; --j) { int v = s[i+1]-s[j]; if(!mp.containsKey(v)){ mp.put(v, new ArrayList<>()); } mp.get(v).add(new int[]{j,i}); } } int all = 0;int vv = -1; for(int v:mp.keySet()){ List<int[]> r = mp.get(v); int sz = r.size();int c = 0; int ri = -2000000000; for(int j=0;j<sz;++j){ if(r.get(j)[0]>ri){ ri = r.get(j)[1];c++; } } if(c>all){ all = c; vv = v; } } println(all); List<int[]> r = mp.get(vv); int sz = r.size();int c = 0; int ri = -2000000000; for(int j=0;j<sz;++j){ if(r.get(j)[0]>ri){ ri = r.get(j)[1];println((1+r.get(j)[0])+" "+(1+r.get(j)[1])); } } //N , M , K , a , b , c , d . 其中N , M是矩阵的行列数;K 是上锁的房间数目,(a, b)是起始位置,(c, d)是出口位置 // int n = ni(); // int m = ni(); // int k = ni(); // int a = ni(); // int b = ni(); // int c = ni(); // int d = ni(); // // // char cc[][] = nm(n,m); // char keys[][] = new char[n][m]; // // char ky = 'a'; // for(int i=0;i<k;++i){ // int x = ni(); // int y = ni(); // keys[x][y] = ky; // ky++; // } // int f1[] = {a,b,0}; // // int dd[][] = {{0,1},{0,-1},{1,0},{-1,0}}; // // Queue<int[]> q = new LinkedList<>(); // q.offer(f1); // int ts = 1; // // boolean vis[][][] = new boolean[n][m][33]; // // while(q.size()>0){ // int sz = q.size(); // while(sz-->0) { // int cur[] = q.poll(); // vis[cur[0]][cur[1]][cur[2]] = true; // // int x = cur[0]; // int y = cur[1]; // // for (int u[] : dd) { // int lx = x + u[0]; // int ly = y + u[1]; // if (lx >= 0 && ly >= 0 && lx < n && ly < m && (cc[lx][ly] != '#')&&!vis[lx][ly][cur[2]]){ // char ck =cc[lx][ly]; // if(ck=='.'){ // if(lx==c&&ly==d){ // println(ts); return; // } // if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') { // int cao = cur[2] | (1 << (keys[lx][ly] - 'a')); // q.offer(new int[]{lx, ly, cao}); // vis[lx][ly][cao] = true; // }else { // // q.offer(new int[]{lx, ly, cur[2]}); // } // // }else if(ck>='A'&&ck<='Z'){ // int g = 1<<(ck-'A'); // if((g&cur[2])>0){ // if(lx==c&&ly==d){ // println(ts); return; // } // if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') { // // int cao = cur[2] | (1 << (keys[lx][ly] - 'a')); // q.offer(new int[]{lx, ly, cao}); // vis[lx][ly][cao] = true;; // }else { // // q.offer(new int[]{lx, ly, cur[2]}); // } // } // } // } // } // // } // ts++; // } // println(-1); // int n = ni(); // // HashSet<String> st = new HashSet<>(); // HashMap<String,Integer> mp = new HashMap<>(); // // // for(int i=0;i<n;++i){ // String s = ns(); // int id= 1; // if(mp.containsKey(s)){ // int u = mp.get(s); // id = u; // // } // // if(st.contains(s)) { // // while (true) { // String ts = s + id; // if (!st.contains(ts)) { // s = ts; // break; // } // id++; // } // mp.put(s,id+1); // }else{ // mp.put(s,1); // } // println(s); // st.add(s); // // } // int t = ni(); // // for(int i=0;i<t;++i){ // int n = ni(); // long w[] = nal(n); // // Map<Long,Long> mp = new HashMap<>(); // PriorityQueue<long[]> q =new PriorityQueue<>((xx,xy)->{return Long.compare(xx[0],xy[0]);}); // // for(int j=0;j<n;++j){ // q.offer(new long[]{w[j],0}); // mp.put(w[j],mp.getOrDefault(w[j],0L)+1L); // } // // while(q.size()>=2){ // long f[] = q.poll(); // long y1 = f[1]; // if(y1==0){ // y1 = mp.get(f[0]); // if(y1==1){ // mp.remove(f[0]); // }else{ // mp.put(f[0],y1-1); // } // } // long g[] = q.poll(); // long y2 = g[1]; // if(y2==0){ // y2 = mp.get(g[0]); // if(y2==1){ // mp.remove(g[0]); // }else{ // mp.put(g[0],y2-1); // } // } // q.offer(new long[]{f[0]+g[0],2L*y1*y2}); // // } // long r[] = q.poll(); // println(r[1]); // // // // // } // int o= 9*8*7*6; // println(o); // int t = ni(); // for(int i=0;i<t;++i){ // long a = nl(); // int k = ni(); // if(k==1){ // println(a); // continue; // } // // int f = (int)(a%10L); // int s = 1; // int j = 0; // for(;j<30;j+=2){ // int u = f-j; // if(u<0){ // u = 10+u; // } // s = u*s; // s = s%10; // if(s==k){ // break; // } // } // // if(s==k) { // println(a - j - 2); // }else{ // println(-1); // } // // // // // } // int m = ni(); // h = new int[n]; // to = new int[2*(n-1)]; // ne = new int[2*(n-1)]; // wt = new int[2*(n-1)]; // // for(int i=0;i<n-1;++i){ // int u = ni()-1; // int v = ni()-1; // // } // long a[] = nal(n); // int n = ni(); // int k = ni(); // t1 = new long[200002]; // // int p[][] = new int[n][3]; // // for(int i=0;i<n;++i){ // p[i][0] = ni(); // p[i][1] = ni(); // p[i][2] = i+1; // } // Arrays.sort(p, new Comparator<int[]>() { // @Override // public int compare(int[] x, int[] y) { // if(x[1]!=y[1]){ // return Integer.compare(x[1],y[1]); // } // return Integer.compare(y[0], x[0]); // } // }); // // for(int i=0;i<n;++i){ // int ck = p[i][0]; // // } } // int []h,to,ne,wt; long t1[]; // long t2[]; void update(long[] t,int i,long v){ for(;i<t.length;i+=(i&-i)){ t[i] += v; } } long get(long[] t,int i){ long s = 0; for(;i>0;i-=(i&-i)){ s += t[i]; } return s; } int equal_bigger(long t[],long v){ int s=0,p=0; for(int i=Integer.numberOfTrailingZeros(Integer.highestOneBit(t.length));i>=0;--i) { if(p+(1<<i)< t.length && s + t[p+(1<<i)] < v){ v -= t[p+(1<<i)]; p |= 1<<i; } } return p+1; } static class S{ int l = 0; int r = 0 ; long le = 0; long ri = 0; long tot = 0; long all = 0; public S(int l,int r) { this.l = l; this.r = r; } } static S a[]; static int[] o; static void init(int[] f){ o = f; int len = o.length; a = new S[len*4]; build(1,0,len-1); } static void build(int num,int l,int r){ S cur = new S(l,r); if(l==r){ a[num] = cur; return; }else{ int m = (l+r)>>1; int le = num<<1; int ri = le|1; build(le, l,m); build(ri, m+1,r); a[num] = cur; pushup(num, le, ri); } } // static int query(int num,int l,int r){ // // if(a[num].l>=l&&a[num].r<=r){ // return a[num].tot; // }else{ // int m = (a[num].l+a[num].r)>>1; // int le = num<<1; // int ri = le|1; // pushdown(num, le, ri); // int ma = 1; // int mi = 100000001; // if(l<=m) { // int r1 = query(le, l, r); // ma = ma*r1; // // } // if(r>m){ // int r2 = query(ri, l, r); // ma = ma*r2; // } // return ma; // } // } static long dd = 10007; static void update(int num,int l,long v){ if(a[num].l==a[num].r){ a[num].le = v%dd; a[num].ri = v%dd; a[num].all = v%dd; a[num].tot = v%dd; }else{ int m = (a[num].l+a[num].r)>>1; int le = num<<1; int ri = le|1; pushdown(num, le, ri); if(l<=m){ update(le,l,v); } if(l>m){ update(ri,l,v); } pushup(num,le,ri); } } static void pushup(int num,int le,int ri){ a[num].all = (a[le].all*a[ri].all)%dd; a[num].le = (a[le].le + a[le].all*a[ri].le)%dd; a[num].ri = (a[ri].ri + a[ri].all*a[le].ri)%dd; a[num].tot = (a[le].tot + a[ri].tot + a[le].ri*a[ri].le)%dd; //a[num].res[1] = Math.min(a[le].res[1],a[ri].res[1]); } static void pushdown(int num,int le,int ri){ } int gcd(int a,int b){ return b==0?a: gcd(b,a%b);} InputStream is;PrintWriter out; void run() throws Exception {is = System.in;out = new PrintWriter(System.out);solve();out.flush();} private byte[] inbuf = new byte[2]; 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 char ncc() {int b;while((b = readByte()) != -1 && !(b >= 32 && b <= 126));return (char)b;} 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 String nline() {int b = skip();StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b);b = readByte(); } return sb.toString();} private char[][] nm(int n, int m) {char[][] a = new char[n][];for (int i = 0; i < n; i++) a[i] = ns(m);return a;} private int[] na(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = ni();return a;} private long[] nal(int n) { long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nl();return a;} private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')){}; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') num = (num << 3) + (num << 1) + (b - '0'); else return minus ? -num : num; b = readByte();}} private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')){}; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') num = num * 10 + (b - '0'); else return minus ? -num : num; b = readByte();}} void print(Object obj){out.print(obj);} void println(Object obj){out.println(obj);} void println(){out.println();} }
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.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); } } LinkedList<Pair<Integer, Integer>>[] l = new LinkedList[h.size() + 1]; for (int i = 1; i <= h.size(); i++) { l[i] = new LinkedList(); } int k = 0, max = 0, index = 0; for (LinkedList<Pair<Integer, Integer>> temp : h.values()) { k++; int i = 0, size = 0; for (Pair<Integer, Integer> pair : temp) { if (pair.getKey() > i) { i = pair.getValue(); l[k].add(pair); size++; if (size > max) { max = size; index = k; } } } } pw.println(l[index].size()); for (Pair<Integer, Integer> pair : l[index]) { pw.println(pair.getKey() + " " + 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
/* Author: Anthony Ngene Created: 05/10/2020 - 14:12 */ import java.io.*; import java.util.*; public class F { // checks: 1. edge cases 2. overflow 3. possible errors (e.g 1/0, arr[out]) 4. time/space complexity void solver() throws IOException { int n = in.intNext(); int[] arr = in.nextIntArray(n); HashMap<Integer, Deque<Tuple>> subSum = new HashMap<>(); Integer best = null; for (int i = 0; i < n; i++) { int total = 0; for (int j = i; j < n; j++) { total += arr[j]; if (!subSum.containsKey(total)) subSum.put(total, new ArrayDeque<>()); Deque<Tuple> rs = subSum.get(total); if (rs.size() > 0 && rs.peekLast().b > j) rs.pollLast(); if (rs.size() == 0 || rs.peekLast().b < i) rs.add(new Tuple(i, j)); if (best == null || rs.size() > subSum.get(best).size()) best = total; } } Deque<Tuple> bestList = subSum.get(best); out.println(bestList.size()); for (Tuple aa: bestList) out.pp(aa.a + 1, aa.b + 1); } // Generated Code Below: private static final FastWriter out = new FastWriter(); private static FastScanner in; static ArrayList<Integer>[] adj; private static long e97 = (long)1e9 + 7; public static void main(String[] args) throws IOException { in = new FastScanner(); new F().solver(); out.close(); } static class FastWriter { private static final int IO_BUFFERS = 128 * 1024; private final StringBuilder out; public FastWriter() { out = new StringBuilder(IO_BUFFERS); } public FastWriter p(Object object) { out.append(object); return this; } public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; } public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; } public FastWriter pp(int[] args) { for (int ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; } public FastWriter pp(long[] args) { for (long ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; } public FastWriter pp(char[] args) { for (char ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; } public void println(long[] arr) { for(long e: arr) out.append(e).append(" "); out.append("\n"); } public void println(int[] arr) { for(int e: arr) out.append(e).append(" "); out.append("\n"); } public void println(char[] arr) { for(char e: arr) out.append(e).append(" "); out.append("\n"); } public void println(double[] arr) { for(double e: arr) out.append(e).append(" "); out.append("\n"); } public void println(boolean[] arr) { for(boolean e: arr) out.append(e).append(" "); out.append("\n"); } public <T>void println(T[] arr) { for(T e: arr) out.append(e).append(" "); out.append("\n"); } public void println(long[][] arr) { for (long[] row: arr) out.append(Arrays.toString(row)).append("\n"); } public void println(int[][] arr) { for (int[] row: arr) out.append(Arrays.toString(row)).append("\n"); } public void println(char[][] arr) { for (char[] row: arr) out.append(Arrays.toString(row)).append("\n"); } public void println(double[][] arr) { for (double[] row: arr) out.append(Arrays.toString(row)).append("\n"); } public <T>void println(T[][] arr) { for (T[] row: arr) out.append(Arrays.toString(row)).append("\n"); } public FastWriter println(Object object) { out.append(object).append("\n"); return this; } public void toFile(String fileName) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(out.toString()); writer.close(); } public void close() throws IOException { System.out.print(out); } } static class FastScanner { private InputStream sin = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; public FastScanner(){} public FastScanner(String filename) throws FileNotFoundException { File file = new File(filename); sin = new FileInputStream(file); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = sin.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long longNext() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while(true){ if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; }else if(b == -1 || !isPrintableChar(b) || b == ':'){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int intNext() { long nl = longNext(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double doubleNext() { return Double.parseDouble(next());} public long[] nextLongArray(final int n){ final long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = longNext(); return a; } public int[] nextIntArray(final int n){ final int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = intNext(); return a; } public double[] nextDoubleArray(final int n){ final double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = doubleNext(); return a; } public ArrayList<Integer>[] getAdj(int n) { ArrayList<Integer>[] adj = new ArrayList[n + 1]; for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>(); return adj; } public ArrayList<Integer>[] adjacencyList(int nodes, int edges) throws IOException { return adjacencyList(nodes, edges, false); } public ArrayList<Integer>[] adjacencyList(int nodes, int edges, boolean isDirected) throws IOException { adj = getAdj(nodes); for (int i = 0; i < edges; i++) { int a = intNext(), b = intNext(); adj[a].add(b); if (!isDirected) adj[b].add(a); } return adj; } } static class u { public static int upperBound(long[] array, long obj) { int l = 0, r = array.length - 1; while (r - l >= 0) { int c = (l + r) / 2; if (obj < array[c]) { r = c - 1; } else { l = c + 1; } } return l; } public static int upperBound(ArrayList<Long> array, long obj) { int l = 0, r = array.size() - 1; while (r - l >= 0) { int c = (l + r) / 2; if (obj < array.get(c)) { r = c - 1; } else { l = c + 1; } } return l; } public static int lowerBound(long[] array, long obj) { int l = 0, r = array.length - 1; while (r - l >= 0) { int c = (l + r) / 2; if (obj <= array[c]) { r = c - 1; } else { l = c + 1; } } return l; } public static int lowerBound(ArrayList<Long> array, long obj) { int l = 0, r = array.size() - 1; while (r - l >= 0) { int c = (l + r) / 2; if (obj <= array.get(c)) { r = c - 1; } else { l = c + 1; } } return l; } static <T> T[][] deepCopy(T[][] matrix) { return Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone()); } static int[][] deepCopy(int[][] matrix) { return Arrays.stream(matrix).map(int[]::clone).toArray($ -> matrix.clone()); } static long[][] deepCopy(long[][] matrix) { return Arrays.stream(matrix).map(long[]::clone).toArray($ -> matrix.clone()); } private static void sort(int[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); } private static void sort(long[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); } private static <T>void rSort(T[] arr) { Arrays.sort(arr, Collections.reverseOrder()); } private static void customSort(int[][] arr) { Arrays.sort(arr, new Comparator<int[]>() { public int compare(int[] a, int[] b) { if (a[0] == b[0]) return Integer.compare(a[1], b[1]); return Integer.compare(a[0], b[0]); } }); } public static int[] swap(int[] arr, int left, int right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; return arr; } public static char[] swap(char[] arr, int left, int right) { char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; return arr; } public static int[] reverse(int[] arr, int left, int right) { while (left < right) { int temp = arr[left]; arr[left++] = arr[right]; arr[right--] = temp; } return arr; } public static boolean findNextPermutation(int[] data) { if (data.length <= 1) return false; int last = data.length - 2; while (last >= 0) { if (data[last] < data[last + 1]) break; last--; } if (last < 0) return false; int nextGreater = data.length - 1; for (int i = data.length - 1; i > last; i--) { if (data[i] > data[last]) { nextGreater = i; break; } } data = swap(data, nextGreater, last); data = reverse(data, last + 1, data.length - 1); return true; } public static int biSearch(int[] dt, int target){ int left=0, right=dt.length-1; int mid=-1; while(left<=right){ mid = (right+left)/2; if(dt[mid] == target) return mid; if(dt[mid] < target) left=mid+1; else right=mid-1; } return -1; } public static int biSearchMax(long[] dt, long target){ int left=-1, right=dt.length; int mid=-1; while((right-left)>1){ mid = left + (right-left)/2; if(dt[mid] <= target) left=mid; else right=mid; } return left; } public static int biSearchMaxAL(ArrayList<Integer> dt, long target){ int left=-1, right=dt.size(); int mid=-1; while((right-left)>1){ mid = left + (right-left)/2; if(dt.get(mid) <= target) left=mid; else right=mid; } return left; } private static <T>void fill(T[][] ob, T res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}} private static void fill(boolean[][] ob,boolean res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}} private static void fill(int[][] ob, int res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}} private static void fill(long[][] ob, long res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}} private static void fill(char[][] ob, char res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}} private static void fill(double[][] ob, double res){for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}} private static void fill(int[][][] ob,int res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}} private static void fill(long[][][] ob,long res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}} private static <T>void fill(T[][][] ob,T res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}} private static void fill_parent(int[] ob){ for(int i=0; i<ob.length; i++) ob[i]=i; } private static boolean same3(long a, long b, long c){ if(a!=b) return false; if(b!=c) return false; if(c!=a) return false; return true; } private static boolean dif3(long a, long b, long c){ if(a==b) return false; if(b==c) return false; if(c==a) return false; return true; } private static double hypotenuse(double a, double b){ return Math.sqrt(a*a+b*b); } private static long factorial(int n) { long ans=1; for(long i=n; i>0; i--){ ans*=i; } return ans; } private static long facMod(int n, long mod) { long ans=1; for(long i=n; i>0; i--) ans = (ans * i) % mod; return ans; } private static long lcm(long m, long n){ long ans = m/gcd(m,n); ans *= n; return ans; } private static long gcd(long m, long n) { if(m < n) return gcd(n, m); if(n == 0) return m; return gcd(n, m % n); } private static boolean isPrime(long a){ if(a==1) return false; for(int i=2; i<=Math.sqrt(a); i++){ if(a%i == 0) return false; } return true; } static long modInverse(long a, long mod) { /* Fermat's little theorem: a^(MOD-1) => 1 Therefore (divide both sides by a): a^(MOD-2) => a^(-1) */ return binpowMod(a, mod - 2, mod); } static long binpowMod(long a, long b, long mod) { long res = 1; while (b > 0) { if (b % 2 == 1) res = (res * a) % mod; a = (a * a) % mod; b /= 2; } return res; } private static int getDigit2(long num){ long cf = 1; int d=0; while(num >= cf){ d++; cf = 1<<d; } return d; } private static int getDigit10(long num){ long cf = 1; int d=0; while(num >= cf){ d++; cf*=10; } return d; } private static boolean isInArea(int y, int x, int h, int w){ if(y<0) return false; if(x<0) return false; if(y>=h) return false; if(x>=w) return false; return true; } private static ArrayList<Integer> generatePrimes(int n) { int[] lp = new int[n + 1]; ArrayList<Integer> pr = new ArrayList<>(); for (int i = 2; i <= n; ++i) { if (lp[i] == 0) { lp[i] = i; pr.add(i); } for (int j = 0; j < pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= n; ++j) { lp[i * pr.get(j)] = pr.get(j); } } return pr; } static long nPrMod(int n, int r, long MOD) { long res = 1; for (int i = (n - r + 1); i <= n; i++) { res = (res * i) % MOD; } return res; } static long nCr(int n, int r) { if (r > (n - r)) r = n - r; long ans = 1; for (int i = 1; i <= r; i++) { ans *= n; ans /= i; n--; } return ans; } static long nCrMod(int n, int r, long MOD) { long rFactorial = nPrMod(r, r, MOD); long first = nPrMod(n, r, MOD); long second = binpowMod(rFactorial, MOD-2, MOD); return (first * second) % MOD; } static void printBitRepr(int n) { StringBuilder res = new StringBuilder(); for (int i = 0; i < 32; i++) { int mask = (1 << i); res.append((mask & n) == 0 ? "0" : "1"); } out.println(res); } static String bitString(int n) {return Integer.toBinaryString(n);} static int setKthBitToOne(int n, int k) { return (n | (1 << k)); } // zero indexed static int setKthBitToZero(int n, int k) { return (n & ~(1 << k)); } static int invertKthBit(int n, int k) { return (n ^ (1 << k)); } static boolean isPowerOfTwo(int n) { return (n & (n - 1)) == 0; } static HashMap<Character, Integer> counts(String word) { HashMap<Character, Integer> counts = new HashMap<>(); for (int i = 0; i < word.length(); i++) counts.merge(word.charAt(i), 1, Integer::sum); return counts; } static HashMap<Integer, Integer> counts(int[] arr) { HashMap<Integer, Integer> counts = new HashMap<>(); for (int value : arr) counts.merge(value, 1, Integer::sum); return counts; } static HashMap<Long, Integer> counts(long[] arr) { HashMap<Long, Integer> counts = new HashMap<>(); for (long l : arr) counts.merge(l, 1, Integer::sum); return counts; } static HashMap<Character, Integer> counts(char[] arr) { HashMap<Character, Integer> counts = new HashMap<>(); for (char c : arr) counts.merge(c, 1, Integer::sum); return counts; } static long hash(int x, int y) { return x* 1_000_000_000L +y; } static final Random random = new Random(); static void sort(int[] a) { int n = a.length;// shuffle, then sort for (int i = 0; i < n; i++) { int oi = random.nextInt(n), temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } static void sort(long[] arr) { shuffleArray(arr); Arrays.sort(arr); } static void shuffleArray(long[] arr) { int n = arr.length; for(int i=0; i<n; ++i){ long tmp = arr[i]; int randomPos = i + random.nextInt(n-i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } } static class Tuple implements Comparable<Tuple> { int a; int b; int c; public Tuple(int a, int b) { this.a = a; this.b = b; this.c = 0; } public Tuple(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public int getA() { return a; } public int getB() { return b; } public int getC() { return c; } public int compareTo(Tuple other) { if (this.a == other.a) { if (this.b == other.b) return Long.compare(this.c, other.c); return Long.compare(this.b, other.b); } return Long.compare(this.a, other.a); } @Override public int hashCode() { return Arrays.deepHashCode(new Integer[]{a, b, c}); } @Override public boolean equals(Object o) { if (!(o instanceof Tuple)) return false; Tuple pairo = (Tuple) o; return (this.a == pairo.a && this.b == pairo.b && this.c == pairo.c); } @Override public String toString() { return String.format("(%d %d %d) ", this.a, this.b, this.c); } } private static int abs(int a){ return (a>=0) ? a: -a; } private static int min(int... ins){ int min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; } private static int max(int... ins){ int max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; } private static int sum(int... ins){ int total = 0; for (int v : ins) { total += v; } return total; } private static long abs(long a){ return (a>=0) ? a: -a; } private static long min(long... ins){ long min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; } private static long max(long... ins){ long max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; } private static long sum(long... ins){ long total = 0; for (long v : ins) { total += v; } return total; } private static double abs(double a){ return (a>=0) ? a: -a; } private static double min(double... ins){ double min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; } private static double max(double... ins){ double max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; } private static double sum(double... ins){ double total = 0; for (double v : ins) { total += v; } return total; } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class CF1141F { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] split = br.readLine().split(" "); int[] terms = new int[n]; int[] sums = new int[n+1]; for(int i=0; i<n; i++) { terms[i] = Integer.parseInt(split[i]); sums[i+1] = sums[i]+terms[i]; } ArrayList<Block> blocks = new ArrayList<>(); for(int i=0; i<n; i++) for(int j=i; j<n; j++){ int s = sums[j+1]-sums[i]; blocks.add(new Block(i, j, s)); } Collections.sort(blocks); ArrayList<Block> best = new ArrayList<>(); int i = 0; while(i<blocks.size()){ int curSum = blocks.get(i).sum; ArrayList<Block> curBlocks = new ArrayList<>(); while(i<blocks.size() && blocks.get(i).sum==curSum) curBlocks.add(blocks.get(i++)); int[] memo = new int[curBlocks.size()+1]; Arrays.fill(memo, -1); memo[curBlocks.size()] = 0; for(int j=curBlocks.size()-1; j>=0; j--){ int idx = Collections.binarySearch(curBlocks, new Block(curBlocks.get(j).r+1, curBlocks.get(j).r+1, curBlocks.get(j).sum)); if(idx<0) idx = -(idx+1); memo[j] = Math.max(memo[j+1], 1+memo[idx]); } if(memo[0]>best.size()){ best = new ArrayList<>(); int idx = 0; while(memo[idx]>=1){ if(memo[idx]>memo[idx+1]) best.add(curBlocks.get(idx)); idx++; } } } StringBuilder sb = new StringBuilder(); sb.append(best.size()).append("\n"); for(Block b : best){ sb.append(b.l+1).append(" ").append(b.r+1).append("\n"); } System.out.print(sb); } static class Block implements Comparable<Block>{ int l, r, sum; Block(int a, int b, int c){ l = a; r = b; sum = c; } @Override public int compareTo(Block o) { if(sum==o.sum){ if(l==o.l) return r-o.r; return l-o.l; } return sum-o.sum; } } }
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.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author ijxjdjd */ 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); SameSumBlocks solver = new SameSumBlocks(); solver.solve(1, in, out); out.close(); } static class SameSumBlocks { int N; public void solve(int testNumber, InputReader in, PrintWriter out) { N = in.nextInt(); int[] arr = new int[N]; for (int i = 1; i <= N; i++) { arr[i - 1] = in.nextInt(); } HashMap<Integer, ArrayList<Segment>> map = new HashMap<>(); for (int i = 1; i <= N; i++) { int sum = 0; for (int j = i; j <= N; j++) { sum += arr[j - 1]; map.putIfAbsent(sum, new ArrayList<>()); map.get(sum).add(new Segment(i, j)); } } int resI = 0; int resVal = 0; int sum = 0; if (arr.length > 1 && arr[1] == -999) { for (int i = 11; i < 130; i++) { sum += arr[i]; } } for (int key : map.keySet()) { if (map.get(key).size() > resI) { int next = largestNon(map.get(key)); if (next > resI) { resVal = key; resI = next; } } } Pair res = largestNonOverlap(map.get(resVal)); out.println(resI); for (int i = 0; i < resI; i++) { out.println(res.used.get(i).li + " " + res.used.get(i).ri); } } int largestNon(ArrayList<Segment> arr) { Collections.sort(arr, new Comparator<Segment>() { public int compare(Segment o1, Segment o2) { return Integer.compare(o1.ri, o2.ri); } }); SameSumBlocks.SegmentTree seg = new SameSumBlocks.SegmentTree(N + 1); for (int i = 0; i < arr.size(); i++) { seg.add(arr.get(i).ri, arr.get(i).ri, 1 + seg.query(0, arr.get(i).li - 1).mx); } return seg.query(0, N).mx; } Pair largestNonOverlap(ArrayList<Segment> arr) { Segment[] segs = new Segment[N + 1]; int[] dp = new int[N + 1]; for (int i = 0; i <= N; i++) { segs[i] = new Segment(-1, 0); } for (Segment s : arr) { if (s.li > segs[s.ri].li) { segs[s.ri] = s; } } int[] used = new int[N + 1]; for (int i = 1; i <= N; i++) { dp[i] = dp[i - 1]; used[i] = used[i - 1]; if (segs[i].li != -1) { if (dp[i] < dp[segs[i].li - 1] + 1) { used[i] = i; dp[i] = dp[segs[i].li - 1] + 1; } } } ArrayList<Segment> res = new ArrayList<>(); int u = used[N]; while (segs[u].li > 0) { res.add(segs[u]); u = used[segs[u].li - 1]; } return new Pair(dp[N], res); } class Segment { int li; int ri; Segment() { } Segment(int li, int ri) { this.li = li; this.ri = ri; } } class Pair { int val; ArrayList<Segment> used = new ArrayList<>(); Pair(int val, ArrayList<Segment> used) { this.val = val; this.used = used; } } static class SegmentTree { Node[] tree; int size = 0; public Node none() { //return a node that will do nothing while merging: ex. Infinity for min query, -Infinity for max query, 0 for sum Node res = new Node(); return res; } public SegmentTree(int N) { tree = new Node[4 * N]; size = N; for (int i = 0; i < 4 * N; i++) { tree[i] = new Node(); } } Node combine(Node a, Node b) { //change when doing different operations Node res = new Node(); res.mx = Math.max(a.mx, b.mx); return res; } public Node query(int l, int r) { return queryUtil(1, 0, size - 1, l, r); } public Node queryUtil(int n, int tl, int tr, int l, int r) { //node number, cur range of node, cur range of query if (l > r) { return none(); } if (tl == l && tr == r) { return tree[n]; } int tm = (tl + tr) / 2; return combine(queryUtil(2 * n, tl, tm, l, Math.min(r, tm)), queryUtil(2 * n + 1, tm + 1, tr, Math.max(tm + 1, l), r)); } public void add(int l, int r, int val) { //change query, not assignment addUtil(1, 0, size - 1, l, r, val); } public void addUtil(int n, int tl, int tr, int l, int r, int val) { if (l > r) { return; } if (tl == l && tr == r) { tree[n].update(val); } else { int tm = (tl + tr) / 2; addUtil(2 * n, tl, tm, l, Math.min(tm, r), val); addUtil(2 * n + 1, tm + 1, tr, Math.max(l, tm + 1), r, val); tree[n] = combine(tree[2 * n], tree[2 * n + 1]); } } class Node { int mx = 0; int lzy = 0; void update(int val) { mx = Math.max(mx, val); lzy += val; } } } } 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.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); long[] arr=new long[n]; for(int i=0;i<n;i++) { arr[i]=s.nextInt(); } long[] pre=new long[n]; pre[0]=arr[0]; for(int i=1;i<n;i++) { pre[i]=pre[i-1]+arr[i]; } HashMap<Long,ArrayList<pair>> map=new HashMap<>(); for(int i=0;i<n;i++) { for(int j=i;j<n;j++) { long key=pre[j]-pre[i]+arr[i]; if(map.containsKey(key)) { pair p=new pair(i+1,j+1); ArrayList<pair> temp=map.get(key); temp.add(p); map.put(key,temp); } else { ArrayList<pair> list=new ArrayList<>(); pair p=new pair(i+1,j+1); list.add(p); map.put(key,list); } } } for(Map.Entry<Long,ArrayList<pair>> entry:map.entrySet()) { ArrayList<pair> curr=entry.getValue(); Collections.sort(curr,new comp()); } long ans=0; long max=-1000000000000l; for(Map.Entry<Long,ArrayList<pair>> entry:map.entrySet()) { ArrayList<pair> curr=entry.getValue(); int count=1; int l=curr.get(0).l; int r=curr.get(0).r; for(int i=1;i<curr.size();i++) { if(curr.get(i).l>r) { count++; l=curr.get(i).l; r=curr.get(i).r; } } if(count>max) { max=count; ans=entry.getKey(); } } System.out.println(max); ArrayList<pair> list=map.get(ans); System.out.println(list.get(0).l+" "+list.get(0).r); int l=list.get(0).l; int r=list.get(0).r; for(int i=1;i<list.size();i++) { if(list.get(i).l>r) { System.out.println(list.get(i).l+" "+list.get(i).r); l=list.get(i).l; r=list.get(i).r; } } } } class pair { int l; int r; public pair(int l,int r) { this.l=l; this.r=r; } } class comp implements Comparator<pair> { public int compare(pair a,pair b) { if(a.r<b.r) return -1; else if(a.r==b.r) { return b.l-a.l; } else return 1; } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; import java.io.*; import java.math.BigInteger; import static java.lang.Math.*; /* spar5h */ public class cf1 implements Runnable { static void addMap(int curr, HashMap<Integer, Integer> map, HashMap<Integer, Integer>[] hm, int j) { int prev = 0; if(map.get(curr) != null) prev = map.get(curr); int val = 0; if(hm[j].get(curr) != null) val = hm[j].get(curr); if(prev + 1 <= val) return; hm[j].put(curr, prev + 1); } public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = s.nextInt(); int[] a = new int[n]; HashMap<Integer, Integer>[] hm = new HashMap[n]; for(int i = 0; i < n; i++) { a[i] = s.nextInt(); hm[i] = new HashMap<Integer, Integer>(); } HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < n; i++) { int curr = 0; for(int j = i; j < n; j++) { curr += a[j]; addMap(curr, map, hm, j); } for(Map.Entry<Integer, Integer> e : hm[i].entrySet()) { if(map.get(e.getKey()) != null && map.get(e.getKey()) >= e.getValue()) continue; map.put(e.getKey(), e.getValue()); } } int key = -1; int value = 0; for(Map.Entry<Integer, Integer> e : map.entrySet()) { if(e.getValue() > value) { key = e.getKey(); value = e.getValue(); } } w.println(value); int prev = -1; for(int i = 0; i < n; i++) { int curr = 0; for(int j = i; j > prev; j--) { curr += a[j]; if(curr == key) { w.println((j + 1) + " " + (i + 1)); prev = i; break; } } } 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 cf1(),"cf1",1<<26).start(); } }
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.TreeMap; import java.util.StringTokenizer; import java.util.Map; import java.util.Map.Entry; 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; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); F solver = new F(); solver.solve(1, in, out); out.close(); } static class F { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.ni(); int[] a = in.na(n); TreeMap<Integer, TreeMap<Integer, Segment>> map = new TreeMap<>(); int[] pref = new int[n + 1]; for (int i = 0; i < n; i++) { pref[i + 1] = pref[i] + a[i]; } for (int i = 0; i < n; i++) { for (int j = i; j >= 0; j--) { int val = pref[i + 1] - pref[j]; TreeMap<Integer, Segment> dp = map.computeIfAbsent(val, k -> new TreeMap<>()); if (!dp.containsKey(i)) { Map.Entry<Integer, Segment> lastEntry = dp.lastEntry(); if (lastEntry == null) { dp.put(i, new Segment(j, i, 1, null)); } else { Segment lastValue = lastEntry.getValue(); Map.Entry<Integer, Segment> prev = dp.lowerEntry(j); if (prev == null) { if (lastValue.dp >= 1) dp.put(i, lastValue); else dp.put(i, new Segment(j, i, 1, null)); } else if (lastValue.dp >= prev.getValue().dp + 1) { dp.put(i, lastValue); } else { dp.put(i, new Segment(j, i, prev.getValue().dp + 1, prev.getValue())); } } } } } Segment best = null; for (TreeMap<Integer, Segment> segments : map.values()) { Segment seg = segments.lastEntry().getValue(); if (best == null || best.dp < seg.dp) { best = seg; } } if (best == null) throw new RuntimeException("Null best"); out.println(best.dp); while (best != null) { out.printf("%d %d%n", best.from + 1, best.to + 1); best = best.prev; } } class Segment { int from; int to; int dp; Segment prev; public Segment(int from, int to, int dp, Segment prev) { this.from = from; this.to = to; this.dp = dp; this.prev = prev; } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int ni() { return Integer.parseInt(ns()); } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; public class Main { static class Node implements Comparable<Node>{ public int l,r; public long s; Node(int l,int r,long s){ this.l=l; this.r=r; this.s=s; } public int compareTo(Node o) { if(o.s==s){ if(r>o.r) return 1; else if(r==o.r) { return 0; } else return -1; } else if(s>o.s){ return 1; } else { return -1; } } } static long[] sum=new long[1550]; public static void main(String[] args) { TreeMap<Long, ArrayList<Node> > mp = new TreeMap<>(); Scanner cin = new Scanner(System.in); int N=cin.nextInt(); for(int i=1;i<=N;i++){ int x=cin.nextInt(); sum[i]=sum[i-1]+x; } //System.out.println("here"); ArrayList<Node> arr = new ArrayList<>(); for(int l=1;l<=N;l++){ for(int r=l;r<=N;r++){ arr.add(new Node(l,r,sum[r]-sum[l-1])); } } Collections.sort(arr); for(int i=0;i<arr.size();i++){ ArrayList<Node> a=mp.get(arr.get(i).s); if(a==null) { a=new ArrayList<>(); mp.put(arr.get(i).s,a); } a.add(arr.get(i)); } int mx=-1; long mxv=-1; Iterator<Long> it=mp.keySet().iterator(); while(it.hasNext()){ int ans=0,t=0; long v=it.next(); ArrayList<Node> vec= mp.get(v); for(int i=0;i<vec.size();i++){ if(t<vec.get(i).l){ ans++; t=vec.get(i).r; } } // if(ans>mx){ mx=ans; mxv=v; // System.out.println(mxv); } } ArrayList<Node> vec=mp.get(mxv); System.out.println(mx); int t=0; for(int i=0;i<vec.size();i++){ // System.out.println(vec.get(i).l+" "+vec.get(i).r); // System.out.println("h"); if(t<vec.get(i).l){ System.out.println(vec.get(i).l+" "+vec.get(i).r); t=vec.get(i).r; } } } }
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.List; import java.util.Map; import java.util.Scanner; import java.util.HashMap; import java.util.ArrayList; /** * 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; Scanner in = new Scanner(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, 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<Pair>> map = new HashMap<>(); for (int r = 0; r < n; r++) { long sum = 0; for (int l = r; l >= 0; l--) { sum += arr[l]; if (map.containsKey(sum)) { map.get(sum).add(new Pair(l, r)); } else { map.put(sum, new ArrayList<>()); map.get(sum).add(new Pair(l, r)); } } } int ans = -1; List<Pair> ansPairs = new ArrayList<>(); for (long sum : map.keySet()) { List<Pair> pairs = map.get(sum); int count = 0; int idx = -1; List<Pair> tempPairs = new ArrayList<>(); for (Pair pair : pairs) { if (pair.i > idx) { idx = pair.j; tempPairs.add(pair); count++; } } if (ans < count) { ans = count; ansPairs = tempPairs; } } out.println(ans); for (Pair pair : ansPairs) { out.print((pair.i + 1) + " " + (pair.j + 1)); out.println(); } } class Pair { int i; int j; Pair(int p, int q) { i = p; j = q; } } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class b { public static void main(String[] rgs) { Scanner s=new Scanner(System.in); int n=s.nextInt(); long[] arr=new long[n]; for(int i=0;i<n;i++) { arr[i]=s.nextLong(); } HashMap<Long,ArrayList<pair>> map=new HashMap<>(); ArrayList<pair> list=new ArrayList<>(); for(int i=0;i<n;i++) { long sum=0; for(int j=i;j<n;j++) { sum=sum+arr[j]; pair ob=new pair(i,j); if(map.containsKey(sum)) { ArrayList p=map.get(sum); p.add(ob); map.put(sum, p); }else { ArrayList<pair> listt=new ArrayList<>(); listt.add(ob); map.put(sum,listt); } } } long in=-1; int max=0; for(Map.Entry<Long, ArrayList<pair>> entry:map.entrySet()) { int l=1; ArrayList<pair> p=entry.getValue(); Collections.sort(p,new comp()); int now=p.get(0).end; for(int j=0;j<p.size();j++) { if(p.get(j).st>now) { l++; now=p.get(j).end; } } if(l>max) { max=l; in=entry.getKey(); } } System.out.println(max); ArrayList<pair> d=map.get(in); int now=-1; for(int j=0;j<d.size();j++) { if(d.get(j).st>now) { System.out.println((d.get(j).st+1)+" "+(d.get(j).end+1)); now=d.get(j).end; } } } } class pair{ //long val; int st; int end; public pair(int st,int end) { //this.val=val; this.st=st; this.end=end; } } class comp implements Comparator<pair>{ public int compare(pair h,pair j) { if(h.end<j.end) { return -1; }else if(h.end==j.end) { if(h.st<j.st) { return 1; }else if(h.st==j.st) { return 0; }else { return -1; } }else { return 1; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.StringTokenizer; public class Solution { static final int INF = (int) 1e9; static final int mod = (int) (1e9 + 7); static final short UNCALC = -1; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int[] a = sc.nextIntArray(n); long[] cum = new long[n]; cum[0] = a[0]; for (int i = 1; i < n; i++) cum[i] = a[i] + cum[i - 1]; HashMap<Long, ArrayList<Pair>> hm = new HashMap<>(); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { long cur = get(cum, i, j); if (!hm.containsKey(cur)) hm.put(cur, new ArrayList<>()); hm.get(cur).add(new Pair(i, j)); } } int max = 0; StringBuilder ans = new StringBuilder(); for (long sum : hm.keySet()) { ArrayList<Pair> cur = hm.get(sum); Collections.sort(cur); int poss = 0; int r = -1; StringBuilder sb = new StringBuilder(); for (int i = 0; i < cur.size(); i++) { if (cur.get(i).left > r) { poss++; r = cur.get(i).right; sb.append(cur.get(i)); } } if (poss> max){ max = poss; ans = sb; } } out.println(max); out.println(ans); out.flush(); out.close(); } static long get(long[] a, int i, int j) { return a[j] - (i > 0 ? a[i - 1] : 0); } static class Pair implements Comparable<Pair> { int left, right; public Pair(int left, int right) { this.left = left; this.right = right; } @Override public int compareTo(Pair o) { return right - o.right; } @Override public String toString() { return (left + 1) + " " + (right + 1) + "\n"; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; import java.io.*; public class SameSumBlock { static BufferedReader br; static StringTokenizer tokenizer; public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); int n = nextInt(); int[] arr = new int[n]; int[] pSum = new int[n]; for(int i = 0; i< n; i++) { arr[i] = nextInt(); if(i != 0) pSum[i] += pSum[i - 1]; pSum[i] += arr[i]; } ArrayList<Interval> sorted = new ArrayList<Interval>(); for(int i = 0; i < n; i++) sorted.add(new Interval(pSum[i],0, i)); for(int i = 1; i < n; i++) { for(int j = i; j < n; j++) { sorted.add(new Interval(pSum[j] - pSum[i - 1], i, j)); } } sorted.sort(null); int i = 0; int max = 0, idx = 0, end = 0; while(i < sorted.size()) { int last = i; int curr = 1; int start = i; sorted.get(i).marked = true; while(i < sorted.size() - 1 && sorted.get(i).val == sorted.get(i + 1).val) { i++; if(sorted.get(i).l > sorted.get(last).r) { sorted.get(i).marked = true; curr++; last = i; } } if(curr > max) { max = curr; idx = start; end = i; } i++; } System.out.println(max); for(int j = idx; j <= end; j++) { if(sorted.get(j).marked) System.out.println(sorted.get(j).l + 1 + " " + (sorted.get(j).r + 1)); } } public static String next() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = br.readLine(); if (line == null) throw new IOException(); tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } } class Interval implements Comparable<Interval> { int val, l, r; boolean marked; public Interval(int val, int l, int r) { super(); this.val = val; this.l = l; this.r = r; } @Override public int compareTo(Interval o) { if(val != o.val) return val - o.val; return r - o.r; } }
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()); //thonky wonky HashMap<Long, ArrayList<Range>> map = new HashMap<Long, ArrayList<Range>>(); 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<Range>()); map.get(sum).add(new Range(i, r)); } } ArrayList<Range> res = new ArrayList<Range>(); for(long key: map.keySet()) { ArrayList<Range> ls = map.get(key); ArrayList<Range> temp = new ArrayList<Range>(); temp.add(ls.get(0)); int r = ls.get(0).r; for(int i=1; i < ls.size(); i++) if(r < ls.get(i).l) { r = ls.get(i).r; temp.add(ls.get(i)); } if(res.size() < temp.size()) res = temp; } System.out.println(res.size()); StringBuilder sb = new StringBuilder(); for(Range x: res) { sb.append(x.l+" "+x.r); sb.append("\n"); } System.out.print(sb); } } class Range { public int l; public int r; public Range(int a, int b) { l = a+1; r = b+1; } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.*; import java.util.*; public class CF1141F { static class V { int l, r, a; V(int l, int r, int a) { this.l = l; this.r = r; this.a = a; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int[] aa = new int[n + 1]; for (int i = 1; i <= n; i++) aa[i] = Integer.parseInt(st.nextToken()); for (int i = 1; i <= n; i++) aa[i] += aa[i - 1]; int m = n * (n + 1) / 2; V[] vv = new V[m]; m = 0; for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) vv[m++] = new V(i, j, aa[j] - aa[i - 1]); Arrays.sort(vv, (u, v) -> u.a != v.a ? u.a - v.a : u.r - v.r); int[] ii_ = new int[m]; int[] ii = new int[m]; int k_ = 0; for (int i = 0, j; i < m; i = j) { j = i + 1; while (j < m && vv[j].a == vv[i].a) j++; int k = 0, r = 0; for (int h = i; h < j; h++) if (vv[h].l > r) { ii[k++] = h; r = vv[h].r; } if (k_ < k) { k_ = k; int[] tmp = ii_; ii_ = ii; ii = tmp; } } pw.println(k_); for (int h = 0; h < k_; h++) { int i = ii_[h]; pw.println(vv[i].l + " " + vv[i].r); } pw.close(); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.*; import java.util.*; public class ProblemF_2 { public static InputStream inputStream = System.in; public static OutputStream outputStream = System.out; public static void main(String[] args) { MyScanner scanner = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); int n = scanner.nextInt(); List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(scanner.nextInt()); } Map<Integer, List<Pair<Integer, Integer>>> map = new HashMap<>(); for (int i = n - 1; i >= 0; i--) { int x = 0; for (int j = i; j >= 0; j--) { x = x + list.get(j); if (!map.containsKey(x)) { map.put(x, new ArrayList<>()); } map.get(x).add(new Pair<>(j + 1, i + 1)); } } List<Pair<Integer, Integer>> ans = new ArrayList<>(); for (Map.Entry<Integer, List<Pair<Integer, Integer>>> entry : map.entrySet()) { List<Pair<Integer, Integer>> segments = entry.getValue(); Collections.reverse(segments); List<Pair<Integer, Integer>> result = new ArrayList<>(); result.add(segments.get(0)); for (int i = 1; i < segments.size(); i++) { if (segments.get(i).first > result.get(result.size() - 1).second) { result.add(segments.get(i)); } } if (result.size() > ans.size()) { ans = result; } } out.println(ans.size()); for (Pair<Integer, Integer> pair : ans) { out.println(pair.first + " " + pair.second); } out.flush(); } private static class MyScanner { private BufferedReader bufferedReader; private StringTokenizer stringTokenizer; private MyScanner(InputStream inputStream) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); } private String next() { while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) { try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return stringTokenizer.nextToken(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } private String nextLine() { String str = ""; try { str = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } private static class Pair<F, S> { private F first; private S second; public Pair() {} public Pair(F first, S second) { this.first = first; this.second = second; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.nio.charset.Charset; import java.util.*; import static java.lang.System.gc; import static java.lang.System.out; public class Main { Scanner scanner = new Scanner(System.in); public static void main(String[] args) { new Main().solve(); } void solve() { int n = scanner.nextInt(); scanner.nextLine(); String s1 = scanner.nextLine(); String s2 = scanner.nextLine(); int ans = 0; boolean a[] = new boolean[30]; boolean b[] = new boolean[30]; for (int i = 0; i < n; i++) { if (s1.charAt(i) != s2.charAt(i)) { ans ++; a[s1.charAt(i) - 'a'] = true; b[s2.charAt(i) - 'a'] = true; } } for (int i = 0; i < n; i++) { if (s1.charAt(i) != s2.charAt(i) && a[s2.charAt(i) - 'a'] && b[s1.charAt(i) - 'a']) { for (int j = i + 1; j < n; j ++) { if (s1.charAt(i) == s2.charAt(j) && s1.charAt(j) == s2.charAt(i)) { out.println(ans - 2); out.println((i + 1) + " " + (j + 1)); return; } } } } for (int i = 0; i < n; i++) { if (s1.charAt(i) != s2.charAt(i) && (a[s2.charAt(i) - 'a'] || b[s1.charAt(i) - 'a'])) { for (int j = i + 1; j < n; j ++) { if (s1.charAt(j) != s2.charAt(j) && (s1.charAt(i) == s2.charAt(j) || s1.charAt(j) == s2.charAt(i))) { out.println(ans - 1); out.println((i + 1) + " " + (j + 1)); return; } } } } out.println(ans); out.println(-1 + " " + -1); } }
quadratic
527_B. Error Correct System
CODEFORCES
import javax.print.attribute.standard.RequestingUserName; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); int tc = in.nextInt(); for(int i = 0; i < tc; i++) solver.solve(i, in, out); out.close(); } static class Task { public void solve(int testNumber, InputReader in, PrintWriter out) { int k = in.nextInt(); int[] s = getArray(in.nextToken()); int[] a = getArray(in.nextToken()); int[] b = getArray(in.nextToken()); int[] per = new int[k]; boolean[] used = new boolean[k]; Arrays.fill(per , -1); if(!check(s , a, per.clone(), k, used)){ out.println("NO"); return; } for(int i = 0; i < s.length; i++){ if(per[s[i]] != -1){ continue; } for(int j = 0; j < k; j++){ if(used[j]){ continue; } per[s[i]] = j; used[j] = true; if(check(s , a , per.clone() , k, used)){ break; } per[s[i]] = -1; used[j] = false; } } for(int i = 0; i < s.length; i++){ if(per[s[i]] == -1){ out.println("NO"); return; } s[i] = per[s[i]]; } if(cmp(s , b) > 0){ out.println("NO"); return; } int last = 0; for(int i = 0; i < k; i++){ if(per[i] == -1) { while(used[last])last++; per[i] = last; used[last] = true; } } char[] result = new char[k]; for(int i = 0; i < k; i++){ result[i] = (char)('a' + per[i]); } out.println("YES"); out.println(new String(result)); } private int cmp(int[] a, int[] b){ for(int i = 0; i < a.length; i++){ if(a[i] != b[i]){ return a[i] < b[i] ? -1 : 1; } } return 0; } private boolean check(int[] s, int[] a, int[] per, int k, boolean[] used) { int res[] = new int[s.length]; int last = k - 1; for(int i = 0; i < res.length; ++i){ if(per[s[i]] == -1){ while(last >= 0 && used[last]){ last--; } if(last < 0){ return false; } per[s[i]] = last; last--; } res[i] = per[s[i]]; } return cmp(a , res) <= 0; } private int[] getArray(String nextToken) { int result[] = new int[nextToken.length()]; for(int i = 0; i < nextToken.length(); i++){ result[i] = nextToken.charAt(i) - 'a'; } return result; } } static class InputReader { BufferedReader in; StringTokenizer tok; public InputReader(InputStream stream){ in = new BufferedReader(new InputStreamReader(stream), 32768); tok = null; } String nextToken() { String line = ""; while(tok == null || !tok.hasMoreTokens()) { try { if((line = in.readLine()) != null) tok = new StringTokenizer(line); else return null; } catch (IOException e) { e.printStackTrace(); return null; } } return tok.nextToken(); } int nextInt(){ return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
quadratic
1086_C. Vasya and Templates
CODEFORCES
import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; /** * Built using CHelper plug-in Actual solution is at the top */ public class Practice { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); String[] arr1 = new String[n]; String[] arr2 = new String[n]; for (int i = 0; i < n; i++) { arr1[i] = in.next(); } for (int i = 0; i < n; i++) { arr2[i] = in.next(); } int ans = 0; boolean arr[]=new boolean[n]; boolean found=false; for (int i = 0; i < arr1.length; i++) { for(int j=0;j<arr1.length;j++){ found=false; if(arr1[i].equals(arr2[j]) && !arr[j]){ found=true; arr[j]=true; break; } } if(!found){ ans++; } } out.println(ans); } } public static boolean checkPrime(int n, int p) { for (int i = 2; i <= Math.sqrt(n) && i <= p; i++) { if (n % i == 0) { return false; } } return true; } public static void mergeArrays(int[] arr1, int[] arr2, int n1, int n2, int[] arr3) { int i = 0, j = 0, k = 0; while (i < n1 && j < n2) { if (arr1[i] < arr2[j]) { arr3[k++] = arr1[i++]; } else { arr3[k++] = arr2[j++]; } } while (i < n1) { arr3[k++] = arr1[i++]; } while (j < n2) { arr3[k++] = arr2[j++]; } } public long GCD(long a, long b) { if (b == 0) { return a; } return GCD(b, a % b); } public static long nCr(int n, int r) { return n * (n - 1) / 2; } 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()); } public double nextDouble() { return Double.parseDouble(next()); } } }
quadratic
1000_A. Codehorses T-shirts
CODEFORCES
import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.*; public class E1180D { public static void main(String args[]) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); // Move from both ends, Time limit exceeded on test 6 for (int i= 1; i<= m/2; i++) { // String s = ""; int i2 = m -i + 1; // the other end of i // i is left row, i2 is right row for (int j = 1; j <= n ; j++) { int j2 = n - j + 1; // start with (i,j), then go thru all the cell with (,i) and (,i2) pw.println(j + " " + i); pw.println(j2+ " " + i2); // s += j + " " + i + "\n" + j2+ " " + i2 + "\n"; } // out.print(s); } // if n is odd, there is one line in the middle if (m % 2 == 1) { int i2 = m /2 + 1; // this is the middle column for (int j = 1; j <= n/2 ; j++) { int j2 = n - j + 1; // start with (i,j), then go thru all the cell with (,i) and (,i2) pw.println(j + " " + i2); pw.println(j2+ " " + i2); } if (n %2 == 1) { int j = n /2 + 1; pw.println(j + " " + i2); } } pw.flush(); pw.close(); } }
quadratic
1179_B. Tolik and His Uncle
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; public class D { int[][] fast(int n, int m){ int[][] ans = new int[2][n * m]; int c = 0; for (int left = 1, right = m; left < right; left++, right--) { for (int l = 1, r = n; l <= n && r >= 1; l++, r--) { ans[0][c] = l; ans[1][c++] = left; ans[0][c] = r; ans[1][c++] = right; } } if (m % 2 == 1) { int x = m/2 + 1; for(int l = 1, r = n;l < r;l++, r--){ ans[0][c] = l; ans[1][c++] = x; ans[0][c] = r; ans[1][c++] = x; if(n % 2 == 1 && l + 2 == r){ ans[0][c] = l+1; ans[1][c++] = x; } } } if(n == 1 && m % 2 == 1){ ans[0][c] = 1; ans[1][c] = m/2 + 1; } return ans; } void stress(){ for(int i = 3;i<=5;i++){ for(int j = 2;j<=5;j++){ int[][] ans = new int[2][]; try{ ans = fast(i, j); }catch(Exception e){ out.println("ошибка"); out.print(i + " " + j); return; } boolean[][] check = new boolean[i][j]; for(int c = 0;c<ans[0].length;c++){ int x = ans[0][c] - 1; int y = ans[1][c] - 1; check[x][y] = true; } for(int c = 0;c<i;c++){ for(int q = 0;q<j;q++){ if(!check[c][q]){ out.println(i + " " + j); out.println("точки"); for(int w = 0;w<ans[0].length;w++){ out.println(ans[0][w] + " " + ans[1][w]); } return; } } } HashSet<String> set = new HashSet<>(); for(int c = 1;c<ans[0].length;c++){ int x = ans[0][c] - ans[0][c- 1]; int y = ans[1][c] - ans[1][c - 1]; set.add(x + " " + y); } if(set.size() < i * j - 1){ out.println(i + " " + j); out.println("вектора"); for(int w = 0;w<ans[0].length;w++){ out.println(ans[0][w] + " " + ans[1][w]); } return; } } } } void normal(){ int n =readInt(); int m = readInt(); int[][] ans = fast(n, m); for(int i = 0;i<ans[0].length;i++){ out.println(ans[0][i] + " " + ans[1][i]); } } boolean stress = false; void solve(){ if(stress) stress(); else normal(); } public static void main(String[] args) { new D().run(); } void run(){ init(); solve(); out.close(); } BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init(){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } String readLine(){ try{ return in.readLine(); }catch(Exception ex){ throw new RuntimeException(ex); } } 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()); } double readDouble(){ return Double.parseDouble(readString()); } }
quadratic
1179_B. Tolik and His Uncle
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { private void solve() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(), m = nextInt(); boolean[][] used = new boolean[n + 1][m + 1]; for (int j = 1; j <= (m + 1) / 2; j++) { int x1 = 1, x2 = n; for (int i = 1; i <= n; i++) { if (x1 <= n && !used[x1][j]) { out.println(x1 + " " + j); used[x1++][j] = true; } if (x2 > 0 && !used[x2][m - j + 1]) { out.println(x2 + " " + (m - j + 1)); used[x2--][m - j + 1] = true; } } } out.close(); } public static void main(String[] args) { new D().solve(); } private BufferedReader br; private StringTokenizer st; private PrintWriter out; private String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return st.nextToken(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } }
quadratic
1179_B. Tolik and His Uncle
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { private void solve() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(), m = nextInt(), u = 1, d = n; while (u < d) { for (int i = 1; i <= m; i++) { out.println(u + " " + i); out.println(d + " " + (m - i + 1)); } u++; d--; } if (u == d) { int l = 1, r = m; while (l < r) { out.println(u + " " + l++); out.println(d + " " + r--); } if (l == r) out.println(u + " " + l); } out.close(); } public static void main(String[] args) { new D().solve(); } private BufferedReader br; private StringTokenizer st; private PrintWriter out; private String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return st.nextToken(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } }
quadratic
1179_B. Tolik and His Uncle
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.InputMismatchException; import java.util.PriorityQueue; import java.util.StringTokenizer; public class D { static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } 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; } BigInteger nextBigInteger() { try { return new BigInteger(nextLine()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } } public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); FastWriter fw = new FastWriter(); int n = fr.nextInt(); int m = fr.nextInt(); for (int r = 0; r < n / 2; r++) { for (int c = 0; c < m; c++) { fw.println((r + 1) + " " + (c + 1)); fw.println((n - r) + " " + (m - c)); } } if (n % 2 != 0) { int r = n / 2; for (int c = 0; c < m / 2; c++) { fw.println((r + 1) + " " + (c + 1)); fw.println((r + 1) + " " + (m - c)); } if (m % 2 != 0) fw.println((r + 1) + " " + (m / 2 + 1)); } fw.close(); } }
quadratic
1179_B. Tolik and His Uncle
CODEFORCES
import java.util.*; import java.lang.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.*; public class Main { public static void main(String[] args) throws Exception{ FastReader sc=new FastReader(); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); int n=sc.nextInt(); int[] font=new int[n]; int[] cost=new int[n]; for(int i=0;i<n;i++) { font[i]=sc.nextInt(); } for(int i=0;i<n;i++) { cost[i]=sc.nextInt(); } int[] dou= new int[n]; for(int i=0;i<n;i++) { int min=Integer.MAX_VALUE; for(int j=0;j<i;j++) { if(font[j]<font[i]) { if(min>cost[i]+cost[j]) { min=cost[i]+cost[j]; } } } dou[i]=min; } int ans=Integer.MAX_VALUE; for(int i=0;i<n;i++) { int min=Integer.MAX_VALUE; for(int j=0;j<i;j++) { if(dou[j]!=Integer.MAX_VALUE && font[j]<font[i]) { if(min>dou[j]+cost[i]) { min=dou[j]+cost[i]; } } } if(min<ans) { ans=min; } } if(ans==Integer.MAX_VALUE) { System.out.println(-1); } else { System.out.println(ans); } } } 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
987_C. Three displays
CODEFORCES
import java.io.*; import java.lang.*; public class CF1003E{ public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] s = br.readLine().split(" "); int n = Integer.parseInt(s[0]); int d = Integer.parseInt(s[1]); int k = Integer.parseInt(s[2]); StringBuffer sb = new StringBuffer(); int[] rem = new int[n]; int[] deg = new int[n]; int i = 0; if(k == 1){ if(n <= 2){ }else{ System.out.println("NO"); return; } } for(i=0;i<d;i++){ if(i>=n-1){ System.out.println("NO"); return; } sb.append((i+1) +" " + (i+2)+"\n"); rem[i] = Math.min(i, d-i); deg[i]++; if(i+1<n) deg[i+1]++; } if(i<n){ rem[i] = 0; deg[i] = 1; } i++; int j = 0; for(;i<n;i++){ //For all remaining Nodes while(true){ if(j>=n){ System.out.println("NO"); return; } if(rem[j] > 0 && deg[j]<k){ deg[j]++; rem[i] = rem[j] - 1; sb.append((j+1)+" "+(i+1)+"\n"); deg[i]++; break; }else{ j++; } } } System.out.println("YES"); System.out.println(sb); } }
quadratic
1003_E. Tree Constructing
CODEFORCES
/** * Created at 22:05 on 2019-09-14 */ import java.io.*; import java.util.*; public class Main { static FastScanner sc = new FastScanner(); static Output out = new Output(System.out); static final int[] dx = {0, 1, 0, -1}; static final int[] dy = {-1, 0, 1, 0}; static final long MOD = (long) (1e9 + 7); static final long INF = Long.MAX_VALUE / 2; static final int e5 = (int) 1e5; public static class Solver { public Solver() { int N = sc.nextInt(); boolean[] flag = new boolean[101]; for (int i=0; i<N; i++) { flag[sc.nextInt()] = true; } int ans = 0; for (int i=1; i<=100; i++) { if (flag[i]) { ans++; for (int j=i*2; j<=100; j+=i) { flag[j] = false; } } } out.println(ans); } public static void sort(int[] a) { shuffle(a); Arrays.sort(a); } public static void sort(long[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(int[] arr){ int n = arr.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = arr[i]; int randomPos = i + rnd.nextInt(n-i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } public static void shuffle(long[] arr){ int n = arr.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = arr[i]; int randomPos = i + rnd.nextInt(n-i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } } public static void main(String[] args) { new Solver(); out.flush(); } static class FastScanner { private InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; public void load() { try { in = new FileInputStream(next()); } catch (Exception e) { e.printStackTrace(); } } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } public boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { return (int) nextLong(); } public int[] nextIntArray(int N, boolean oneBased) { if (oneBased) { int[] array = new int[N + 1]; for (int i = 1; i <= N; i++) { array[i] = sc.nextInt(); } return array; } else { int[] array = new int[N]; for (int i = 0; i < N; i++) { array[i] = sc.nextInt(); } return array; } } public long[] nextLongArray(int N, boolean oneBased) { if (oneBased) { long[] array = new long[N + 1]; for (int i = 1; i <= N; i++) { array[i] = sc.nextLong(); } return array; } else { long[] array = new long[N]; for (int i = 0; i < N; i++) { array[i] = sc.nextLong(); } return array; } } } static class Output extends PrintWriter { private long startTime; public Output(PrintStream ps) { super(ps); } public void print(int[] a, String separator) { for (int i = 0; i < a.length; i++) { if (i == 0) print(a[i]); else print(separator + a[i]); } println(); } public void print(long[] a, String separator) { for (int i = 0; i < a.length; i++) { if (i == 0) print(a[i]); else print(separator + a[i]); } println(); } public void print(String[] a, String separator) { for (int i = 0; i < a.length; i++) { if (i == 0) print(a[i]); else print(separator + a[i]); } println(); } public void print(ArrayList a, String separator) { for (int i = 0; i < a.size(); i++) { if (i == 0) print(a.get(i)); else print(separator + a.get(i)); } println(); } public void start() { startTime = System.currentTimeMillis(); } public void time(String s) { long time = System.currentTimeMillis() - startTime; println(s + "(" + time + ")"); } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; public class A { public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(System.in); FastPrinter out = new FastPrinter(System.out); new A().run(sc, out); out.close(); } public void run(FastScanner sc, FastPrinter out) throws Exception { int N = sc.nextInt(); int[] arr = sc.nextIntArray(N); Arrays.sort(arr); boolean[] done = new boolean[N]; int ans = 0; for (int i = 0; i < N; i++) { if (done[i]) continue; ans++; for (int j = i; j < N; j++) { if (arr[j] % arr[i] == 0) { done[j] = true; } } } out.println(ans); } public void shuffle(int[] arr) { for (int i = 0; i < arr.length; i++) { int r = (int) (Math.random() * arr.length); if (i != r) { arr[i] ^= arr[r]; arr[r] ^= arr[i]; arr[i] ^= arr[r]; } } } static class FastScanner { final private int BUFFER_SIZE = 1 << 10; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastScanner() { this(System.in); } public FastScanner(InputStream stream) { din = new DataInputStream(stream); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastScanner(String fileName) throws IOException { Path p = Paths.get(fileName); buffer = Files.readAllBytes(p); bytesRead = buffer.length; } int[] nextIntArray(int N) throws IOException { int[] arr = new int[N]; for (int i = 0; i < N; i++) { arr[i] = nextInt(); } return arr; } String nextLine() throws IOException { int c = read(); while (c != -1 && isEndline(c)) c = read(); if (c == -1) { return null; } StringBuilder res = new StringBuilder(); do { if (c >= 0) { res.appendCodePoint(c); } c = read(); } while (!isEndline(c)); return res.toString(); } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } String next() throws Exception { int c = readOutSpaces(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 { if (din == null) { bufferPointer = 0; bytesRead = -1; } else { 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++]; } private int readOutSpaces() throws IOException { while (true) { if (bufferPointer == bytesRead) fillBuffer(); int c = buffer[bufferPointer++]; if (!isSpaceChar(c)) { return c; } } } public void close() throws IOException { if (din == null) return; din.close(); } public int[][] readGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception { int[][] adj = new int[N][]; int[] numNodes = new int[N]; int[][] input = new int[M][2]; for (int i = 0; i < M; i++) { int a = nextInt(); int b = nextInt(); if (zeroIndexed) { a--; b--; } input[i][0] = a; input[i][1] = b; numNodes[a]++; if (bidirectional) numNodes[b]++; } for (int i = 0; i < N; i++) { adj[i] = new int[numNodes[i]]; numNodes[i] = 0; } for (int i = 0; i < M; i++) { int a = input[i][0]; int b = input[i][1]; adj[a][numNodes[a]++] = b; if (bidirectional) adj[b][numNodes[b]++] = a; } return adj; } public int[][][] readWeightedGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception { int[][][] adj = new int[N][][]; int[] numNodes = new int[N]; int[][] input = new int[M][3]; for (int i = 0; i < M; i++) { int a = nextInt(); int b = nextInt(); if (zeroIndexed) { a--; b--; } int d = nextInt(); input[i][0] = a; input[i][1] = b; input[i][2] = d; numNodes[a]++; if (bidirectional) numNodes[b]++; } for (int i = 0; i < N; i++) { adj[i] = new int[numNodes[i]][2]; numNodes[i] = 0; } for (int i = 0; i < M; i++) { int a = input[i][0]; int b = input[i][1]; int d = input[i][2]; adj[a][numNodes[a]][0] = b; adj[a][numNodes[a]][1] = d; numNodes[a]++; if (bidirectional) { adj[b][numNodes[b]][0] = a; adj[b][numNodes[b]][1] = d; numNodes[b]++; } } return adj; } } static class FastPrinter { static final char ENDL = '\n'; StringBuilder buf; PrintWriter pw; public FastPrinter(OutputStream stream) { buf = new StringBuilder(); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))); } public FastPrinter(String fileName) throws Exception { buf = new StringBuilder(); pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); } public FastPrinter(StringBuilder buf) { this.buf = buf; } public void print(int a) { buf.append(a); } public void print(long a) { buf.append(a); } public void print(char a) { buf.append(a); } public void print(char[] a) { buf.append(a); } public void print(double a) { buf.append(a); } public void print(String a) { buf.append(a); } public void print(Object a) { buf.append(a.toString()); } public void println() { buf.append(ENDL); } public void println(int a) { buf.append(a); buf.append(ENDL); } public void println(long a) { buf.append(a); buf.append(ENDL); } public void println(char a) { buf.append(a); buf.append(ENDL); } public void println(char[] a) { buf.append(a); buf.append(ENDL); } public void println(double a) { buf.append(a); buf.append(ENDL); } public void println(String a) { buf.append(a); buf.append(ENDL); } public void println(Object a) { buf.append(a.toString()); buf.append(ENDL); } public void printf(String format, Object... args) { buf.append(String.format(format, args)); } public void close() { pw.print(buf); pw.close(); } public void flush() { pw.print(buf); pw.flush(); buf.setLength(0); } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.exit; import static java.util.Arrays.sort; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A { static void solve() throws Exception { int n = scanInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanInt(); } sort(a); int ans = 0; ans: while (true) { for (int i = 0;; i++) { if (i == n) { break ans; } if (a[i] != 0) { ++ans; int t = a[i]; a[i] = 0; for (i++; i < n; i++) { if (a[i] % t == 0) { a[i] = 0; } } break; } } } out.print(ans); } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; public class Main { 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(); String ss[]=s.split(" "); int arr[]=new int[n]; for(int i=0;i<n;i++) arr[i]=Integer.parseInt(ss[i]); Arrays.sort(arr); int coun=0,coun2=0; for(int i=arr[0],k=0;k<n;) { for(int j=k;j<n;j++) { if(arr[j]%i==0) { arr[j]=-1; coun2++; } } Arrays.sort(arr); k=coun2; coun++; if(coun2<n) i=arr[coun2]; else break; } System.out.println(coun); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author null */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, Input in, PrintWriter out) { try { int n = in.readInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.readInt(); } Arrays.sort(a); boolean[] b = new boolean[n]; int ans = 0; while (true) { int x = 0; for (int i = 0; i < n; i++) { if (!b[i] && x == 0) { x = a[i]; } if (x != 0 && a[i] % x == 0) { b[i] = true; } } if (x == 0) { break; } ans++; } out.println(ans); } catch (Exception e) { throw new RuntimeException(e); } } } static class Input { public final BufferedReader reader; private String line = ""; private int pos = 0; public Input(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private boolean isSpace(char ch) { return ch <= 32; } public String readWord() throws IOException { skip(); int start = pos; while (pos < line.length() && !isSpace(line.charAt(pos))) { pos++; } return line.substring(start, pos); } public int readInt() throws IOException { return Integer.parseInt(readWord()); } private void skip() throws IOException { while (true) { if (pos >= line.length()) { line = reader.readLine(); pos = 0; } while (pos < line.length() && isSpace(line.charAt(pos))) { pos++; } if (pos < line.length()) { return; } } } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; import java.io.*; public class Main { static Scanner console; public static void main(String[] args) { console = new Scanner(System.in); int n = console.nextInt(); List<Integer> arr= new ArrayList<>(); for(int i = 0; i < n; i++) arr.add( console.nextInt()); Collections.sort(arr); List<Integer> groups = new ArrayList<>(); // System.out.println(arr); for(int i = 0; i < arr.size() - 1; i++) { int j = i+1; groups.add(arr.get(i)); // System.out.println(groups); while(j < arr.size()) { // System.out.println(j); if(arr.get(j) % arr.get(i) == 0) { arr.remove(j); } else { // groups.add(arr.get(j)); j++; } } } // System.out.println(arr); System.out.println(arr.size()); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; // Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail public class Ideone { public static void main(String args[] ) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n,i,j,k,temp ; n = ni(br.readLine()); int[] a = nia(br); Arrays.sort(a); int c = 0; for( i = 0; i< n ; i++) { if(a[i] > 0) { c++; temp = a[i]; for(j = i+1; j< n; j++) { if(a[j] % temp == 0) a[j] = 0; } } } System.out.println(c); } static Integer[] nIa(BufferedReader br) throws Exception{ String sa[]=br.readLine().split(" "); Integer [] a = new Integer [sa.length]; for(int i = 0; i< sa.length; i++){ a[i]= ni(sa[i]); } return a; } static int[] nia(BufferedReader br) throws Exception{ String sa[]=br.readLine().split(" "); int [] a = new int [sa.length]; for(int i = 0; i< sa.length; i++){ a[i]= ni(sa[i]); } return a; } static int ni(String s){ return Integer.parseInt(s); } static float nf(String s){ return Float.parseFloat(s); } static double nd(String s){ return Double.parseDouble(s); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class problemA { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] numbs = new int[n]; int[] smallest_color = new int[n]; for(int i = 0; i < n;i++){ numbs[i] = scan.nextInt(); } Arrays.sort(numbs); int count = 0; for(int i =0; i < n; i++){ for(int j=0; j <n;j++ ){ if(smallest_color[j] == 0){ count++; smallest_color[j] = numbs[i]; break; } if(numbs[i] % smallest_color[j] == 0){ break; } } } System.out.println(count); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; //****Use Integer Wrapper Class for Arrays.sort()**** public class AG1 { public static void main(String[] Args){ FastReader scan=new FastReader(); int n=scan.nextInt(); int[] arr=new int[n]; for (int i = 0; i <n ; i++) { arr[i]=scan.nextInt(); } Arrays.sort(arr); boolean[] done=new boolean[n]; int ans=0; for(int i=0;i<n;i++){ if(!done[i]){ done[i]=true; ans++; for(int j=i+1;j<n;j++){ if(arr[j]%arr[i]==0){ done[j]=true; } } } } System.out.println(ans); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class Main { static final long MOD = 998244353; //static final long MOD = 1000000007; static boolean[] visited; public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); int N = sc.nextInt(); int[] nums = new int[N]; for (int i = 0; i < N; i++) { nums[i] = sc.nextInt(); } Arrays.sort(nums); boolean[] hit = new boolean[N]; int colors = 0; int index = 0; while (index < N) { if (hit[index] == false) { colors++; int div = nums[index]; for (int i = index; i < N; i++) { if (nums[i] % div == 0) { hit[i] = true; } } } index++; } System.out.println(colors); } public static int[][] sort(int[][] array) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i< array.length; i++) { int randomPosition = rgen.nextInt(array.length); int[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } Arrays.sort(array, new Comparator<int[]>() { @Override public int compare(int[] arr1, int[] arr2) { //Ascending order if (arr1[0] != arr2[0]) return arr1[0]-arr2[0]; else return arr2[1]-arr1[1]; } }); return array; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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; } } } class Node { public HashSet<Node> children; public int n; public Node(int n) { this.n = n; children = new HashSet<Node>(); } public void addChild(Node node) { children.add(node); } public void removeChild(Node node) { children.remove(node); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return n; } @Override public boolean equals(Object obj) { if (! (obj instanceof Node)) { return false; } else { Node node = (Node) obj; return (n == node.n); } } public String toString() { return (this.n+1)+""; } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; public class codea{ public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int arr[] = new int[n]; for(int i =0;i<n;i++) arr[i]= in.nextInt(); Arrays.sort(arr); int max =0; boolean check[]= new boolean [n]; int count=0; for(int i =0;i<n;i++) { if(!check[i]) { count++; for(int j=i;j<n;j++) { if(arr[j]%arr[i]==0) check[j]=true; } } } System.out.println(count); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
//package Round584; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class typeA { public static void main(String[] args) { FastReader s = new FastReader(); int n = s.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) { arr[i]=s.nextInt(); } boolean[] arr2 = new boolean[n]; Arrays.sort(arr); for(int i=0;i<arr2.length;i++) { arr2[i]=true; } //arr2[0]=true; for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { if(arr[j]%arr[i]==0) { arr2[j]=false; } } } int count=0; for(int i=0;i<n;i++) { if(arr2[i]==true) { count++; } } System.out.println(count); } 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
1209_A. Paint the Numbers
CODEFORCES
import java.lang.*; import java.util.*; import java.io.*; public class Main { void solve() { int n=ni(); int a[]=new int[n+1]; for(int i=1;i<=n;i++) a[i]=ni(); int vis[]=new int[101]; int ans=0; Arrays.sort(a,1,n+1); for(int i=1;i<=n;i++){ if(vis[a[i]]==1) continue; ans++; for(int j=a[i];j<=100;j+=a[i]) vis[j]=1; } pw.println(ans); } long M = (long)1e9+7; // END PrintWriter pw; StringTokenizer st; BufferedReader br; void run() throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); } public static void main(String[] args) throws Exception { new Main().run(); } String ns() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() throws Exception { String str = ""; try { str = br.readLine(); } catch (IOException e) { throw new Exception(e.toString()); } return str; } int ni() { return Integer.parseInt(ns()); } long nl() { return Long.parseLong(ns()); } double nd() { return Double.parseDouble(ns()); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static void banana() throws IOException { int n = nextInt(); int[] a = new int[n]; int[] color = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } int c = 0; while(true) { int mn = 1000; for (int i = 0; i < n; i++) { if(color[i] == 0) { mn = Math.min(mn, a[i]); } } if (mn == 1000) { break; } c++; for (int i = 0; i < n; i++) { if (color[i] == 0) { if (a[i] % mn == 0) { color[i] = c; } } } } writer.println(c); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); banana(); reader.close(); writer.close(); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.lang.*; import java.util.*; public class Solver { public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); TaskC solver = new TaskC(in, out); solver.solve(); out.close(); } static class TaskC { FastReader in; PrintWriter out; public TaskC(FastReader in, PrintWriter out) { this.in = in; this.out = out; } public void solve() { solveA(); } public void solveA() { int n = in.nextInt(); int[] inputColors = in.nextIntArray(n); int colors = 0; Arrays.sort(inputColors); for (int i = 0; i < inputColors.length; i++) { if (inputColors[i] == -1) { continue; } int colorCode = inputColors[i]; boolean colorFound = false; for (int j = i; j < inputColors.length; j++) { if (inputColors[j] != -1 && inputColors[j] % colorCode == 0) { if (!colorFound) { colorFound = true; colors++; } inputColors[j] = -1; } } } out.println(colors); } public void solveB() { } public void solveC() { } public void solveD() { } public void solveE() { } public void solveF() { } public void solveG() { } public void solveH() { } } private static long gcd(long a, long b) { if (a == 0) { return b; } return gcd(b % a, a); } private static long lcm(long a, long b) { return (a * b) / gcd(a, b); } private static int min(int a, int b) { return a < b ? a : b; } private static int max(int a, int b) { return a > b ? a : b; } private static int min(ArrayList<Integer> list) { int min = Integer.MAX_VALUE; for (int el : list) { if (el < min) { min = el; } } return min; } private static int max(ArrayList<Integer> list) { int max = Integer.MIN_VALUE; for (int el : list) { if (el > max) { max = el; } } return max; } private static int min(int[] list) { int min = Integer.MAX_VALUE; for (int el : list) { if (el < min) { min = el; } } return min; } private static int max(int[] list) { int max = Integer.MIN_VALUE; for (int el : list) { if (el > max) { max = el; } } return max; } private static void fill(int[] array, int value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } 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; } int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = Integer.parseInt(sc.next()); int[] a = new int[N]; int[] flag = new int[N]; int ans = 0; for (int i=0;i<N;i++) { a[i] = Integer.parseInt(sc.next()); } Arrays.sort(a); for (int i=0;i<N;i++) { int used = 0; for (int j=0;j<N;j++) { if (flag[j]==1) { continue; } else { if (a[j]%a[i]==0) { used=1; flag[j]=1; } } } if (used==1) { ans++; } } System.out.println(ans); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class a1 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int a[] = new int[n]; HashMap<Integer,ArrayList<Integer>> h = new HashMap<>(); boolean visited[] = new boolean[n]; for(int i=0;i<n;i++) { a[i] = s.nextInt(); } Arrays.sort(a); for(int i=0;i<n;i++) { if(h.containsKey(a[i])) { ArrayList<Integer> temp = h.get(a[i]); temp.add(i); h.put(a[i],temp); } else { ArrayList<Integer> k =new ArrayList<>(); k.add(i); h.put(a[i], k); } } int ctr=0; for(int i=0;i<n;i++) { if(!visited[i]) { //System.out.println(a[i]); ctr++; for(int j=a[i];j<=100;j+=a[i]) { if(h.containsKey(j)) { ArrayList<Integer> m = h.get(j); for(int k=0;k<m.size();k++) { visited[m.get(k)]=true; } h.remove(j); } } } } System.out.println(ctr); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; public class PTM { public static void main(String[] args) throws Exception { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printWriter = new PrintWriter(System.out); int N = Integer.parseInt(bufferedReader.readLine()); String[] strings = bufferedReader.readLine().split(" "); int[] arr = new int[strings.length]; HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < N; i++) { arr[i] = Integer.parseInt(strings[i]); set.add(arr[i]); } Arrays.sort(arr); int c = 0; for (int i = 0; i < N; i++) { int value = arr[i]; if (!set.contains(value)) { continue; } for (int j = 1; j <= 100; j++) { if (set.contains(value * j)) { set.remove(value * j); } } c++; } printWriter.println(c); printWriter.flush(); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; public class A { FastScanner in; PrintWriter out; void solve() { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); int res = 0; for (int i = 0; i < n; i++) { boolean ok = false; for (int j = 0; j < i; j++) { if (a[i] % a[j] == 0) { ok = true; } } if (!ok) { res++; } } out.println(res); } void run() { try { in = new FastScanner(new File("A.in")); out = new PrintWriter(new File("A.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new A().runIO(); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Dasha { static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out), pw2 = new PrintWriter(System.out); public static void main(String[] args) throws IOException { int n=sc.nextInt(); int[] arr=new int[101]; for(int i=0;i<n;i++) arr[sc.nextInt()]++; boolean [] vis=new boolean[101]; int c=0; for(int i=1;i<=100;i++){ if(!vis[i]&&arr[i]>0){ c++; for(int j=i+i;j<=100;j+=i) vis[j]=true; } } pw.println(c); pw.flush(); } public static <E> void print2D(E[][] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { pw.println(arr[i][j]); } } } public static int digitSum(String s) { int toReturn = 0; for (int i = 0; i < s.length(); i++) toReturn += Integer.parseInt(s.charAt(i) + " "); return toReturn; } public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (long i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static long pow(long a, long pow) { return pow == 0 ? 1 : pow % 2 == 0 ? pow(a * a, pow >> 1) : a * pow(a * a, pow >> 1); } public static long sumNum(long a) { return a * (a + 1) / 2; } public static int gcd(int n1, int n2) { return n2 == 0 ? n1 : gcd(n2, n1 % n2); } public static long factorial(long a) { return a == 0 || a == 1 ? 1 : a * factorial(a - 1); } public static void sort(int arr[]) { shuffle(arr); Arrays.sort(arr); } public static void shuffle(int arr[]) { Random rnd = new Random(); for (int i = arr.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); int temp = arr[index]; arr[index] = arr[i]; arr[i] = temp; } } public static Double[] solveQuadratic(double a, double b, double c) { double result = (b * b) - 4.0 * a * c; double r1; if (result > 0.0) { r1 = ((double) (-b) + Math.pow(result, 0.5)) / (2.0 * a); double r2 = ((double) (-b) - Math.pow(result, 0.5)) / (2.0 * a); return new Double[]{r1, r2}; } else if (result == 0.0) { r1 = (double) (-b) / (2.0 * a); return new Double[]{r1, r1}; } else { return new Double[]{null, null}; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } static class pair<E1, E2> implements Comparable<pair> { E1 x; E2 y; pair(E1 x, E2 y) { this.x = x; this.y = y; } @Override public int compareTo(pair o) { return x.equals(o.x) ? (Integer) y - (Integer) o.y : (Integer) x - (Integer) o.x; } @Override public String toString() { return x + " " + y; } public double pointDis(pair p1) { return Math.sqrt(((Integer) y - (Integer) p1.y) * ((Integer) y - (Integer) p1.y) + ((Integer) x - (Integer) p1.x) * ((Integer) x - (Integer) p1.x)); } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { FastReader in = new FastReader(); int n = in.nextInt(); int[] a = new int[101]; for (int i = 0; i < n; i++) { a[in.nextInt()]++; } int count = 0; for (int i = 1; i < 101; i++) { if (a[i] > 0) { count++; for (int j = i; j < 101; j += i) { a[j] = 0; } } } System.out.println(count); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int[] nextSortedIntArray(int n) { int array[] = nextIntArray(n); Arrays.sort(array); return array; } public int[] nextSumIntArray(int n) { int[] array = new int[n]; array[0] = nextInt(); for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt(); return array; } public long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; ++i) array[i] = nextLong(); return array; } public long[] nextSumLongArray(int n) { long[] array = new long[n]; array[0] = nextInt(); for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt(); return array; } public long[] nextSortedLongArray(int n) { long array[] = nextLongArray(n); Arrays.sort(array); return array; } 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
1209_A. Paint the Numbers
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author KharYusuf */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); APaintTheNumbers solver = new APaintTheNumbers(); solver.solve(1, in, out); out.close(); } static class APaintTheNumbers { public void solve(int testNumber, FastReader s, PrintWriter w) { int n = s.nextInt(); boolean[] b = new boolean[n]; int[] a = new int[n]; int ans = 0; for (int i = 0; i < n; i++) { a[i] = s.nextInt(); } func.sort(a); for (int i = 0; i < n; i++) { if (!b[i]) { ans++; b[i] = true; for (int j = i + 1; j < n; j++) { //w.println(a[j]+" "+a[i]); if (a[j] % a[i] == 0) { b[j] = true; } } } } w.println(ans); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 func { public static void sort(int[] arr) { int n = arr.length, mid, h, s, l, i, j, k; int[] res = new int[n]; for (s = 1; s < n; s <<= 1) { for (l = 0; l < n - 1; l += (s << 1)) { h = Math.min(l + (s << 1) - 1, n - 1); mid = Math.min(l + s - 1, n - 1); i = l; j = mid + 1; k = l; while (i <= mid && j <= h) res[k++] = (arr[i] <= arr[j] ? arr[i++] : arr[j++]); while (i <= mid) res[k++] = arr[i++]; while (j <= h) res[k++] = arr[j++]; for (k = l; k <= h; k++) arr[k] = res[k]; } } } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String [] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int numbers[] = new int[n]; for (int i = 0; i < n; i++) { numbers[i] = scanner.nextInt(); } scanner.close(); Arrays.sort(numbers); boolean[] colored = new boolean[n]; int res = 0; for (int i = 0; i < n; i++) { if (!colored[i]) { res += 1; } for (int j = i; j < n; j++) { if (numbers[j] % numbers[i] == 0) { colored[j] = true; } } } System.out.println(res); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
//package practice; import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.Stack; import java.util.regex.Pattern; public class ROUGH { public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static long mod = (long) (1e9+7); static int N = (int) 1e5; // Scanner sc = new Scanner(System.in); public static void main(String[] args) { FastReader sc = new FastReader(); int n = sc.nextInt(); int[] a = new int[n]; TreeSet<Integer> set = new TreeSet<Integer>(); for(int i=0;i<n;++i) { a[i] = sc.nextInt(); set.add(a[i]); } long ans = 0; while(set.size() > 0) { ++ans; int min = set.first(); TreeSet<Integer> temp = new TreeSet<>(); for(int x : set) { if(x%min != 0) temp.add(x); } set = temp; } out.print(ans); out.close(); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Contest { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Contest().run(); } void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time(ms) = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } class MyComparator implements Comparable<MyComparator> { int x; int y; public MyComparator(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(MyComparator a) { if (x == a.x) { return (y - a.y); } return x - a.x; } } public static boolean isPrime(int num) { if (num > 2 && num % 2 == 0) { //System.out.println(num + " is not prime"); return false; } int top = (int) Math.sqrt(num) + 1; for (int i = 3; i < top; i += 2) { if (num % i == 0) { //System.out.println(num + " is not prime"); return false; } } //System.out.println(num + " is prime"); return true; } private static int lowerBound(int[] a, int low, int high, int element) { while (low < high) { int middle = low + (high - low) / 2; if (element > a[middle]) { low = middle + 1; } else { high = middle; } } return low; } private static int upperBound(int[] a, int low, int high, int element) { while (low < high) { int middle = low + (high - low) / 2; if (a[middle] > element) { high = middle; } else { low = middle + 1; } } return low; } public void solve() throws IOException { int num_a = readInt(); int[] array = new int[num_a]; for (int i = 0; i < num_a; i++) { array[i] = readInt(); } int result = 0; Arrays.sort(array); for (int i = 0; i < array.length; i++) { if (array[i] == -1) { continue; } for (int j = 0; j < array.length; j++) { if (array[j] != -1 && array[j] % array[i] == 0 && j != i) { //System.out.println(array[j]); array[j] = -1; //result++; } } result++; } System.out.println(result); } /** * * @param a * @param b * @return */ private BigInteger lcm(BigInteger a, BigInteger b) { return a.multiply(b.divide(a.gcd(b))); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Colours { public static void main(String args[] ) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int n = Integer.parseInt(line); line = br.readLine(); String[] values = line.split(" "); int[] arr = new int[n]; TreeSet<Integer> set = new TreeSet<>(); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(values[i]); set.add(arr[i]); } int count=0; TreeSet<Integer> copy = new TreeSet<>(); // for(int i=0;i<n;i++) copy.addAll(set); int prev = copy.size(); for(Integer i: set){ // System.out.println("i "+i); if(copy.size()==0){ break; } Iterator<Integer> iterator = copy.iterator(); while (iterator.hasNext()) { Integer e = iterator.next(); if (e % i == 0) { iterator.remove(); } } if(copy.size()!=prev){ count++; prev = copy.size(); } // System.out.println("size "+copy.size()); } System.out.println(count); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Main implements Runnable { boolean multiiple = false; void solve() throws Exception { int n = sc.nextInt(); ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(sc.nextInt()); Collections.sort(list); int ans = 0; while (!list.isEmpty()) { ans++; int next = list.get(0); for (int i = list.size() - 1; i >= 1; i--) { if (list.get(i) % next == 0) list.remove(i); } list.remove(0); } System.out.println(ans); } @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); if (multiiple) { int q = sc.nextInt(); for (int i = 0; i < q; i++) solve(); } else solve(); } catch (Throwable uncaught) { Main.uncaught = uncaught; } finally { out.close(); } } public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Main(), "", (1 << 26)); thread.start(); thread.join(); if (Main.uncaught != null) { throw Main.uncaught; } } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; public class Kaudo { static Reader in =new Reader(); static StringBuilder Sd=new StringBuilder(); static long ans,res,lot,max; static List<Integer>gr[]; static ArrayList<Integer> A=new ArrayList(); static String ch[]; public static void main(String [] args) { int n=in.nextInt(),a[]=new int [n],g=0; for(int i=0;i<n;i++){ a[i]=in.nextInt(); if(a[i]==1){System.out.println("1");return;} } ans=0; Arrays.sort(a); for(int i=0;i<n;i++){ int x=a[i]; if(x>0){ans++; for(int u=i;u<n;u++){ if(a[u]%x==0){a[u]=0;} }} } System.out.println(ans); } static int gcd(int a,int b){ if(b==0)return a; return gcd(b,a%b); } 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 int nextInt(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; public class PaintNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = in.nextInt(); } boolean[] visited = new boolean[n]; int min = Integer.MAX_VALUE; int a = 0; boolean cont = true; while (cont) { for (int i = 0; i < n; i++) { if (!visited[i]) { min = Math.min(min, nums[i]); } } cont = false; for (int i = 0; i < n; i++) { if (!visited[i] && nums[i] % min == 0) { cont = true; visited[i] = true; } } a++; min = Integer.MAX_VALUE; } System.out.println(a - 1); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; import static java.util.Arrays.fill; import static java.util.Arrays.copyOfRange; import static java.util.Arrays.binarySearch; import static java.lang.Math.min; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.max; import java.util.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; public class Main { public static void main(String[] args) throws IOException { int n = in.nextInt(); int[] a = in.nextIntArray(n); sort(a); int ans = 0; boolean[] done = new boolean[n]; for(int i = 0; i < n; i ++) { if(done[i]) continue; ans ++; for(int j = i + 1; j < n; j ++) if(a[j] % a[i] == 0) done[j] = true; } out.write(ans + "\n"); out.flush(); } public static FastReader in = new FastReader(); public static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); public static void gcj(int cn, Object ans) throws IOException { System.out.print("Case #" + cn + ": " + ans + "\n"); } public static ArrayList <Integer>[] ALArrayI(int size) { ArrayList <Integer>[] l = new ArrayList[size]; for(int i = 0; i < size; i ++) l[i] = new ArrayList <> (); return l; } public static ArrayList <Long>[] ALArrayL(int size) { ArrayList <Long>[] l = new ArrayList[size]; for(int i = 0; i < size; i ++) l[i] = new ArrayList <> (); return l; } public static Integer[] integerList(int fi, int fo) { Integer[] l = new Integer[fo - fi]; for(int i = 0; i < fo - fi; i ++) l[i] = fi + i; return l; } } class Graph { TreeSet <Integer>[] g; public Graph(int n) { g = new TreeSet[n]; for(int i = 0; i < n; i ++) g[i] = new TreeSet <> (); } public void addEdge(int u, int v) { g[u].add(v); } public TreeSet <Integer> getAdj(int u) { return g[u]; } public int nodes() { return g.length; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.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 String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i ++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) { Integer[] a = new Integer[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 String[] nextStringArray(int n) { String[] a = new String[n]; for(int i = 0; i < n; i ++) a[i] = next(); return a; } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; import java.lang.*; import static java.lang.Math.*; public class TaskA implements Runnable { long m = (int) 1e9 + 7; PrintWriter w; InputReader c; /*Global Variables*/ public void run() { c = new InputReader(System.in); w = new PrintWriter(System.out); int n = c.nextInt(); int a[] = scanArrayI(n); boolean vis[] = new boolean[n]; Arrays.sort(a); int ans=0; for(int i=0;i<n;i++){ if(vis[i]) continue; vis[i] = true; for(int j=i+1;j<n;j++){ if(a[j]%a[i] == 0){ vis[j] = true; } } ans++; boolean check = false; for(int j=0;j<n;j++){ if(!vis[j]) check = true; } if(!check) break; } w.println(ans); w.close(); } class pair{ int x,y,step; @Override public String toString() { return "pair{" + "x=" + x + ", y=" + y + ", step=" + step + '}'; } public pair(int x, int y, int s) { this.x = x; this.y = y; step = s; } } /*Template Stuff*/ class HashMapUtil<T, U> { void addHash(HashMap<T, Integer> hm, T a) { if (hm.containsKey(a)) hm.put(a, hm.get(a) + 1); else hm.put(a, 1); } void iterateHashMap(HashMap<T, U> hm) { for (Map.Entry<T, U> e : hm.entrySet()) { T key = e.getKey(); U value = e.getValue(); } } } public int search(int input[], int search) { int low = 0; int high = input.length - 1; int mid; while (low <= high) { mid = low + ((high - low) / 2); if (input[mid] == search) { return mid; } else if (input[mid] < search) { low = mid + 1; } else { high = mid - 1; } } return -1; } public void sort(int arr[]) { int n = arr.length, mid, h, s, l, i, j, k; int[] res = new int[n]; for (s = 1; s < n; s <<= 1) { for (l = 0; l < n - 1; l += (s << 1)) { h = min(l + (s << 1) - 1, n - 1); mid = min(l + s - 1, n - 1); i = l; j = mid + 1; k = l; while (i <= mid && j <= h) res[k++] = (arr[i] <= arr[j] ? arr[i++] : arr[j++]); while (i <= mid) res[k++] = arr[i++]; while (j <= h) res[k++] = arr[j++]; for (k = l; k <= h; k++) arr[k] = res[k]; } } } public int nextPowerOf2(int num) { if (num == 0) { return 1; } if (num > 0 && (num & (num - 1)) == 0) { return num; } while ((num & (num - 1)) > 0) { num = num & (num - 1); } return num << 1; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static void sortbyColumn(int arr[][], int col) { Arrays.sort(arr, new Comparator<int[]>() { public int compare(int[] o1, int[] o2) { return (Integer.valueOf(o1[col]).compareTo(o2[col])); } }); } public void printArray(int[] a) { for (int i = 0; i < a.length; i++) w.print(a[i] + " "); w.println(); } public int[] scanArrayI(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = c.nextInt(); return a; } public long[] scanArrayL(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = c.nextLong(); return a; } public void printArray(long[] a) { for (int i = 0; i < a.length; i++) w.print(a[i] + " "); w.println(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 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() { 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 TaskA(), "TaskA", 1 << 26).start(); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.ArrayList; import java.util.Scanner; public class PaintTheNumber { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); ArrayList<Integer> l=new ArrayList<Integer>(); for(int i=0; i<n; i++) { l.add(sc.nextInt()); } boolean c=false; for(int i=0; i<l.size(); i++) { if(l.get(i)==-1) continue; for(int j=0; j<l.size(); j++) { if(i==j || l.get(j)==-1) continue; else { if(l.get(j)%l.get(i)==0) { l.set(j, -1); } } } } int nbr=0; for(int i=0; i<l.size(); i++) if(l.get(i)!=-1) nbr++; System.out.println(nbr); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class A { public static void main(String[] args) { Scanner input = new Scanner(); StringBuilder output = new StringBuilder(); int n = input.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = input.nextInt(); } Arrays.sort(a); boolean[] colored = new boolean[n]; int colors = 0; for (int i = 0; i < n; i++) { if (!colored[i]) { colors ++; colored[i] = true; for (int j = i+1; j < n; j++) { if (a[j] % a[i] == 0) { colored[j] = true; } } } } System.out.println(colors); } private static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(Reader in) { br = new BufferedReader(in); } public Scanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } // end Scanner }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author gaidash */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); ARaskrashivanieChisel solver = new ARaskrashivanieChisel(); solver.solve(1, in, out); out.close(); } static class ARaskrashivanieChisel { public void solve(int testNumber, InputReader in, OutputWriter out) { final int MAX = 100; int n = in.nextInt(); int[] a = in.nextSortedIntArray(n); int ret = 0; boolean[] used = new boolean[MAX + 1]; for (int i = 0; i < n; i++) { if (!used[a[i]]) { used[a[i]] = true; ret++; for (int j = i + 1; j < n; j++) { if (a[j] % a[i] == 0 && !used[a[j]]) { used[a[j]] = true; } } } } out.println(ret); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int[] nextSortedIntArray(int n) { int array[] = nextIntArray(n); Arrays.sort(array); return array; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class A { public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int t = 1; while(t-->0) solver.solve(1, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader scan, PrintWriter out) { int n = scan.nextInt(); int[] a = new int[n]; boolean[] b = new boolean[n]; int count = 0; for(int i = 0; i < n; i++) a[i] = scan.nextInt(); Arrays.sort(a); for(int i = 0; i < n; i++) { if(b[i]) continue; count++; for(int j = i; j < n; j++) { if(a[j]%a[i] == 0) b[j] = true; } } out.println(count); } } static void shuffle(int[] a) { Random get = new Random(); for(int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for(int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new PrintStream(System.out)); int n=Integer.parseInt(f.readLine()); StringTokenizer st=new StringTokenizer(f.readLine()); int[]arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=Integer.parseInt(st.nextToken()); } Arrays.sort(arr); int ans=0; boolean[]used=new boolean[n]; for(int i=0;i<n;i++){ if(!used[i]){ ans++; for(int j=i+1;j<n;j++){ if(!used[j] && arr[j]%arr[i]==0){ used[j]=true; } } used[i]=true; } } System.out.print(ans); f.close(); out.close(); } } class pair implements Comparable <pair>{ int num; int idx; public int compareTo(pair other){ return num- other.num; } pair(int a, int b) { num=a; idx=b; } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; public class Main { static StringBuilder data = new StringBuilder(); final static FastReader in = new FastReader(); public static void main(String[] args) { int n = in.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); int answ = 0; for (int i = 0; i < n; i++) { if (a[i] != 0) { for (int j = i + 1; j < n; j++) { if (a[j] % a[i] == 0) { a[j] = 0; } } answ++; a[i]=0; } } System.out.println(answ); } static void fileOut(String s) { File out = new File("output.txt"); try { FileWriter fw = new FileWriter(out); fw.write(s); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String path) { try { br = new BufferedReader(new InputStreamReader(new FileInputStream(path))); } catch (FileNotFoundException e) { e.printStackTrace(); } } 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()); } float nextFloat() { return Float.parseFloat(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class first { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int n=s.nextInt(); int[] a=new int[n]; for (int i = 0; i < a.length; i++) { a[i]=s.nextInt(); } Arrays.sort(a); int count=0; for (int i = 0; i < a.length; i++) { if(a[i]!=0) { int x=a[i]; count++; for (int j = i; j < a.length; j++) { if(a[j]%x==0) { a[j]=0; } } } } System.out.println(count); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class PaintTheNumbers { public static void main(String[] args) throws IOException { int[] colors = new int[101]; BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); int N = Integer.parseInt(st.nextToken()); st = new StringTokenizer(f.readLine()); for (int i = 0; i < N; i++) { colors[Integer.parseInt(st.nextToken())]++; } int colorCount = 0; for (int i = 1; i <= 100; i++) { if (colors[i] != 0) { colors[i] = 0; for (int multiple = 2; multiple * i <= 100; multiple++) { colors[i*multiple] = 0; } colorCount++; } } System.out.println(colorCount); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; public class TaskA { public static void main(String[] args) { FastReader in = new FastReader(System.in); // FastReader in = new FastReader(new FileInputStream("input.txt")); PrintWriter out = new PrintWriter(System.out); // PrintWriter out = new PrintWriter(new FileOutputStream("output.txt")); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); int ans = 1; for (int i = 1; i < n; i++) { boolean bb = false; for (int j = i - 1; j >= 0; j--) { if (a[i] % a[j] == 0) { bb = true; break; } } if (!bb) ans++; } out.println(ans); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } Integer nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } Double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author unknown */ 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); APaintTheNumbers solver = new APaintTheNumbers(); solver.solve(1, in, out); out.close(); } static class APaintTheNumbers { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.i(); int[] a = in.ia(n); RadixSort.radixSort(a); boolean[] flag = new boolean[n]; int count = 0; for (int i = 0; i < n; i++) { if (!flag[i]) { ++count; flag[i] = true; for (int j = 0; j < n; j++) { if (!flag[j] && a[j] % a[i] == 0) { flag[j] = true; } } } } out.printLine(count); } } static class RadixSort { public static int[] radixSort(int[] f) { return radixSort(f, f.length); } public static int[] radixSort(int[] f, int n) { // credits uwi int[] to = new int[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]; int[] 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]; int[] d = f; f = to; to = d; } return f; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static class InputReader { private InputStream is; private byte[] inbuf = new byte[1024]; private int lenbuf = 0; private int ptrbuf = 0; public InputReader(InputStream is) { this.is = is; } 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++]; } public int[] ia(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = i(); return a; } public int i() { 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(); } } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class A { FastScanner in; PrintWriter out; boolean systemIO = true; public class Fenvik { int[] sum; public Fenvik(int n) { sum = new int[n]; } public void add(int x) { for (; x < sum.length; x = (x | (x + 1))) { sum[x]++; } } public int sum(int r) { int ans = 0; for (; r >= 0; r = (r & (r + 1)) - 1) { ans += sum[r]; } return ans; } } public int gcd(int x, int y) { if (y == 0) { return x; } if (x == 0) { return y; } return gcd(y, x % y); } public class Edge { int to; long s; public Edge(int to, long s) { this.to = to; this.s = s; } } public long dfs(int v, int prev, long sumth, long minsum, long s) { tin[v] = timer; timer++; up[v][0] = new Edge(prev, s); for (int i = 1; i <= l; i++) { Edge e = up[v][i - 1]; up[v][i] = new Edge(up[e.to][i - 1].to, up[e.to][i - 1].s + e.s); } minsum = Math.min(minsum, sumth); maxup[v] = sumth - minsum; long mxdown = sumth; for (Edge e : list[v]) { if (e.to != prev) { mxdown = Math.max(mxdown, dfs(e.to, v, sumth + e.s, minsum, e.s)); } } tout[v] = timer; timer++; maxdown[v] = mxdown - sumth; return mxdown; } public boolean upper(int a1, int b1) { return tin[a1] <= tin[b1] && tout[a1] >= tout[b1]; } public Edge lca(int a, int b) { if (a == b) { return new Edge(a, 0); } int v = -1; int a1 = a; int b1 = b; if (tin[a] <= tin[b] && tout[a] >= tout[b]) { v = b; long lenb = 0; for (int i = l; i >= 0; i--) { a1 = up[v][i].to; b1 = a; if (!(tin[a1] <= tin[b1] && tout[a1] >= tout[b1])) { lenb += up[v][i].s; v = up[v][i].to; } } lenb += up[v][0].s; v = up[v][0].to; return new Edge(v, lenb); } if (upper(b, a)) { v = a; long lena = 0; for (int i = l; i >= 0; i--) { a1 = up[v][i].to; b1 = b; if (!(tin[a1] <= tin[b1] && tout[a1] >= tout[b1])) { lena += up[v][i].s; v = up[v][i].to; } } lena += up[v][0].s; v = up[v][0].to; return new Edge(v, lena); } v = a; long lena = 0; for (int i = l; i >= 0; i--) { a1 = up[v][i].to; b1 = b; if (!(tin[a1] <= tin[b1] && tout[a1] >= tout[b1])) { lena += up[v][i].s; v = up[v][i].to; } } lena += up[v][0].s; v = up[v][0].to; v = b; long lenb = 0; for (int i = l; i >= 0; i--) { a1 = up[v][i].to; b1 = a; if (!(tin[a1] <= tin[b1] && tout[a1] >= tout[b1])) { lenb += up[v][i].s; v = up[v][i].to; } } lenb += up[v][0].s; v = up[v][0].to; return new Edge(v, lena + lenb); } int n; int l; int[] tin; int[] tout; int timer = 0; long[] maxup; long[] maxdown; Edge[][] up; ArrayList<Edge>[] list; public void solve() { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); } Arrays.sort(a); int ans = 0; boolean[] used = new boolean[n]; for (int i = 0; i < used.length; i++) { if (!used[i]) { ans++; for (int j = i; j < used.length; j++) { if (a[j] % a[i] == 0) { used[j] = true; } } } } out.print(ans); } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA public static void main(String[] arg) { new A().run(); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; import java.math.BigInteger; import java.util.Map.Entry; import static java.lang.Math.*; public class A extends PrintWriter { void run() { int n = nextInt(); int m = 101; boolean[] c = new boolean[m]; for (int i = 0; i < n; i++) { int v = nextInt(); c[v] = true; } int ans = 0; for (int v = 1; v < m; v++) { if (c[v]) { ++ans; for (int u = v; u < m; u += v) { c[u] = false; } } } println(ans); } boolean skip() { while (hasNext()) { next(); } return true; } int[][] nextMatrix(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) matrix[i][j] = nextInt(); return matrix; } String next() { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String line = nextLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } int[] nextArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return reader.readLine(); } catch (IOException err) { return null; } } public A(OutputStream outputStream) { super(outputStream); } static BufferedReader reader; static StringTokenizer tokenizer = new StringTokenizer(""); static Random rnd = new Random(); static boolean OJ; public static void main(String[] args) throws IOException { OJ = System.getProperty("ONLINE_JUDGE") != null; A solution = new A(System.out); if (OJ) { reader = new BufferedReader(new InputStreamReader(System.in)); solution.run(); } else { reader = new BufferedReader(new FileReader(new File(A.class.getName() + ".txt"))); long timeout = System.currentTimeMillis(); while (solution.hasNext()) { solution.run(); solution.println(); solution.println("----------------------------------"); } solution.println("time: " + (System.currentTimeMillis() - timeout)); } solution.close(); reader.close(); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Es1 { static IO io = new IO(); public static void main(String[] args) { int n = io.getInt(); int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = io.getInt(); Arrays.sort(a); int[] color = new int[n]; int num = 1; for(int i=0; i<n; i++){ if(color[i]==0){ for(int j=i+1; j<n; j++){ if(a[j]%a[i]==0) color[j] = num; } num++; } } io.println(num-1); io.close(); } } class IO extends PrintWriter { public IO() { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(System.in)); } public IO(String fileName) { super(new BufferedOutputStream(System.out)); try{ r = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { this.println("File Not Found"); } } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } public String getLine(){ try{ st = null; return r.readLine(); } catch(IOException ex){} return null; } private BufferedReader r; private String line; private StringTokenizer st; private String token; 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
1209_A. Paint the Numbers
CODEFORCES
import java.util.Scanner; public class Main { 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 min; int count = 0; int c = 0; while (count != n) { min = 1000; for (int i = 0; i < n; i++) { if (a[i] < min) { min = a[i]; } } for (int i = 0; i < n; i++) { if (a[i] != 1000 && a[i] % min == 0) { count++; a[i] = 1000; } } c++; } System.out.println(c); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES