src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.ObjectInputStream.GetField; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import javax.sound.sampled.ReverbType; public class N718 { static PrintWriter out; static Scanner sc; static ArrayList<int[]>q,w,x; static ArrayList<Integer>adj[]; static HashSet<Integer>primesH; static boolean prime[]; //static ArrayList<Integer>a; static HashSet<Long>tmp; static int[][][]dist; static boolean[]v; static int[]a,b,c,d; static Boolean[][]dp; static char[][]mp; static int A,B,n,m,h,ans,sum; //static String a,b; static long oo=(long)1e9+7; public static void main(String[]args) throws IOException { sc=new Scanner(System.in); out=new PrintWriter(System.out); //A(); //B(); //C(); D(); //E(); //F(); //G(); out.close(); } private static void A() throws IOException { int t=ni(); while(t-->0) { long l=nl(); if(l%2050!=0)ol(-1); else { long num=l/2050; int cnt=0; while(num>0) { cnt+=num%10; num/=10; } ol(cnt); } } } static void B() throws IOException { int t=ni(); while(t-->0) { int n=ni(),m=ni(); int[][]a=nmi(n,m); PriorityQueue<int[]>pq=new PriorityQueue<int[]>((u,v)->u[0]-v[0]); ArrayList<Integer>[]nums=new ArrayList[n]; for(int i=0;i<n;i++) { //nums[i]=new ArrayList<Integer>(); for(int j=0;j<m;j++) { ///nums[i].add(a[i][j]); pq.add(new int[] {a[i][j],i}); } } int[][]ans=new int[n][m]; for(int i=0;i<m;i++) { int[]x=pq.poll(); ans[x[1]][i]=x[0]; } int []indices=new int[n]; while(!pq.isEmpty()) { int[]x=pq.poll(); int i=x[1]; while(ans[i][indices[i]]!=0) { indices[i]++; } ans[i][indices[i]]=x[0]; } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { out.print(ans[i][j]+" "); } ol(""); } } } static void C() throws IOException{ int t=1; while(t-->0) { int n=ni(); a=nai(n); int[][]ans=new int[n][n]; for(int i=0;i<n;i++)ans[i][i]=a[i]; for(int i=n-1;i>=0;i--) { int j=i,k=i; int cur=ans[i][i]; cur--; while(cur>0) { j++; if(j>=n||ans[j][k]!=0) { j--; k--; } ans[j][k]=ans[i][i]; cur--; } } for(int i=0;i<n;i++) { for(int j=0;j<=i;j++) { out.print(ans[i][j]+" "); } ol(""); } } } private static Boolean dp(int i, int j) { if(j>sum/2)return false; if(i==x.size()) { return sum/2==j; } if(dp[i][j]!=null)return dp[i][j]; return dp[i][j]=dp(i+1,j+x.get(i)[0])||dp(i+1,j); } static boolean isPrime(long n) { if(n==2)return true; if(n<2||n%2==0)return false; for(long i=3L;i*i<n;i+=2l) { long rem=(n%i); if(rem==0)return false; } return true; } static void D() throws IOException { int t=1; while(t-->0) { int n=ni(),m=ni(),k=ni(); int[][]ans=new int[n][m]; dist=new int[n][m][4]; for(int i=0;i<n;i++)for(int j=0;j>m;j++) Arrays.fill(dist[i][j], Integer.MAX_VALUE); int x; for(int i=0;i<n;i++) { for(int j=0;j<m-1;j++) { dist[i][j][2]=(x=ni()); dist[i][j+1][3]=x; } } for(int i=0;i<n-1;i++) { for(int j=0;j<m;j++) { dist[i][j][1]=(x=ni()); dist[i+1][j][0]=x; } } int[][]nans=new int[n][m]; if(k%2==1) { for(int i=0;i<n;i++)Arrays.fill(ans[i], -1); }else { for(int ii=0;ii<k/2;ii++) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { nans[i][j]=Integer.MAX_VALUE; if(i>0) nans[i][j]=Math.min(nans[i][j], ans[i-1][j]+2*dist[i-1][j][1]); if(i<n-1) nans[i][j]=Math.min(nans[i][j], ans[i+1][j]+2*dist[i+1][j][0]); if(j>0) nans[i][j]=Math.min(nans[i][j], ans[i][j-1]+2*dist[i][j-1][2]); if(j<m-1) nans[i][j]=Math.min(nans[i][j], ans[i][j+1]+2*dist[i][j+1][3]); } } int[][]tmp=ans; ans=nans; nans=tmp; } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { out.print(ans[i][j]+" "); } ol(""); } } } private static int bfs(int i, int j,int k) { boolean [][]vis=new boolean[dist.length][dist[0].length]; Queue<int[]>q=new LinkedList<int[]>(); int mn=Integer.MAX_VALUE; q.add(new int[] {i,j,0,0}); int[]dx=new int[] {-1,1,0,0}; int[]dy=new int[] {0,0,1,-1}; while(!q.isEmpty()) { int []x=q.poll(); vis[x[0]][x[1]]=true; int c=x[2]; if(c>k/2)continue; if(c>0&&k%c==0&&(k/c)%2==0) { mn=Math.min(mn,x[3]*k/c ); } for(int a=0;a<4;a++) { int nx=x[0]+dx[a]; int ny=x[1]+dy[a]; if(valid(nx,ny)&&!vis[nx][ny]) { q.add(new int[] {nx,ny,c+1,x[3]+dist[x[0]][x[1]][a]}); } } } return mn; } private static boolean valid(int nx, int ny) { return nx>=0&&nx<dist.length&&ny>=0&&ny<dist[0].length; } static int gcd (int a, int b) { return b==0?a:gcd (b, a % b); } static void E() throws IOException { int t=ni(); while(t-->0) { } } static void F() throws IOException { int t=ni(); while(t-->0) { } } static void CC() throws IOException { for(int kk=2;kk<21;kk++) { ol(kk+" -------"); int n=kk; int k=n-2; int msk=1<<k; int[]a=new int[k]; for(int i=0;i<a.length;i++)a[i]=i+2; int mx=1; int ms=0; for(int i=1;i<msk;i++) { long prod=1; int cnt=0; for(int j=0;j<a.length;j++) { if(((i>>j)&1)!=0) { prod*=a[j]; cnt++; } } if(cnt>=mx&&prod%n==1) { mx=cnt; ms=i; } } ol(mx==1?mx:mx+1); out.print(1+" "); long pr=1; for(int j=0;j<a.length;j++) { if(((ms>>j)&1)!=0) { out.print(a[j]+" "); pr*=a[j]; } } ol(""); ol("Prod: "+pr); ol(n+"*"+((pr-1)/n)+" + "+1); } } static int ni() throws IOException { return sc.nextInt(); } static double nd() throws IOException { return sc.nextDouble(); } static long nl() throws IOException { return sc.nextLong(); } static String ns() throws IOException { return sc.next(); } static int[] nai(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); return a; } static long[] nal(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = sc.nextLong(); return a; } static int[][] nmi(int n,int m) throws IOException{ int[][]a=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=sc.nextInt(); } } return a; } static long[][] nml(int n,int m) throws IOException{ long[][]a=new long[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=sc.nextLong(); } } return a; } static void o(String x) { out.print(x); } static void ol(String x) { out.println(x); } static void ol(int x) { out.println(x); } static void disp1(int []a) { for(int i=0;i<a.length;i++) { out.print(a[i]+" "); } out.println(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public boolean hasNext() {return st.hasMoreTokens();} 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();} public boolean ready() throws IOException {return br.ready(); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; public class P1517D { // author: Nagabhushan S Baddi // PRIMARY VARIABLES private static int n, m, k; private static int[][] hor, ver, a, b; private static long ans; private static int[][] id; private static Integer[][][] dp; private static int idf; private static String s, t; private static HashMap<Integer, ArrayList<Integer>> g; // CONSTANTS private static final int MOD = (int) 1e9 + 7; public static void main(String[] args) { n = ini(); m = ini(); k = ini(); if (k%2!=0) { for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { print(-1+" "); } println(); } out.flush(); return; } hor = new int[n][m-1]; ver = new int[n-1][m]; for(int i=0; i<n; i++) { for(int j=0; j<m-1; j++) { hor[i][j] = ini(); } } for(int i=0; i<n-1; i++) { for(int j=0; j<m; j++) { ver[i][j] = ini(); } } dp = new Integer[n][m][k+1]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { print(2*solve(i, j, k/2)+" "); } println(); } out.flush(); out.close(); } private static int solve(int i, int j, int kLeft) { if (i<0 || i>=n || j<0 || j>=m) { return (int)1e9; } else if (kLeft==0) { return 0; } if (dp[i][j][kLeft]!=null) { return dp[i][j][kLeft]; } int ans = (int)1e9; final int[] dx = {-1, 1, 0, 0}; final int[] dy = {0, 0, -1, 1}; for(int type=0; type<4; type++) { int ni = i+dx[type]; int nj = j+dy[type]; if (ni<0 || ni>=n || nj<0 || nj>=m) continue; int inhibit = 0; if (type==0) { inhibit = ver[ni][nj]; } else if (type==1) { inhibit = ver[i][j]; } else if (type==2) { inhibit = hor[ni][nj]; } else { inhibit = hor[i][j]; } ans = Math.min(ans, inhibit+solve(ni, nj, kLeft-1)); } return dp[i][j][kLeft]=ans; } // INIT private static void initCase(int z) { idf = z; ans = 0; } // PRINT ANSWER private static void printAns(Object o) { out.println(o); } private static void printAns(Object o, int testCaseNo) { out.println("Case #" + testCaseNo + ": " + o); } private static void printArray(Object[] a) { for (int i = 0; i < a.length; i++) { out.print(a[i] + " "); } out.println(); } // SORT SHORTCUTS - QUICK SORT TO MERGE SORT private static void sort(int[] a) { int n = a.length; Integer[] b = new Integer[n]; for (int i = 0; i < n; i++) { b[i] = a[i]; } Arrays.sort(b); for (int i = 0; i < n; i++) { a[i] = b[i]; } } private static void sort(long[] a) { int n = a.length; Long[] b = new Long[n]; for (int i = 0; i < n; i++) { b[i] = a[i]; } Arrays.sort(b); for (int i = 0; i < n; i++) { a[i] = b[i]; } } // INPUT SHORTCUTS private static int[] ina(int n) { int[] temp = new int[n]; for (int i = 0; i < n; i++) { temp[i] = in.nextInt(); } return temp; } private static int[][] ina2d(int n, int m) { int[][] temp = new int[n][m]; for (int i = 0; i < n; i++) { temp[i] = ina(m); } return temp; } private static int ini() { return in.nextInt(); } private static long inl() { return in.nextLong(); } private static double ind() { return Double.parseDouble(ins()); } private static String ins() { return in.readString(); } // PRINT SHORTCUTS private static void println(Object... o) { for (Object x : o) { out.write(x + ""); } out.write("\n"); } private static void pd(Object... o) { for (Object x : o) { out.write(x + ""); } out.flush(); out.write("\n"); } private static void print(Object... o) { for (Object x : o) { out.write(x + ""); } } // GRAPH SHORTCUTS private static HashMap<Integer, ArrayList<Integer>> intree(int n) { HashMap<Integer, ArrayList<Integer>> g = new HashMap<>(); for (int i = 0; i < n; i++) { g.put(i, new ArrayList<>()); } for (int i = 0; i < n - 1; i++) { int u = ini() - 1; int v = ini() - 1; g.get(u).add(v); g.get(v).add(u); } return g; } private static HashMap<Integer, ArrayList<Integer>> ingraph(int n, int m) { HashMap<Integer, ArrayList<Integer>> g = new HashMap<>(); for (int i = 0; i < n; i++) { g.put(i, new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = ini() - 1; int v = ini() - 1; g.get(u).add(v); g.get(v).add(u); } return g; } private static HashMap<Integer, ArrayList<Integer>> indirectedgraph(int n, int m) { HashMap<Integer, ArrayList<Integer>> g = new HashMap<>(); for (int i = 0; i < n; i++) { g.put(i, new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = ini() - 1; int v = ini() - 1; g.get(u).add(v); } return g; } private static HashMap<Integer, ArrayList<Edge>> inweightedgraph(int n, int m) { HashMap<Integer, ArrayList<Edge>> g = new HashMap<>(); for (int i = 0; i < n; i++) { g.put(i, new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = ini() - 1; int v = ini() - 1; int w = ini(); Edge edge = new Edge(u, v, w); g.get(u).add(edge); g.get(v).add(edge); } return g; } private static class Edge implements Comparable<Edge> { private int u, v; private long w; public Edge(int a, int b, long c) { u = a; v = b; w = c; } public int other(int x) { return (x == u ? v : u); } public int compareTo(Edge edge) { return Long.compare(w, edge.w); } } private static class Pair { private int u, v; public Pair(int a, int b) { u = a; v = b; } public int hashCode() { return u + v + u * v; } public boolean equals(Object object) { Pair pair = (Pair) object; return u == pair.u && v == pair.v; } } private static class Node implements Comparable<Node> { private int u; private long dist; public Node(int a, long b) { u = a; dist = b; } public int compareTo(Node node) { return Long.compare(dist, node.dist); } } // MATHS AND NUMBER THEORY SHORTCUTS private static int gcd(int a, int b) { // O(log(min(a,b))) if (b == 0) return a; return gcd(b, a % b); } private static long modExp(long a, long b) { if (b == 0) return 1; a %= MOD; long exp = modExp(a, b / 2); if (b % 2 == 0) { return (exp * exp) % MOD; } else { return (a * ((exp * exp) % MOD)) % MOD; } } private long mul(int a, int b) { return a * 1L * b; } // Segment Tree private static class SegmentTree<T extends Comparable<T>> { private int n, m; private T[] a; private T[] seg; private T NULLVALUE; public SegmentTree(int n, T NULLVALUE) { this.NULLVALUE = NULLVALUE; this.n = n; m = 4 * n; seg = (T[]) new Object[m]; } public SegmentTree(T[] a, int n, T NULLVALUE) { this.NULLVALUE = NULLVALUE; this.a = a; this.n = n; m = 4 * n; seg = (T[]) new Object[m]; construct(0, n - 1, 0); } private void update(int pos) { // Range Sum // seg[pos] = seg[2*pos+1]+seg[2*pos+2]; // Range Min if (seg[2 * pos + 1].compareTo(seg[2 * pos + 2]) <= 0) { seg[pos] = seg[2 * pos + 1]; } else { seg[pos] = seg[2 * pos + 2]; } } private T optimum(T leftValue, T rightValue) { // Range Sum // return leftValue+rightValue; // Range Min if (leftValue.compareTo(rightValue) <= 0) { return leftValue; } else { return rightValue; } } public void construct(int low, int high, int pos) { if (low == high) { seg[pos] = a[low]; return; } int mid = (low + high) / 2; construct(low, mid, 2 * pos + 1); construct(mid + 1, high, 2 * pos + 2); update(pos); } public void add(int index, T value) { add(index, value, 0, n - 1, 0); } private void add(int index, T value, int low, int high, int pos) { if (low == high) { seg[pos] = value; return; } int mid = (low + high) / 2; if (index <= mid) { add(index, value, low, mid, 2 * pos + 1); } else { add(index, value, mid + 1, high, 2 * pos + 2); } update(pos); } public T get(int qlow, int qhigh) { return get(qlow, qhigh, 0, n - 1, 0); } public T get(int qlow, int qhigh, int low, int high, int pos) { if (qlow > low || low > qhigh) { return NULLVALUE; } else if (qlow <= low || qhigh >= high) { return seg[pos]; } else { int mid = (low + high) / 2; T leftValue = get(qlow, qhigh, low, mid, 2 * pos + 1); T rightValue = get(qlow, qhigh, mid + 1, high, 2 * pos + 2); return optimum(leftValue, rightValue); } } } // DSU private static class DSU { private int[] id; private int[] size; private int n; public DSU(int n) { this.n = n; id = new int[n]; for (int i = 0; i < n; i++) { id[i] = i; } size = new int[n]; Arrays.fill(size, 1); } private int root(int u) { while (u != id[u]) { id[u] = id[id[u]]; u = id[u]; } return u; } public boolean connected(int u, int v) { return root(u) == root(v); } public void union(int u, int v) { int p = root(u); int q = root(v); if (size[p] >= size[q]) { id[q] = p; size[p] += size[q]; } else { id[p] = q; size[q] += size[p]; } } } // KMP private static int countSearch(String s, String p) { int n = s.length(); int m = p.length(); int[] b = backTable(p); int j = 0; int count = 0; for (int i = 0; i < n; i++) { if (j == m) { j = b[j - 1]; count++; } while (j != 0 && s.charAt(i) != p.charAt(j)) { j = b[j - 1]; } if (s.charAt(i) == p.charAt(j)) { j++; } } if (j == m) count++; return count; } private static int[] backTable(String p) { int m = p.length(); int j = 0; int[] b = new int[m]; for (int i = 1; i < m; i++) { while (j != 0 && p.charAt(i) != p.charAt(j)) { j = b[j - 1]; } if (p.charAt(i) == p.charAt(j)) { b[i] = ++j; } } return b; } private static class LCA { private HashMap<Integer, ArrayList<Integer>> g; private int[] level; private int[] a; private int[][] P; private int n, m; private int[] xor; public LCA(HashMap<Integer, ArrayList<Integer>> g, int[] a) { this.g = g; this.a = a; n = g.size(); m = (int) (Math.log(n) / Math.log(2)) + 5; P = new int[n][m]; xor = new int[n]; level = new int[n]; preprocess(); } private void preprocess() { dfs(0, -1); for (int j = 1; j < m; j++) { for (int i = 0; i < n; i++) { if (P[i][j - 1] != -1) { P[i][j] = P[P[i][j - 1]][j - 1]; } } } } private void dfs(int u, int p) { P[u][0] = p; xor[u] = a[u] ^ (p == -1 ? 0 : xor[p]); level[u] = (p == -1 ? 0 : level[p] + 1); for (int v : g.get(u)) { if (v == p) continue; dfs(v, u); } } public int lca(int u, int v) { if (level[v] > level[u]) { int temp = v; v = u; u = temp; } for (int j = m; j >= 0; j--) { if (level[u] - (1 << j) < level[v]) { continue; } else { u = P[u][j]; } } if (u == v) return u; for (int j = m - 1; j >= 0; j--) { if (P[u][j] == -1 || P[u][j] == P[v][j]) { continue; } else { u = P[u][j]; v = P[v][j]; } } return P[u][0]; } private int xor(int u, int v) { int l = lca(u, v); return xor[u] ^ xor[v] ^ a[l]; } } // FAST INPUT OUTPUT LIBRARY private static InputReader in = new InputReader(System.in); private static PrintWriter out = new PrintWriter(System.out); private static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Lynn */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { Scanner in; PrintWriter out; public void solve(int testNumber, Scanner in, PrintWriter out) { this.in = in; this.out = out; run(); } void run() { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int[][][] dis = new int[n][m][4]; int[][] dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; int tmp; final int M = (int) (1e8); Algo.fill(dis, M); for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { tmp = in.nextInt(); dis[i][j][0] = tmp; dis[i][j + 1][1] = tmp; } } for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { tmp = in.nextInt(); dis[i][j][2] = tmp; dis[i + 1][j][3] = tmp; } } int[][] ans = new int[n][m]; if (k % 2 == 1) { Algo.fill(ans, -1); } else { int halfK = k / 2; int[][][] dp = new int[halfK + 1][n][m]; Algo.fill(dp, M); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dp[0][i][j] = 0; } } for (int step = 1; step <= halfK; step++) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int d = 0; d < dir.length; d++) { int toX = i + dir[d][0]; int toY = j + dir[d][1]; if (toX < 0 || toY < 0 || toX >= n || toY >= m) continue; dp[step][i][j] = Math.min(dp[step - 1][toX][toY] + 2 * dis[i][j][d], dp[step][i][j]); } } } } ans = dp[halfK]; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(ans[i][j]); out.print(' '); } out.println(""); } } } static class Algo { public static void fill(int[][] iss, int v) { for (int[] is : iss) Arrays.fill(is, v); } public static void fill(int[][][] isss, int v) { for (int[][] iss : isss) Algo.fill(iss, v); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } private void eat(String s) { st = new StringTokenizer(s); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } public boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } public String next() { hasNext(); return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Main m = new Main(); m.run(); m.out.close(); } void run() throws IOException { int n = nextInt(); int m = nextInt(); int k = nextInt(); long[][] r = new long[n][m - 1]; long[][] d = new long[n - 1][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { r[i][j] = nextInt(); } } for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { d[i][j] = nextInt(); } } if (k % 2 != 0) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(-1+" "); } out.println(); } return; } long[][][] dp = new long[n][m][k + 1]; for (int kk = 2; kk <= k; kk += 2) for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { long ans = (long) 1e18; if (i + 1 < n) { ans = Math.min(ans, dp[i + 1][j][kk - 2] + d[i][j]*2); } if (i - 1 > -1) ans = Math.min(ans, dp[i - 1][j][kk - 2] + d[i - 1][j]*2); if (j + 1 < m) ans = Math.min(ans, dp[i][j + 1][kk - 2] + r[i][j]*2); if (j - 1 > -1) ans = Math.min(ans, dp[i][j - 1][kk - 2] + r[i][j - 1]*2); dp[i][j][kk] = ans; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(dp[i][j][k] + " "); } out.println(); } } int gcd(int a, int b) { while (a % b != 0) { int h = a % b; a = b; b = h; } return b; } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer in = new StringTokenizer(""); // pairs class pil implements Comparable<pil> { int first; long second; pil(int f, long s) { this.first = f; this.second = s; } public int compareTo(pil o) { if (first != o.first) return Integer.compare(first, o.first); return Long.compare(second, o.second); } } class pii implements Comparable<pii> { int fi; int se; pii(int f, int s) { se = s; fi = f; } public int compareTo(pii o) { if (fi != o.fi) return Integer.compare(fi, o.fi); return Integer.compare(se, o.se); } } class pis implements Comparable<pis> { int fi; String s; pis(int f, String s) { this.s = s; fi = f; } public int compareTo(pis o) { return Integer.compare(fi, o.fi); } } class vert { int to; int iter; int idx; int ed; vert(int s, int f, int zz, int gg) { to = s; iter = f; idx = zz; ed = gg; } } class pll implements Comparable<pll> { long first; long second; pll(long f, long s) { this.first = f; this.second = s; } public int compareTo(pll o) { if (first != o.first) return Long.compare(first, o.first); return Long.compare(second, o.second); } } class pli implements Comparable<pli> { long first; int second; pli(long f, int s) { this.first = f; this.second = s; } public int compareTo(pli o) { if (first != o.first) return Long.compare(first, o.first); return Integer.compare(second, o.second); } } boolean hasNext() throws IOException { if (in.hasMoreTokens()) return true; String s; while ((s = br.readLine()) != null) { in = new StringTokenizer(s); if (in.hasMoreTokens()) return true; } return false; } String nextToken() throws IOException { while (!in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.ObjectInputStream.GetField; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import javax.sound.sampled.ReverbType; public class N718 { static PrintWriter out; static Scanner sc; static ArrayList<int[]>q,w,x; static ArrayList<Integer>adj[]; static HashSet<Integer>primesH; static boolean prime[]; //static ArrayList<Integer>a; static HashSet<Long>tmp; static int[][][]dist; static boolean[]v; static int[]a,b,c,d; static Boolean[][]dp; static char[][]mp; static int A,B,n,m,h,ans,sum; //static String a,b; static long oo=(long)1e9+7; public static void main(String[]args) throws IOException { sc=new Scanner(System.in); out=new PrintWriter(System.out); //A(); //B(); //C(); D(); //E(); //F(); //G(); out.close(); } private static void A() throws IOException { int t=ni(); while(t-->0) { long l=nl(); if(l%2050!=0)ol(-1); else { long num=l/2050; int cnt=0; while(num>0) { cnt+=num%10; num/=10; } ol(cnt); } } } static void B() throws IOException { int t=ni(); while(t-->0) { int n=ni(),m=ni(); int[][]a=nmi(n,m); PriorityQueue<int[]>pq=new PriorityQueue<int[]>((u,v)->u[0]-v[0]); ArrayList<Integer>[]nums=new ArrayList[n]; for(int i=0;i<n;i++) { //nums[i]=new ArrayList<Integer>(); for(int j=0;j<m;j++) { ///nums[i].add(a[i][j]); pq.add(new int[] {a[i][j],i}); } } int[][]ans=new int[n][m]; for(int i=0;i<m;i++) { int[]x=pq.poll(); ans[x[1]][i]=x[0]; } int []indices=new int[n]; while(!pq.isEmpty()) { int[]x=pq.poll(); int i=x[1]; while(ans[i][indices[i]]!=0) { indices[i]++; } ans[i][indices[i]]=x[0]; } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { out.print(ans[i][j]+" "); } ol(""); } } } static void C() throws IOException{ int t=1; while(t-->0) { int n=ni(); a=nai(n); int[][]ans=new int[n][n]; for(int i=0;i<n;i++)ans[i][i]=a[i]; for(int i=n-1;i>=0;i--) { int j=i,k=i; int cur=ans[i][i]; cur--; while(cur>0) { j++; if(j>=n||ans[j][k]!=0) { j--; k--; } ans[j][k]=ans[i][i]; cur--; } } for(int i=0;i<n;i++) { for(int j=0;j<=i;j++) { out.print(ans[i][j]+" "); } ol(""); } } } private static Boolean dp(int i, int j) { if(j>sum/2)return false; if(i==x.size()) { return sum/2==j; } if(dp[i][j]!=null)return dp[i][j]; return dp[i][j]=dp(i+1,j+x.get(i)[0])||dp(i+1,j); } static boolean isPrime(long n) { if(n==2)return true; if(n<2||n%2==0)return false; for(long i=3L;i*i<n;i+=2l) { long rem=(n%i); if(rem==0)return false; } return true; } static void D() throws IOException { int t=1; while(t-->0) { int n=ni(),m=ni(),k=ni(); int[][]ans=new int[n][m]; dist=new int[n][m][4]; for(int i=0;i<n;i++)for(int j=0;j>m;j++) Arrays.fill(dist[i][j], Integer.MAX_VALUE); int x; for(int i=0;i<n;i++) { for(int j=0;j<m-1;j++) { dist[i][j][2]=(x=ni()); dist[i][j+1][3]=x; } } for(int i=0;i<n-1;i++) { for(int j=0;j<m;j++) { dist[i][j][1]=(x=ni()); dist[i+1][j][0]=x; } } int[][]nans=new int[n][m]; if(k%2==1) { for(int i=0;i<n;i++)Arrays.fill(ans[i], -1); }else { for(int ii=0;ii<k/2;ii++) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { nans[i][j]=Integer.MAX_VALUE; if(i>0) nans[i][j]=Math.min(nans[i][j], ans[i-1][j]+dist[i-1][j][1]); if(i<n-1) nans[i][j]=Math.min(nans[i][j], ans[i+1][j]+dist[i+1][j][0]); if(j>0) nans[i][j]=Math.min(nans[i][j], ans[i][j-1]+dist[i][j-1][2]); if(j<m-1) nans[i][j]=Math.min(nans[i][j], ans[i][j+1]+dist[i][j+1][3]); } } int[][]tmp=ans; ans=nans; nans=tmp; } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(ans[i][j]!=-1)ans[i][j]*=2; out.print(ans[i][j]+" "); } ol(""); } } } private static int bfs(int i, int j,int k) { boolean [][]vis=new boolean[dist.length][dist[0].length]; Queue<int[]>q=new LinkedList<int[]>(); int mn=Integer.MAX_VALUE; q.add(new int[] {i,j,0,0}); int[]dx=new int[] {-1,1,0,0}; int[]dy=new int[] {0,0,1,-1}; while(!q.isEmpty()) { int []x=q.poll(); vis[x[0]][x[1]]=true; int c=x[2]; if(c>k/2)continue; if(c>0&&k%c==0&&(k/c)%2==0) { mn=Math.min(mn,x[3]*k/c ); } for(int a=0;a<4;a++) { int nx=x[0]+dx[a]; int ny=x[1]+dy[a]; if(valid(nx,ny)&&!vis[nx][ny]) { q.add(new int[] {nx,ny,c+1,x[3]+dist[x[0]][x[1]][a]}); } } } return mn; } private static boolean valid(int nx, int ny) { return nx>=0&&nx<dist.length&&ny>=0&&ny<dist[0].length; } static int gcd (int a, int b) { return b==0?a:gcd (b, a % b); } static void E() throws IOException { int t=ni(); while(t-->0) { } } static void F() throws IOException { int t=ni(); while(t-->0) { } } static void CC() throws IOException { for(int kk=2;kk<21;kk++) { ol(kk+" -------"); int n=kk; int k=n-2; int msk=1<<k; int[]a=new int[k]; for(int i=0;i<a.length;i++)a[i]=i+2; int mx=1; int ms=0; for(int i=1;i<msk;i++) { long prod=1; int cnt=0; for(int j=0;j<a.length;j++) { if(((i>>j)&1)!=0) { prod*=a[j]; cnt++; } } if(cnt>=mx&&prod%n==1) { mx=cnt; ms=i; } } ol(mx==1?mx:mx+1); out.print(1+" "); long pr=1; for(int j=0;j<a.length;j++) { if(((ms>>j)&1)!=0) { out.print(a[j]+" "); pr*=a[j]; } } ol(""); ol("Prod: "+pr); ol(n+"*"+((pr-1)/n)+" + "+1); } } static int ni() throws IOException { return sc.nextInt(); } static double nd() throws IOException { return sc.nextDouble(); } static long nl() throws IOException { return sc.nextLong(); } static String ns() throws IOException { return sc.next(); } static int[] nai(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); return a; } static long[] nal(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = sc.nextLong(); return a; } static int[][] nmi(int n,int m) throws IOException{ int[][]a=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=sc.nextInt(); } } return a; } static long[][] nml(int n,int m) throws IOException{ long[][]a=new long[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=sc.nextLong(); } } return a; } static void o(String x) { out.print(x); } static void ol(String x) { out.println(x); } static void ol(int x) { out.println(x); } static void disp1(int []a) { for(int i=0;i<a.length;i++) { out.print(a[i]+" "); } out.println(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public boolean hasNext() {return st.hasMoreTokens();} 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();} public boolean ready() throws IOException {return br.ready(); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.io.*; public class ExplorerSpace { private static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static int[][][] dp; public static boolean valid(int i, int j, int n, int m) { return i>=0 && i<n &&j>=0 && j<m; } public static void solution(int n, int m, int k, int[][] h, int[][] v) { if(k%2==1) { for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) out.print(-1+" "); out.println(); } return; } dp = new int[n][m][k/2+1]; for(int t = 1; t<=k/2; t++) { for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) { dp[i][j][t] = Integer.MAX_VALUE; } } } for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) { dp[i][j][0] = 0; } } for(int t = 1; t<=k/2; t++) { for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) { if(valid(i,j+1,n,m)) dp[i][j][t] = Math.min(dp[i][j][t], h[i][j] + dp[i][j+1][t-1]); if(valid(i,j-1,n,m)) dp[i][j][t] = Math.min(dp[i][j][t], h[i][j-1] + dp[i][j-1][t-1]); if(valid(i+1,j,n,m)) dp[i][j][t] = Math.min(dp[i][j][t], v[i][j] + dp[i+1][j][t-1]); if(valid(i-1,j,n,m)) dp[i][j][t] = Math.min(dp[i][j][t], v[i-1][j] + dp[i-1][j][t-1]); } } } for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) out.print((dp[i][j][k/2]*2)+" "); out.println(); } } private static PrintWriter out = new PrintWriter(System.out); public static void main (String[] args) { MyScanner s = new MyScanner(); int n = s.nextInt(); int m = s.nextInt(); int k = s.nextInt(); int[][] h = new int[n][m-1]; for(int i = 0; i<n; i++) { for(int j = 0; j<m-1; j++) { h[i][j] = s.nextInt(); } } int[][] v = new int[n-1][m]; for(int i = 0; i<n-1; i++) { for(int j = 0; j<m; j++) { v[i][j] = s.nextInt(); } } solution(n,m,k,h,v); out.flush(); out.close(); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]),k=Integer.parseInt(s[2]); int i,j,max=n*m,in[][]=new int[n][m],x=0; if(k%2==1) //not possible { for(i=0;i<n;i++) { for(j=0;j<m;j++) sb.append("-1 "); sb.append("\n"); } System.out.print(sb); return; } for(i=0;i<n;i++) for(j=0;j<m;j++) in[i][j]=x++; ArrayList<Edge> g[]=new ArrayList[max]; for(i=0;i<max;i++) g[i]=new ArrayList<>(); for(i=0;i<n;i++) { s=bu.readLine().split(" "); for(j=0;j<m-1;j++) { int u=in[i][j],v=in[i][j+1],w=Integer.parseInt(s[j]); g[u].add(new Edge(v,w)); g[v].add(new Edge(u,w)); } } for(i=0;i<n-1;i++) { s=bu.readLine().split(" "); for(j=0;j<m;j++) { int u=in[i][j],v=in[i+1][j],w=Integer.parseInt(s[j]); g[u].add(new Edge(v,w)); g[v].add(new Edge(u,w)); } } k/=2; int dp[][]=new int[k][max]; for(i=0;i<max;i++) { dp[0][i]=Integer.MAX_VALUE; for(Edge e:g[i]) dp[0][i]=Math.min(dp[0][i],2*e.w); } for(i=1;i<k;i++) for(j=0;j<max;j++) { dp[i][j]=Integer.MAX_VALUE; for(Edge e:g[j]) dp[i][j]=Math.min(dp[i][j],dp[i-1][e.v]+2*e.w); } for(i=0;i<n;i++) { for(j=0;j<m;j++) sb.append(dp[k-1][in[i][j]]+" "); sb.append("\n"); } System.out.print(sb); } static class Edge { int v,w,d; Edge(int a,int b) { v=a; w=b; d=0; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; /** * A simple template for competitive programming problems. */ public class Solution { //InputReader in = new InputReader("input.txt"); final InputReader in = new InputReader(System.in); final PrintWriter out = new PrintWriter(System.out); int n,m; void solve() { n = in.nextInt(); m = in.nextInt(); int k = in.nextInt(); int[][] hor = new int[n][m-1]; int[][] ver = new int[n-1][m]; for(int i=0; i<n; i++) { for(int j=0; j<m-1; j++) { hor[i][j] = in.nextInt(); //hor[i][j]=mat[i][j] -> mat[i][j+1] } } for(int i=0; i<n-1; i++) { for(int j=0; j<m; j++) { ver[i][j] = in.nextInt(); //ver[i][j]= mat[i][j] -> mat[i+1][j] } } int[][] ans = new int[n][m]; if(k%2==1) { for(int i=0; i<n; i++) Arrays.fill(ans[i], -1); } else { for(int dummy=0; dummy<k>>1; dummy++) { int[][] newAns = new int[n][m]; for(int i=0; i<n; i++) { Arrays.fill(newAns[i], Integer.MAX_VALUE); for(int j=0; j<m; j++) { if(isGood(i+1, j)) { newAns[i][j] = Math.min(newAns[i][j], 2*ver[i][j] + ans[i+1][j]); } if(isGood(i, j+1)) { newAns[i][j] = Math.min(newAns[i][j], 2*hor[i][j] + ans[i][j+1]); } if(isGood(i, j-1)) { newAns[i][j] = Math.min(newAns[i][j], 2*hor[i][j-1] + ans[i][j-1]); } if(isGood(i-1, j)) { newAns[i][j] = Math.min(newAns[i][j], 2*ver[i-1][j] + ans[i-1][j]); } } } ans = newAns; } } for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { out.print(ans[i][j] + " "); } out.println(); } } boolean isGood(int i, int j) { return i>=0 && i<n && j>=0 && j<m; } private void shuffle(int[] a) { int n = a.length; Random random = new Random(); random.nextInt(); for (int i = 0; i < n; i++) { int change = i + random.nextInt(n - i); swap(a, i, change); } } private static void swap(int[] a, int i, int change) { int helper = a[i]; a[i] = a[change]; a[change] = helper; } public static void main(final String[] args) throws FileNotFoundException { final Solution s = new Solution(); final Long t1 = System.currentTimeMillis(); s.solve(); System.err.println(System.currentTimeMillis() - t1 + " ms"); s.out.close(); } public Solution() throws FileNotFoundException { } private static class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; Random r = new Random(); InputReader(final InputStream stream) { this.stream = stream; } InputReader(final String fileName) { InputStream stream = null; try { stream = new FileInputStream(fileName); } catch (final FileNotFoundException e) { e.printStackTrace(); } this.stream = stream; } int[] nextArray(final int n) { final int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } int[][] nextMatrix(final int n, final int m) { final 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 nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); final StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); final StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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; } 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; } double nextDouble() { return Double.parseDouble(nextString()); } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (final IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } private boolean isSpaceChar(final int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(final int c) { return c == '\n' || c == '\r' || c == -1; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.util.Map.Entry; import java.math.*; import java.io.*; public class Main { static int[][] to = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; public static void main(String[] args) throws FileNotFoundException { InputReader in = new InputReader(System.in); // Scanner in = new Scanner(System.in); // Scanner in = new Scanner(new BufferedReader(new // InputStreamReader(System.in))); PrintWriter out = new PrintWriter(System.out); // InputReader in = new InputReader(new // File("ethan_traverses_a_tree.txt")); // PrintWriter out = new PrintWriter(new // File("ethan_traverses_a_tree-output.txt")); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int[][][] cost = new int[n][m][4]; for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { int u = in.nextInt(); cost[i][j][1] = u; cost[i][j + 1][3] = u; } } for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { int u = in.nextInt(); cost[i][j][0] = u; cost[i + 1][j][2] = u; } } if (k % 2 == 0) { k = k / 2; int[][][] dp = new int[k + 1][n][m]; for (int i = 0; i <= k; i++) { for (int x = 0; x < n; x++) { for (int y = 0; y < m; y++) { if (i == 0) { dp[i][x][y] = 0; } else { int min = 1000000000; for (int way = 0; way < to.length; way++) { int nextx = x + to[way][0]; int nexty = y + to[way][1]; if (nextx >= 0 && nextx < n && nexty >= 0 && nexty < m) { min = Math.min(min, dp[i - 1][nextx][nexty] + cost[x][y][way]); } } dp[i][x][y] = min; } } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (j == m - 1) { out.printf("%d\n", dp[k][i][j] * 2); } else { out.printf("%d ", dp[k][i][j] * 2); } } } } else { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (j == m - 1) { out.printf("-1\n"); } else { out.printf("-1 "); } } } } out.close(); } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public boolean hasNext() { 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; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; import java.util.Map.Entry; public class E { FastScanner in; PrintWriter out; boolean systemIO = true; public class DSU { int[] sz; int[] p; public DSU(int n) { sz = new int[n]; p = new int[n]; for (int i = 0; i < p.length; i++) { p[i] = i; sz[i] = 1; } } public int get(int x) { if (x == p[x]) { return x; } int par = get(p[x]); p[x] = par; return par; } public boolean unite(int a, int b) { int pa = get(a); int pb = get(b); if (pa == pb) { return false; } if (sz[pa] < sz[pb]) { p[pa] = pb; sz[pb] += sz[pa]; } else { p[pb] = pa; sz[pa] += sz[pb]; } return true; } } public class SegmentTreeAdd { int pow; long[] min; long[] delta; boolean[] flag; public SegmentTreeAdd(long[] a) { pow = 1; while (pow < a.length) { pow *= 2; } flag = new boolean[2 * pow]; min = new long[2 * pow]; delta = new long[2 * pow]; for (int i = 0; i < min.length; i++) { min[i] = Long.MAX_VALUE / 2; } for (int i = 0; i < a.length; i++) { min[pow + i] = a[i]; } for (int i = pow - 1; i > 0; i--) { min[i] = f(min[2 * i], min[2 * i + 1]); } } public long get(int l, int r) { return get(1, 0, pow, l, r); } private long get(int v, int tl, int tr, int l, int r) { push(v, tl, tr); if (l >= tr || r <= tl) { return Long.MAX_VALUE / 2; } if (l <= tl && r >= tr) { return min[v]; } int tm = (tl + tr) / 2; return f(get(2 * v, tl, tm, l, r), get(2 * v + 1, tm, tr, l, r)); } public void set(int l, int r, long x) { set(1, 0, pow, l, r, x); } private void set(int v, int tl, int tr, int l, int r, long x) { push(v, tl, tr); if (l >= tr || r <= tl) { return; } if (l <= tl && r >= tr) { delta[v] += x; flag[v] = true; push(v, tl, tr); return; } int tm = (tl + tr) / 2; set(2 * v, tl, tm, l, r, x); set(2 * v + 1, tm, tr, l, r, x); min[v] = f(min[2 * v], min[2 * v + 1]); } public void push(int v, int tl, int tr) { if (flag[v]) { if (v < pow) { flag[2 * v] = true; flag[2 * v + 1] = true; delta[2 * v] += delta[v]; delta[2 * v + 1] += delta[v]; } flag[v] = false; min[v] += delta[v]; delta[v] = 0; } } public long f(long a, long b) { return Math.min(a, b); } } public class SegmentTreeSet { int pow; int[] sum; int[] delta; boolean[] flag; public SegmentTreeSet(int[] a) { pow = 1; while (pow < a.length) { pow *= 2; } flag = new boolean[2 * pow]; sum = new int[2 * pow]; delta = new int[2 * pow]; for (int i = 0; i < a.length; i++) { sum[pow + i] = a[i]; } } public int get(int v, int tl, int tr, int l, int r) { push(v, tl, tr); if (l > r) { return 0; } if (l == tl && r == tr) { return sum[v]; } int tm = (tl + tr) / 2; return f(get(2 * v, tl, tm, l, Math.min(r, tm)), get(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r)); } public void set(int v, int tl, int tr, int l, int r, int x) { push(v, tl, tr); if (l > tr || r < tl) { return; } if (l <= tl && r >= tr) { delta[v] = x; flag[v] = true; push(v, tl, tr); return; } int tm = (tl + tr) / 2; set(2 * v, tl, tm, l, r, x); set(2 * v + 1, tm + 1, tr, l, r, x); sum[v] = f(sum[2 * v], sum[2 * v + 1]); } public void push(int v, int tl, int tr) { if (flag[v]) { if (v < pow) { flag[2 * v] = true; flag[2 * v + 1] = true; delta[2 * v] = delta[v]; delta[2 * v + 1] = delta[v]; } flag[v] = false; sum[v] = delta[v] * (tr - tl + 1); } } public int f(int a, int b) { return a + b; } } Random random = new Random(); public void shuffle(Pair[] a) { for (int i = 0; i < a.length; i++) { int x = random.nextInt(i + 1); Pair t = a[x]; a[x] = a[i]; a[i] = t; } } public void sort(int[][] a) { for (int i = 0; i < a.length; i++) { Arrays.sort(a[i]); } } public void add(HashMap<Long, Integer> map, long l) { if (map.containsKey(l)) { map.put(l, map.get(l) + 1); } else { map.put(l, 1); } } public void remove(TreeMap<Integer, Integer> map, Integer s) { if (map.get(s) > 1) { map.put(s, map.get(s) - 1); } else { map.remove(s); } } double eps = 1e-10; public int signum(double x) { if (x > eps) { return 1; } if (x < -eps) { return -1; } return 0; } public long abs(long x) { return x < 0 ? -x : x; } public long min(long x, long y) { return x < y ? x : y; } public long max(long x, long y) { return x > y ? x : y; } public long gcd(long x, long y) { while (y > 0) { long c = y; y = x % y; x = c; } return x; } // public class Vector implements Comparable<Vector> { // long x; // long y; // int type; // int number; // // public Vector() { // x = 0; // y = 0; // } // // public Vector(long x, long y, int type, int number) { // this.x = x; // this.y = y; // this.type = type; // this.number = number; // } // // public Vector(long x, long y) { // // } // // public Vector(Point begin, Point end) { // this(end.x - begin.x, end.y - begin.y); // } // // public void orient() { // if (x < 0) { // x = -x; // y = -y; // } // if (x == 0 && y < 0) { // y = -y; // } // } // // public void normalize() { // long gcd = gcd(abs(x), abs(y)); // x /= gcd; // y /= gcd; // } // // public String toString() { // return x + " " + y; // } // // public boolean equals(Vector v) { // return x == v.x && y == v.y; // } // // public boolean collinear(Vector v) { // return cp(this, v) == 0; // } // // public boolean orthogonal(Vector v) { // return dp(this, v) == 0; // } // // public Vector ort(Vector v) { // return new Vector(-y, x); // } // // public Vector add(Vector v) { // return new Vector(x + v.x, y + v.y); // } // // public Vector multiply(long c) { // return new Vector(c * x, c * y); // } // // public int quater() { // if (x > 0 && y >= 0) { // return 1; // } // if (x <= 0 && y > 0) { // return 2; // } // if (x < 0) { // return 3; // } // return 0; // } // // public long len2() { // return x * x + y * y; // } // // @Override // public int compareTo(Vector o) { // if (quater() != o.quater()) { // return quater() - o.quater(); // } // return signum(cp(o, this)); // } // } // public long dp(Vector v1, Vector v2) { // return v1.x * v2.x + v1.y * v2.y; // } // // public long cp(Vector v1, Vector v2) { // return v1.x * v2.y - v1.y * v2.x; // } // public class Line implements Comparable<Line> { // Point p; // Vector v; // // public Line(Point p, Vector v) { // this.p = p; // this.v = v; // } // // public Line(Point p1, Point p2) { // if (p1.compareTo(p2) < 0) { // p = p1; // v = new Vector(p1, p2); // } else { // p = p2; // v = new Vector(); // } // } // // public boolean collinear(Line l) { // return v.collinear(l.v); // } // // public boolean inLine(Point p) { // return hv(p) == 0; // } // // public boolean inSegment(Point p) { // if (!inLine(p)) { // return false; // } // Point p1 = p; // Point p2 = p.add(v); // return p1.x <= p.x && p.x <= p2.x && min(p1.y, p2.y) <= p.y && p.y <= // max(p1.y, p2.y); // } // // public boolean equalsSegment(Line l) { // return p.equals(l.p) && v.equals(l.v); // } // // public boolean equalsLine(Line l) { // return collinear(l) && inLine(l.p); // } // // public long hv(Point p) { // Vector v1 = new Vector(this.p, p); // return cp(v, v1); // } // // public double h(Point p) { // Vector v1 = new Vector(this.p, p); // return cp(v, v1) / Math.sqrt(v.len2()); // } // // public long[] intersectLines(Line l) { // if (collinear(l)) { // return null; // } // long[] ans = new long[4]; // // return ans; // } // // public long[] intersectSegment(Line l) { // long[] ans = intersectLines(l); // if (ans == null) { // return null; // } // Point p1 = p; // Point p2 = p.add(v); // boolean f1 = p1.x * ans[1] <= ans[0] && ans[0] <= p2.x * ans[1] && min(p1.y, // p2.y) * ans[3] <= ans[2] // && ans[2] <= max(p1.y, p2.y) * ans[3]; // p1 = l.p; // p2 = l.p.add(v); // boolean f2 = p1.x * ans[1] <= ans[0] && ans[0] <= p2.x * ans[1] && min(p1.y, // p2.y) * ans[3] <= ans[2] // && ans[2] <= max(p1.y, p2.y) * ans[3]; // if (!f1 || !f2) { // return null; // } // return ans; // } // // @Override // public int compareTo(Line o) { // return v.compareTo(o.v); // } // } public class Rect { long x1; long x2; long y1; long y2; int number; public Rect(long x1, long x2, long y1, long y2, int number) { this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; this.number = number; } } public static class Fenvik { int[] t; public Fenvik(int n) { t = new int[n]; } public void add(int x, int delta) { for (int i = x; i < t.length; i = (i | (i + 1))) { t[i] += delta; } } private int sum(int r) { int ans = 0; int x = r; while (x >= 0) { ans += t[x]; x = (x & (x + 1)) - 1; } return ans; } public int sum(int l, int r) { return sum(r) - sum(l - 1); } } public class SegmentTreeMaxSum { int pow; int[] sum; int[] maxPrefSum; int[] maxSufSum; int[] maxSum; public SegmentTreeMaxSum(int[] a) { pow = 1; while (pow < a.length) { pow *= 2; } sum = new int[2 * pow]; maxPrefSum = new int[2 * pow]; maxSum = new int[2 * pow]; maxSufSum = new int[2 * pow]; for (int i = 0; i < a.length; i++) { sum[pow + i] = a[i]; maxSum[pow + i] = Math.max(a[i], 0); maxPrefSum[pow + i] = maxSum[pow + i]; maxSufSum[pow + i] = maxSum[pow + i]; } for (int i = pow - 1; i > 0; i--) { update(i); } } public int[] get(int v, int tl, int tr, int l, int r) { if (r <= tl || l >= tr) { int[] ans = { 0, 0, 0, 0 }; return ans; } if (l <= tl && r >= tr) { int[] ans = { maxPrefSum[v], maxSum[v], maxSufSum[v], sum[v] }; return ans; } int tm = (tl + tr) / 2; int[] left = get(2 * v, tl, tm, l, r); int[] right = get(2 * v + 1, tm, tr, l, r); int[] ans = { Math.max(left[0], right[0] + left[3]), Math.max(left[1], Math.max(right[1], left[2] + right[0])), Math.max(right[2], left[2] + right[3]), left[3] + right[3] }; return ans; } public void set(int v, int tl, int tr, int x, int value) { if (v >= pow) { sum[v] = value; maxSum[v] = Math.max(value, 0); maxPrefSum[v] = maxSum[v]; maxSufSum[v] = maxSum[v]; return; } int tm = (tl + tr) / 2; if (x < tm) { set(2 * v, tl, tm, x, value); } else { set(2 * v + 1, tm, tr, x, value); } update(v); } public void update(int i) { sum[i] = f(sum[2 * i], sum[2 * i + 1]); maxSum[i] = Math.max(maxSum[2 * i], Math.max(maxSum[2 * i + 1], maxSufSum[2 * i] + maxPrefSum[2 * i + 1])); maxPrefSum[i] = Math.max(maxPrefSum[2 * i], maxPrefSum[2 * i + 1] + sum[2 * i]); maxSufSum[i] = Math.max(maxSufSum[2 * i + 1], maxSufSum[2 * i] + sum[2 * i + 1]); } public int f(int a, int b) { return a + b; } } public class Fraction implements Comparable<Fraction> { long x; long y; public Fraction(long x, long y, boolean needNorm) { this.x = x; this.y = y; if (y < 0) { this.x *= -1; this.y *= -1; } if (needNorm) { long gcd = gcd(this.x, this.y); this.x /= gcd; this.y /= gcd; } } public Fraction clone() { return new Fraction(x, y, false); } public String toString() { return x + "/" + y; } @Override public int compareTo(Fraction o) { long res = x * o.y - y * o.x; if (res > 0) { return 1; } if (res < 0) { return -1; } return 0; } } public class Event implements Comparable<Event> { Fraction f; int type; public Event(Fraction f, int type) { this.f = f; this.type = type; } @Override public int compareTo(Event o) { int c = f.compareTo(o.f); if (c != 0) { return c; } return type - o.type; } } public double sq(double x) { return x * x; } public long sq(long x) { return x * x; } public double hypot2(double x, double y) { return sq(x) + sq(y); } public long hypot2(long x, long y) { return sq(x) + sq(y); } public boolean kuhn(int v, int[][] edge, boolean[] used, int[] mt) { used[v] = true; for (int u : edge[v]) { if (mt[u] < 0 || (!used[mt[u]] && kuhn(mt[u], edge, used, mt))) { mt[u] = v; return true; } } return false; } public int matching(int[][] edge) { int n = edge.length; int[] mt = new int[n]; Arrays.fill(mt, -1); boolean[] used = new boolean[n]; int ans = 0; for (int i = 0; i < n; i++) { if (!used[i] && kuhn(i, edge, used, mt)) { Arrays.fill(used, false); ans++; } } return ans; } double sq2 = Math.sqrt(2); public class MyStack { int[] st; int sz; public MyStack(int n) { this.st = new int[n]; sz = 0; } public boolean isEmpty() { return sz == 0; } public int peek() { return st[sz - 1]; } public int pop() { sz--; return st[sz]; } public void clear() { sz = 0; } public void add(int x) { st[sz++] = x; } public int get(int x) { return st[x]; } } public int[][] readGraph(int n, int m) { int[][] to = new int[n][]; int[] sz = new int[n]; int[] x = new int[m]; int[] y = new int[m]; for (int i = 0; i < m; i++) { x[i] = in.nextInt() - 1; y[i] = in.nextInt() - 1; sz[x[i]]++; sz[y[i]]++; } for (int i = 0; i < to.length; i++) { to[i] = new int[sz[i]]; sz[i] = 0; } for (int i = 0; i < x.length; i++) { to[x[i]][sz[x[i]]++] = y[i]; to[y[i]][sz[y[i]]++] = x[i]; } return to; } public class Pol { double[] coeff; public Pol(double[] coeff) { this.coeff = coeff; } public Pol mult(Pol p) { double[] ans = new double[coeff.length + p.coeff.length - 1]; for (int i = 0; i < ans.length; i++) { for (int j = Math.max(0, i - p.coeff.length + 1); j < coeff.length && j <= i; j++) { ans[i] += coeff[j] * p.coeff[i - j]; } } return new Pol(ans); } public String toString() { String ans = ""; for (int i = 0; i < coeff.length; i++) { ans += coeff[i] + " "; } return ans; } public double value(double x) { double ans = 0; double p = 1; for (int i = 0; i < coeff.length; i++) { ans += coeff[i] * p; p *= x; } return ans; } public double integrate(double r) { Pol p = new Pol(new double[coeff.length + 1]); for (int i = 0; i < coeff.length; i++) { p.coeff[i + 1] = coeff[i] / fact[i + 1]; } return p.value(r); } public double integrate(double l, double r) { return integrate(r) - integrate(l); } } int mod = 1000000007; public int sum(int a, int b) { if (a + b >= mod) { return a + b - mod; } return a + b; } public int diff(int a, int b) { if (a < b) { return a + mod - b; } return a - b; } public int mult(int a, int b) { return (int) ((a * 1L * b) % (1L * mod)); } public int pow(int x, int p) { if (p <= 0) { return 1; } int ans = pow(x, p / 2); ans = mult(ans, ans); if (p % 2 == 1) { ans = mult(ans, x); } return ans; } public int modInv(int x) { return pow(x, mod - 2); } public int c_n_k(int n, int k) { if (n < 0 || k < 0 || n - k < 0) { return 0; } return mult(fact[n], mult(factInv[k], factInv[n - k])); } public class LinAl01 { public class Vector { BitSet vec; BitSet swtch; public Vector(BitSet vec, BitSet swtch) { this.vec = vec; this.swtch = swtch; } public String toString() { String s = ""; for (int i = 0; i < basis.length; i++) { s += (vec.get(i) ? 1 : 0); } s += " "; for (int i = 0; i < basis.length; i++) { s += (swtch.get(i) ? 1 : 0); } return s; } } int n; Vector[] basis; public void update(Vector v) { for (int i = 0; i < n; i++) { if (v.vec.get(i)) { if (basis[i] == null) { basis[i] = v; break; } v.vec.xor(basis[i].vec); v.swtch.xor(basis[i].swtch); } } } public void diagonalize() { for (int i = 0; i < n; i++) { if (basis[i] == null) { continue; } for (int j = 0; j < i; j++) { if (basis[j] != null && basis[j].vec.get(i)) { basis[j].vec.xor(basis[i].vec); basis[j].swtch.xor(basis[i].swtch); } } } } } public class Point implements Comparable<Point> { double x; double y; public Point() { x = 0; y = 0; } public Point(double x, double y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Point p) { return x == p.x && y == p.y; } public double dist2() { return x * x + y * y; } public Point add(Point v) { return new Point(x + v.x, y + v.y); } public Point subtract(Point v) { return new Point(x - v.x, y - v.y); } @Override public int compareTo(Point o) { int z = signum(x + y - o.x - o.y); if (z != 0) { return z; } return signum(x - o.x) != 0 ? signum(x - o.x) : signum(y - o.y); } } public class Circle { Point p; long r; public Circle(Point p, long r) { this.p = p; this.r = r; } public boolean intersect(Line l) { return Math.abs(l.a * p.x + l.b * p.y + l.c) / Math.hypot(l.a, l.b) < r; } public boolean inside(Point p) { return hypot2(p.x - this.p.x, p.y - this.p.y) <= sq(r); } } public class Line { long a; long b; long c; public Line(long a, long b, long c) { if (a < 0 || (a == 0 && b < 0)) { a = -a; b = -b; c = -c; long gcd = gcd(a, Math.abs(b)); a /= gcd; b /= gcd; } this.a = a; this.b = b; this.c = c; } public String toString() { return a + " " + b + " " + c; } // public Line(Point a, Point b) { // this.a = a.y - b.y; // this.b = b.x - a.x; // this.c = a.x * b.y - a.y * b.x; // } } // public long compareDist(Circle a, Circle b, Circle c) { // tangent to a, b; a.r, b.r may be < 0 // long x = b.p.x - a.p.x; // long y = b.p.y - a.p.y; // long r = b.r - a.r; // long dx = c.p.x - a.p.x; // long dy = c.p.y - a.p.y; // long dr = c.r - a.r; // long left = y * dx - x * dy; // long sqrt = x * x + y * y - r * r; // long right = dr * (x * x + y * y) - r * (x * dx + y * dy); // if (sqrt == 0 || left == 0) { // if (right > 0) { // return -1; // } // if (right < 0) { // return 1; // } // return 0; // } // if (right == 0) { // if (left > 0) { // return 1; // } // return -1; // } // if (left > 0 && right < 0) { // return 1; // } // if (left < 0 && right > 0) { // return -1; // } // int mult = 1; // if (left < 0) { // mult = -1; // } // return BigInteger.valueOf(left).pow(2).multiply(BigInteger.valueOf(sqrt)) // .compareTo(BigInteger.valueOf(right).pow(2)) * mult; // } // public boolean inOrTang(Circle a, Circle b, Circle c) { // return compareDist(a, b, c) <= 0 && compareDist(a, b, new Circle(c.p, -c.r)) >= 0; // } // public boolean in(Circle a, Circle b, Circle c) { // return compareDist(a, b, c) < 0 && compareDist(a, b, new Circle(c.p, -c.r)) > 0; // } public long sqr(long a) { return a * a; } // public void tangents(Point c, long r1, long r2, ArrayList<Line> ans) { // long r = r2 - r1; // long z = sqr(c.x) + sqr(c.y); // long delta = z - sqr(r); // if (delta <= 0) { // return; // } // double d = Math.sqrt(Math.abs(delta)); // Line l = new Line((c.x * r + c.y * d) / z, (c.y * r - c.x * d) / z, r1); // if (r1 * r2 >= 0) { // ans.add(new Line(l.a, l.b, l.c + eps)); // ans.add(new Line(l.a, l.b, l.c - eps)); // } else { // double sqrt = Math.hypot(c.x, c.y); // double da = eps * c.y / sqrt; // double db = -eps * c.x / sqrt; // ans.add(new Line(l.a + da, l.b + db, l.c)); // ans.add(new Line(l.a - da, l.b - db, l.c)); // } // } // public ArrayList<Line> tangents(Circle a, Circle b) { // ArrayList<Line> ans = new ArrayList<>(); // for (int i = -1; i <= 1; i += 2) { // for (int j = -1; j <= 1; j += 2) { // tangents(b.p.subtract(a.p), a.r * i, b.r * j, ans); // } // } // for (int i = 0; i < ans.size(); ++i) { // ans.get(i).c -= ans.get(i).a * a.p.x + ans.get(i).b * a.p.y; // } // return ans; // } int[] fact = new int[1000001]; int[] factInv = new int[1000001]; public int[] intersect(int y, int xdown, int ydown, int xup, int yup) { if (yup < y || ydown > y || (ydown == yup)) { return null; } long p = xup * 1L * (y - ydown) + xdown * 1L * (yup - y); if (p < 0) { int[] ans = { -1, 0 }; return ans; } long q = 2 * (yup - ydown); int[] ans = { (int) (p / q), (int) ((p + q - 1) / q) }; return ans; } public void I(int[][] a) { for (int i = 0; i < a.length; i++) { int[] b = new int[a.length]; for (int j = 0; j < b.length; j++) { b[a[i][j]] = j; } a[i] = b; } } public void C(int[][] a) { for (int i = 0; i < a.length; i++) { int[] b = new int[a.length]; for (int j = 0; j < b.length; j++) { b[a[j][i]] = j; } for (int j = 0; j < b.length; j++) { a[j][i] = b[j]; } } } public class SegmentTree { int pow; Pair[] min; public SegmentTree(int[] a) { pow = 1; while (pow < a.length) { pow *= 2; } min = new Pair[2 * pow]; for (int i = 0; i < a.length; i++) { min[pow + i] = new Pair(a[i], i); } for (int i = a.length; i < pow; i++) { min[pow + i] = new Pair(Integer.MAX_VALUE / 2, -1); } for (int i = pow - 1; i > 0; i--) { min[i] = f(min[2 * i], min[2 * i + 1]); } } public Pair get(int l, int r) { return get(1, 0, pow, l, r); } private Pair get(int v, int tl, int tr, int l, int r) { if (l >= tr || r <= tl) { return new Pair(Integer.MAX_VALUE / 2, -1); } if (l <= tl && r >= tr) { return min[v]; } int tm = (tl + tr) / 2; return f(get(2 * v, tl, tm, l, r), get(2 * v + 1, tm, tr, l, r)); } public void set(int x, int value) { set(1, 0, pow, x, value); } private void set(int v, int tl, int tr, int x, int value) { if (x >= tr || x < tl) { return; } if (v >= pow) { min[v] = new Pair(value, -1); return; } int tm = (tl + tr) / 2; set(2 * v, tl, tm, x, value); set(2 * v + 1, tm, tr, x, value); min[v] = f(min[2 * v], min[2 * v + 1]); } public Pair f(Pair a, Pair b) { if (a.compareTo(b) <= 0) { return a.clone(); } return b.clone(); } } public boolean nextPermutation(int[] a) { int n = a.length; for (int i = n - 2; i >= 0; i--) { if (a[i] < a[i + 1]) { for (int d = 1; d <= (n - 1 - i) / 2; d++) { a[i + d] ^= a[n - d]; a[n - d] = a[i + d] ^ a[n - d]; a[i + d] = a[i + d] ^ a[n - d]; } for (int j = i + 1; j < n; j++) { if (a[j] > a[i]) { a[i] ^= a[j]; a[j] = a[i] ^ a[j]; a[i] = a[i] ^ a[j]; return true; } } } } return false; } public class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } public Pair add(Pair p) { return new Pair(x + p.x, y + p.y); } public Pair clone() { return new Pair(x, y); } public String toString() { return x + " " + y; } @Override public int compareTo(Pair o) { if (x < o.x) { return -1; } if (x > o.x) { return 1; } if (y > o.y) { return 1; } if (y < o.y) { return -1; } return 0; } } public double intersection(Pair p1, Pair p2) { return (p2.y - p1.y) * 1.0 / (p1.x - p2.x); } HashMap<Integer, Integer> even = new HashMap<>(); HashMap<Integer, Integer> odd = new HashMap<>(); public void addOdd(int key, int value) { if (odd.containsKey(key)) { odd.put(key, Math.min(odd.get(key), value)); } else { odd.put(key, value); } } public void addEven(int key, int value) { if (even.containsKey(key)) { even.put(key, Math.min(even.get(key), value)); } else { even.put(key, value); } } public void solve() { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); // int n = 500; // int m = 500; // int k = 20; if (k % 2 == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(-1 + " "); } out.println(); } return; } k /= 2; int[][] hor = new int[n][m - 1]; for (int i = 0; i < hor.length; i++) { for (int j = 0; j < hor[0].length; j++) { hor[i][j] = in.nextInt() * 2; // hor[i][j] = random.nextInt(1000000) + 1; } } int[][] vert = new int[n - 1][m]; for (int i = 0; i < vert.length; i++) { for (int j = 0; j < vert[0].length; j++) { vert[i][j] = in.nextInt() * 2; // vert[i][j] = random.nextInt(1000000) + 1; } } long time = System.currentTimeMillis(); int[][][] ans = new int[k + 1][n][m]; for (int l = 1; l <= k; l++) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ans[l][i][j] = Integer.MAX_VALUE; if (i > 0) { ans[l][i][j] = Math.min(ans[l][i][j], ans[l - 1][i - 1][j] + vert[i - 1][j]); } if (j > 0) { ans[l][i][j] = Math.min(ans[l][i][j], ans[l - 1][i][j - 1] + hor[i][j - 1]); } if (i < n - 1) { ans[l][i][j] = Math.min(ans[l][i][j], ans[l - 1][i + 1][j] + vert[i][j]); } if (j < m - 1) { ans[l][i][j] = Math.min(ans[l][i][j], ans[l - 1][i][j + 1] + hor[i][j]); } } } } // for (int i = 0; i < n; i++) { // for (int j = 0; j < m; j++) { // even.clear(); // odd.clear(); // even.put(i * m + j, 0); // for (int l = 0; l < k; l++) { // if (l % 2 == 0) { // odd.clear(); // for (Entry<Integer, Integer> e : even.entrySet()) { // int x = e.getKey() / m; // int y = e.getKey() % m; // int value = e.getValue(); // if (x > 0) { // addOdd((x - 1) * m + y, value + vert[x - 1][y]); // } // if (y > 0) { // addOdd(x * m + y - 1, value + hor[x][y - 1]); // } // if (x < n - 1) { // addOdd((x + 1) * m + y, value + vert[x][y]); // } // if (y < m - 1) { // addOdd(x * m + y + 1, value + hor[x][y]); // } // } // } else { // even.clear(); // for (Entry<Integer, Integer> e : odd.entrySet()) { // int x = e.getKey() / m; // int y = e.getKey() % m; // int value = e.getValue(); // if (x > 0) { // addEven((x - 1) * m + y, value + vert[x - 1][y]); // } // if (y > 0) { // addEven(x * m + y - 1, value + hor[x][y - 1]); // } // if (x < n - 1) { // addEven((x + 1) * m + y, value + vert[x][y]); // } // if (y < m - 1) { // addEven(x * m + y + 1, value + hor[x][y]); // } // } // } // } // ans[i][j] = Integer.MAX_VALUE; // if (k % 2 == 0) { // for (Entry<Integer, Integer> e : even.entrySet()) { // ans[i][j] = Math.min(ans[i][j], e.getValue() * 2); // } // } else { // for (Entry<Integer, Integer> e : odd.entrySet()) { // ans[i][j] = Math.min(ans[i][j], e.getValue() * 2); // } // } // } // } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(ans[k][i][j] + " "); } out.println(); } System.err.println(System.currentTimeMillis() - time); } public void add(HashMap<Integer, Integer> map, int x) { if (map.containsKey(x)) { map.put(x, map.get(x) + 1); } else { map.put(x, 1); } } 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 E().run(); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; /* height == 2, width == 3 2 3 2 1 1 1 1 1 1 1 */ public class D { public static void main(String[] args) { FastScanner fs=new FastScanner(); int h=fs.nextInt(), w=fs.nextInt(), k=fs.nextInt(); PrintWriter out=new PrintWriter(System.out); if (k%2==1) { for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { if (x!=0) out.print(" "); out.print(-1); } out.println(); } out.close(); return; } k/=2; int[][] rightCost=new int[w-1][h]; int[][] downCost=new int[w][h-1]; for (int y=0; y<h; y++) for (int x=0; x<w-1; x++) rightCost[x][y]=fs.nextInt(); for (int y=0; y<h-1; y++) for (int x=0; x<w; x++) downCost[x][y]=fs.nextInt(); long[][] dp=new long[w][h]; long[][] dpNext=new long[w][h]; for (int i=0; i<k; i++) { for (int x=0; x<w; x++) { for (int y=0; y<h; y++) { long ans=(long)1e18; if (x!=0) ans=Math.min(ans, dp[x-1][y]+rightCost[x-1][y]); if (y!=0) ans=Math.min(ans, dp[x][y-1]+downCost[x][y-1]); if (x!=w-1) ans=Math.min(ans, dp[x+1][y]+rightCost[x][y]); if (y!=h-1) ans=Math.min(ans, dp[x][y+1]+downCost[x][y]); dpNext[x][y]=ans; } } dp=dpNext; dpNext=new long[w][h]; } //TODO: double answer for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { if (x!=0) out.print(" "); out.print(2*dp[x][y]); } out.println(); } out.close(); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args)throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); //idea 1 : K/2번까지만 실행해서, 그 최솟값 *2를 하면 된다 //bfs로 i,j칸에 크거나 같은 값을 가지고 진입하면, 즉시 cut StringTokenizer st = new StringTokenizer(br.readLine(), " "); n = pint(st.nextToken()); m = pint(st.nextToken()); k = pint(st.nextToken()); //up down left right //0 is wall map = new int[n][m][4]; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine(), " "); for (int j = 0; j < m-1; j++) { int temp = pint(st.nextToken()); map[i][j][3]=temp; map[i][j+1][2]=temp; } } for (int i = 0; i < n-1; i++) { st = new StringTokenizer(br.readLine(), " "); for (int j = 0; j < m; j++) { int temp = pint(st.nextToken()); map[i][j][1]=temp; map[i+1][j][0]=temp; } } ans = new int[n][m][k/2+1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if(k%2==1) { sb.append("-1 "); continue; } int min=rec(i,j,0,k/2); sb.append(min*2).append(" "); }sb.append("\n"); } System.out.println(sb); } static int n,m,k; //up down left right static int[]dx = {-1,1, 0, 0}; static int[]dy = {0, 0, -1,1}; static int[][][]map; static int[][][]ans; static int rec(int x, int y, int cost, int cnt) { if(cnt==0) { return 0; } if(ans[x][y][cnt]!=0)return ans[x][y][cnt]; int temp=Integer.MAX_VALUE; for (int i = 0; i < 4; i++) { int tx=x+dx[i], ty=y+dy[i]; if(tx<0||tx>=n||ty<0||ty>=m)continue; if(map[x][y][i]!=0) { temp=Math.min(temp, rec(tx, ty, cost, cnt-1)+map[x][y][i]); } } ans[x][y][cnt]=temp; return ans[x][y][cnt]; } static int pint(String s) { return Integer.parseInt(s); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Practice { public static long mod = (long) Math.pow(10, 9) + 7; public static long[][][]dp; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); // int t = Integer.parseInt(br.readLine()); // while (t-- > 0) { String[] s2 = br.readLine().split(" "); int n = Integer.parseInt(s2[0]); int m = Integer.parseInt(s2[1]); int k = Integer.parseInt(s2[2]); dp=new long[n][m][k+1]; int[][] hori = new int[n][m - 1]; int[][] verti = new int[n - 1][m]; for (int i = 0; i < n; i++) { String str = (br.readLine()); String[] s1 = str.split(" "); for (int j = 0; j < m - 1; j++) { hori[i][j] = Integer.parseInt(s1[j]); } } for (int i = 0; i < n - 1; i++) { String str = (br.readLine()); String[] s1 = str.split(" "); for (int j = 0; j < m; j++) { verti[i][j] = Integer.parseInt(s1[j]); } } long[][]ans=new long[n][m]; if(k%2!=0) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { ans[i][j]=-1; } } }else { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { ans[i][j]=findAns(i,j,k,hori,verti,n,m,Integer.MAX_VALUE); } } } for(int i=0;i<n;i++) { StringBuilder str=new StringBuilder(); for(int j=0;j<m;j++) { str.append(ans[i][j]+" "); }pw.println(str.toString()); } // } pw.close(); } private static long findAns(int i, int j, int k, int[][] hori, int[][] verti, int n, int m, int last) { // TODO Auto-generated method stub if(k==0) { return 0; } if(i<n&&j<m&&i>=0&&j>=0) { }else { return 100000000; } // System.out.println(i+" "+j+" "+k); if(dp[i][j][k]!=0) { return dp[i][j][k]; } long ans=k*((long)last); if(j>0) { long curr=2*hori[i][j-1]; curr+=findAns(i, j-1, k-2, hori, verti, n, m, hori[i][j-1]); ans=Math.min(ans, curr); } // System.out.println(ans+" 0"); if(j<m-1) { long curr=2*hori[i][j]; curr+=findAns(i, j+1, k-2, hori, verti, n, m, hori[i][j]); ans=Math.min(ans, curr); } // System.out.println(ans+" 1"); if(i>0) { long curr=2*verti[i-1][j]; curr+=findAns(i-1, j, k-2, hori, verti, n, m, verti[i-1][j]); ans=Math.min(ans, curr); } // System.out.println(ans+" 2"); if(i<n-1) { long curr=2*verti[i][j]; curr+=findAns(i+1, j, k-2, hori, verti, n, m, verti[i][j]); ans=Math.min(ans, curr); } // System.out.println(ans+" 3"); dp[i][j][k]=ans; return ans; } } //private static long getGCD(long l, long m) { //// TODO Auto-generated method stub // //long t1 = Math.min(l, m); //long t2 = Math.max(l, m); //while (true) { // long temp = t2 % t1; // if (temp == 0) { // return t1; // } // t2 = t1; // t1 = temp; //} //}
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; public class _1517_D { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer line = new StringTokenizer(in.readLine()); int n = Integer.parseInt(line.nextToken()); int m = Integer.parseInt(line.nextToken()); int k = Integer.parseInt(line.nextToken()); int[][] edges1 = new int[n][m - 1]; int[][] edges2 = new int[n - 1][m]; for(int i = 0; i < n; i++) { line = new StringTokenizer(in.readLine()); for(int j = 0; j < m - 1; j++) { edges1[i][j] = Integer.parseInt(line.nextToken()); } } for(int i = 0; i < n - 1; i++) { line = new StringTokenizer(in.readLine()); for(int j = 0; j < m; j++) { edges2[i][j] = Integer.parseInt(line.nextToken()); } } if(k % 2 == 1) { for(int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < m; j++) { sb.append(-1); if(j < m - 1) sb.append(' '); } out.println(sb.toString()); } }else { int[][][] dp = new int[n][m][k + 1]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { Arrays.fill(dp[i][j], Integer.MAX_VALUE); dp[i][j][0] = 0; } } for(int a = 2; a <= k; a += 2) { for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(i > 0) { dp[i][j][a] = Math.min(dp[i][j][a], dp[i - 1][j][a - 2] + 2 * edges2[i - 1][j]); } if(i < n - 1) { dp[i][j][a] = Math.min(dp[i][j][a], dp[i + 1][j][a - 2] + 2 * edges2[i][j]); } if(j > 0) { dp[i][j][a] = Math.min(dp[i][j][a], dp[i][j - 1][a - 2] + 2 * edges1[i][j - 1]); } if(j < m - 1) { dp[i][j][a] = Math.min(dp[i][j][a], dp[i][j + 1][a - 2] + 2 * edges1[i][j]); } } } } for(int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(); for(int j = 0; j < m; j++) { sb.append(dp[i][j][k]); if(j < m - 1) sb.append(' '); } out.println(sb.toString()); } } in.close(); out.close(); } }
cubic
1517_D. Explorer Space
CODEFORCES
/* bts songs to dance to: I need U Run ON Filter I'm fine */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; public class x1517D2 { static final int INF = Integer.MAX_VALUE/3; public static void main(String hi[]) throws Exception { FastScanner infile = new FastScanner(); int N = infile.nextInt(); int M = infile.nextInt(); int K = infile.nextInt(); int[][] weights1 = new int[N][M-1]; for(int r=0; r < N; r++) weights1[r] = infile.nextInts(M-1); int[][] weights2 = new int[N-1][M]; for(int r=0; r < N-1; r++) weights2[r] = infile.nextInts(M); //all are -1 if K is odd int[][] res = new int[N][M]; if(K%2 == 1) { StringBuilder sb = new StringBuilder(); for(int r=0; r < N; r++) { for(int c=0; c < M; c++) sb.append("-1 "); sb.append("\n"); } System.out.print(sb); return; } int[][] dp = new int[N][M]; StringBuilder sb = new StringBuilder(); for(int k=0; k < K/2; k++) { int[][] next = new int[N][M]; for(int r=0; r < N; r++) Arrays.fill(next[r], INF); for(int r=0; r < N; r++) for(int c=0; c < M; c++) { if(r > 0) next[r-1][c] = min(next[r-1][c], dp[r][c]+weights2[r-1][c]); if(r+1 < N) next[r+1][c] = min(next[r+1][c], dp[r][c]+weights2[r][c]); if(c > 0) next[r][c-1] = min(next[r][c-1], dp[r][c]+weights1[r][c-1]); if(c+1 < M) next[r][c+1] = min(next[r][c+1], dp[r][c]+weights1[r][c]); } dp = next; } for(int r=0; r < N; r++) { for(int x: dp[r]) sb.append((2*x)+" "); sb.append("\n"); } System.out.print(sb); } } 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 double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } 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; } } }
cubic
1517_D. Explorer Space
CODEFORCES
// Author : RegalBeast import java.io.*; import java.util.*; public class Main { static final FastReader FR = new FastReader(); static final BufferedWriter BW = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws IOException { StringBuilder solution = new StringBuilder(); int rows = FR.nextInt(); int cols = FR.nextInt(); int moves = FR.nextInt(); Map<Integer, Integer> horizontalEdgeWeights = new HashMap<Integer, Integer>(); for (int r = 0; r < rows; r++) { for (int c = 0; c < cols - 1; c++) { int hash = getHash(r, c); horizontalEdgeWeights.put(hash, FR.nextInt()); } } Map<Integer, Integer> verticalEdgeWeights = new HashMap<Integer, Integer>(); for (int r = 0; r < rows - 1; r++) { for (int c = 0; c < cols; c++) { int hash = getHash(r, c); verticalEdgeWeights.put(hash, FR.nextInt()); } } List<List<Integer>> result = getResult(rows, cols, moves, horizontalEdgeWeights, verticalEdgeWeights); for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { int value = (result != null ? result.get(r).get(c) : -1); solution.append(value + " "); } solution.append("\n"); } BW.write(solution.toString()); BW.close(); } static List<List<Integer>> getResult(int rows, int cols, int moves, Map<Integer, Integer> horizontalEdgeWeights, Map<Integer, Integer> verticalEdgeWeights) { if ((moves & 1) == 1) { return null; } int mid = moves >> 1; List<List<List<Integer>>> minForDistance = new ArrayList<List<List<Integer>>>(rows); for (int r = 0; r < rows; r++) { minForDistance.add(new ArrayList<List<Integer>>(cols)); for (int c = 0; c < cols; c++) { minForDistance.get(r).add(new ArrayList<Integer>(Collections.nCopies(mid+1, Integer.MAX_VALUE))); minForDistance.get(r).get(c).set(0, 0); } } for (int m = 1; m <= mid; m++) { for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { int minBoredom = minForDistance.get(r).get(c).get(m); int hash = getHash(r, c); if (r > 0) { if (minForDistance.get(r-1).get(c).get(m-1) < Integer.MAX_VALUE) { int candidateBoredom = minForDistance.get(r-1).get(c).get(m-1) + verticalEdgeWeights.get(getHash(r-1, c)); minBoredom = Math.min(minBoredom, candidateBoredom); } } if (c > 0) { if (minForDistance.get(r).get(c-1).get(m-1) < Integer.MAX_VALUE) { int candidateBoredom = minForDistance.get(r).get(c-1).get(m-1) + horizontalEdgeWeights.get(getHash(r, c-1)); minBoredom = Math.min(minBoredom, candidateBoredom); } } if (r + 1 < rows) { if (minForDistance.get(r+1).get(c).get(m-1) < Integer.MAX_VALUE) { int candidateBoredom = minForDistance.get(r+1).get(c).get(m-1) + verticalEdgeWeights.get(hash); minBoredom = Math.min(minBoredom, candidateBoredom); } } if (c + 1 < cols) { if (minForDistance.get(r).get(c+1).get(m-1) < Integer.MAX_VALUE) { int candidateBoredom = minForDistance.get(r).get(c+1).get(m-1) + horizontalEdgeWeights.get(hash); minBoredom = Math.min(minBoredom, candidateBoredom); } } minForDistance.get(r).get(c).set(m, minBoredom); } } } List<List<Integer>> result = new ArrayList<List<Integer>>(rows); for (int r = 0; r < rows; r++) { result.add(new ArrayList<Integer>(cols)); for (int c = 0; c < cols; c++) { result.get(r).add(minForDistance.get(r).get(c).get(mid) << 1); } } return result; } static int getHash(int row, int col) { return (row * 1000 + col); } static int getRow(int hash) { return hash / 1000; } static int getCol(int hash) { return hash % 1000; } 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; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1517d { public static void main(String[] args) throws IOException { int n = rni(), m = ni(), k = ni(), ans[][] = new int[n][m]; WGraph g = wgraph(n * m); for (int i = 0; i < n; ++i) { r(); for (int j = 0; j < m - 1; ++j) { g.c(i * m + j, i * m + j + 1, ni()); } } for (int i = 0; i < n - 1; ++i) { r(); for (int j = 0; j < m; ++j) { g.c(i * m + j, (i + 1) * m + j, ni()); } } if (k % 2 == 1) { for (int[] row : ans) { fill(row, -1); prln(row); } close(); return; } k >>= 1; for (int l = 0; l < k; ++l) { int nans[][] = new int[n][m]; for (int[] row : nans) { fill(row, IBIG); } for (int i = 0; i < n * m; ++i) { for (int ed[] : g.get(i)) { int j = ed[0], d = ed[1]; if (ans[i / m][i % m] + d < nans[j / m][j % m]) { nans[j / m][j % m] = ans[i / m][i % m] + d; } } } ans = nans; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { ans[i][j] *= 2; } } for (int[] row : ans) { prln(row); } close(); } static int solve(WGraph g, int i, int k) { List<Map<Integer, Integer>> cost = new ArrayList<>(); for (int j = 0; j <= k; ++j) { cost.add(new HashMap<>()); } PriorityQueue<int[]> dijk = new PriorityQueue<>((a, b) -> a[2] - b[2]); dijk.offer(new int[] {i, 0, 0}); cost.get(0).put(i, 0); while (!dijk.isEmpty()) { int e[] = dijk.poll(), node = e[0], dist = e[1], co = e[2]; if (co > cost.get(dist).get(node)) { continue; } if (dist == k) { return 2 * co; } if (dist < k) { for (int ed[] : g.get(node)) { int j = ed[0], c = ed[1]; if (co + c < cost.get(dist + 1).getOrDefault(j, IBIG)) { cost.get(dist + 1).put(j, co + c); dijk.offer(new int[] {j, dist + 1, co + c}); } } } } return -1; } static WGraph wgraph(int n) { WGraph g = new WGraph(); for (int i = 0; i < n; ++i) { g.add(new ArrayList<>()); } return g; } static WGraph wgraph(int n, int m) throws IOException { WGraph g = wgraph(n); for (int i = 0; i < m; ++i) { g.c(rni() - 1, ni() - 1, ni()); } return g; } static WGraph wdigraph(int n, int m) throws IOException { WGraph g = wgraph(n); for (int i = 0; i < m; ++i) { g.cto(rni() - 1, ni() - 1, ni()); } return g; } static class WGraph extends ArrayList<List<int[]>> { void cto(int u, int v, int w) { get(u).add(new int[] {v, w}); } void c(int u, int v, int w) { cto(u, v, w); cto(v, u, w); } } static BufferedReader __i = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __o = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __r = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final long LMAX = 9223372036854775807L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcd(int a, int b) {return b == 0 ? a : gcd(b, a % b);} static long gcd(long a, long b) {return b == 0 ? a : gcd(b, a % b);} static int[] exgcd(int a, int b) {if (b == 0) return new int[] {1, 0}; int[] y = exgcd(b, a % b); return new int[] {y[1], y[0] - y[1] * (a / b)};} static long[] exgcd(long a, long b) {if (b == 0) return new long[] {1, 0}; long[] y = exgcd(b, a % b); return new long[] {y[1], y[0] - y[1] * (a / b)};} static int randInt(int min, int max) {return __r.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __i.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} // output static void pr(int i) {__o.print(i);} static void prln(int i) {__o.println(i);} static void pr(long l) {__o.print(l);} static void prln(long l) {__o.println(l);} static void pr(double d) {__o.print(d);} static void prln(double d) {__o.println(d);} static void pr(char c) {__o.print(c);} static void prln(char c) {__o.println(c);} static void pr(char[] s) {__o.print(new String(s));} static void prln(char[] s) {__o.println(new String(s));} static void pr(String s) {__o.print(s);} static void prln(String s) {__o.println(s);} static void pr(Object o) {__o.print(o);} static void prln(Object o) {__o.println(o);} static void prln() {__o.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;}; static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;} static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__o.flush();} static void close() {__o.close();} }
cubic
1517_D. Explorer Space
CODEFORCES
// Author : RegalBeast import java.io.*; import java.util.*; public class Main { static final FastReader FR = new FastReader(); static final PrintWriter PW = new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) { StringBuilder solution = new StringBuilder(); int rows = FR.nextInt(); int cols = FR.nextInt(); int moves = FR.nextInt(); int[][] horizontalEdgeWeights = new int[rows][cols-1]; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols - 1; c++) { horizontalEdgeWeights[r][c] = FR.nextInt(); } } int[][] verticalEdgeWeights = new int[rows-1][cols]; for (int r = 0; r < rows - 1; r++) { for (int c = 0; c < cols; c++) { verticalEdgeWeights[r][c] = FR.nextInt(); } } int[][] result = getResult(rows, cols, moves, horizontalEdgeWeights, verticalEdgeWeights); for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { solution.append(result[r][c] + " "); } solution.append("\n"); } PW.print(solution.toString()); PW.close(); } static int[][] getResult(int rows, int cols, int moves, int[][] horizontalEdgeWeights, int[][] verticalEdgeWeights) { int[][] result = new int[rows][cols]; if ((moves & 1) == 1) { for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { result[r][c] = -1; } } return result; } int mid = moves >> 1; int[][][] minForDistance = new int[rows][cols][mid+1]; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { for (int m = 1; m <= mid; m++) { minForDistance[r][c][m] = Integer.MAX_VALUE; } } } for (int m = 1; m <= mid; m++) { for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { int minBoredom = minForDistance[r][c][m]; if (r > 0) { int candidateBoredom = minForDistance[r-1][c][m-1] + verticalEdgeWeights[r-1][c]; minBoredom = Math.min(minBoredom, candidateBoredom); } if (c > 0) { int candidateBoredom = minForDistance[r][c-1][m-1] + horizontalEdgeWeights[r][c-1]; minBoredom = Math.min(minBoredom, candidateBoredom); } if (r + 1 < rows) { int candidateBoredom = minForDistance[r+1][c][m-1] + verticalEdgeWeights[r][c]; minBoredom = Math.min(minBoredom, candidateBoredom); } if (c + 1 < cols) { int candidateBoredom = minForDistance[r][c+1][m-1] + horizontalEdgeWeights[r][c]; minBoredom = Math.min(minBoredom, candidateBoredom); } minForDistance[r][c][m] = minBoredom; } } } for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { result[r][c] = minForDistance[r][c][mid] << 1; } } return result; } 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; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; public class Main { static class Fast { StringTokenizer st; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 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()); } } static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static Fast scn = new Fast(); public static void main(String args[]) throws Exception { int t = 1; while(t-- > 0){ func(); } bw.close(); } private static void func() throws Exception{ int n = scn.nextInt(); int m = scn.nextInt(); int k = scn.nextInt(); int[][] hori = new int[n][m - 1]; int[][] vert = new int[n - 1][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m - 1; j++){ hori[i][j] = scn.nextInt(); } } for(int i = 0; i < n - 1; i++){ for(int j = 0; j < m; j++){ vert[i][j] = scn.nextInt(); } } if(k % 2 != 0){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ bw.append(-1 + " "); } bw.append("\n"); } return; } int[][][] strg = new int[n][m][k + 1]; // for(int i = 0; i < n; i++){ // for(int j = 0; j < m; j++){ // for(int x = 0; x < k; x++) // } // } int[][] answer = new int[n][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ answer[i][j] = steps(i, j, hori, vert, k, strg); } } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ bw.append(answer[i][j] + " "); } bw.append("\n"); } } static int steps(int x, int y, int[][] hori, int[][] vert, int k, int[][][] strg){ if(k == 0) return 0; if(strg[x][y][k] != 0) return strg[x][y][k]; int xmove = x; int ymove = y; int ans = 0; int val = Integer.MAX_VALUE; if(y < hori[0].length){ xmove = x; ymove = y + 1; val = Math.min(val, steps(xmove, ymove, hori, vert, k - 2, strg) + (2 * hori[x][y])); } if(y - 1 >= 0){ xmove = x; ymove = y - 1; val = Math.min(val, steps(xmove, ymove, hori, vert, k - 2, strg) + (2 * hori[x][y - 1])); // val = hori[x][y - 1]; } if(x - 1 >= 0){ xmove = x - 1; ymove = y; val = Math.min(val, steps(xmove, ymove, hori, vert, k - 2, strg) + (2 * vert[x - 1][y])); // val = vert[x - 1][y]; } if(x < vert.length){ xmove = x + 1; ymove = y; val = Math.min(val, steps(xmove, ymove, hori, vert, k - 2, strg) + (2 * vert[x][y])); // val = vert[x + 1][y]; } // System.out.println(val); ans += val; return strg[x][y][k] = ans; } }
cubic
1517_D. Explorer Space
CODEFORCES
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; /** * * @author is2ac */ public class D_CF { public static void main(String[] args) { FastScanner58 fs = new FastScanner58(); PrintWriter pw = new PrintWriter(System.out); //int t = fs.ni(); int t = 1; // for (int tc = 0; tc < t; tc++) { for (int tc = 0; tc < t; tc++) { int n = fs.ni(); int m = fs.ni(); int k = fs.ni(); int[][] a = new int[n][m - 1]; int[][] b = new int[n - 1][m]; for (int i = 0; i < n; i++) { a[i] = fs.intArray(m - 1); } for (int i = 0; i < n - 1; i++) { b[i] = fs.intArray(m); } int[][] res = new int[n][m]; Integer[][][] dp = new Integer[n][m][k / 2 + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { res[i][j] = recur(i, j, k / 2, dp, a, b) * 2; } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < res.length; i++) { for (int j = 0; j < m; j++) { //matrix[i][j]++; if (k%2==1) { sb.append(-1 + " "); } else { sb.append(res[i][j] + " "); } } sb.append("\n"); } pw.println(sb); } pw.close(); } public static int recur(int i, int j, int k, Integer[][][] dp, int[][] a, int[][] b) { if (k == 0) { return 0; } int n = (int) (1e9); if (dp[i][j][k] != null) { return dp[i][j][k]; } if (i != 0) { n = Math.min(n, recur(i - 1, j, k - 1, dp, a, b) + b[i - 1][j]); } if (j != 0) { n = Math.min(n, recur(i, j - 1, k - 1, dp, a, b) + a[i][j - 1]); } if (i != a.length - 1) { n = Math.min(n, recur(i + 1, j, k - 1, dp, a, b) + b[i][j]); } if (j != b[0].length - 1) { n = Math.min(n, recur(i, j + 1, k - 1, dp, a, b) + a[i][j]); } return dp[i][j][k] = n; } } class FastScanner58 { BufferedReader br; StringTokenizer st; public FastScanner58() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[] intArray(int N) { int[] ret = new int[N]; for (int i = 0; i < N; i++) { ret[i] = ni(); } return ret; } long nl() { return Long.parseLong(next()); } long[] longArray(int N) { long[] ret = new long[N]; for (int i = 0; i < N; i++) { ret[i] = nl(); } return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } class UnionFind17 { int[] id; public UnionFind17(int size) { id = new int[size]; for (int i = 0; i < size; i++) { id[i] = i; } } public int find(int p) { int root = p; while (root != id[root]) { root = id[root]; } while (p != root) { int next = id[p]; id[p] = root; p = next; } return root; } public void union(int p, int q) { int a = find(p), b = find(q); if (a == b) { return; } id[b] = a; } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; public class Main { static FastScanner sc = new FastScanner(System.in); static PrintWriter pw = new PrintWriter(System.out); static StringBuilder sb = new StringBuilder(); static long mod = (long) 1e9 + 7; public static void main(String[] args) throws Exception { solve(); pw.flush(); } static ArrayList<ArrayList<ArrayList<int[]>>> kruscal = new ArrayList<>(); static long ans = Integer.MAX_VALUE; static int[][][] map; public static void solve() { int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt(); for(int i = 0; i < n; i++){ kruscal.add(new ArrayList<>()); for(int j = 0; j < m; j++){ kruscal.get(i).add(new ArrayList<>()); } } map = new int[n][m][k+1]; for(int i = 0; i < n; i++){ for(int j = 0; j < m-1; j++){ //int now = (int)(Math.random()*1000000)*2; int now = sc.nextInt(); kruscal.get(i).get(j).add(new int[]{now,i,j+1}); kruscal.get(i).get(j+1).add(new int[]{now,i,j}); } } for(int i = 0; i < n-1; i++){ for(int j = 0; j < m; j++){ //int now = (int)(Math.random()*1000000)*2; int now = sc.nextInt(); kruscal.get(i).get(j).add(new int[]{now,i+1,j}); kruscal.get(i+1).get(j).add(new int[]{now,i,j}); } } if(k % 2 != 0){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ sb.append(-1).append(" "); } pw.println(sb.toString().trim()); sb.setLength(0); } return; } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ Arrays.fill(map[i][j],Integer.MAX_VALUE/2); map[i][j][k/2] = 0; } } for(int kk = k/2; kk > 0; kk--){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ for(int[] next : kruscal.get(i).get(j)){ int d = next[0], i2 = next[1], j2 = next[2]; map[i2][j2][kk-1] = Math.min(map[i2][j2][kk-1],map[i][j][kk]+d); } } } } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ sb.append(map[i][j][0]*2).append(" "); } pw.println(sb.toString().trim()); sb.setLength(0); } } static void dfs(Stack<Integer> st, int y, int x, int cnt, long total){ if(st.size() == cnt){ ans = Math.min(total,ans); } for(int[] next : kruscal.get(y).get(x)){ int d = next[0], i = next[1], j = next[2]; if(Math.abs(i-y)+Math.abs(j-x)-st.size() < 0){ continue; } Stack<Integer> stk = (Stack<Integer>)st.clone(); stk.push(d); dfs(stk,i,j,cnt,total + d); } int rem = cnt - st.size(); long tmp = 0; int c = 0; while(st.size() > 0){ tmp += st.pop(); c++; if(rem % c == 0){ ans = Math.min(ans,total + tmp * (rem/c)); } } } static class ArrayComparator implements Comparator<int[]> { @Override public int compare(int[] a1, int[] a2) { for (int i = 0; i < a1.length; i++) { if (a1[i] < a2[i]) { return -1; } else if (a1[i] > a2[i]) { return 1; } } if (a1.length < a2.length) { return -1; } else if (a1.length > a2.length) { return 1; } else { return 0; } } } private static String ArraysToString(int[] arr){ String s = Arrays.toString(arr); s = s.replaceAll(",",""); s = s.substring(1,s.length()-1); return s; } static class GeekInteger { public static void save_sort(int[] array) { shuffle(array); Arrays.sort(array); } public static int[] shuffle(int[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); int randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } public static void save_sort(long[] array) { shuffle(array); Arrays.sort(array); } public static long[] shuffle(long[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); long randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } } } class DSU { private int n; private int[] parentOrSize; private java.util.ArrayList<java.util.ArrayList<Integer>> map; public DSU(int n) { this.n = n; this.map = new java.util.ArrayList<java.util.ArrayList<Integer>>(); for (int i = 0; i < n; i++) { this.map.add(new java.util.ArrayList<Integer>()); this.map.get(i).add(i); } this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; this.map.get(x).addAll(this.map.get(y)); return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } java.util.ArrayList<java.util.ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new java.util.ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(java.util.ArrayList::isEmpty); return result; } java.util.ArrayList<Integer> getArray(int n) { return this.map.get(n); } } class FastScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } public FastScanner(FileReader in) { reader = new BufferedReader(in); tokenizer = null; } public String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String[] nextArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class A { private static final int INF = (int) 1e9 + 7; public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter pr = new PrintWriter(System.out); // int T=fs.nextInt(); // for (int tt=1; tt<=T; tt++) { int n = fs.nextInt(), m = fs.nextInt(), k = fs.nextInt(); int[][] right = new int[n][m -1], down = new int[n - 1][m]; for(int i = 0; i < n; i++) right[i] = fs.readArray(m - 1); for(int i = 0; i < n - 1; i++) down[i] = fs.readArray(m); if (k % 2 == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) pr.print(-1 + " "); pr.println(); } } else { int[][][] dp = new int[k / 2 + 1][n][m]; for(int r = 1; 2 * r <= k; r++) { for(int i = 0; i < n; i++) Arrays.fill(dp[r][i], INF); for(int i = 0; i < n; i++) for(int j = 0; j + 1 < m; j++) { int cost = right[i][j]; dp[r][i][j] = Integer.min(dp[r][i][j], dp[r - 1][i][j + 1] + cost); dp[r][i][j + 1] = Integer.min(dp[r][i][j + 1], dp[r - 1][i][j] + cost); } for(int i = 0; i + 1 < n; i++) for(int j = 0; j < m; j++) { int cost = down[i][j]; dp[r][i][j] = Integer.min(dp[r][i][j], dp[r - 1][i + 1][j] + cost); dp[r][i + 1][j] = Integer.min(dp[r][i + 1][j], dp[r - 1][i][j] + cost); } } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { pr.print(2 * dp[k/2][i][j] + " "); } pr.println(); } } // } pr.flush(); pr.close(); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; public class a{ static BufferedReader br; static PrintWriter pw; static int N, M, K; static ArrayList<Integer> graph[][]; public static void main(String args[]) throws IOException{ br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); K = Integer.parseInt(st.nextToken()); if(K % 2 == 1){ for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ pw.print("-1 "); } pw.println(); } br.close(); pw.close(); return; } graph = new ArrayList[N][M]; for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ graph[i][j] = new ArrayList<Integer>(); } } for(int i = 0; i < N; i++){ st = new StringTokenizer(br.readLine()); for(int j = 0; j < M-1; j++){ int w = Integer.parseInt(st.nextToken()); graph[i][j].add(w); } } for(int i = 0; i < N; i++){ graph[i][M-1].add(0); } for(int i = 0; i < N-1; i++){ st = new StringTokenizer(br.readLine()); for(int j = 0; j < M; j++){ int w = Integer.parseInt(st.nextToken()); graph[i][j].add(w); } } K /= 2; for(int i = 0; i < M; i++) graph[N-1][i].add(0); long ans[][][] = new long[K+1][N][M]; for(int i = 0; i < N; i++){ Arrays.fill(ans[0][i], 0); } for(int i = 1; i <= K; i++){ for(int x = 0; x < N; x++){ for(int y = 0; y < M; y++){ long cur = (long)1e17; if(x < N-1){ cur = (long)Math.min(cur, graph[x][y].get(1) + ans[i-1][x+1][y]); } if(y < M-1){ cur = (long)Math.min(cur, graph[x][y].get(0) + ans[i-1][x][y+1]); } if(x > 0){ cur = (long)Math.min(cur, graph[x-1][y].get(1) + ans[i-1][x-1][y]); //pw.println("CUR: " + cur + " X: " + x + " Y: " + y + " get = " + graph[x-1][y].get(0)); } if(y > 0){ cur = (long)Math.min(cur, graph[x][y-1].get(0) + ans[i-1][x][y-1]); } ans[i][x][y] = cur; } } } for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++){ pw.print(ans[K][i][j] * 2 + " "); } pw.println(); } br.close(); pw.close(); } static class pii implements Comparable<pii>{ int f, s, k; pii(int f, int s, int k){ this.f = f; this.s = s; this.k = k; } public int compareTo(pii x){ return Integer.compare(f, x.f); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * @Author: * @Date: 2021/4/23 23:55 */ public class ExplorerSpace { static int n; static int m; static int k; static int [][] rows; static int [][] cols; static int max; static int orix; static int oriy; static int [][] dirs = new int[][]{{0,1},{0,-1},{1,0},{-1,0}}; static int [][][][][] mem; public static void main(String[] args) { FastScanner fs = new FastScanner(); n = fs.nextInt(); m =fs.nextInt(); k = fs.nextInt(); rows = new int[n][m-1]; cols = new int[n-1][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m-1; j++){ rows[i][j] = fs.nextInt(); } } for(int i = 0; i < n-1; i++){ for(int j = 0; j < m; j++){ cols[i][j] = fs.nextInt(); } } int [][][] res = new int[100][n][m]; for(int o = 2; o <= k; o+=2){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ res[o][i][j] = 0x3f3f3f3f; if(i>0){ res[o][i][j] = Math.min(res[o][i][j], res[o-2][i-1][j] + 2*cols[i-1][j]); } if(i+1<n){ res[o][i][j] = Math.min(res[o][i][j], res[o-2][i+1][j] + 2 * cols[i][j]); } if(j>0){ res[o][i][j] = Math.min(res[o][i][j], res[o-2][i][j-1] + 2 * rows[i][j-1]); } if(j+1<m){ res[o][i][j] = Math.min(res[o][i][j], res[o-2][i][j+1] + 2 * rows[i][j]); } } } } for(int i = 0; i < n; i++){ for(int j = 0; j < m;j ++){ if(k%2==1){ System.out.print(-1+" "); }else{ System.out.print(res[k][i][j] + " "); } } System.out.println(); } } // static void dfs(int x, int y,int cur, int left){ // if(x<0||x>=n||y<0||y>=m){ // return; // } // if(left==0&&x==orix&&y==oriy){ // max = Math.min(max,cur); // return; // } // if(left<=0){ // return; // } // if(cur>=max){ // return; // } // if(x+1<n){ // dfs(x+1,y,cur+cols[x][y],left-1); // } // if(x-1>=0){ // dfs(x-1,y,cur+cols[x-1][y],left-1); // } // if(y+1<m){ // dfs(x,y+1,cur+rows[x][y],left-1); // } // if(y-1>=0){ // dfs(x,y-1,cur+rows[x][y-1],left-1); // } // // } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while (!st.hasMoreTokens()){ try { st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.awt.*; import java.io.*; import java.sql.Array; import java.util.*; import java.util.List; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static final int N=205; static final int mod=1000000007; static final int INF=1000000009; static final int numBit=17; static FastReader r=new FastReader(); static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { int n=r.nextInt(); int m=r.nextInt(); int k=r.nextInt(); int [][]hor=new int[n][m-1]; int [][]ver=new int[n-1][m]; for(int i=0;i<n;++i){ for(int j=0;j<m-1;++j) hor[i][j]=r.nextInt(); } for(int i=0;i<n-1;++i){ for(int j=0;j<m;++j) ver[i][j]=r.nextInt(); } int [][]dp=new int[n][m]; if(k%2!=0){ for(int i=0;i<n;++i){ for(int j=0;j<m;++j) dp[i][j]=-1; } } else{ int [][]new_dp=new int[n][m]; for(int step=0;step<k/2;++step){ for(int i=0;i<n;++i){ for(int j=0;j<m;++j){ new_dp[i][j]=INF; if(i>0){ new_dp[i][j]=Math.min(new_dp[i][j],dp[i-1][j]+ver[i-1][j]*2); } if(i<n-1){ new_dp[i][j]=Math.min(new_dp[i][j],dp[i+1][j]+ver[i][j]*2); } if(j>0){ new_dp[i][j]=Math.min(new_dp[i][j],dp[i][j-1]+hor[i][j-1]*2); } if(j<m-1){ new_dp[i][j]=Math.min(new_dp[i][j],dp[i][j+1]+hor[i][j]*2); } } } for(int i=0;i<n;++i){ for(int j=0;j<m;++j){ dp[i][j]=new_dp[i][j]; } } } } for(int i=0;i<n;++i){ for(int j=0;j<m;++j){ pw.print(dp[i][j]+" "); } pw.println(); } pw.close(); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.io.*; public class ExplorerSpace { private static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static long[][][] dp; public static boolean valid(int i, int j, int n, int m) { return i>=0 && i<n &&j>=0 && j<m; } public static void solution(int n, int m, int k, int[][] h, int[][] v) { if(k%2==1) { for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) out.print(-1+" "); out.println(); } return; } dp = new long[n][m][k/2+1]; for(int t = 1; t<=k/2; t++) { for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) { dp[i][j][t] = Long.MAX_VALUE; } } } for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) { dp[i][j][0] = 0; } } for(int t = 1; t<=k/2; t++) { for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) { if(valid(i,j+1,n,m)) dp[i][j][t] = Math.min(dp[i][j][t], h[i][j] + dp[i][j+1][t-1]); if(valid(i,j-1,n,m)) dp[i][j][t] = Math.min(dp[i][j][t], h[i][j-1] + dp[i][j-1][t-1]); if(valid(i+1,j,n,m)) dp[i][j][t] = Math.min(dp[i][j][t], v[i][j] + dp[i+1][j][t-1]); if(valid(i-1,j,n,m)) dp[i][j][t] = Math.min(dp[i][j][t], v[i-1][j] + dp[i-1][j][t-1]); } } } for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) out.print((dp[i][j][k/2]*2)+" "); out.println(); } } private static PrintWriter out = new PrintWriter(System.out); public static void main (String[] args) { MyScanner s = new MyScanner(); int n = s.nextInt(); int m = s.nextInt(); int k = s.nextInt(); int[][] h = new int[n][m-1]; for(int i = 0; i<n; i++) { for(int j = 0; j<m-1; j++) { h[i][j] = s.nextInt(); } } int[][] v = new int[n-1][m]; for(int i = 0; i<n-1; i++) { for(int j = 0; j<m; j++) { v[i][j] = s.nextInt(); } } solution(n,m,k,h,v); out.flush(); out.close(); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; public class Main { static public void main(String args[]) throws Exception { Scanner s = new Scanner(System.in); int n = s.nextInt(), m = s.nextInt(), K = s.nextInt(); int[][] p = new int[n][m - 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { p[i][j] = s.nextInt(); } } int[][] v = new int[n - 1][m]; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { v[i][j] = s.nextInt(); } } if (K % 2 == 1){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print("-1 "); } System.out.println(); } return; } long[][][] dp = new long[K + 1][n][m]; for (int k = 2; k <= K; k += 2) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { long res = Long.MAX_VALUE; if (i + 1 < n) { res = Math.min(res, dp[k - 2][i + 1][j] + v[i][j] * 2); } if (i - 1 >= 0) { res = Math.min(res, dp[k - 2][i - 1][j] + v[i - 1][j] * 2); } if (j + 1 < m) { res = Math.min(res, dp[k - 2][i][j + 1] + p[i][j] * 2); } if (j - 1 >= 0) { res = Math.min(res, dp[k - 2][i][j - 1] + p[i][j - 1] * 2); } dp[k][i][j] = res; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print(dp[K][i][j] + " "); } System.out.println(); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; import java.lang.*; public class Main{ static InputReader sc; static PrintWriter pw; public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; sc = new InputReader(inputStream); pw = new PrintWriter(outputStream); solve(); pw.close(); } // static int L,R,top,bottom; // static int cnt,edge; // static long ans; public static void solve() { // int t=sc.nextInt(); int t=1; u:while(t-->0){ int n=s(0); int m=s(0); int k=s(0); long [][][]arr=new long [n][m][4]; for(int i=0;i<n;i++){ for(int j=0;j<m-1;j++){ long v=s(0l); arr[i][j][0]=v; arr[i][j+1][2]=v; } } for(int i=0;i<n-1;i++){ for(int j=0;j<m;j++){ long v=s(0l); arr[i][j][1]=v; arr[i+1][j][3]=v; } } Long [][][]dp=new Long [n][m][k+1]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++) for(int p=1;p<=k;p++) helper(i,j,p,dp,arr,n,m); } for(int i=0;i<n;i++){ for(int j=0;j<m;j++) p(dp[i][j][k]+" "); pln(""); } } } static int [][]dir=new int [][]{{0,1},{1,0},{0,-1},{-1,0}}; public static long helper(int i, int j, int k, Long [][][]dp, long [][][]arr, int n, int m){ if(k<0) return -1; if(k==0) return 0; if(dp[i][j][k]!=null) return dp[i][j][k]; int x, y; long ans=Long.MAX_VALUE,val; for(int d=0;d<4;d++){ x=i+dir[d][0]; y=j+dir[d][1]; if(x<0||x>=n||y<0||y>=m) continue; val=helper(x,y,k-2,dp,arr,n,m); if(val!=-1) ans=Math.min(ans,val+2*arr[i][j][d]); } return dp[i][j][k]=(ans==Long.MAX_VALUE?-1:ans); } public static int find(List<Integer> list, int x){ int l=0,r=list.size()-1,m; while(l<=r){ m=(r-l)/2+l; if(list.get(m)<=x) l=m+1; else r=m-1; } return r; } static class Node{ int val; long cost; Node next; Node(int v,long c){ val=v; next=null; cost=c; } } public static long sum(long n){ long val=0l; while(n>0){ val+=n%10; n/=10; } return val; } // static class Node{ // int left,right; // Node prev,next; // Node(int i, int v){ // left=i; // right=v; // prev=next=null; // } // void remove(){ // this.prev.next=this.next; // this.next.prev=this.prev; // } // void insert(Node node){ // node.next=this; // node.prev=this.prev; // node.prev.next=node; // this.prev=node; // } // } public static int findDiameter(int r, List<List<Integer>>list){ return findFarthest(findFarthest(r,list)[0],list)[1]; } public static int[] findFarthest(int u, List<List<Integer>>list){ int n=list.size(); boolean []vis=new boolean[n+1]; Queue<Integer>q=new LinkedList<>(); q.offer(u); vis[u]=true; int s,pr,cnt=0; int []ar=new int[]{u,0}; while(q.size()>0){ s=q.size(); while(s-->0){ pr=q.poll(); if(ar[1]<cnt){ ar[1]=cnt; ar[0]=pr; } for(int i:list.get(pr)){ if(!vis[i]){ vis[i]=true; q.offer(i); } } } cnt++; } return ar; } public static long atMostK(char []chrr, int k){ if(k<0) return 0; int l=0,cnt=0; long ans=0l; for(int i=0;i<chrr.length;i++){ if(chrr[i]=='1') cnt++; while(cnt>k){ if(chrr[l++]=='1') cnt--; } ans+=(long)(i-l)+1l; } return ans; } public static int ask(int l){ System.out.println(l); System.out.flush(); return sc.nextInt(); } public static void sort(long []arr){ ArrayList<Long> list=new ArrayList<>(); for(int i=0;i<arr.length;i++) list.add(arr[i]); Collections.sort(list); for(int i=0;i<arr.length;i++) arr[i]=list.get(i); } public static void swap(char []chrr, int i, int j){ char temp=chrr[i]; chrr[i]=chrr[j]; chrr[j]=temp; } public static int countSetBits(long n){ int a=0; while(n>0){ a+=(n&1); n>>=1; } return a; } static class Pair{ int v,w; Pair(int V, int W){ v=V; w=W; } //* } /*/ public int compareTo(Pair p){ return (b-p.b); } public int hashCode(){ int hashcode = (a+" "+b).hashCode(); return hashcode; } public boolean equals(Object obj){ if (obj instanceof Pair) { Pair p = (Pair) obj; return (p.a==this.a && p.b == this.b); } return false; } } //*/ 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 (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (b == 0) return a; return a>b?gcd(b, a % b):gcd(a, b % a); } static long fast_pow(long base,long n,long M){ if(n==0) return 1; if(n==1) return base; long halfn=fast_pow(base,n/2,M); if(n%2==0) return ( halfn * halfn ) % M; else return ( ( ( halfn * halfn ) % M ) * base ) % M; } static long modInverse(long n,long M){ return fast_pow(n,M-2,M); } public static int s(int n){ return sc.nextInt(); } public static long s(long n){ return sc.nextLong(); } public static String s(String n){ return sc.next(); } public static double s(double n){ return sc.nextDouble(); } public static void p(int n){ pw.print(n); } public static void p(long n){ pw.print(n); } public static void p(String n){ pw.print(n); } public static void p(double n){ pw.print(n); } public static void pln(int n){ pw.println(n); } public static void pln(long n){ pw.println(n); } public static void pln(String n){ pw.println(n); } public static void pln(double n){ pw.println(n); } public static void feedArr(long []arr){ for(int i=0;i<arr.length;i++) arr[i]=sc.nextLong(); } public static void feedArr(double []arr){ for(int i=0;i<arr.length;i++) arr[i]=sc.nextDouble(); } public static void feedArr(int []arr){ for(int i=0;i<arr.length;i++) arr[i]=sc.nextInt(); } public static void feedArr(String []arr){ for(int i=0;i<arr.length;i++) arr[i]=sc.next(); } public static String printArr(int []arr){ StringBuilder sbr=new StringBuilder(); for(int i:arr) sbr.append(i+" "); return sbr.toString(); } public static String printArr(long []arr){ StringBuilder sbr=new StringBuilder(); for(long i:arr) sbr.append(i+" "); return sbr.toString(); } public static String printArr(String []arr){ StringBuilder sbr=new StringBuilder(); for(String i:arr) sbr.append(i+" "); return sbr.toString(); } public static String printArr(double []arr){ StringBuilder sbr=new StringBuilder(); for(double i:arr) sbr.append(i+" "); return sbr.toString(); } 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()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.PriorityQueue; public class D_Rnd718_Explorer { static int row, col; static int INF = 1_000_000_000; static int[] dx = {0, 0, 1, -1}; static int[] dy = {1, -1, 0, 0}; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader scan = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] in = scan.readLine().split(" "); row = parse(in[0]); col = parse(in[1]); int k = parse(in[2]); int[][] xMove = new int[row][col-1]; for(int i = 0; i < row; i++) { in = scan.readLine().split(" "); for(int j = 0; j < col - 1; j++) xMove[i][j] = parse(in[j]); } int[][] yMove = new int[row - 1][col]; for(int i = 0; i < row - 1; i++) { in = scan.readLine().split(" "); for(int j = 0; j < col; j++) yMove[i][j] = parse(in[j]); } int[][] output = new int[row][col]; if(k % 2 != 0) fill(-1, output); else { Point[][] grid = new Point[row][col]; for(int i = 0; i < row; i++) for(int j = 0; j < col; j++) grid[i][j] = new Point(i, j); parseMoves(grid, xMove, yMove); solve(grid, k, output); } print(output, out); out.flush(); } private static void solve(Point[][] grid, int k, int[][] output) { // try bfs (hoping it passes the time constraint) /*int target = k / 2; for(int i = 0; i < row; i++) for(int j = 0; j < col; j++) output[i][j] = bfs(j, i, target, grid) << 1;*/ int target = k / 2; int[][][] dist = new int[row][col][k/2]; fill(dist, grid); for(int steps = 1; steps < target; steps++ ) { for(int i = 0; i < row; i++) { for(int j = 0; j < col;j ++) { dist[i][j][steps] = getDist(i, j, steps, dist, grid); } } } for(int i = 0; i < row; i++) for(int j = 0; j < col;j ++) output[i][j] = (dist[i][j][target - 1] << 1); } private static int getDist(int y, int x, int steps, int[][][] dist, Point[][] grid) { for(int d = 0; d < 4; d++) { int i = y + dy[d]; int j = x + dx[d]; if(valid(i, j)) { dist[y][x][steps] = Math.min(dist[y][x][steps], dist[i][j][steps - 1] + grid[y][x].weight[d]); } } return dist[y][x][steps]; } private static void fill(int[][][] dist, Point[][] grid) { for(int i = 0; i < row; i++) for(int j = 0; j < col;j ++) for(int s = 0; s < dist[0][0].length; s++) dist[i][j][s] = INF; for(int i = 0; i < row; i++) for(int j = 0; j < col; j++) for(int d = 0; d < 4; d++) dist[i][j][0] = Math.min(dist[i][j][0], grid[i][j].weight[d]); } private static boolean valid(int y, int x) { return y >= 0 && x >= 0 && y < row && x < col; } /*private static int bfs(int xStart, int yStart, int target, Point[][] grid) { PriorityQueue<Step> q = new PriorityQueue<Step>(); q.add(new Step(grid[yStart][xStart], 0, 0)); Step s; int w; while(!q.isEmpty()) { s = q.poll(); if(s.numSteps == target) return s.length; // try to go in each of the four directions for(int d = 0; d < 4; d++) { w = s.current.weight[d]; if(w != -1) q.add(new Step(grid[s.current.y + s.current.dy[d]][s.current.x + s.current.dx[d]], s.length + w, s.numSteps + 1)); } } return -1; }*/ private static void parseMoves(Point[][] grid, int[][] xMove, int[][] yMove) { for(int i = 0; i < xMove.length; i++) { for(int j = 0; j < xMove[i].length; j++) { grid[i][j].weight[2] = xMove[i][j]; // right grid[i][j + 1].weight[3] = xMove[i][j]; // left } } for(int i = 0; i < yMove.length; i++) { for(int j = 0; j < yMove[i].length; j++) { grid[i][j].weight[0] = yMove[i][j]; // down grid[i + 1][j].weight[1] = yMove[i][j]; // up } } } private static void fill(int val, int[][] output) { for(int i = 0; i < output.length; i++) Arrays.fill(output[i], val); } private static void print(int[][] ray, PrintWriter out) { for(int i = 0; i < ray.length; i++) { out.print(ray[i][0]); for(int j = 1; j < ray[i].length; j++) out.print(" " + ray[i][j]); out.println(); } } public static int parse(String num) { return Integer.parseInt(num); } static class Point { int[] weight = new int[4]; // down, up, right, left int x, y; public Point(int i, int j) { y = i; x = j; Arrays.fill(weight, INF); } } static class Step implements Comparable<Step> { int length, numSteps; Point current; public Step(Point p, int weight, int s) { current = p; length = weight; numSteps = s; } @Override public int compareTo(Step s) { if(length == s.length) return numSteps - s.numSteps; return length - s.length; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); DExplorerSpace solver = new DExplorerSpace(); solver.solve(1, in, out); out.close(); } static class DExplorerSpace { int n; int m; int k; int[][] col; int[][] row; long[][][] memo; public void readInput(Scanner sc) { n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt(); col = new int[n][m - 1]; for (int i = 0; i < n; i++) for (int j = 0; j < m - 1; j++) col[i][j] = sc.nextInt(); row = new int[n - 1][m]; for (int i = 0; i < n - 1; i++) for (int j = 0; j < m; j++) row[i][j] = sc.nextInt(); } public void solve(int testNumber, Scanner sc, PrintWriter pw) { int q = 1; while (q-- > 0) { readInput(sc); if (k % 2 == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) pw.print(-1 + " "); pw.println(); } return; } memo = new long[k + 1][n][m]; for (long[][] x : memo) for (long[] y : x) Arrays.fill(y, -1); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { pw.print(2l * dp(i, j, k / 2) + " "); } pw.println(); } } } private long dp(int i, int j, int rem) { if (rem == 0) return 0; if (memo[rem][i][j] != -1) return memo[rem][i][j]; long min = (long) 1e18; if (j <= m - 2) min = Math.min(min, col[i][j] + dp(i, j + 1, rem - 1)); if (j > 0) min = Math.min(min, col[i][j - 1] + dp(i, j - 1, rem - 1)); if (i <= n - 2) min = Math.min(min, row[i][j] + dp(i + 1, j, rem - 1)); if (i > 0) min = Math.min(min, row[i - 1][j] + dp(i - 1, j, rem - 1)); return memo[rem][i][j] = min; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.PrintWriter; import java.util.*; public class D { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = 1; for (int i = 0; i < t; i++) { solve(sc, pw); } pw.close(); } static void solve(Scanner in, PrintWriter out){ int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(); int[][] ri = new int[n][m - 1]; int[][] dn = new int[n - 1][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { ri[i][j] = in.nextInt(); } } for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { dn[i][j] = in.nextInt(); } } long[][][] dp = new long[n][m][k + 1]; if (k % 2 == 1){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(-1 +" "); } out.println(); } }else{ for (int l = 2; l <= k; l += 2) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { long dm = Long.MAX_VALUE; if (i > 0){ int pi = i - 1, pj = j; dm = Math.min(dm, dp[pi][pj][l - 2] + dn[pi][pj] * 2); } if (j > 0){ int pi = i ,pj = j - 1; dm = Math.min(dm, dp[pi][pj][l - 2] + ri[pi][pj] * 2); } if (i < n - 1){ dm = Math.min(dm, dp[i + 1][j][l - 2] + dn[i][j] * 2); } if (j < m - 1){ dm = Math.min(dm, dp[i][j + 1][l - 2] + ri[i][j] * 2); } dp[i][j][l] = dm; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (dp[i][j][k] == Long.MAX_VALUE){ out.print(-1 +" "); }else{ out.print(dp[i][j][k] +" "); } } out.println(); } } } static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } // method to return LCM of two numbers static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } public static int[] sieveEratosthenes(int n) { if (n <= 32) { int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int i = 0; i < primes.length; i++) { if (n < primes[i]) { return Arrays.copyOf(primes, i); } } return primes; } int u = n + 32; double lu = Math.log(u); int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)]; ret[0] = 2; int pos = 1; int[] isnp = new int[(n + 1) / 32 / 2 + 1]; int sup = (n + 1) / 32 / 2 + 1; int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int tp : tprimes) { ret[pos++] = tp; int[] ptn = new int[tp]; for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31); for (int j = 0; j < sup; j += tp) { for (int i = 0; i < tp && i + j < sup; i++) { isnp[j + i] |= ptn[i]; } } } // 3,5,7 // 2x+3=n int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14}; int h = n / 2; for (int i = 0; i < sup; i++) { for (int j = ~isnp[i]; j != 0; j &= j - 1) { int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27]; int p = 2 * pp + 3; if (p > n) break; ret[pos++] = p; if ((long) p * p > n) continue; for (int q = (p * p - 3) / 2; q <= h; q += p) isnp[q >> 5] |= 1 << q; } } return Arrays.copyOf(ret, pos); } // reverse division for 2 public static long[] rdiv2(int n, int mod){ long[] arr = new long[n + 5]; arr[0] = 1; long rev2 = (mod + 1) / 2; for (int i = 1; i < n; i++) { arr[i] = arr[i - 1] * rev2 % mod; } return arr; } static List<Integer> primeFactors(int n) { // Print the number of 2s that divide n List<Integer> ls = new ArrayList<>(); if (n % 2 == 0) ls.add(2); while (n%2==0) { n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n if (n % i == 0) ls.add(i); while (n%i == 0) { n /= i; } } if (n > 1) ls.add(n); return ls; } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; public class D { private static void run() throws IOException { int n = in.nextInt(); int m = in.nextInt(); int p = in.nextInt(); int[] dx = {1, -1, 0, 0}; int[] dy = {0, 0, 1, -1}; int[][][] map = new int[n][m][4]; ArrayList<Edge> edges = new ArrayList<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { int len = in.nextInt(); edges.add(new Edge(new Point[]{new Point(i, j), new Point(i, j + 1)}, len)); map[i][j][2] = map[i][j + 1][3] = len; } } for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { int len = in.nextInt(); edges.add(new Edge(new Point[]{new Point(i, j), new Point(i + 1, j)}, len)); map[i][j][0] = map[i + 1][j][1] = len; } } if (p % 2 != 0) { int[] ans = new int[m]; for (int i = 0; i < m; i++) { ans[i] = -1; } for (int i = 0; i < n; i++) { print_array(ans); } return; } edges.sort(Comparator.comparingInt(o -> o.len)); int[][][] dp = new int[2][n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int min = Integer.MAX_VALUE; for (int k = 0; k < 4; k++) { if (map[i][j][k] == 0) continue; min = Math.min(min, map[i][j][k]); } dp[1][i][j] = min * 2; } } for (int k = 2; k <= p / 2; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dp[k & 1][i][j] = Integer.MAX_VALUE; for (int d = 0; d < 4; d++) { int nx = i + dx[d]; int ny = j + dy[d]; if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue; dp[k & 1][i][j] = Math.min(dp[(k - 1) & 1][nx][ny] + map[i][j][d] * 2, dp[k&1][i][j]); } } } } for (int i = 0; i < n; i++) { print_array(dp[(p / 2) & 1][i]); } } static class Edge { Point[] points; int len; public Edge(Point[] points, int len) { this.points = points; this.len = len; } } static class Point { final int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(new OutputStreamWriter(System.out)); // int t = in.nextInt(); // for (int i = 0; i < t; i++) { // } run(); out.flush(); in.close(); out.close(); } private static int gcd(int a, int b) { if (a == 0 || b == 0) return 0; while (b != 0) { int tmp; tmp = a % b; a = b; b = tmp; } return a; } static final long mod = 1000000007; static long pow_mod(long a, long b) { long result = 1; while (b != 0) { if ((b & 1) != 0) result = (result * a) % mod; a = (a * a) % mod; b >>= 1; } return result; } private static long multiplied_mod(long... longs) { long ans = 1; for (long now : longs) { ans = (ans * now) % mod; } return ans; } @SuppressWarnings("FieldCanBeLocal") private static Reader in; private static PrintWriter out; private static void print_array(int[] array) { for (int now : array) { out.print(now); out.print(' '); } out.println(); } private static void print_array(long[] array) { for (long now : array) { out.print(now); out.print(' '); } out.println(); } static class Reader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { final byte[] buf = new byte[1024]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextSign() throws IOException { byte c = read(); while ('+' != c && '-' != c) { c = read(); } return '+' == c ? 0 : 1; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() throws IOException { int b; // noinspection ALL while ((b = read()) != -1 && isSpaceChar(b)) { ; } return b; } public char nc() throws IOException { return (char) skip(); } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final 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(); } final 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(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; } } private byte read() throws IOException { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } public void close() throws IOException { din.close(); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); DExplorerSpace solver = new DExplorerSpace(); solver.solve(1, in, out); out.close(); } } static class DExplorerSpace { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.ri(); int m = in.ri(); int k = in.ri(); int[][] lr = new int[n][m - 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { lr[i][j] = in.ri(); } } int[][] ud = new int[n - 1][m]; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { ud[i][j] = in.ri(); } } if (k % 2 == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.append(-1).append(' '); } out.println(); } return; } k /= 2; int inf = (int) 1e9; int[][][] dp = new int[k + 1][n][m]; for (int i = 1; i <= k; i++) { for (int j = 0; j < n; j++) { for (int t = 0; t < m; t++) { dp[i][j][t] = inf; //left if (t > 0) { dp[i][j][t] = Math.min(dp[i][j][t], dp[i - 1][j][t - 1] + lr[j][t - 1]); } //right if (t + 1 < m) { dp[i][j][t] = Math.min(dp[i][j][t], dp[i - 1][j][t + 1] + lr[j][t]); } //bot if (j + 1 < n) { dp[i][j][t] = Math.min(dp[i][j][t], dp[i - 1][j + 1][t] + ud[j][t]); } //top if (j > 0) { dp[i][j][t] = Math.min(dp[i][j][t], dp[i - 1][j - 1][t] + ud[j - 1][t]); } } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.append(dp[k][i][j] * 2).append(' '); } out.println(); } } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 32 << 10; private final Writer os; private StringBuilder cache = new StringBuilder(THRESHOLD * 2); public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } private void afterWrite() { if (cache.length() < THRESHOLD) { return; } flush(); } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); afterWrite(); return this; } public FastOutput append(int c) { cache.append(c); afterWrite(); return this; } public FastOutput println() { return append('\n'); } public FastOutput flush() { try { // boolean success = false; // if (stringBuilderValueField != null) { // try { // char[] value = (char[]) stringBuilderValueField.get(cache); // os.write(value, 0, cache.length()); // success = true; // } catch (Exception e) { // } // } // if (!success) { os.append(cache); // } os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int ri() { return readInt(); } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; public class temp { public static void main(String str[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int arr[][] = new int[n][m]; int cross[][] = new int[n][m-1]; int up[][] = new int[n-1][m]; for(int i=0;i<n;i++){ for(int j=0;j<m-1;j++){ cross[i][j] = sc.nextInt(); } } for(int i=0;i<n-1;i++){ for(int j=0;j<m;j++){ up[i][j] = sc.nextInt(); } } int[][] fans = new int[n][m]; if (k % 2 != 0) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { fans[i][j] = -1; } } } else { int[][][] ans = new int[(k/2)+1][n][m]; for (int l = 1; l <= k / 2; l++){ for (int i = 0; i < n ; i++) { for (int j = 0; j < m; j++) { int min = Integer.MAX_VALUE; if(i>0){ min = Math.min(min, up[i-1][j] + ans[l-1][i-1][j]); } if(j>0){ min = Math.min(min, cross[i][j-1] + ans[l-1][i][j-1]); } if(i<n-1){ min = Math.min(min, up[i][j] + ans[l-1][i+1][j]); } if(j<m-1){ min = Math.min(min, cross[i][j] + ans[l-1][i][j+1]); } ans[l][i][j] = min; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { fans[i][j] = 2*ans[k/2][i][j]; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print(fans[i][j]+" "); } System.out.println(); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.lang.*; import java.util.function.Predicate; public class Main{ public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static long MOD = (long) (1e9 + 7); // static long MOD = 998244353; static long MOD2 = MOD * MOD; static FastReader sc = new FastReader(); static int pInf = Integer.MAX_VALUE; static int nInf = Integer.MIN_VALUE; static long ded = (long)(1e17)+9; public static void main(String[] args) throws Exception { int test = 1; // test = sc.nextInt(); for (int i = 1; i <= test; i++){ // out.print("Case #"+i+": "); solve(); } out.flush(); out.close(); } static int n,m; static int[][] hor,ver; static Long[][][] dp; static void solve(){ n = sc.nextInt(); m = sc.nextInt(); int k = sc.nextInt(); dp = new Long[n+1][m+1][k+1]; hor = new int[n][m-1]; ver = new int[n-1][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m-1; j++){ hor[i][j] = sc.nextInt(); } } for(int i = 0; i < n-1; i++){ for(int j = 0; j < m; j++){ ver[i][j] = sc.nextInt(); } } if(k%2==1){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ out.print(-1+" "); } out.println(); } return; } k = k/2; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ long ans = cal(i,j,k); out.print((2*ans)+" "); } out.println(); } } static long cal(int i, int j,int k){ if(k==0)return 0; if(dp[i][j][k]!=null)return dp[i][j][k]; long ans = ded; for(int h = 0; h < 4; h++){ int ni = i+di[h]; int nj = j+dj[h]; if(e(ni,nj)){ int cost = 0; if(ni==i){ if(nj>j){ cost = hor[i][j]; }else{ cost = hor[i][nj]; } }if(nj==j){ if(ni>i){ cost = ver[i][j]; }else{ cost = ver[ni][j]; } } ans = Math.min(ans,(cost)+cal(ni,nj,k-1)); } } return dp[i][j][k] = ans; } static int[] di = new int[]{0,-1,0,1}; static int[] dj = new int[]{-1,0,1,0}; static boolean e(int i, int j){ return i>=0&&j>=0&&i<n&&j<m; } static class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o){ return this.x-o.x; } @Override public String toString() { return "Pair{" + "x=" + x + ", y=" + y + '}'; } public boolean equals(Pair o){ return this.x==o.x&&this.y==o.y; } } public static long mul(long a, long b) { return ((a % MOD) * (b % MOD)) % MOD; } public static long add(long a, long b) { return ((a % MOD) + (b % MOD)) % MOD; } public static long c2(long n) { if ((n & 1) == 0) { return mul(n / 2, n - 1); } else { return mul(n, (n - 1) / 2); } } //Shuffle Sort static final Random random = new Random(); static void ruffleSort(int[] a) { int n = a.length;//shuffle, then sort for (int i = 0; i < n; i++) { int oi = random.nextInt(n); int temp= a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } //Brian Kernighans Algorithm static long countSetBits(long n) { if (n == 0) return 0; return 1 + countSetBits(n & (n - 1)); } //Euclidean Algorithm static long gcd(long A, long B) { if (B == 0) return A; return gcd(B, A % B); } //Modular Exponentiation static long fastExpo(long x, long n) { if (n == 0) return 1; if ((n & 1) == 0) return fastExpo((x * x) % MOD, n / 2) % MOD; return ((x % MOD) * fastExpo((x * x) % MOD, (n - 1) / 2)) % MOD; } //AKS Algorithm 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 (int i = 5; i <= Math.sqrt(n); i += 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static long modinv(long x) { return modpow(x, MOD - 2); } public static long modpow(long a, long b) { if (b == 0) { return 1; } long x = modpow(a, b / 2); x = (x * x) % MOD; if (b % 2 == 1) { return (x * a) % MOD; } return x; } 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; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; public class D7182 { public static void main(String[] args) throws IOException { init_io(); int N = nint(), M = nint(), K = nint(); if (K % 2 == 0) { int[][][] grid = new int[K+1][N][M]; int[][][] edges = new int[4][N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M-1; j++) { edges[0][i][j] = edges[2][i][j+1] = nint(); } } for (int i = 0; i < N-1; i++) { for (int j = 0; j < M; j++) { edges[1][i][j] = edges[3][i+1][j] = nint(); } } for (int k = 1; k <= K/2; k++) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int min = Integer.MAX_VALUE; if (i != N-1) { min = Math.min(min, grid[k-1][i+1][j] + edges[1][i][j]); } if (j != M-1) { min = Math.min(min, grid[k-1][i][j+1] + edges[0][i][j]); } if (i != 0) { min = Math.min(min, grid[k-1][i-1][j] + edges[3][i][j]); } if (j != 0) { min = Math.min(min, grid[k-1][i][j-1] + edges[2][i][j]); } grid[k][i][j] = min; } } } for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { out.print(grid[K/2][i][j]*2 + " "); } out.println(); } } else { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { out.print(-1 + " "); } out.println(); } } out.close(); } static StreamTokenizer in; static PrintWriter out; static BufferedReader br; static int nint() throws IOException { in.nextToken(); return (int) in.nval; } static void init_io() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); in = new StreamTokenizer(br); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } }
cubic
1517_D. Explorer Space
CODEFORCES
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static int n; public static int m; public static int k; public static int[][] right; public static int[][] down; public static int[][][] dp; public static void recur(int i, int j, int depth) { if(dp[i][j][depth]!=-1) return; int min=Integer.MAX_VALUE; // left if(j>0) { recur(i, j-1, depth-1); min=Math.min(min, dp[i][j-1][depth-1] + right[i][j-1]); } // right if(j<m-1) { recur(i, j+1, depth-1); min=Math.min(min, dp[i][j+1][depth-1] + right[i][j]); } // up if(i>0) { recur(i-1, j, depth-1); min=Math.min(min, dp[i-1][j][depth-1] + down[i-1][j]); } // down if(i<n-1) { recur(i+1, j, depth-1); min=Math.min(min, dp[i+1][j][depth-1] + down[i][j]); } dp[i][j][depth]=min; } public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc=new Scanner(System.in); n=sc.nextInt(); m=sc.nextInt(); k=sc.nextInt(); right=new int[n][m-1]; down=new int[n-1][m]; for(int i=0;i<n;i++) for(int j=0;j<m-1;j++) right[i][j]=sc.nextInt(); for(int i=0;i<n-1;i++) for(int j=0;j<m;j++) down[i][j]=sc.nextInt(); if(k%2==1) { for(int i=0;i<n;++i) { for (int j = 0; j < m; j++) System.out.print(-1 + " "); System.out.println(); } } else { k/=2; dp=new int[n][m][k+1]; for(int i=0;i<n;++i) for(int j=0;j<m;j++) for(int z=1;z<=k;z++) dp[i][j][z]=-1; for(int i=0;i<n;++i) for(int j=0;j<m;j++) recur(i,j,k); for(int i=0;i<n;++i) { for (int j = 0; j < m; j++) System.out.print((dp[i][j][k] * 2) + " "); System.out.println(); } } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Stack; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int tc = 0; tc < t; ++tc) { int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < a.length; ++i) { a[i] = sc.nextInt(); } System.out.println(solve(a)); } sc.close(); } static String solve(int[] a) { List<String> result = new ArrayList<>(); Stack<Integer> stack = new Stack<>(); for (int ai : a) { if (ai != 1) { while (stack.peek() + 1 != ai) { stack.pop(); } stack.pop(); } stack.push(ai); result.add(stack.stream().map(String::valueOf).collect(Collectors.joining("."))); } return String.join("\n", result); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
//I'm Whiplash99 import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,N; int T=Integer.parseInt(br.readLine().trim()); StringBuilder sb=new StringBuilder(); while (T-->0) { N=Integer.parseInt(br.readLine().trim()); int[] a=new int[N]; for(i=0;i<N;i++) a[i]=Integer.parseInt(br.readLine().trim()); int end=1; int[][] ans=new int[N][N+10]; ans[0][0]=1; for(i=1;i<N;i++) { while (true) { if(ans[i-1][end]==a[i]-1) break; end--; } for(int j=0;j<end;j++) ans[i][j]=ans[i-1][j]; ans[i][end]=a[i]; end++; } for(i=0;i<N;i++) { for(int j=0;j<N&&ans[i][j]!=0;j++) { sb.append(ans[i][j]); if(ans[i][j+1]!=0) sb.append('.'); } sb.append("\n"); } } System.out.println(sb); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class C { static BufferedReader br; static StringTokenizer st; static PrintWriter pw; static String nextToken() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } static int nextInt() { return Integer.parseInt(nextToken()); } static long nextLong() { return Long.parseLong(nextToken()); } static double nextDouble() { return Double.parseDouble(nextToken()); } static String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); solve(); pw.close(); } private static void solve() { int t = nextInt(); int[] stack = new int[1000000]; for (int i = 0; i < t; i++) { int n = nextInt(); stack[0] = nextInt(); int id = 1; pp(stack, id); for (int j = 1; j < n; j++) { int x = nextInt(); if (x == 1) { stack[id++] = x; } else { while (true) { int p = stack[--id]; if (p + 1 == x) { stack[id++] = x; break; } } } pp(stack, id); } } } private static void pp(int[] stack, int size) { for (int i = 0; i < size - 1; i++) { pw.print(stack[i] + "."); } pw.println(stack[size - 1]); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; /* polyakoff */ public class Main { static FastReader in; static PrintWriter out; static Random rand = new Random(); static final int oo = (int) 1e9 + 10; static final long OO = (long) 1e18 + 10; static final int MOD = (int) 1e9 + 7; static void solve() { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Stack<Integer> st = new Stack<>(); for (int i = 0; i < n; i++) { if (a[i] != 1) { while (!st.empty() && st.peek() + 1 != a[i]) st.pop(); st.pop(); } st.push(a[i]); for (int j = 0; j < st.size(); j++) { out.print(st.get(j)); if (j < st.size() - 1) out.print('.'); } out.println(); } } public static void main(String[] args) { in = new FastReader(); out = new PrintWriter(System.out); int t = 1; t = in.nextInt(); while (t-- > 0) { solve(); } out.flush(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { this(System.in); } FastReader(String file) throws FileNotFoundException { this(new FileInputStream(file)); } FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } int 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 line; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.lang.*; public class Practice { public static long mod = (long) Math.pow(10, 9) + 7; public static long tt = 0; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int c = 1; int t = Integer.parseInt(br.readLine()); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); HashMap<Integer, Integer> map = new HashMap<>(); // map.put(1, 0); int curr = 0; for (int i = 0; i < n; i++) { int tt = Integer.parseInt(br.readLine()); if (tt == 1) { curr++; map.put(curr, 1); } else { ArrayList<Integer> list = new ArrayList<Integer>(map.keySet()); Collections.sort(list); for (int a = list.size() - 1; a >= 0; a--) { if (map.get(list.get(a)) == tt - 1) { map.put(list.get(a), tt); break; } else { curr--; map.remove(list.get(a)); } } } ArrayList<Integer> list = new ArrayList<Integer>(map.keySet()); Collections.sort(list); StringBuilder str=new StringBuilder(); for(int a=0;a<list.size();a++) { if(list.size()-1==a) { str.append(map.get(list.get(a))); continue; } str.append(map.get(list.get(a))+"."); }pw.println(str); } } pw.close(); } // private static long getGCD(long l, long m) { // // TODO Auto-generated method stub // // long t1 = Math.min(l, m); // long t2 = Math.max(l, m); // while (true) { // long temp = t2 % t1; // if (temp == 0) { // return t1; // } // t2 = t1; // t1 = temp; // } // } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=input.nextInt(); while(T-->0) { int n=input.nextInt(); int b[]=new int[n]; for(int i=0;i<n;i++) { b[i]=input.nextInt(); } StringBuilder sb=new StringBuilder(""); int arr[]=new int[n+1]; out.println('1'); sb.append('1'); int size=1; arr[size-1]=1; for(int i=1;i<n;i++) { int a=b[i]; if(a==1) { size++; arr[size-1]=1; sb.append(".1"); out.println(sb.toString()); } else { sb=new StringBuilder(""); int in=0; for(int j=size-1;j>=0;j--) { if(arr[j]==a-1) { in=j; break; } } for(int j=0;j<in;j++) { sb.append(arr[j]+"."); } sb.append(a); size=in+1; arr[size-1]=a; out.println(sb.toString()); } } } out.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; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; import java.io.*; 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); solve(in, out); out.close(); } static String reverse(String s) { return (new StringBuilder(s)).reverse().toString(); } static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar) { factors[1]=1; int p; for(p = 2; p*p <=n; p++) { if(factors[p] == 0) { ar.add(p); factors[p]=p; for(int i = p*p; i <= n; i += p) factors[i] = p; } } for(;p<=n;p++){ if(factors[p] == 0) { ar.add(p); } } } static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } static int findMax(int a[], int n, int vis[], int i, int d){ if(i>=n) return 0; if(vis[i]==1) return findMax(a, n, vis, i+1, d); int max = 0; for(int j=i+1;j<n;j++){ if(Math.abs(a[i]-a[j])>d||vis[j]==1) continue; vis[j] = 1; max = Math.max(max, 1 + findMax(a, n, vis, i+1, d)); vis[j] = 0; } return max; } public static void solve(InputReader sc, PrintWriter pw){ int i, j = 0; // int t = 1; int t = sc.nextInt(); u: while (t-- > 0) { int n = sc.nextInt(); int a[] = new int[n]; ArrayList<Integer> ar = new ArrayList<>(); ar.add(0); for(i=0;i<1000;i++){ ar.add(0); } int m = 1; for(i=0;i<n;i++){ a[i] = sc.nextInt(); if(a[i]==1){ ar.set(m,1); m++; } else{ while(m>0&&ar.get(m-1)!=a[i]-1){ m--; } ar.set(m-1,a[i]); } pw.print(ar.get(1)); for(j=2;j<m;j++){ pw.print("."+ar.get(j)); } pw.println(); } } } static long findOne(int n, int sz[], ArrayList<Integer> ar){ long paths = n-1; long till = 0; for(int v:ar){ paths += till*sz[v]; till += sz[v]; } return paths; } static void assignAnc(ArrayList<Integer> ar[],int sz[], int pa[] ,int curr, int par){ sz[curr] = 1; pa[curr] = par; for(int v:ar[curr]){ if(par==v) continue; assignAnc(ar, sz, pa, v, curr); sz[curr] += sz[v]; } } static int findLCA(int a, int b, int par[][], int depth[]){ if(depth[a]>depth[b]){ a = a^b; b = a^b; a = a^b; } int diff = depth[b] - depth[a]; for(int i=19;i>=0;i--){ if((diff&(1<<i))>0){ b = par[b][i]; } } if(a==b) return a; for(int i=19;i>=0;i--){ if(par[b][i]!=par[a][i]){ b = par[b][i]; a = par[a][i]; } } return par[a][0]; } static void formArrayForBinaryLifting(int n, int par[][]){ for(int j=1;j<20;j++){ for(int i=0;i<n;i++){ if(par[i][j-1]==-1) continue; par[i][j] = par[par[i][j-1]][j-1]; } } } static long lcm(int a, int b){ return a*b/gcd(a,b); } static class Pair1 { long a; long b; Pair1(long a, long b) { this.a = a; this.b = b; } } static class Pair implements Comparable<Pair> { int a; int b; int c; Pair(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public int compareTo(Pair p) { // if(a!=p.a) // return a-p.a; // return b-p.b; return p.c - c; } } // static boolean isPrime(long n) { // if (n <= 1) // return false; // if (n <= 999) // return true; // if (n % 2 == 0 || n % 999 == 0) // return false; // for (int i = 5; i * i <= n; i = i + 6) // if (n % i == 0 || n % (i + 2) == 0) // return false; // return true; // } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 9992768); 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()); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int tests = in.nextInt(); for (int t = 0; t < tests; t++) { int numLines = in.nextInt(); // greedy, maintain stack, keep stack as big as possible int stackIdx = -1; int[] stack = new int[10000]; String prev = ""; for (int x = 0; x < numLines; x++) { int depth = 0; int next = in.nextInt(); boolean found = false; for (int i = stackIdx; i >= 0; i--) { if (next == stack[i] + 1) { depth = i; found = true; break; } } if (found == true) { stackIdx = depth; stack[depth] = next; for (int i = 0; i <= depth; i++) { if (i != 0) { out.print("."); } out.print(stack[i]); } out.println(); } else if (next == 1) { stackIdx++; stack[stackIdx] = 1; for (int i = 0; i <= stackIdx; i++) { if (i != 0) { out.print("."); } out.print(stack[i]); } out.println(); } else { // start a new one stackIdx = 0; stack[0] = next; out.println(next); } } } } } 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() { writer.println(); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class C { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader s = new FastReader(); static PrintWriter out = new PrintWriter(System.out); private static int[] rai(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); } return arr; } private static int[][] rai(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = s.nextInt(); } } return arr; } private static long[] ral(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextLong(); } return arr; } private static long[][] ral(int n, int m) { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = s.nextLong(); } } return arr; } private static int ri() { return s.nextInt(); } private static long rl() { return s.nextLong(); } private static String rs() { return s.next(); } static long gcd(long a,long b) { if(b==0) { return a; } return gcd(b,a%b); } static int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } static boolean isPrime(int n) { //check if n is a multiple of 2 if (n % 2 == 0) return false; //if not, then just check the odds for (int i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } static int MOD=1000000007; static long mpow(long base,long pow) { long res=1; while(pow>0) { if(pow%2==1) { res=(res*base)%MOD; } pow>>=1; base=(base*base)%MOD; } return res; } public static void main(String[] args) { StringBuilder ans = new StringBuilder(); int t = ri(); // int t = 1; while (t-- > 0) { int n=ri(); int[] arr=rai(n); List<Integer> list = new ArrayList<>(); for(int i:arr) { if(i==1) { list.add(i); } else { int ind = list.size()-1; while(list.size()>0 && list.get(ind)+1!=i ) { list.remove(list.size()-1); ind=list.size()-1; } if(list.size()>0) { list.remove(list.size()-1); } list.add(i); } for(int j=0;j<list.size()-1;j++) { ans.append(list.get(j)).append("."); } ans.append(list.get(list.size()-1)).append("\n"); } } out.print(ans.toString()); out.flush(); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class C1523 { public static void print(Stack<Integer> st, PrintWriter pw) { for (int i = 0; i < st.size(); i++) { pw.print(st.get(i)); if (i != st.size() - 1) { pw.print("."); } } pw.println(); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] arr = sc.nextIntArr(n); Stack<Integer> st = new Stack<Integer>(); st.add(arr[0]); print(st, pw); for (int i = 1; i < n; i++) { if (arr[i] == 1) { st.add(arr[i]); } else { while (st.peek() != arr[i] - 1) { st.pop(); } st.pop(); st.add(arr[i]); } print(st, pw); } } pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for(int q=0;q<t;q++){ String s = br.readLine(); int n = Integer.parseInt(s); int a[] = new int[1000]; int index=0; for(int i=0;i<n;i++){ int x = Integer.parseInt(br.readLine()); for(int j=index;j>=0;j--){ if(x-1==a[j]){ a[j]=x; for(int k=0;k<j;k++){ System.out.print(a[k]+"."); } System.out.print(a[j]); System.out.println(); for(int k=j+1;k<1000;k++){ if(a[k]!=0) a[k]=0; else break; } index=j+1; // System.out.println(a[j]+"*"+j); break; } } } } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.ArrayList; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Arrays; import java.util.Random; import java.io.FileWriter; import java.io.PrintWriter; /* Solution Created: 19:12:30 30/05/2021 Custom Competitive programming helper. */ public class Main { public static void solve() { int n = in.nextInt(); ArrayList<Integer> ans = new ArrayList<>(); out.println(in.nextInt()); ans.add(1); for(int i = 0; i<n-1; i++) { int cur = in.nextInt(); if(ans.isEmpty() || cur==1) ans.add(cur); else { while((!ans.isEmpty()) && (ans.get(ans.size()-1)+1!=cur)) ans.remove(ans.size()-1); if(!ans.isEmpty()) ans.remove(ans.size()-1); ans.add(cur); } int cnt = 0; for(int j : ans) { cnt++; out.print(j+(cnt==ans.size()?"":".")); } out.println(); } } static boolean equal(ArrayList<Integer> a, ArrayList<Integer> b) { if(a.size()!=b.size()) return false; for(int i = 0; i<a.size(); i++) if(a.get(i)!=b.get(i)) return false; return true; } public static void main(String[] args) { in = new Reader(); out = new Writer(); int t = in.nextInt(); while(t-->0) solve(); out.exit(); } static Reader in; static Writer out; static class Reader { static BufferedReader br; static StringTokenizer st; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public Reader(String f){ try { this.br = new BufferedReader(new FileReader(f)); } catch (IOException e) { e.printStackTrace(); } } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nd(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nca() { return next().toCharArray(); } public String[] ns(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { ensureNext(); return Integer.parseInt(st.nextToken()); } public double nextDouble() { ensureNext(); return Double.parseDouble(st.nextToken()); } public Long nextLong() { ensureNext(); return Long.parseLong(st.nextToken()); } public String next() { ensureNext(); return st.nextToken(); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } private void ensureNext() { if (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } } } static class Util{ private static Random random = new Random(); static long[] fact; public static void initFactorial(int n, long mod) { fact = new long[n+1]; fact[0] = 1; for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod; } public static long modInverse(long a, long MOD) { long[] gcdE = gcdExtended(a, MOD); if (gcdE[0] != 1) return -1; // Inverted doesn't exist long x = gcdE[1]; return (x % MOD + MOD) % MOD; } public static long[] gcdExtended(long p, long q) { if (q == 0) return new long[] { p, 1, 0 }; long[] vals = gcdExtended(q, p % q); long tmp = vals[2]; vals[2] = vals[1] - (p / q) * vals[2]; vals[1] = tmp; return vals; } public static long nCr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nCr(int n, int r) { return (fact[n]/fact[r])/fact[n-r]; } public static long nPr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nPr(int n, int r) { return fact[n]/fact[n-r]; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } public static int gcd(int a, int b) { int tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static long gcd(long a, long b) { long tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static int random(int min, int max) { return random.nextInt(max-min+1)+min; } public static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } public static void reverse(int[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { int tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(int[] s) { reverse(s, 0, s.length-1); } public static void reverse(long[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { long tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(long[] s) { reverse(s, 0, s.length-1); } public static void reverse(float[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { float tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(float[] s) { reverse(s, 0, s.length-1); } public static void reverse(double[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { double tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(double[] s) { reverse(s, 0, s.length-1); } public static void reverse(char[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { char tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(char[] s) { reverse(s, 0, s.length-1); } public static <T> void reverse(T[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { T tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static <T> void reverse(T[] s) { reverse(s, 0, s.length-1); } public static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(float[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); float t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(double[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); double t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } public static <T> void shuffle(T[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); T t = s[i]; s[i] = s[j]; s[j] = t; } } public static void sortArray(int[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(long[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(float[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(double[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(char[] a) { shuffle(a); Arrays.sort(a); } public static <T extends Comparable<T>> void sortArray(T[] a) { Arrays.sort(a); } } static class Writer { private PrintWriter pw; public Writer(){ pw = new PrintWriter(System.out); } public Writer(String f){ try { pw = new PrintWriter(new FileWriter(f)); } catch (IOException e) { e.printStackTrace(); } } public void printArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void printArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void print(Object o) { pw.print(o.toString()); } public void println(Object o) { pw.println(o.toString()); } public void println() { pw.println(); } public void flush() { pw.flush(); } public void exit() { pw.close(); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class C { static int ar[]; static HashMap<String, ArrayList<String>> map; static int location = 0; static StringBuilder sb; static int N; public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(br.readLine()); while(t --> 0) { int n = Integer.parseInt(br.readLine()); ar = new int[n]; location = 0; map = new HashMap<String, ArrayList<String>>(); sb = new StringBuilder(); N = n; for(int i = 0; i < n; i++) { ar[i] = Integer.parseInt(br.readLine()); } int idx = 2; location = 1; sb.append("1\n"); while(location < n) { if(ar[location] == 1) { nl((idx-1)+"."); }else { sb.append(idx+"\n"); idx++; location++; } } System.out.println(sb); } } public static void nl(String l) { int idx = 1; //System.out.println(location + " " + l); while(location < N) { if(idx == ar[location]) { sb.append(l + idx + "\n"); idx++; location++; }else if(ar[location] == 1) { nl(l + (idx-1) + "."); }else { return; } } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; import java.text.*; public class CF_1523_C{ //SOLUTION BEGIN void pre() throws Exception{} void solve(int TC) throws Exception{ int N = ni(); int[] A = new int[N]; for(int i = 0; i< N; i++)A[i] = ni(); // Stack<Integer> stack = new Stack<>(); int[] stack = new int[2*N]; int sz = 0; for(int i = 0; i< N; i++){ if(A[i] == 1)stack[sz++] = 1; else{ while (sz > 0 && stack[sz-1]+1 != A[i])sz--;//!stack.isEmpty() && stack.peek()+1 != A[i])stack.pop(); hold(sz != 0); stack[sz-1]++; hold(stack[sz-1] == A[i]); } hold(sz != 0); StringBuilder st = new StringBuilder(); for(int s = 0; s< sz; s++){ st.append(stack[s]); if(s+1 < sz)st.append("."); } pn(st.toString()); } } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} void exit(boolean b){if(!b)System.exit(0);} static void dbg(Object... o){System.err.println(Arrays.deepToString(o));} final long IINF = (long)1e17; final int INF = (int)1e9+2; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8; static boolean multipleTC = true, memory = true, fileIO = false; FastReader in;PrintWriter out; void run() throws Exception{ long ct = System.currentTimeMillis(); if (fileIO) { in = new FastReader(""); out = new PrintWriter(""); } else { in = new FastReader(); out = new PrintWriter(System.out); } //Solution Credits: Taranpreet Singh int T = multipleTC? ni():1; pre(); for (int t = 1; t <= T; t++) solve(t); out.flush(); out.close(); System.err.println(System.currentTimeMillis() - ct); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new CF_1523_C().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 28).start(); else new CF_1523_C().run(); } int[][] make(int n, int e, int[] from, int[] to, boolean f){ int[][] g = new int[n][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = to[i]; if(f)g[to[i]][--cnt[to[i]]] = from[i]; } return g; } int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){ int[][][] g = new int[n][][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0}; if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1}; } return g; } int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));} int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;} long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object... o){for(Object oo:o)out.print(oo+" ");} void pn(Object... o){for(int i = 0; i< o.length; i++)out.print(o[i]+(i+1 < o.length?" ":"\n"));} void pni(Object... o){for(Object oo:o)out.print(oo+" ");out.println();out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { int n=Integer.parseInt(bu.readLine()); int cur[]=new int[n],i,cr=-1; for(i=0;i<n;i++) { int j,d=Integer.parseInt(bu.readLine()),f=-1; for(j=cr;j>=0;j--) if(cur[j]==d-1) {f=j; break;} if(f==-1) { cr++; f=cr; } cur[f]=d; cr=f; for(j=f+1;j<n;j++) cur[j]=0; sb.append(cur[0]); for(j=1;j<n;j++) if(cur[j]==0) break; else sb.append("."+cur[j]); sb.append("\n"); } } System.out.print(sb); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author wilso */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class codeforces { static final long MOD2 = 998_244_353; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int tc = sc.ni(); // int tc = 1; for (int rep = 0; rep < tc; rep++) { int N = sc.ni(); int[] arr = sc.intArray(N); pw.println(solve(arr)); } pw.close(); } static String solve(int[] arr) { StringBuilder sb = new StringBuilder(); List<Integer> list = new ArrayList(); list.add(0); for (int i = 0; i < arr.length; i++) { int x = arr[i]; for (int j = list.size() - 1; j >= 0; j--) { if (x - 1 == list.get(j)) { list.set(j, x); while (list.size() > j+1) { list.remove(list.size() - 1); } list.add(0); //append for (int idx = 0; idx < list.size() - 1; idx++) { sb.append(list.get(idx) + "."); } sb.setLength(sb.length() - 1); sb.append("\n"); break; } } } sb.setLength(sb.length() - 1); return sb.toString(); } static int summation(int x) { return x * (x+1) / 2; } static long pow(long num, long exp, long mod){ long ans=1; for(int i=1;i<=exp;i++){ ans=(ans*num)%mod; } return ans; } static boolean isPrime(int n) { if (n <= 1) return false; else if (n == 2) return true; else if (n % 2 == 0) return false; for (int i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } public static void sort(int[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); int temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } public static void sort(long[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); long temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } static int charint(char c) { return Integer.parseInt(String.valueOf(c)); } /* */ //printing methods /* */ //WOW! /* */ public static void printArr(PrintWriter pw, int[] arr) { StringBuilder sb = new StringBuilder(); for (int x : arr) { sb.append(x + ""); } sb.setLength(sb.length() - 1); pw.println(sb.toString()); } public static void printArr2d(PrintWriter pw, int[][] arr) { StringBuilder sb = new StringBuilder(); for (int[] row : arr) { for (int x : row) { sb.append(x + " "); } sb.setLength(sb.length() - 1); sb.append("\n"); } pw.println(sb.toString()); } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[] intArray(int N) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = ni(); return ret; } long nl() { return Long.parseLong(next()); } long[] longArray(int N) { long[] ret = new long[N]; for (int i = 0; i < N; i++) ret[i] = nl(); return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } class MultiSet { TreeMap<Long, Integer> map = new TreeMap<>(); private int size = 0; public MultiSet() { } public void add(Long val) { map.put(val, map.getOrDefault(val, 0) + 1); size++; } public void remove(Long val) { map.put(val, map.get(val) - 1); if (map.get(val) == 0) { map.remove(val); } size--; } public int size() { return size; } public Long higher(Long val) { return map.higherKey(val); } public Long lower(Long val) { return map.lowerKey(val); } public Long ceiling(Long val) { return map.ceilingKey(val); } public Long floor(Long val) { return map.floorKey(val); } public Long first() { return map.firstKey(); } public Long last() { return map.lastKey(); } public boolean isEmpty() { return map.isEmpty(); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class q3 { public static void main(String[] args) throws Exception { // String[] parts=br.readLine().split(" "); // int n=Integer.parseInt(parts[0]); // int k=Integer.parseInt(parts[1]); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tests = Integer.parseInt(br.readLine()); for (int test = 1;test <= tests;test++) { String[] parts = br.readLine().split(" "); int n = Integer.parseInt(parts[0]); StringBuilder temp = new StringBuilder(); int curr = Integer.parseInt(br.readLine()); temp.append("1"); System.out.println(1); for(int i = 0;i < n - 1;i++){ curr = Integer.parseInt(br.readLine()); if(curr == 1){ temp.append('.').append('1'); System.out.println(temp); }else{ while(temp.length() > 0){ int idx = temp.length() - 1; while(idx >= 0 && temp.charAt(idx) != '.') idx--; idx++; int val = Integer.parseInt(temp.substring(idx)); temp.delete(idx,temp.length()); if(curr == val + 1){ temp.append(String.valueOf(curr)); break; } temp.deleteCharAt(temp.length() - 1); } System.out.println(temp); } } } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*;import java.io.*;import java.math.*; public class Main { public static void process()throws IOException { int n=ni(); int[]A=new int[n]; int point = -1; for(int _i=0;_i<n;_i++){ int x =ni(); if(x==1){ point++; A[point]=1; } else{ while(x!=A[point]+1){ A[point]=0; point--; } } A[point]=x; for(int i=0;i<point;i++) p(A[i]+"."); pn(A[point]); } } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} int t=1; t=ni(); while(t-- > 0) {process();} out.flush();out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class tank { static final FastScanner fs = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int t = fs.nextInt(); while(t-->0) { run_case(); } out.close(); } static void run_case() { int n = fs.nextInt(), prevLen = 1, one = 1; int[] arr = fs.readArray(n); int[] len = new int[1001]; StringBuilder[] prev = new StringBuilder[1001]; len[1] = 1; out.println(1); for (int i = 0; i < 1001; i++) { prev[i] = new StringBuilder(); } prev[1].append("1"); for (int i = 1; i < n; i++) { if(arr[i] == 1) { prev[prevLen + 1] = new StringBuilder(prev[prevLen]); prev[prevLen + 1].append(".1"); out.println(prev[prevLen + 1]); prevLen++; len[prevLen] = 1; }else { for (int j = 1000; j > 0; j--) { if(len[j] == arr[i] - 1 && j <= prevLen) { char[] tmp = prev[j].toString().toCharArray(); if(fn(tmp)) { prev[j] = new StringBuilder("" + (len[j] + 1)); }else { prev[j] = new StringBuilder(); int ub = fn2(tmp); for (int k = 0; k <= ub; k++) { prev[j].append(tmp[k]); } prev[j].append(len[j] + 1); } out.println(prev[j]); len[j] = len[j] + 1; prevLen = j; break; } if(j == 1) { prev[j] = new StringBuilder("" + (one + 1)); out.println(prev[j]); len[j] = one + 1; prevLen = j; one++; } } } } } static boolean fn(char[] arr) { for(char c: arr) { if(c == '.') return false; } return true; } static int fn2(char[] arr) { int ret = 0; for (int i = 0; i < arr.length; i++) { if(arr[i] == '.') ret = i; } return ret; } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } String nextLine(){ try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return ""; } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; import java.util.Random; import java.util.StringTokenizer; public final class C { static class Node { int val; String path; Node node; Node(String p, int t) { path = p; val = t; } } public static void main(String[] args) { final FastScanner fs = new FastScanner(); final int t = fs.nextInt(); final StringBuilder sb = new StringBuilder(); for (int test = 0; test < t; test++) { final int n = fs.nextInt(); final Deque<Node> dq = new ArrayDeque<>(); dq.offerLast(new Node("", 0)); for (int i = 0; i < n; i++) { final int next = fs.nextInt(); if (dq.getFirst().val + 1 != next) { if (next == 1) { final Node peek = dq.getFirst(); final String p = peek.path.isEmpty() ? String.valueOf(peek.val) : (peek.path + '.' + peek.val); dq.addFirst(new Node(p, 1)); } else { while (dq.getFirst().val + 1 != next) { dq.removeFirst(); } dq.getFirst().val++; } } else { dq.getFirst().val++; } add(sb, dq.getFirst(), dq.getFirst().val); } } System.out.println(sb); } private static void add(StringBuilder sb, Node node, int val) { final String p = node.path.isEmpty() ? String.valueOf(val) : (node.path + '.' + val); sb.append(p); sb.append('\n'); } static final class Utils { private static class Shuffler { private static void shuffle(int[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } private static void shuffle(long[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } private static void swap(int[] x, int i, int j) { final int t = x[i]; x[i] = x[j]; x[j] = t; } private static void swap(long[] x, int i, int j) { final long t = x[i]; x[i] = x[j]; x[j] = t; } } public static void shuffleSort(int[] arr) { Shuffler.shuffle(arr); Arrays.sort(arr); } public static void shuffleSort(long[] arr) { Shuffler.shuffle(arr); Arrays.sort(arr); } private Utils() {} } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); private String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] nextIntArray(int n) { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { final long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class C { private static FastReader fr = new FastReader(); private static PrintWriter out=new PrintWriter(System.out); private static Random random = new Random(); public static void main(String[] args) throws IOException { StringBuilder sb = new StringBuilder(); // code goes here int t = fr.nextInt(); while (t-- > 0){ int n = fr.nextInt(); int[] arr = fr.nextIntArray(n); sb.append(1).append("\n"); List<Integer> state = new ArrayList<>(); state.add(1); for(int i = 1; i < n; i++){ List<Integer> nextState = new ArrayList<>(); boolean found = false; int till = -1; for(int j = state.size() - 1; j >= 0; j--){ if(state.get(j) + 1 == arr[i]){ till = j; found = true; break; } } if(found){ for(int j = 0; j < till; j++){ nextState.add(state.get(j)); } nextState.add(arr[i]); sb.append(nextState.get(0)); for(int z = 1; z < nextState.size(); z++){ sb.append(".").append(nextState.get(z)); } sb.append("\n"); } if(!found){ nextState.addAll(state); nextState.add(arr[i]); sb.append(nextState.get(0)); for(int z = 1; z < nextState.size(); z++){ sb.append(".").append(nextState.get(z)); } sb.append("\n"); } state = nextState; } } System.out.print(sb.toString()); } static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastReader{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] nextIntArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } public long[] nextLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } static class Pair<A, B>{ A first; B second; public Pair(A first, B second){ this.first = first; this.second = second; } } static long mod(String num, long a) { // Initialize result long res = 0; // One by one process all digits of 'num' for (int i = 0; i < num.length(); i++) res = (res*10 + num.charAt(i) - '0') %a; return res; } static long binomialCoeff(long n, long k, long MOD) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); res %= MOD; } return res; } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static long modInverse(long n, long p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static long nCrModPFermat(int n, int r, long p) { // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r long[] fac = new long[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.*; public class B { public static void main(String[] args) throws IOException { Reader scan = new Reader(); int t = scan.nextInt(); for(int tt = 0;tt<t;tt++) { int n = scan.nextInt(); int arr[] = new int[n]; for(int i = 0;i<n;i++) arr[i] = scan.nextInt(); List<Integer> list = new ArrayList<>(); int j = -1; StringBuilder s = new StringBuilder(); for(int i = 0;i<n;i++) { if(list.isEmpty() || arr[i]==1) { //add list.add(arr[i]); j++; } else if(arr[i] == list.get(j)+1) { //replace list.set(j, arr[i]); } else { for(int k = j;k>=0;k--) { if(arr[i] == list.get(k)+1) {//replace list.set(k, arr[i]); break; } else {//delete list.remove(k); j--; } } } s.delete(0, s.length()); for(Integer p:list) { s.append(p+"."); } s.deleteCharAt(s.length()-1); System.out.println(s.toString()); } } scan.close(); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int MOD = 1000000007; // After writing solution, quick scan for: // array out of bounds // special cases e.g. n=1? // npe, particularly in maps // // Big numbers arithmetic bugs: // int overflow // sorting, or taking max, after MOD void solve() throws IOException { int T = ri(); for (int Ti = 0; Ti < T; Ti++) { int n = ri(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ri(); Deque<int[]> stack = new ArrayDeque<>(); stack.addLast(new int[]{1}); pw.println("1"); for (int i = 1; i < n; i++) { if (a[i] == 1) { int[] prev = stack.peekLast(); int[] curr = new int[prev.length+1]; System.arraycopy(prev, 0, curr, 0, prev.length); curr[curr.length-1] = 1; printArr(curr); stack.addLast(curr); continue; } while (!stack.isEmpty()) { int[] prev = stack.removeLast(); if (a[i] == prev[prev.length-1] + 1) { prev[prev.length-1]++; printArr(prev); stack.addLast(prev); break; } else { continue; } } } } } // IMPORTANT // DID YOU CHECK THE COMMON MISTAKES ABOVE? void printArr(int[] a) { pw.print(a[0]); for (int j = 1; j < a.length; j++) pw.print("." + a[j]); pw.println(); } // Template code below BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { Main m = new Main(); m.solve(); m.close(); } void close() throws IOException { pw.flush(); pw.close(); br.close(); } int ri() throws IOException { return Integer.parseInt(br.readLine().trim()); } long rl() throws IOException { return Long.parseLong(br.readLine().trim()); } int[] ril(int n) throws IOException { int[] nums = new int[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } long[] rll(int n) throws IOException { long[] nums = new long[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); long x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } int[] rkil() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return ril(x); } long[] rkll() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return rll(x); } char[] rs() throws IOException { return br.readLine().toCharArray(); } void sort(int[] A) { Random r = new Random(); for (int i = A.length-1; i > 0; i--) { int j = r.nextInt(i+1); int temp = A[i]; A[i] = A[j]; A[j] = temp; } Arrays.sort(A); } void printDouble(double d) { pw.printf("%.16f", d); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class C2 { String filename = null; InputReader sc; void solve() { int n = sc.nextInt(); int[] a = sc.nextArray(n); int[] ps = new int[n]; int[] q = new int[n]; int[] qs = new int[n]; int nq = 0; for (int i = 1; i < n; i++) { if (a[i] == 1) { qs[nq] = i - 1; q[nq++] = a[i - 1] + 1; ps[i] = i - 1; } else { if (a[i] == a[i - 1] + 1) { qs[nq] = i - 1; q[nq++] = 1; ps[i] = i - 1; } else { for (int j = nq - 1; j >= 0; j--) { if (a[i] == q[j]) { ps[i] = qs[j]; nq = j; break; } } } } } int[] parents = ps; String[] strs = new String[n]; strs[0] = "1"; System.out.println(strs[0]); for (int i = 1; i < n; i++) { String p = strs[parents[i]]; if (a[i] == 1) { strs[i] = p + ".1"; } else { int lastDot = p.lastIndexOf("."); if (lastDot == -1) { strs[i] = a[i] + ""; } else { strs[i] = p.substring(0, lastDot) + "." + a[i]; } } System.out.println(strs[i]); } } public void run() throws FileNotFoundException { if (filename == null) { sc = new InputReader(System.in); } else { sc = new InputReader(new FileInputStream(new File(filename))); } int nTests = sc.nextInt(); for (int test = 0; test < nTests; test++) { solve(); } } public static void main(String[] args) { C2 sol = new C2(); try { sol.run(); } catch (FileNotFoundException e) { e.printStackTrace(); } } 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 float nextFloat() { return Float.parseFloat(next()); } public double nextDouble() { return Float.parseFloat(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] nextArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class C{ public static void main(String[] args) throws IOException { // br = new BufferedReader(new FileReader(".in")); // out = new PrintWriter(new FileWriter(".out")); //new Thread(null, new (), "peepee", 1<<28).start(); read(); int t= RI(); while(t-->0) { read(); int n = RI(); List<Integer> cur = new ArrayList<Integer>(); int[] lvl = new int[n+10]; while(n-->0) { read(); int x = RI(); if (cur.size() == 0) { cur.add(x); lvl[cur.size()]=x; } else { while (!cur.isEmpty()) { if (x == 1+lvl[cur.size()]) { int size = cur.size(); cur.remove(size-1); cur.add(1+lvl[size]); lvl[size] = x; break; } else { // Either add to a new level or go to existing one. if (x == 1) { // add cur.add(x); lvl[cur.size()] = x; break; } else { lvl[cur.size()] = 0; cur.remove(cur.size()-1); } } } if (cur.size() == 0) { cur.add(x); lvl[cur.size()]=x; } } for (int i = 0; i < cur.size(); i++) { out.print(cur.get(i)); if (i != cur.size()-1) out.print("."); } out.println(); } } out.close(); } static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static StringTokenizer st; static void read() throws IOException{st = new StringTokenizer(br.readLine());} static int RI() throws IOException{return Integer.parseInt(st.nextToken());} static long RL() throws IOException{return Long.parseLong(st.nextToken());} static double RD() throws IOException{return Double.parseDouble(st.nextToken());} }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import java.awt.Point; public class Main { static final long MOD = 1000000007L; //static final long MOD2 = 1000000009L; //static final long MOD = 998244353L; //static final long INF = 500000000000L; static final int INF = 1000000005; static final int NINF = -1000000005; //static final long INF = 1000000000000000000L; static FastScanner sc; static PrintWriter pw; static final int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}}; public static void main(String[] args) { sc = new FastScanner(); pw = new PrintWriter(System.out); int Q = sc.ni(); for (int q = 0; q < Q; q++) { int N = sc.ni(); int[] nums = sc.intArray(N, 0); pw.println(1); ArrayDeque<Integer> ad = new ArrayDeque<Integer>(); ad.push(1); for (int i = 1; i < N; i++) { if (nums[i]==1) { ad.push(1); } else { while (!ad.isEmpty()) { int d = ad.pop(); if (d==nums[i]-1) { ad.push(nums[i]); break; } } } printAD(ad); } } pw.close(); } public static void printAD(ArrayDeque<Integer> v) { Object[] arr = v.toArray(); for (int i = arr.length-1; i >= 0; i--) { pw.print(arr[i]); if (i>0) pw.print("."); } pw.println(); } public static void sort(int[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); int temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } public static void sort(long[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); long temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } //Sort an array (immune to quicksort TLE) public static void sort(int[][] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); int[] temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { return a[0]-b[0]; } }); } public static void sort(long[][] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); long[] temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr, new Comparator<long[]>() { @Override public int compare(long[] a, long[] b) { if (a[0] > b[0]) return 1; else if (a[0] < b[0]) return -1; else return 0; //Ascending order. } }); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[][] graph(int N, int[][] edges) { int[][] graph = new int[N][]; int[] sz = new int[N]; for (int[] e: edges) { sz[e[0]] += 1; sz[e[1]] += 1; } for (int i = 0; i < N; i++) { graph[i] = new int[sz[i]]; } int[] cur = new int[N]; for (int[] e: edges) { graph[e[0]][cur[e[0]]] = e[1]; graph[e[1]][cur[e[1]]] = e[0]; cur[e[0]] += 1; cur[e[1]] += 1; } return graph; } int[] intArray(int N, int mod) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = ni()+mod; return ret; } char[] charArray(int N) { char[] ret = new char[N]; for (int i = 0; i < N; i++) ret[i] = next().charAt(0); return ret; } long nl() { return Long.parseLong(next()); } long[] longArray(int N, long mod) { long[] ret = new long[N]; for (int i = 0; i < N; i++) ret[i] = nl()+mod; return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import javafx.util.Pair; import java.io.*; import java.util.*; public class C { static HashMap<Integer, ArrayList<Integer>> tree = new HashMap<>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintStream out = System.out; int t = Integer.parseInt(br.readLine()); for (int i = 0; i < t; i++) { int n = Integer.parseInt(br.readLine()); ArrayList<Integer> depth = new ArrayList<>(); int y = 0; String[] ans = new String[n]; for (int x = 0; x < n; x++) { int in = Integer.parseInt(br.readLine()); if (in == 1) { if (y == depth.size()) depth.add(1); else depth.set(y, 1); y++; StringBuilder curr = new StringBuilder(); curr.append(depth.get(0)); for (int a = 1; a < y; a++) { curr.append('.'); curr.append(depth.get(a)); } ans[x] = curr.toString(); continue; } for (int d = y-1; d >= 0; d--) { if (depth.get(d) == in-1) { y = d+1; depth.set(d, depth.get(d)+1); StringBuilder curr = new StringBuilder(); for (int a = 0; a < d; a++) { curr.append(depth.get(a)); curr.append('.'); } curr.append(in); ans[x] = curr.toString(); break; } } } //Arrays.sort(ans); for (String x : ans) out.println(x); } System.out.flush(); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class EdF { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; public static void main(String[] havish) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); Stack<Integer> st = new Stack<>(); Stack<Integer> temporary = new Stack<>(); for(int j = 0;j<n;j++){ int val = sc.nextInt(); boolean found = false; while(!st.isEmpty()){ int temp = st.peek(); if (val == temp+1){ found = true; st.pop(); break; } else{ temporary.add(st.pop()); } } if (!found){ while(!temporary.isEmpty()){ st.add(temporary.pop()); } } st.add(val); ArrayList<Integer> arr = new ArrayList<>(); for(int s : st){ arr.add(s); } for (int s =0 ;s<arr.size()-1;s++){ out.print(arr.get(s)); out.print("."); } out.println(arr.get(arr.size()-1)); temporary.clear(); } } out.close(); } public static void sort(int[] array){ ArrayList<Integer> copy = new ArrayList<>(); for (int i : array) copy.add(i); Collections.sort(copy); for(int i = 0;i<array.length;i++) array[i] = copy.get(i); } static String[] readArrayString(int n){ String[] array = new String[n]; for(int j =0 ;j<n;j++) array[j] = sc.next(); return array; } static int[] readArrayInt(int n){ int[] array = new int[n]; for(int j = 0;j<n;j++) array[j] = sc.nextInt(); return array; } static int[] readArrayInt1(int n){ int[] array = new int[n+1]; for(int j = 1;j<=n;j++){ array[j] = sc.nextInt(); } return array; } static long[] readArrayLong(int n){ long[] array = new long[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextLong(); return array; } static double[] readArrayDouble(int n){ double[] array = new double[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextDouble(); return array; } static int minIndex(int[] array){ int minValue = Integer.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(long[] array){ long minValue = Long.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(double[] array){ double minValue = Double.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static long power(long x, long y){ if (y == 0) return 1; if (y%2 == 1) return (x*power(x, y-1))%mod; return power((x*x)%mod, y/2)%mod; } static void verdict(boolean a){ out.println(a ? "YES" : "NO"); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } //StringJoiner sj = new StringJoiner(" "); //sj.add(strings) //sj.toString() gives string of those stuff w spaces or whatever that sequence is
cubic
1523_C. Compression and Expansion
CODEFORCES
//Implemented By Aman Kotiyal Date:-30-May-2021 Time:-7:54:28 pm import java.io.*; import java.util.*; public class ques3 { public static void main(String[] args)throws Exception{ new ques3().run();} long mod=1000000000+7; void solve() throws Exception { for(int ii=ni();ii>0;ii--) { int n=ni(); //ArrayList<Integer> al=new ArrayList<Integer>(); Stack<Integer> st=new Stack<Integer>(); int x=ni(); //al.add(1); st.add(1); out.println("1"); for(int i=2;i<=n;i++) { x=ni(); if(x==1) { st.add(1); Stack<Integer> tep=(Stack<Integer>) st.clone(); display(tep); continue; } int top=st.peek(); if(top+1==x) { st.pop(); st.add(x); Stack<Integer> tep=(Stack<Integer>) st.clone(); display(tep); continue; } while(true) { top=st.peek(); if(top+1==x) { st.pop(); st.add(x); Stack<Integer> tep=(Stack<Integer>) st.clone(); display(tep); break; } top=st.pop(); } } } } void display(Stack<Integer> st) { ArrayList<Integer> al = new ArrayList<>(); while(st.size()!=0) { int tem=st.pop(); al.add(tem); } Collections.reverse(al); for (int i = 0; i <al.size()-1; i++) { out.print(al.get(i)+"."); } out.println(al.get(al.size()-1)); } /*FAST INPUT OUTPUT & METHODS BELOW*/ private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; private SpaceCharFilter filter; PrintWriter out; int min(int... ar){int min=Integer.MAX_VALUE;for(int i:ar)min=Math.min(min, i);return min;} long min(long... ar){long min=Long.MAX_VALUE;for(long i:ar)min=Math.min(min, i);return min;} int max(int... ar) {int max=Integer.MIN_VALUE;for(int i:ar)max=Math.max(max, i);return max;} long max(long... ar) {long max=Long.MIN_VALUE;for(long i:ar)max=Math.max(max, i);return max;} void reverse(int a[]){for(int i=0;i<a.length>>1;i++){int tem=a[i];a[i]=a[a.length-1-i];a[a.length-1-i]=tem;}} void reverse(long a[]){for(int i=0;i<a.length>>1;i++){long tem=a[i];a[i]=a[a.length-1-i];a[a.length-1-i]=tem;}} String reverse(String s){StringBuilder sb=new StringBuilder(s);sb.reverse();return sb.toString();} void shuffle(int a[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i=0;i<a.length;i++) al.add(a[i]); Collections.sort(al); for(int i=0;i<a.length;i++) a[i]=al.get(i); } long lcm(long a,long b) { return (a*b)/(gcd(a,b)); } int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } /* for (1/a)%mod = ( a^(mod-2) )%mod ----> use expo to calc -->(a^(mod-2)) */ long expo(long p,long q) /* (p^q)%mod */ { long z = 1; while (q>0) { if (q%2 == 1) { z = (z * p)%mod; } p = (p*p)%mod; q >>= 1; } return z; } void run()throws Exception { in=System.in; out = new PrintWriter(System.out); solve(); out.flush(); } private int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } private int ni() throws IOException { int c = scan(); while (isSpaceChar(c)) c = scan(); int sgn = 1; if (c == '-') { sgn = -1; c = scan(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = scan(); } while (!isSpaceChar(c)); return res * sgn; } private long nl() throws IOException { long num = 0; int b; boolean minus = false; while ((b = scan()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = scan(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = scan(); } } private double nd() throws IOException{ return Double.parseDouble(ns()); } private String ns() throws IOException { int c = scan(); while (isSpaceChar(c)) c = scan(); StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) res.appendCodePoint(c); c = scan(); } while (!isSpaceChar(c)); return res.toString(); } private String nss() throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); return br.readLine(); } private char nc() throws IOException { int c = scan(); while (isSpaceChar(c)) c = scan(); return (char) c; } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } private boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhiteSpace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
/* stream Butter! eggyHide eggyVengeance I need U xiao rerun when */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class x1523C { public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int[] arr = new int[N]; for(int i=0; i < N; i++) arr[i] = Integer.parseInt(infile.readLine()); ArrayList<Integer>[] buckets = new ArrayList[N]; buckets[0] = new ArrayList<Integer>(); buckets[0].add(arr[0]); //first element always 1? for(int i=1; i < N; i++) { ArrayList<Integer> ls = new ArrayList<Integer>(); if(arr[i] == 1) { for(int x: buckets[i-1]) ls.add(x); ls.add(1); } else { int dex = -1; for(int a=0; a < buckets[i-1].size(); a++) if(buckets[i-1].get(a) == arr[i]-1) dex = a; for(int a=0; a < dex; a++) ls.add(buckets[i-1].get(a)); ls.add(arr[i]); } buckets[i] = ls; } //output answer for(int a=0; a < N; a++) { for(int i=0; i < buckets[a].size()-1; i++) { sb.append(buckets[a].get(i)); sb.append("."); } sb.append(arr[a]); sb.append("\n"); } } System.out.print(sb); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.Scanner; public class C_1523 { static Scanner input = new Scanner(System.in); static int n; public static void main(String[] args) { int t = input.nextInt(); for(int test = 0; test < t; test++){ n = input.nextInt(); int num = input.nextInt(); if(num == 1){ n--; recur(""); }else{ System.out.println("ERROR"); } } } public static int recur(String before){ int num = 1; System.out.println(before + num); while(n > 0){ int val = input.nextInt(); n--; if(val == 1){ val = recur(before + num + "."); } if(val == num + 1){ num++; System.out.println(before + num); }else{ return val; } } return -1; } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class codeforces { public static void main(String[] args) throws Exception { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int[]a=sc.nextIntArray(n); LinkedList<Integer>ll=new LinkedList<Integer>(); for(int i=0;i<n;i++) { if(a[i]==1) { ll.addLast(a[i]); }else if(ll.isEmpty()) { ll.addLast(a[i]); }else { while(!(ll.getLast()==a[i]-1)) { ll.removeLast(); } ll.removeLast(); ll.addLast(a[i]); } int ii=0; for(int j:ll) { pw.print(j); if(ii!=ll.size()-1){ pw.print('.'); } ii++; } pw.println(); } } pw.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } 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 long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public 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 boolean ready() throws IOException { return br.ready(); } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return this.z - other.z; } return this.y - other.y; } else { return this.x - other.x; } } } static long mod = 1000000007; static Random rn = new Random(); static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class C { public static void main(String[] args) throws IOException { /**/ Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in))); /*/ Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/c.in")))); /**/ int t = sc.nextInt(); for (int z = 0; z < t; ++z) { int n = sc.nextInt(); ArrayList<Integer> al = new ArrayList<>(); for (int i = 0; i < n; ++i) { int x = sc.nextInt(); if (x==1) { al.add(x); } else { while (al.get(al.size()-1)!=x-1) { al.remove(al.size()-1); } al.remove(al.size()-1); al.add(x); } StringBuilder pr = new StringBuilder(); String d = ""; for (int xx : al) { pr.append(d+xx); d = "."; } System.out.println(pr); } } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.PI; import static java.lang.System.in; import static java.lang.System.out; import static java.lang.System.err; /* 11 1 1 1 2 2 1 2 1 2 2 3 */ public class C { static public void main(String... args) throws Exception { Foster sc = new Foster(); PrintWriter p = new PrintWriter(out); int t = sc.nextInt(); while(t--!=0){ int n = sc.nextInt(); int a[] = sc.intArray(n); ArrayList<ArrayList<Integer>> arr = new ArrayList<>(); for(int i = 0; i < n; i++){ ArrayList<Integer> temp = new ArrayList<>(); if(i-1 < 0){ temp.add(1); } else{ ArrayList<Integer> inner = arr.get(i-1); int last = inner.get(inner.size()-1); ArrayDeque<Integer> q = new ArrayDeque<>(); for(int j : inner){ q.addLast(j); } // if current is one greater then increment if(last+1 == a[i]){ q.pollLast(); q.addLast(a[i]); } // move the chain else if(a[i]==1){ q.addLast(a[i]); } // move back else{ while(!q.isEmpty() && a[i]-q.peekLast() != 1){ q.pollLast(); } if(q.isEmpty()) q.addLast(a[i]); else{ q.pollLast(); q.addLast(a[i]); } } // transfer queue to list while(!q.isEmpty()){ temp.add(q.pollFirst()); } } arr.add(temp); } // output answer for(int i = 0; i < arr.size(); i++){ p.print(arr.get(i).get(0)); for(int j = 1; j < arr.get(i).size(); j++){ p.print("." + arr.get(i).get(j)); } p.println(); } } p.close(); } static long[] sort(long a[]){ ArrayList<Long> arr = new ArrayList<>(); for(long i : a){ arr.add(i); } Collections.sort(arr); for(int i = 0; i < arr.size(); i++){ a[i] = arr.get(i); } return a; } static int[] sort(int a[]){ ArrayList<Integer> arr = new ArrayList<>(); for(int i : a){ arr.add(i); } Collections.sort(arr); // Collections.reverse(arr); for(int i = 0; i < arr.size(); i++){ a[i] = arr.get(i); } return a; } /* */ /* 1. Check overflow in pow function or in general 2. Check indices of read array function 3. Think of an easier solution because the problems you solve are always easy 4. Check iterator of loop 5. If still doesn't work, then jump from the 729th floor 'coz "beta tumse na ho paayega" Move to top!! */ static class Foster { BufferedReader br = new BufferedReader(new InputStreamReader(in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] intArray(int n) { // Check indices int arr[] = new int[n]; for(int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } long[] longArray(int n) { // Check indices long arr[] = new long[n]; for(int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } int[] getBits(int n) { //in Reverse Order int a[] = new int[31]; for(int i = 0; i < 31; i++) { if(((1<<i) & n) != 0) a[i] = 1; } return a; } static long pow(long... a) { long mod = Long.MAX_VALUE; if(a.length == 3) mod = a[2]; long res = 1; while(a[1] > 0) { if((a[1] & 1) == 1) res = (res * a[0]) % mod; a[1] /= 2; a[0] = (a[0] * a[0]) % mod; } return res; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } //System.out.println("YES"); //System.out.println("NO"); //int n=sc.nextInt(); //int a[]=new int[n]; //for(int i=0;i<n;i++) //a[i]=sc.nextInt(); //int n=sc.nextInt(); //long a[]=new long[n]; //for(int i=0;i<n;i++) //a[i]=sc.nextLong(); //System.out.println(); //String str=sc.next(); //long n=sc.nextLong(); public static void main(String[] args) throws IOException{ Scanner sc=new Scanner(System.in); // Reader sc=new Reader(); PrintWriter out=new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0) { int n=sc.nextInt(); ArrayList<Integer> al[]=new ArrayList[n+1]; for(int i=0;i<=n;i++) al[i]=new ArrayList<>(); al[0].add(1); int y; y=sc.nextInt(); boolean flag=true; for(int i=1;i<=n-1;i++) { int x=sc.nextInt(); int idx=al[i-1].size()-1; if(x!=1) { while(flag) { int ans=x-1; if(al[i-1].get(idx)==ans) { idx--; break; } idx--; } } for(int j=0;j<=idx;j++) { al[i].add(al[i-1].get(j)); } al[i].add(x); } for(int i=0;i<=n-1;i++) { out.print(al[i].get(0)); for(int j=1;j<=al[i].size()-1;j++) { out.print("."+al[i].get(j)); } out.println(); } } out.flush(); out.close(); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class C { public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(f.readLine()); while(t-->0){ int n = Integer.parseInt(f.readLine()); int[] arr = new int[n]; for(int i = 0; i < n; i++){ arr[i] = Integer.parseInt(f.readLine()); } int[] levels = new int[n]; int curr_level = 0; for(int i = 0; i < n; i++){ if(levels[curr_level] == arr[i]-1){ levels[curr_level]++; }else if(arr[i] == 1){ curr_level++; levels[curr_level]++; }else if(arr[i] > 1){ while(curr_level > 0 && levels[curr_level] != arr[i]-1){ levels[curr_level] = 0; curr_level--; } levels[curr_level]++; } StringBuilder ostring = new StringBuilder(); for(int level = 0; level <= curr_level; level++){ ostring.append(levels[level]); if(level != curr_level) ostring.append("."); } out.println(ostring); } } out.close(); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
//package deltix2021; import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Queue; public class C { InputStream is; FastWriter out; String INPUT = ""; void solve() { for(int T = ni();T > 0;T--)go(); } void go() { int n = ni(); int[] st = new int[n]; int sp = 0; for(int i = 0;i < n;i++){ int x = ni(); if(x == 1){ st[sp++] = 1; }else{ while(sp > 0){ if(st[sp-1] + 1 == x){ st[sp-1]++; break; }else{ sp--; } } } for(int j = 0;j < sp;j++){ if(j > 0)out.print("."); out.print(st[j]); } out.println(); } } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new FastWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new C().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private 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 char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[][] nmi(int n, int m) { int[][] map = new int[n][]; for(int i = 0;i < n;i++)map[i] = na(m); return map; } private int ni() { return (int)nl(); } 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(); } } public static class FastWriter { private static final int BUF_SIZE = 1<<13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter(){out = null;} public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if(ptr == BUF_SIZE)innerflush(); return this; } public FastWriter write(char c) { return write((byte)c); } public FastWriter write(char[] s) { for(char c : s){ buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte)c; if(ptr == BUF_SIZE)innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if(x == Integer.MIN_VALUE){ return write((long)x); } if(ptr + 12 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if(x == Long.MIN_VALUE){ return write("" + x); } if(ptr + 21 >= BUF_SIZE)innerflush(); if(x < 0){ write((byte)'-'); x = -x; } int d = countDigits(x); for(int i = ptr + d - 1;i >= ptr;i--){ buf[i] = (byte)('0'+x%10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if(x < 0){ write('-'); x = -x; } x += Math.pow(10, -precision)/2; // if(x < 0){ x = 0; } write((long)x).write("."); x -= (long)x; for(int i = 0;i < precision;i++){ x *= 10; write((char)('0'+(int)x)); x -= (int)x; } return this; } public FastWriter writeln(char c){ return write(c).writeln(); } public FastWriter writeln(int x){ return write(x).writeln(); } public FastWriter writeln(long x){ return write(x).writeln(); } public FastWriter writeln(double x, int precision){ return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for(int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for(long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte)'\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for(char[] line : map)write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c){ return writeln(c); } public FastWriter println(int x){ return writeln(x); } public FastWriter println(long x){ return writeln(x); } public FastWriter println(double x, int precision){ return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } public void trnz(int... o) { for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" "); System.out.println(); } // print ids which are 1 public void trt(long... o) { Queue<Integer> stands = new ArrayDeque<>(); for(int i = 0;i < o.length;i++){ for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x)); } System.out.println(stands); } public void tf(boolean... r) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } public void tf(boolean[]... b) { for(boolean[] r : b) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } System.out.println(); } public void tf(long[]... b) { if(INPUT.length() != 0) { for (long[] r : b) { for (long x : r) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } System.out.println(); } } public void tf(long... b) { if(INPUT.length() != 0) { for (long x : b) { for (int i = 0; i < 64; i++) { System.out.print(x << ~i < 0 ? '#' : '.'); } } System.out.println(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; /** __ __ ( _) ( _) / / \\ / /\_\_ / / \\ / / | \ \ / / \\ / / |\ \ \ / / , \ , / / /| \ \ / / |\_ /| / / / \ \_\ / / |\/ _ '_| \ / / / \ \\ | / |/ 0 \0\ / | | \ \\ | |\| \_\_ / / | \ \\ | | |/ \.\ o\o) / \ | \\ \ | /\\`v-v / | | \\ | \/ /_| \\_| / | | \ \\ | | /__/_ `-` / _____ | | \ \\ \| [__] \_/ |_________ \ | \ () / [___] ( \ \ |\ | | // | [___] |\| \| / |/ /| [____] \ |/\ / / || ( \ [____ / ) _\ \ \ \| | || \ \ [_____| / / __/ \ / / // | \ [_____/ / / \ | \/ // | / '----| /=\____ _/ | / // __ / / | / ___/ _/\ \ | || (/-(/-\) / \ (/\/\)/ | / | / (/\/\) / / // _________/ / / \____________/ ( @author NTUDragons-Reborn */ public class C{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ double eps= 0.00000001; static final int MAXN = 10000001; // stores smallest prime factor for every number static int spf[] = new int[MAXN]; Map<Integer,Set<Integer>> dp= new HashMap<>(); // Calculating SPF (Smallest Prime Factor) for every // number till MAXN. // Time Complexity : O(nloglogn) public void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) // marking smallest prime factor for every // number to be itself. spf[i] = i; // separately marking spf for every even // number as 2 for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { // checking if i is prime if (spf[i] == i) { // marking SPF for all numbers divisible by i for (int j=i*i; j<MAXN; j+=i) // marking spf[j] if it is not // previously marked if (spf[j]==j) spf[j] = i; } } } // A O(log n) function returning primefactorization // by dividing by smallest prime factor at every step public Set<Integer> getFactorization(int x) { if(dp.containsKey(x)) return dp.get(x); Set<Integer> ret = new HashSet<>(); while (x != 1) { if(spf[x]!=2) ret.add(spf[x]); x = x / spf[x]; } dp.put(x,ret); return ret; } // function to find first index >= x public int lowerIndex(List<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y public int upperIndex(List<Integer> arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range public int countInRange(List<Integer> arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } InputReader in; PrintWriter out; public void solve(InputReader in, PrintWriter out) { this.in=in; this.out=out; int t=in.nextInt(); while(t-->0){ int n= in.nextInt(); int[] arr= new int[n]; for(int i=0;i<n;i++) arr[i]= in.nextInt(); int[] cur= new int[n]; int idx=0; for(int num: arr){ if(idx<n && num==cur[idx]+1){ cur[idx]=num; printRes(cur, idx); idx++; } else{ for(int i=idx;i>=0;i--){ if(i<n && num!=cur[i]+1) cur[i]=0; else{ cur[i]=num; printRes(cur,i); i++; idx=i; break; } } } } } } public void printRes(int[] cur, int idx){ for(int i=0;i<idx;i++) out.print(cur[i]+"."); out.println(cur[idx]); } public boolean ok(char[] s){ boolean allEqual = true; boolean Alternate = true; for (int i = 0; i < s.length - 1; i++){ if (s[i]!=s[i+1]){ allEqual = false; } else{ Alternate = false; } } if (s[0] == '0' || s[s.length-1] == '0'){ return false; } return allEqual || Alternate; } // private int cal() public static boolean nextPermutation(char[] array){ boolean hasNext = false; int i; for(i = array.length-2; i >= 0; i--){ if(array[i] < array[i+1]){ hasNext = true; break; } } if(!hasNext){// If all elements are arranged from largest to smallest, it means the largest string return false; } // Find backward from the subscript of i + 1 (must be monotonically decreasing), find a smallest element in the set larger than array [i] int j; for(j = i+1; j < array.length; j++){ if(array[j] <= array[i]){ break; } } j--; // Swap these two elements, and then reverse all the elements in i + 1 and later (i + 1, array.length) swap(array, i, j); reverse(array, i+1, array.length); return true; } public static void swap(char[] array, int i, int j) { char temp =array[i]; array[i] = array[j]; array[j] =temp; } public static void reverse(char[] array, int start, int end){ for(int i = start, j = end-1; i < j; i++, j--) { swap(array, i, j); } } public static class compareL implements Comparator<Tuple>{ @Override public int compare(Tuple t1, Tuple t2) { return t2.l - t1.l; } } public static class compareR implements Comparator<Tuple>{ @Override public int compare(Tuple t1, Tuple t2) { return t1.r - t2.r; } } public static class Tuple{ public int l, r, w; public Tuple(int l, int r,int w){ this.l = l; this.r= r; this.w =w; } } public static class Range implements Comparable<Range>{ public int l, r; List<Integer> data; int weight; public Range(int l, int r, List<Integer> data){ this.data = data; this.l = l; this.r =r; this.weight = (int)1e9; } @Override public int compareTo(Range o) { return this.l - o.l; } } public int _gcd(int a, int b) { if(b == 0) { return a; } else { return _gcd(b, a % b); } } } static class Tuple implements Comparable<Tuple>{ int x, y, z; public Tuple(int x, int y, int z){ this.x= x; this.y= y; this.z=z; } @Override public int compareTo(Tuple o){ return this.x-o.x; } } static class Pair implements Comparable<Pair>{ public int x; public int y; public Pair(int x, int y){ this.x= x; this.y= y; } @Override public int compareTo(Pair o) { return this.x-o.x; } } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; public class C { public static void main(String[] args) throws Exception { BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int t = Integer.parseInt(buffer.readLine()); while (t-- > 0) { int n = Integer.parseInt(buffer.readLine()); ArrayList<Integer>list = new ArrayList<>(); for (int i = 0; i < n; i++) { int a = Integer.parseInt(buffer.readLine()); if (a == 1) list.add(1); else { for (int j = list.size()-1; j >= 0; j--) { if (list.get(j)+1 == a) break; list.remove(list.size()-1); } list.remove(list.size()-1); list.add(a); } for (int j = 0; j < list.size(); j++) { sb.append(list.get(j)); if (j == list.size()-1) sb.append("\n"); else sb.append("."); } } } System.out.println(sb); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.Deque; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.ArrayDeque; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); CCompressionAndExpansion solver = new CCompressionAndExpansion(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } static class CCompressionAndExpansion { Node end = new Node(null, -1); FastOutput out; public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.ri(); List<Node> seq = new ArrayList<>(n); Deque<Node> dq = new ArrayDeque<>(n); end = new Node(null, -1); dq.addLast(end); for (int i = 0; i < n; i++) { int x = in.ri(); while (true) { Node last = dq.peekLast(); if (last.nextChild != x) { dq.removeLast(); continue; } last.nextChild++; dq.addLast(new Node(dq.peekLast(), x)); break; } seq.add(dq.peekLast()); } this.out = out; for (Node node : seq) { print(node); out.println(); } } void print(Node root) { if (root.p != end) { print(root.p); out.append('.'); } out.append(root.index); } } static class FastInput { private final InputStream is; private StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public String next() { return readString(); } public int ri() { return readInt(); } public int readInt() { boolean rev = false; skipBlank(); if (next == '+' || next == '-') { rev = next == '-'; next = read(); } int val = 0; while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } return rev ? val : -val; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } } static class Node { Node p; int index; int nextChild = 1; public Node(Node p, int index) { this.p = p; this.index = index; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 32 << 10; private final Writer os; private StringBuilder cache = new StringBuilder(THRESHOLD * 2); public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } private void afterWrite() { if (cache.length() < THRESHOLD) { return; } flush(); } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); afterWrite(); return this; } public FastOutput append(int c) { cache.append(c); afterWrite(); return this; } public FastOutput println() { return append('\n'); } public FastOutput flush() { try { // boolean success = false; // if (stringBuilderValueField != null) { // try { // char[] value = (char[]) stringBuilderValueField.get(cache); // os.write(value, 0, cache.length()); // success = true; // } catch (Exception e) { // } // } // if (!success) { os.append(cache); // } os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.StringTokenizer; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.io.IOException; import java.io.BufferedReader; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.ArrayList; public class p3 { 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()); } byte nextByte() { return Byte.parseByte(next()); } short nextShort() { return Short.parseShort(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader fr=new FastReader(); byte t=fr.nextByte(); while(t-->0) { short n=fr.nextShort(); short a[]=new short [n]; for (short i=-1;++i<n;) a[i]=fr.nextShort(); String s="1"; System.out.println(s); for(short i=0;++i<n;) { if(a[i]==1) { s+=".1"; System.out.println(s); } else if(a[i]==a[i-1]+1) { int c=s.lastIndexOf("."); s=s.substring(0,c+1)+a[i]; System.out.println(s); } else { for(;;) { s=s.substring(0,s.lastIndexOf(".")); int c=s.lastIndexOf("."); int b=Integer.parseInt(s.substring(c+1,s.length())); if(b+1==a[i]) { s=s.substring(0,c+1)+a[i]; System.out.println(s); break; } } } } } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; @SuppressWarnings("unused") public class C{ static long inf = (long)1e15; public static void main(String[] args) throws IOException { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int tt = fs.nextInt(); outer: while(tt-->0) { int n = fs.nextInt(); int[] a = fs.readArray(n); ArrayList<Integer>[] l = new ArrayList[n]; for(int i=0;i<n;i++) l[i] = new ArrayList<Integer>(); l[0].add(1); for(int i=1;i<n;i++) { if(a[i]==1) { for(int j=0;j<l[i-1].size();j++) l[i].add(l[i-1].get(j)); l[i].add(1); } else { int ind = -1; for(int j=l[i-1].size()-1;j>=0;j--) { if(l[i-1].get(j)+1==a[i]) { ind = j; break; } } for(int j=0;j<ind;j++) l[i].add(l[i-1].get(j)); l[i].add(a[i]); } } for(int i=0;i<n;i++) { out.print(l[i].get(0)); for(int j=1;j<l[i].size();j++) out.print("."+l[i].get(j)); out.println(); } } out.close(); } static final Random random=new Random(); static <T> void shuffle(T[] arr) { int n = arr.length; for(int i=0;i<n;i++ ) { int k = random.nextInt(n); T temp = arr[k]; arr[k] = arr[i]; arr[i] = temp; } } static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); int temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void reverse(int[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++){ int temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static void reverse(long[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++){ long temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static <T> void reverse(T[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++) { T temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } 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(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public char nextChar() { return next().toCharArray()[0]; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Stack; public class C { private static PrintWriter out = new PrintWriter(System.out); public static void solve() { In in = new In(); int tests = in.ni(); while (tests-- > 0) { int n = in.ni(); int[] a = in.nia(n); Stack<Integer> st = new Stack<>(); StringBuilder sb = new StringBuilder(); for (int num : a) { // System.out.println("Checking " + num); if (st.isEmpty()) { st.push(num); sb.append(num); } else { // increment current level if (num == st.peek() + 1) { st.pop(); st.push(num); while (sb.length() > 0 && sb.charAt(sb.length() - 1) != '.') { sb.deleteCharAt(sb.length() - 1); } sb.append(num); } // expand current level by 1 else if (num == 1) { st.push(num); sb.append("."); sb.append(num); } // increment higher level else { // search which higher level is the previous of the current number while (!st.isEmpty() && st.peek() + 1 != num) { st.pop(); while (sb.length() > 0 && sb.charAt(sb.length() - 1) != '.') { sb.deleteCharAt(sb.length() - 1); } if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1); } // System.out.println(" " + st.toString() + " " + sb.toString()); if (!st.isEmpty() && st.peek() + 1 == num) { st.pop(); st.add(num); while (sb.length() > 0 && sb.charAt(sb.length() - 1) != '.') { sb.deleteCharAt(sb.length() - 1); } sb.append(num); } } } // System.out.println(">>" + st.toString()); out.println(sb); } } } public static void main(String[] args) throws IOException { // long start = System.nanoTime(); solve(); // System.out.println("Elapsed: " + (System.nanoTime() - start) / 1000000 + // "ns"); out.flush(); } @SuppressWarnings("unused") private static class In { final private static int BUFFER_SIZE = 1024; private byte[] buf; private InputStream is; private int buflen; private int bufptr; public In() { is = System.in; buf = new byte[BUFFER_SIZE]; buflen = bufptr = 0; } public In(String input) { is = new ByteArrayInputStream(input.getBytes()); buf = new byte[BUFFER_SIZE]; buflen = bufptr = 0; } public int readByte() { if (bufptr >= buflen) { try { buflen = is.read(buf); } catch (IOException ioe) { throw new InputMismatchException(); } bufptr = 0; } if (buflen <= 0) return -1; return buf[bufptr++]; } public boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } /* Next character */ public char nc() { return (char) skip(); } /* Next double */ public double nd() { return Double.parseDouble(ns()); } /* Next string */ public String ns() { final StringBuilder sb = new StringBuilder(); int b = skip(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } /* Next integer */ public int ni() { boolean minus = false; int num = 0; int b; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); b = readByte(); } return minus ? -num : num; } /* Next long */ public long nl() { boolean minus = false; long num = 0; int b; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); b = readByte(); } return minus ? -num : num; } /* Next integer 1D array */ public int[] nia(int n) { final int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = ni(); return arr; } /* Next long 1D array */ public long[] nla(int n) { final long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nl(); return arr; } /* Next string 1D array */ public String[] nsa(int n) { final String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = ns(); return arr; } /* Next char 1D array */ public char[] nca(int n) { final char[] arr = new char[n]; for (int i = 0; i < n; i++) arr[i] = nc(); return arr; } /* Next double 1D array */ public double[] nda(int n) { final double[] arr = new double[n]; for (int i = 0; i < n; i++) arr[i] = nc(); return arr; } /* Next integer matrix */ public int[][] nim(int n, int m) { final int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = ni(); return arr; } /* Next long matrix */ public long[][] nlm(int n, int m) { final long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nl(); return arr; } /* Next string matrix */ public String[][] nsm(int n, int m) { final String[][] arr = new String[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = ns(); return arr; } /* Next char matrix */ public char[][] ncm(int n, int m) { final char[][] arr = new char[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nc(); return arr; } /* Next double matrix */ public double[][] ndm(int n, int m) { final double[][] arr = new double[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nd(); return arr; } public static void log(Object... o) { System.out.println(Arrays.deepToString(o)); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
/* ⠀⠀⠀⠀⣠⣶⡾⠏⠉⠙⠳⢦⡀⠀⠀⠀⢠⠞⠉⠙⠲⡀⠀ ⠀⠀⠀⣴⠿⠏⠀⠀⠀⠀⠀⠀⢳⡀⠀⡏⠀⠀Y⠀⠀⢷ ⠀⠀⢠⣟⣋⡀⢀⣀⣀⡀⠀⣀⡀⣧⠀⢸⠀⠀A⠀⠀ ⡇ ⠀⠀⢸⣯⡭⠁⠸⣛⣟⠆⡴⣻⡲⣿⠀⣸⠀⠀S⠀ ⡇ ⠀⠀⣟⣿⡭⠀⠀⠀⠀⠀⢱⠀⠀⣿⠀⢹⠀⠀H⠀⠀ ⡇ ⠀⠀⠙⢿⣯⠄⠀⠀⠀⢀⡀⠀⠀⡿⠀⠀⡇⠀⠀⠀⠀⡼ ⠀⠀⠀⠀⠹⣶⠆⠀⠀⠀⠀⠀⡴⠃⠀⠀⠘⠤⣄⣠⠞⠀ ⠀⠀⠀⠀⠀⢸⣷⡦⢤⡤⢤⣞⣁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⢀⣤⣴⣿⣏⠁⠀⠀⠸⣏⢯⣷⣖⣦⡀⠀⠀⠀⠀⠀⠀ ⢀⣾⣽⣿⣿⣿⣿⠛⢲⣶⣾⢉⡷⣿⣿⠵⣿⠀⠀⠀⠀⠀⠀ ⣼⣿⠍⠉⣿⡭⠉⠙⢺⣇⣼⡏⠀⠀⠀⣄⢸⠀⠀⠀⠀⠀⠀ ⣿⣿⣧⣀⣿………⣀⣰⣏⣘⣆⣀⠀⠀ */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; // System.out is a PrintStream // import java.util.Arrays; import java.util.ArrayDeque; // import java.util.ArrayList; // import java.util.Collections; // for sorting ArrayList mainly // import java.util.HashMap; // import java.util.HashSet; // import java.util.Random; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { FastScanner scn = new FastScanner(); PrintWriter out = new PrintWriter(System.out); for (int tc = scn.nextInt(); tc > 0; tc--) { int N = scn.nextInt(); int[] arr = new int[N]; for (int i = 0; i < N; i++) { arr[i] = scn.nextInt(); } StringBuilder[] ans = new StringBuilder[N]; ans[0] = new StringBuilder("1"); ArrayDeque<Integer> st = new ArrayDeque<>(); st.addLast(0); for (int i = 1; i < N; i++) { // System.out.println(st); ans[i] = new StringBuilder(); if (arr[i] == 1) { st.addLast(i); ans[i].append(ans[i - 1].toString() + ".1"); } else { while (arr[st.getLast()] != arr[i] - 1) { st.removeLast(); } int pos = st.removeLast(); String[] prev = ans[pos].toString().split("[.]"); for (int j = 0, sz = prev.length - 1; j < sz; j++) { ans[i].append(prev[j] + "."); } ans[i].append(arr[i] + ""); st.addLast(i); } } for (StringBuilder str : ans) { out.println(str); } } out.close(); } private static int gcd(int num1, int num2) { int temp = 0; while (num2 != 0) { temp = num1; num1 = num2; num2 = temp % num2; } return num1; } private static int lcm(int num1, int num2) { return (int)((1L * num1 * num2) / gcd(num1, num2)); } private static void ruffleSort(int[] arr) { // int N = arr.length; // Random rand = new Random(); // for (int i = 0; i < N; i++) { // int oi = rand.nextInt(N), temp = arr[i]; // arr[i] = arr[oi]; // arr[oi] = temp; // } // Arrays.sort(arr); } private static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { this.br = new BufferedReader(new InputStreamReader(System.in)); this.st = new StringTokenizer(""); } String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException err) { err.printStackTrace(); } } return st.nextToken(); } String nextLine() { if (st.hasMoreTokens()) { return st.nextToken("").trim(); } try { return br.readLine().trim(); } catch (IOException err) { err.printStackTrace(); } return ""; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; public class Solution { public static void main(String[] args)throws IOException { FastReader in=new FastReader(System.in); int t=in.nextInt(); StringBuilder sb=new StringBuilder(); int i,j,tc=0; while(tc++<t) { int n=in.nextInt(); int arr[]=new int[n]; for(i=0;i<n;i++) arr[i]=in.nextInt(); int ans[]=new int[n+4]; ans[0]=1; int pos=0; sb.append("1\n"); for(i=1;i<n;i++){ if(arr[i]==arr[i-1]+1){ ans[pos]=ans[pos]+1; } else if(arr[i]==1){ pos++; ans[pos]=1; } else{ while(ans[pos]!=arr[i]-1) pos--; ans[pos]=ans[pos]+1; } for(j=0;j<=pos;j++){ if(j<pos) sb.append(ans[j]).append("."); else sb.append(ans[j]).append("\n"); } } } System.out.println(sb); } } class Node { int setroot, dist; public Node(int setroot, int dist){ this.setroot = setroot; this.dist = dist; } @Override public String toString() { return String.format(setroot + ", " + dist); } } class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Main implements Runnable { final static int mod = 1000000007; static FastReader sc; static PrintWriter out; static boolean test_case_input = true; static final int MAX = 1000000000; static final int MIN = -1000000000; public static void print(int a[], int point) { out.print(a[1]); for(int i = 2; i <= point; i++) { out.print("." + a[i]); } out.println(); } public static void solution(int test_case) throws IOException { // code int n = sc.nextInt(); int a[] = sc.intarr(n); int lev[] = new int[n + 1]; lev[1] = 1; int point = 1; out.println(1); for(int i=1; i < n; i++) { if(a[i] == 1) { point++; lev[point] = 1; print(lev, point); } else if(a[i] == lev[point] + 1) { lev[point]++; print(lev, point); } else { while(lev[point] + 1 != a[i]) { point--; } lev[point]++; print(lev, point); } } } // log A base B public static int logint(int x, int base) { return (int) (Math.log(x) / Math.log(base)); } public static int logint(long x, long base) { return (int) (Math.log(x) / Math.log(base)); } public static int logint(double x, double base) { return (int) (Math.log(x) / Math.log(base)); } public static double logdouble(int x, int base) { return (Math.log(x) / Math.log(base)); } public static double logdouble(long x, long base) { return (Math.log(x) / Math.log(base)); } public static double logdouble(double x, double base) { return (Math.log(x) / Math.log(base)); } public static long loglong(int x, int base) { return (long) (Math.log(x) / Math.log(base)); } public static long loglong(long x, long base) { return (long) (Math.log(x) / Math.log(base)); } public static long loglong(double x, double base) { return (long) (Math.log(x) / Math.log(base)); } // Debug public static void debug(String msg, Object value) { File output = new File("output.txt"); if (!output.exists()) return; String type = value.getClass().getSimpleName(); if (type.equals("int[]")) out.println(msg + " => " + Arrays.toString((int[]) value)); else if (type.equals("double[]")) out.println(msg + " => " + Arrays.toString((double[]) value)); else if (type.equals("float[]")) out.println(msg + " => " + Arrays.toString((float[]) value)); else if (type.equals("long[]")) out.println(msg + " => " + Arrays.toString((long[]) value)); else if (type.equals("char[]")) out.println(msg + " => " + Arrays.toString((char[]) value)); else if (type.equals("String[]")) out.println(msg + " => " + Arrays.toString((String[]) value)); else if (type.equals("int[][]")) { out.println(msg + "=>"); for (int i[] : (int[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("double[][]")) { out.println(msg + "=>"); for (double i[] : (double[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("float[][]")) { out.println(msg + "=>"); for (float i[] : (float[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("long[][]")) { out.println(msg + "=>"); for (long i[] : (long[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("char[][]")) { out.println(msg + "=>"); for (char i[] : (char[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("String[][]")) { out.println(msg + "=>"); for (String i[] : (String[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else out.println(msg + " => " + value); } public static void debug(Object value) { File output = new File("output.txt"); if (!output.exists()) return; String type = value.getClass().getSimpleName(); if (type.equals("int[]")) out.println(" => " + Arrays.toString((int[]) value)); else if (type.equals("double[]")) out.println(" => " + Arrays.toString((double[]) value)); else if (type.equals("float[]")) out.println(" => " + Arrays.toString((float[]) value)); else if (type.equals("long[]")) out.println(" => " + Arrays.toString((long[]) value)); else if (type.equals("char[]")) out.println(" => " + Arrays.toString((char[]) value)); else if (type.equals("String[]")) out.println(" => " + Arrays.toString((String[]) value)); else if (type.equals("int[][]")) { out.println("=>"); for (int i[] : (int[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("double[][]")) { out.println("=>"); for (double i[] : (double[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("float[][]")) { out.println("=>"); for (float i[] : (float[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("long[][]")) { out.println("=>"); for (long i[] : (long[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("char[][]")) { out.println("=>"); for (char i[] : (char[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("String[][]")) { out.println("=>"); for (String i[] : (String[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else out.println(" => " + value); } // Graph Functions public static void addUndirectedEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) { adj.get(u).add(v); adj.get(v).add(u); } public static void addDirectedEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) { adj.get(u).add(v); } public static <T> void addUndirectedEdge(ArrayList<ArrayList<Point>> adj, int u, int v, T weight) { adj.get(u).add(new Point(v, weight)); adj.get(v).add(new Point(u, weight)); } public static <T> void addDirectedEdge(ArrayList<ArrayList<Point>> adj, int u, int v, T weight) { adj.get(u).add(new Point(v, weight)); } public static <T> void toString(String msg, ArrayList<ArrayList<T>> adj) { out.println(msg + ":"); int count = 0; for (ArrayList<T> i : adj) { out.print("\t" + count++ + ": "); for (T j : i) { out.print(j + " "); } out.println(); } } public static void addUndirectedEdge(Map<Integer, ArrayList<Integer>> adj, int u, int v) { if (adj.containsKey(u)) { ArrayList<Integer> temp = adj.get(u); temp.add(v); adj.put(u, temp); } else { ArrayList<Integer> temp = new ArrayList<>(); temp.add(v); adj.put(u, temp); } if (adj.containsKey(v)) { ArrayList<Integer> temp = adj.get(v); temp.add(u); adj.put(v, temp); } else { ArrayList<Integer> temp = new ArrayList<>(); temp.add(u); adj.put(v, temp); } } public static void addDirectedEdge(Map<Integer, ArrayList<Integer>> adj, int u, int v) { if (adj.containsKey(u)) { ArrayList<Integer> temp = adj.get(u); temp.add(v); adj.put(u, temp); } else { ArrayList<Integer> temp = new ArrayList<>(); temp.add(v); adj.put(u, temp); } } public static <T> void addUndirectedEdge(Map<Integer, ArrayList<Point>> adj, int u, int v, T weight) { if (adj.containsKey(u)) { ArrayList<Point> temp = adj.get(u); temp.add(new Point(v, weight)); adj.put(u, temp); } else { ArrayList<Point> temp = new ArrayList<>(); temp.add(new Point(v, weight)); adj.put(u, temp); } if (adj.containsKey(v)) { ArrayList<Point> temp = adj.get(v); temp.add(new Point(u, weight)); adj.put(v, temp); } else { ArrayList<Point> temp = new ArrayList<>(); temp.add(new Point(u, weight)); adj.put(v, temp); } } public static <T> void addDirectedEdge(Map<Integer, ArrayList<Point>> adj, int u, int v, T weight) { if (adj.containsKey(u)) { ArrayList<Point> temp = adj.get(u); temp.add(new Point(v, weight)); adj.put(u, temp); } else { ArrayList<Point> temp = new ArrayList<>(); temp.add(new Point(v, weight)); adj.put(u, temp); } } public static <T> void toString(String msg, Map<T, ArrayList<T>> adj) { out.println(msg + ":"); for (Map.Entry<T, ArrayList<T>> entry : adj.entrySet()) { out.println("\t" + entry.getKey() + ": " + entry.getValue()); } } // GCD public static int __gcd(int a, int b) { BigInteger n1 = BigInteger.valueOf(a); BigInteger n2 = BigInteger.valueOf(b); BigInteger gcd = n1.gcd(n2); return gcd.intValue(); } public static long __gcd(long a, long b) { BigInteger n1 = BigInteger.valueOf(a); BigInteger n2 = BigInteger.valueOf(b); BigInteger gcd = n1.gcd(n2); return gcd.longValue(); } public static void main(String args[]) throws IOException { new Thread(null, new Main(), "random", 1 << 26).start(); } @Override public void run() { long start = 0, end = 0; try { File output = new File("output.txt"); sc = new FastReader(); if (output.exists()) { out = new PrintWriter(new FileOutputStream("output.txt")); start = System.nanoTime(); } else { out = new PrintWriter(System.out); } int test_cases = 1; if (test_case_input) test_cases = sc.nextInt(); for (int i = 1; i <= test_cases; i++) { solution(i); } if (output.exists()) { end = System.nanoTime(); out.println("Execution time: " + (end - start) / 1000000 + " ms"); } out.flush(); out.close(); } catch (Exception e) { out.println("Exception: " + e); out.println("At Line no. : " + e.getStackTrace()[0].getLineNumber()); out.flush(); out.close(); return; } } // Edge Class static class Edge implements Comparable<Edge> { Object u; Object v; Object wt; public Edge(Object origin, Object destination, Object weight) { u = origin; v = destination; wt = weight; } public String toString() { String ans = u + " -> " + v + " : " + wt; return ans; } public int getIntOrigin() { return (int) u; } public int getIntDestination() { return (int) v; } public int getIntWeight() { return (int) wt; } public long getLongOrigin() { return (long) u; } public long getLongDestination() { return (long) v; } public long getLongWeight() { return (long) wt; } @Override public int compareTo(Edge edge) { if ((edge.u).getClass() == Long.class) return (((Long) this.wt).compareTo((Long) edge.wt)); else return (((Integer) this.wt).compareTo((Integer) edge.wt)); } } // Point Class static class Point implements Comparable<Point> { Object x; Object y; public Point(Object a, Object b) { x = a; y = b; } public int getIntX() { return (int) x; } public int getIntY() { return (int) y; } public long getLongX() { return (long) x; } public long getLongY() { return (long) y; } public int compareTo(Point obj) { if (obj.x.equals(this.x)) { if ((obj.y).getClass() == Long.class) return ((Long) this.y).compareTo((Long) obj.y); else return ((Integer) this.y).compareTo((Integer) obj.y); } else { if ((obj.x).getClass() == Long.class) return ((Long) this.x).compareTo((Long) obj.x); else return ((Integer) this.x).compareTo((Integer) obj.x); } } public String toString() { String ans = "(" + x + ", " + y + ")"; return ans; } @Override public int hashCode() { int hash = 7; hash = 71 * hash + (int) this.x; hash = 71 * hash + (int) this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) return false; Point point = (Point) obj; if (point.x.equals(this.x) && point.y.equals(this.y)) return true; else return false; } } // Fast IO static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() throws FileNotFoundException { File in = new File("input.txt"); if (in.exists()) { br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } else { 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()); } float nextFloat() { return Float.parseFloat(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] intarr(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(next()); } return a; } long[] longarr(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = Long.parseLong(next()); } return a; } float[] floatarr(int n) { float a[] = new float[n]; for (int i = 0; i < n; i++) { a[i] = Float.parseFloat(next()); } return a; } double[] doublearr(int n) { double a[] = new double[n]; for (int i = 0; i < n; i++) { a[i] = Double.parseDouble(next()); } return a; } int[][] intmatrix(int row, int col) { int a[][] = new int[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { a[i][j] = Integer.parseInt(next()); } } return a; } long[][] longmatrix(int row, int col) { long a[][] = new long[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { a[i][j] = Long.parseLong(next()); } } return a; } float[][] floatmatrix(int row, int col) { float a[][] = new float[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { a[i][j] = Float.parseFloat(next()); } } return a; } double[][] doublematrix(int row, int col) { double a[][] = new double[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { a[i][j] = Double.parseDouble(next()); } } return a; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.arraycopy; import static java.lang.System.exit; import static java.util.Arrays.copyOf; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.util.StringTokenizer; public class C { static class IntList { int data[] = new int[3]; int size = 0; boolean isEmpty() { return size == 0; } int size() { return size; } int get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } return data[index]; } void clear() { size = 0; } void set(int index, int value) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } data[index] = value; } void expand() { if (size >= data.length) { data = copyOf(data, (data.length << 1) + 1); } } void insert(int index, int value) { if (index < 0 || index > size) { throw new IndexOutOfBoundsException(); } expand(); arraycopy(data, index, data, index + 1, size++ - index); data[index] = value; } int delete(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } int value = data[index]; arraycopy(data, index + 1, data, index, --size - index); return value; } void push(int value) { expand(); data[size++] = value; } int pop() { if (size == 0) { throw new NoSuchElementException(); } return data[--size]; } void unshift(int value) { expand(); arraycopy(data, 0, data, 1, size++); data[0] = value; } int shift() { if (size == 0) { throw new NoSuchElementException(); } int value = data[0]; arraycopy(data, 1, data, 0, --size); return value; } } static void solve() throws Exception { int tests = scanInt(); IntList stack = new IntList(); for (int test = 0; test < tests; test++) { stack.clear(); int n = scanInt(); for (int i = 0; i < n; i++) { int v = scanInt(); if (v == 1) { stack.push(v); } else { while (stack.pop() != v - 1) { } stack.push(v); } for (int j = 0; j < stack.size; j++) { if (j != 0) { out.print('.'); } out.print(stack.data[j]); } out.println(); } } } 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); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class C { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(int arr[],int l1,int r1,int l2,int r2) { int tmp[]=new int[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(long arr[],int l1,int r1,int l2,int r2) { long tmp[]=new long[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void main(String args[]) throws IOException { Scan input=new Scan(); StringBuilder ans=new StringBuilder(""); int test=input.scanInt(); for(int tt=1;tt<=test;tt++) { int n=input.scanInt(); ArrayList<Integer> arrli[]=new ArrayList[n]; for(int i=0;i<n;i++) { arrli[i]=new ArrayList<>(); } for(int i=0;i<n;i++) { int tmp=input.scanInt(); if(i==0) { arrli[0].add(1); continue; } if(tmp==1) { for(int j=0;j<arrli[i-1].size();j++) { arrli[i].add(arrli[i-1].get(j)); } arrli[i].add(tmp); continue; } int indx=-1; for(int j=0;j<arrli[i-1].size();j++) { if(arrli[i-1].get(j)==tmp-1) { indx=j; } } for(int j=0;j<indx;j++) { arrli[i].add(arrli[i-1].get(j)); } arrli[i].add(tmp); } for(int i=0;i<n;i++) { for(int j=0;j<arrli[i].size();j++) { ans.append(arrli[i].get(j)); if(j!=arrli[i].size()-1) { ans.append("."); } } ans.append("\n"); } } System.out.println(ans); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class B{ public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = fs.nextInt(); for(int tt=0;tt<t;tt++) { int n = fs.nextInt(); int[] arr = fs.readArray(n); List<String> ans = new ArrayList(); List<Integer> temp = new ArrayList(); temp.add(arr[0]); ans.add(""+arr[0]); for(int i=1;i<n;i++) { int ch = arr[i]; if(ch == 1) { temp.add(1); StringBuilder sb = new StringBuilder(); for(int j=0;j<temp.size();j++) { sb.append(temp.get(j)); if(j != temp.size()-1) { sb.append('.'); } } ans.add(sb.toString()); } else { int j = temp.size()-1; while(j>=0) { if(ch - temp.get(j) == 1) { temp.set(j,ch); break; } else { j--; } } int extra = temp.size()-1; while(extra>j) { temp.remove(temp.size()-1); extra--; } StringBuilder sb = new StringBuilder(); for(int jj=0;jj<temp.size();jj++) { sb.append(temp.get(jj)); if(jj != temp.size()-1) { sb.append('.'); } } ans.add(sb.toString()); } // out.println("Here: "+temp); } for(String str:ans) { out.println(str); } } out.close(); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } public static int[] sort(int[] arr) { List<Integer> temp = new ArrayList(); for(int i:arr)temp.add(i); Collections.sort(temp); int start = 0; for(int i:temp)arr[start++]=i; return arr; } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Stack; public class Main { static void debug(Object... args) { System.out.println(Arrays.deepToString(args)); } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int T = Integer.parseInt(br.readLine()); while (T-- > 0) { int N = Integer.parseInt(br.readLine()); Stack<LN> nodes = new Stack<>(); int a0 = Integer.parseInt(br.readLine()); LN root = new LN(1, 0, ""); nodes.add(root); pw.println(root); for (int i = 0; i < N - 1; i++) { int ai = Integer.parseInt(br.readLine()); while (!nodes.isEmpty()) { LN nn = nodes.pop(); if (ai == 1) { LN e = new LN(1, nn.depth + 1, nn.toString()); nodes.add(nn); nodes.add(e); pw.println(e); break; } else if (nn.lv == ai - 1) { LN e = new LN(ai, nn.depth, nn.base); nodes.add(e); pw.println(e); break; } } } } pw.flush(); } static class LN { int lv; int depth; String base; public LN(int lv, int depth, String prev) { this.lv = lv; this.depth = depth; base = prev; } @Override public String toString() { StringBuilder bob = new StringBuilder(base); if (depth > 0) { bob.append("."); } bob.append(lv); return bob.toString(); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static MyScanner scan; static PrintWriter pw; static long MOD = 1_000_000_007; static long INF = 2_000_000_000_000_000_000L; static long inf = 2_000_000_000; public static void main(String[] args) { new Thread(null, null, "_", 1 << 27) { public void run() { try { solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws java.lang.Exception { //initIo(true, ""); initIo(false, ""); StringBuilder sb = new StringBuilder(); int t = ni(); while (t-->0) { int n = ni(); ArrayList<ArrayList<Integer>> ans = new ArrayList<>(); ArrayList<Integer> prev = new ArrayList<>(); prev.add(1); ni(); for(int i=1;i<n;i++) { int x = ni(); ans.add(prev); ArrayList<Integer> next = new ArrayList<>(); int idx = -1; for(int j=prev.size()-1;j>=0;--j) { if(prev.get(j)==x-1) { for(int k=0;k<j;++k) { next.add(prev.get(k)); } next.add(x); idx = j; break; } } if(idx==-1) { assert_in_range("x", x, 1, 1); for(int e : prev) { next.add(e); } next.add(1); } prev = next; } ans.add(prev); for(ArrayList<Integer> list: ans) { print(list); } } pw.flush(); pw.close(); } static void print(ArrayList<Integer> list) { for(int i=0;i<list.size();i++) { pw.print(list.get(i)); if(i==list.size()-1) { continue; } pw.print("."); } pl(); } static void assert_in_range(String varName, int n, int l, int r) { if (n >=l && n<=r) return; System.out.println(varName + " is not in range. Actual: "+n+" l : "+l+" r: "+r); System.exit(1); } static void assert_in_range(String varName, long n, long l, long r) { if (n>=l && n<=r) return; System.out.println(varName + " is not in range. Actual: "+n+" l : "+l+" r: "+r); System.exit(1); } static void initIo(boolean isFileIO, String suffix) throws IOException { scan = new MyScanner(isFileIO, suffix); if(isFileIO) { pw = new PrintWriter("/Users/dsds/Desktop/output"+suffix+".txt"); } else { pw = new PrintWriter(System.out, true); } } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static String ne() throws IOException { return scan.next(); } static String nel() throws IOException { return scan.nextLine(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String arrayName, TreeSet<Integer> set) { pl(arrayName+" : "); for(Object o : set) p(o); pl(); } static void pa(String arrayName, boolean arr[]) { pl(arrayName+" : "); for(boolean o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } static void pa(String arrayName, boolean[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(boolean o : arr[i]) p(o); pl(); } } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner(boolean readingFromFile, String suffix) throws IOException { if(readingFromFile) { br = new BufferedReader(new FileReader("/Users/ddfds/Desktop/input"+suffix+".txt")); } else { br = new BufferedReader(new InputStreamReader(System.in)); } } String nextLine()throws IOException { return br.readLine(); } String next() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class C { public static void main(String[] args) { FastScanner sc = new FastScanner(); int T = sc.nextInt(); StringBuilder sb = new StringBuilder(); while(T-->0) { int n = sc.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } int[] p = new int[n]; int[] base = new int[n]; p[0] = -1; base[0] = -1; boolean[] used = new boolean[n]; for(int i = 1; i < n; i++) { if(arr[i] == 1) { p[i] = i-1; base[i] = i-1; } else { for(int j = i-1; j >= 0; j--) { if(used[j]) continue; if(arr[j] == arr[i]-1) { p[i] = j; used[j] = true; base[i] = base[j]; break; } else used[j] = true; } } } StringBuilder[] res = new StringBuilder[n]; res[0] = new StringBuilder("1"); sb.append("1\n"); for(int i = 1; i < n; i++) { if(base[i] == -1) { res[i] = new StringBuilder(); } else { res[i] = new StringBuilder(res[base[i]]); res[i].append("."); } res[i].append(arr[i]+""); sb.append(res[i]); sb.append("\n"); } } PrintWriter pw = new PrintWriter(System.out); pw.println(sb.toString().trim()); pw.flush(); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import javax.print.DocFlavor; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.util.Stack; public class p1523C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t ; i++) { int n = sc.nextInt(); ArrayList<Stack<Integer>> ar = new ArrayList<Stack<Integer>>(); for (int j = 0; j < n + 1; j++) { ar.add(new Stack<Integer>()); } HashMap <Integer , Integer> hm = new HashMap<Integer, Integer>(); StringBuilder cur = new StringBuilder(); int l = 0; for (int j = 0; j < n; j++) { int a = sc.nextInt(); if( a == 1) { if(cur.length() == 0) cur.append("1"); else cur.append(".1"); l++; ar.get(1).add(l); hm.put(l , 1); } else { int newl = ar.get( a - 1).pop(); for (int k = newl + 1; k <= l ; k++) { ar.get(hm.get(k)).pop(); hm.remove(k); cur.delete(cur.lastIndexOf(".") + 1, cur.length()); cur.delete(cur.length() - 1 , cur.length()); } cur.delete(cur.lastIndexOf(".") + 1, cur.length()); cur.append(a); ar.get(a).add(newl); hm.put(newl , a); l = newl; } System.out.println(cur); } } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; /** * * @author is2ac */ public class C_CF { public static void main(String[] args) { FastScanner57 fs = new FastScanner57(); PrintWriter pw = new PrintWriter(System.out); int t = fs.ni(); //int t = 1; for (int tc = 0; tc < t; tc++) { int n = fs.ni(); int[] q = new int[n+5]; int ind = 0; q[0] = 1; for (int i = 0; i < n; i++) { int a = fs.ni(); while (q[ind]!=a) ind--; StringBuilder sb = new StringBuilder(); for (int j = 0; j < ind; j++) { sb.append(q[j]-1); sb.append("."); } sb.append(a); q[ind]++; q[ind+1] = 1; ind++; pw.println(sb); } } pw.close(); } static class BIT18 { int[] bit; public BIT18(int size) { bit = new int[size]; } public void update(int ind, int delta) { while (ind < bit.length) { bit[ind] += delta; ind = ind + (ind & (-1 * ind)); } } public int sum(int ind) { int s = 0; while (ind > 0) { s += bit[ind]; ind = ind - (ind & (-1 * ind)); } return s; } public int query(int l, int r) { return sum(r) - sum(l); } } // 0 -> left was chosen // 1 -> right was chosen public static long recur(int ind, int p, int prev, long[] v, Long[][] dp, long[][] lr, List<List<Integer>> list) { long last = v[0]; long ls = 0L; long rs = 0L; if (p == 1) { last = v[1]; } if (ind != 0) { ls += (long) Math.abs(last - lr[ind][0]); } if (ind != 0) { rs += (long) Math.abs(last - lr[ind][1]); } if (dp[ind][p] != null) { return dp[ind][p]; } long[] cur = lr[ind]; List<Integer> temp = list.get(ind); for (int val : temp) { if (prev == val) { continue; } ls += recur(val, 0, ind, cur, dp, lr, list); rs += recur(val, 1, ind, cur, dp, lr, list); } return dp[ind][p] = Math.max(ls, rs); } public static void sort(long[] a) { List<Long> list = new ArrayList(); for (int i = 0; i < a.length; i++) { list.add(a[i]); } Collections.sort(list); for (int i = 0; i < a.length; i++) { a[i] = list.get(i); } } public static long gcd(long n1, long n2) { if (n2 == 0) { return n1; } return gcd(n2, n1 % n2); } } class UnionFind16 { int[] id; public UnionFind16(int size) { id = new int[size]; for (int i = 0; i < size; i++) { id[i] = i; } } public int find(int p) { int root = p; while (root != id[root]) { root = id[root]; } while (p != root) { int next = id[p]; id[p] = root; p = next; } return root; } public void union(int p, int q) { int a = find(p), b = find(q); if (a == b) { return; } id[b] = a; } } class FastScanner57 { BufferedReader br; StringTokenizer st; public FastScanner57() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[] intArray(int N) { int[] ret = new int[N]; for (int i = 0; i < N; i++) { ret[i] = ni(); } return ret; } long nl() { return Long.parseLong(next()); } long[] longArray(int N) { long[] ret = new long[N]; for (int i = 0; i < N; i++) { ret[i] = nl(); } return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class Main { private static HashMap<String, Integer> nodes; private static void dfs(String cur, PrintWriter out) { if(cur.length() > 0) { out.println(cur.substring(1)); } int children = nodes.get(cur); for(int i = 1; i <= children; i++) { dfs(cur+"."+i, out); } } public static void main(String[] args) throws IOException { //Scanner f = new Scanner(new File("uva.in")); //Scanner f = new Scanner(System.in); //BufferedReader f = new BufferedReader(new FileReader("uva.in")); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int t = Integer.parseInt(f.readLine()); while(t-- > 0) { int n = Integer.parseInt(f.readLine()); nodes = new HashMap<>(); nodes.put("", 0); String cur = ""; for(int i = 0; i < n; i++) { int a = Integer.parseInt(f.readLine()); while(nodes.get(cur) != a-1) { cur = cur.substring(0, cur.lastIndexOf(".")); } nodes.put(cur, a); cur = cur+"."+a; nodes.put(cur, 0); } dfs("", out); } f.close(); out.close(); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
/** * @author: Prasad Chaudhari * @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/ * @git: https://github.com/Prasad-Chaudhari */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; public class Main { public static void main(String[] args) throws Exception { FastIO in = new FastIO(args); int t = in.ni(); while (t-- > 0) { int n = in.ni(); LinkedList<Integer> l = new LinkedList<>(); ArrayList<LinkedList<Integer>> al = new ArrayList<>(); for (int i = 0; i < n; i++) { int p = in.ni(); if (p == 1) { l.addFirst(1); } else { while (true) { if (l.peekFirst() == p - 1) { l.addFirst(l.removeFirst() + 1); break; } else { l.removeFirst(); } } } al.add(new LinkedList<>(l)); } for (LinkedList<Integer> ll : al) { while (ll.size() > 1) { System.out.print(ll.removeLast() + "."); } System.out.println(ll.remove()); } System.out.println(); } in.bw.flush(); } static boolean willbealive(int i, int a[]) { if (i < 0 || i >= a.length) return false; if (a.length == 1) return false; if (a[i] == 1) return false; if (i == 0) return a[1] == 1; else if (i == a.length - 1) return a[i - 1] == 1; else return (a[i - 1] == 1) ^ (a[i + 1] == 1); } static class Data implements Comparable<Data> { int a, b; public Data(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Data o) { if (a == o.a) { return Integer.compare(b, o.b); } return Integer.compare(a, o.a); } public static void sort(int a[]) { Data d[] = new Data[a.length]; for (int i = 0; i < a.length; i++) { d[i] = new Data(a[i], 0); } Arrays.sort(d); for (int i = 0; i < a.length; i++) { a[i] = d[i].a; } } } static class FastIO { private final BufferedReader br; private final BufferedWriter bw; private String s[]; private int index; public FastIO(String[] args) throws IOException { if (args.length > 1) { br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(args[0])))); bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(args[1])))); } else { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8")); } s = br.readLine().split(" "); index = 0; } public int ni() throws IOException { return Integer.parseInt(nextToken()); } public double nd() throws IOException { return Double.parseDouble(nextToken()); } public long nl() throws IOException { return Long.parseLong(nextToken()); } public String next() throws IOException { return nextToken(); } public String nli() throws IOException { try { return br.readLine(); } catch (IOException ex) { } return null; } public int[] gia(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public int[] gia(int n, int start, int end) throws IOException { validate(n, start, end); int a[] = new int[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } public double[] gda(int n) throws IOException { double a[] = new double[n]; for (int i = 0; i < n; i++) { a[i] = nd(); } return a; } public double[] gda(int n, int start, int end) throws IOException { validate(n, start, end); double a[] = new double[n]; for (int i = start; i < end; i++) { a[i] = nd(); } return a; } public long[] gla(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nl(); } return a; } public long[] gla(int n, int start, int end) throws IOException { validate(n, start, end); long a[] = new long[n]; for (int i = start; i < end; i++) { a[i] = nl(); } return a; } public void print(String s) throws IOException { bw.write(s); } public void println(String s) throws IOException { bw.write(s); bw.newLine(); } public void print(int s) throws IOException { bw.write(s + ""); } public void println(int s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(long s) throws IOException { bw.write(s + ""); } public void println(long s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(double s) throws IOException { bw.write(s + ""); } public void println(double s) throws IOException { bw.write(s + ""); bw.newLine(); } private String nextToken() throws IndexOutOfBoundsException, IOException { if (index == s.length) { s = br.readLine().split(" "); index = 0; } return s[index++]; } private void validate(int n, int start, int end) { if (start < 0 || end >= n) { throw new IllegalArgumentException(); } } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.lang.*; import java.util.*; import java.io.*; public class Main { static void deal(int n,int[] arr) { int[] a = new int[n]; a[0] = 1; int l = 1; out.println(toString(a,l)); for(int i=1;i<n;i++) { if(arr[i] == 1) { a[l] = 1; l++; } else { int index = l-1; while(index>=0 && a[index] != arr[i]-1) { index--; } a[index]++; l = index+1; } out.println(toString(a,l)); } } static String toString(int[] arr,int l) { StringBuilder sb = new StringBuilder(); for(int i=0;i<l-1;i++) { sb.append(arr[i]); sb.append('.'); } sb.append(arr[l-1]); return sb.toString(); } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); for(int i=0;i<t;i++) { int n = sc.nextInt(); int[] arr = new int[n]; for(int j=0;j<n;j++) arr[j] = sc.nextInt(); deal(n,arr); } out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class C { static FastIO f; public static void main(String args[]) throws IOException { f = new FastIO(); int t, n, a, i; Node r, p, c; t = f.ni(); while(t-->0) { n = f.ni(); r = p = new Node(-1, null); // f.out("1\n"); for(i = 0; i < n; i++) { a = f.ni(); if(a != 1) { while(a != p.i + 1) p = p.p; p = p.p; } // if(a == p.i + 1) // p = p.p; // else if(p.p != null && a == p.p.i + 1) // p = p.p.p; c = new Node(a, p); p.c.add(c); p = c; } dfs(r, ""); } f.flush(); } public static void dfs(Node n, String s) throws IOException { String t; if(n.i == -1) t = s; else { t = s + n.i + "."; f.out(s + n.i + "\n"); } for(Node c : n.c) dfs(c, t); } static class Node { int i; Node p; ArrayList<Node> c; Node(int x, Node y) { i = x; p = y; c = new ArrayList<>(); } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { Node that = (Node)obj; return super.equals(obj); } @Override public String toString() { return "[" + "PARAMETERS" + "]"; } } public static class FastIO { BufferedReader br; BufferedWriter bw, be; StringTokenizer st; public FastIO() { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out)); be = new BufferedWriter(new OutputStreamWriter(System.err)); st = new StringTokenizer(""); } private void read() throws IOException { st = new StringTokenizer(br.readLine()); } public String ns() throws IOException { while(!st.hasMoreTokens()) read(); return st.nextToken(); } public int ni() throws IOException { return Integer.parseInt(ns()); } public long nl() throws IOException { return Long.parseLong(ns()); } public float nf() throws IOException { return Float.parseFloat(ns()); } public double nd() throws IOException { return Double.parseDouble(ns()); } public char nc() throws IOException { return ns().charAt(0); } public int[] nia(int n) throws IOException { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } public long[] nla(int n) throws IOException { long[] a = new long[n]; for(int i = 0; i < n; i++) a[i] = nl(); return a; } public char[] nca() throws IOException { return ns().toCharArray(); } public void out(String s) throws IOException { bw.write(s); } public void flush() throws IOException { bw.flush(); be.flush(); } public void err(String s) throws IOException { be.write(s); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { FastIO io = new FastIO(); int test=io.nextInt(); while(test>0) { int n=io.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++)arr[i]=io.nextInt(); List<int[]> list=new ArrayList<>(); Stack<int[]> stk=new Stack<>(); int temp[]={1}; list.add(temp); stk.push(temp); for(int i=1;i<n;i++) { if(arr[i]==1) { int t[]=stk.peek(); int nt[]=new int[t.length+1]; for(int j=0;j<t.length;j++)nt[j]=t[j]; nt[nt.length-1]=arr[i]; stk.push(nt); list.add(nt); continue; } while(stk.size()>0) { int t[]=stk.peek(); if(t[t.length-1]+1==arr[i]){ int nt[]=new int[t.length]; for(int j=0;j<t.length-1;j++)nt[j]=t[j]; nt[t.length-1]=arr[i]; stk.pop(); stk.push(nt); list.add(nt); break; } else { stk.pop(); } } } for(int i=0;i<list.size();i++) { StringBuilder sb=new StringBuilder(); sb.append(list.get(i)[0]); for(int j=1;j<list.get(i).length;j++) { sb.append("."+list.get(i)[j]); } io.println(sb.toString()); } test--; } io.close(); } } class FastIO extends PrintWriter { private InputStream stream; private byte[] buf = new byte[1<<16]; private int curChar, numChars; // standard input public FastIO() { this(System.in,System.out); } public FastIO(InputStream i, OutputStream o) { super(o); stream = i; } // file input public FastIO(String i, String o) throws IOException { super(new FileWriter(o)); stream = new FileInputStream(i); } // throws InputMismatchException() if previously detected end of file private int nextByte() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars == -1) return -1; // end of file } return buf[curChar++]; } public String nextLine() { int c; do { c = nextByte(); } while (c <= '\n'); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n'); return res.toString(); } public String next() { int c; do { c = nextByte(); } while (c <= ' '); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > ' '); return res.toString(); } public int nextInt() { int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10*res+c-'0'; c = nextByte(); } while (c > ' '); return res * sgn; } public long nextLong() { int c; do { c = nextByte(); } while (c <= ' '); long sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10*res+c-'0'; c = nextByte(); } while (c > ' '); return res * sgn; } public double nextDouble() { return Double.parseDouble(next()); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class C{ private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main (String[] args) throws IOException { int t = Integer.parseInt(br.readLine()); while(t-- > 0) { int n = Integer.parseInt(br.readLine()); int prev = 1; ArrayList<Integer> nums = new ArrayList<>(); nums.add(1); String till = "1"; for(int i=0;i<n;i++) { int ln = Integer.parseInt(br.readLine()); if(i == 0) { bw.write("1\n"); continue; } if(ln == 1) { nums.add(1); }else if(ln == prev + 1) { nums.set(nums.size()-1, ln); }else { int idx = -1; for(int j=nums.size()-1;j>=0;j--) { if(nums.get(j) == ln-1) { idx = j; break; } } ArrayList<Integer> temp = new ArrayList<>(); for(int j=0;j<idx;j++) { temp.add(nums.get(j)); } temp.add(ln); nums.clear(); nums = temp; } for(int j=0;j<nums.size()-1;j++) { bw.write(nums.get(j) + "."); } bw.write(nums.get(nums.size()-1) + "\n"); prev = ln; } } bw.flush(); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.util.Map.Entry; import java.io.*; import java.math.*; import static java.util.stream.Collectors.*; import static java.util.Map.Entry.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws Exception { final long mod=(long) (1e9+7); final long mod1=(long) 998244353; Reader s=new Reader(); PrintWriter pt=new PrintWriter(System.out); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int T=s.nextInt(); // int T=Integer.parseInt(br.readLine()); // int T=1; while(T-->0) { int n=s.nextInt(); int arr[]=new int[n]; int brr[]=new int[n]; int e=-1; for(int i=0;i<n;i++) { arr[i]=s.nextInt(); if(e==-1) { brr[e+1]=arr[i]; e++; } else { if(arr[i]==1) { e++; brr[e]=arr[i]; } else { int j=e; for(j=e;j>=0;j--) { if((arr[i]-1)==brr[j]) break; } e=j; brr[e]=arr[i]; } } pt.print(brr[0]); for(int j=1;j<=e;j++) { pt.print("."+brr[j]); } pt.println(); } } pt.close(); } static boolean allOne(String str) { for(int i=0;i<str.length();i++) { if(str.charAt(i)=='0') return false; } return true; } static boolean isPartition(int arr[], int n) { int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; boolean part[][]=new boolean[sum/2+1][n+1]; // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = true; // initialize leftmost column, except part[0][0], as false for (i = 1; i <= sum / 2; i++) part[i][0] = false; // Fill the partition table in bottom up manner for (i = 1; i <= sum / 2; i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } return part[sum / 2][n]; } static int setBit(int S, int j) { return S | 1 << j; } static int clearBit(int S, int j) { return S & ~(1 << j); } static int toggleBit(int S, int j) { return S ^ 1 << j; } static boolean isOn(int S, int j) { return (S & 1 << j) != 0; } static int turnOnLastZero(int S) { return S | S + 1; } static int turnOnLastConsecutiveZeroes(int S) { return S | S - 1; } static int turnOffLastBit(int S) { return S & S - 1; } static int turnOffLastConsecutiveBits(int S) { return S & S + 1; } static int lowBit(int S) { return S & -S; } static int setAll(int N) { return (1 << N) - 1; } static int modulo(int S, int N) { return (S & N - 1); } //S%N, N is a power of 2 static boolean isPowerOfTwo(int S) { return (S & S - 1) == 0; } static boolean isWithin(long x, long y, long d, long k) { return x*k*x*k + y*k*y*k <= d*d; } static long modFact(long n, long p) { if (n >= p) return 0; long result = 1; for (int i = 1; i <= n; i++) result = (result * i) % p; return result; } static int sum(int[] arr, int n) { int inc[]=new int[n+1]; int dec[]=new int[n+1]; inc[0] = arr[0]; dec[0] = arr[0]; for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[j] > arr[i]) { dec[i] = max(dec[i], inc[j] + arr[i]); } else if (arr[i] > arr[j]) { inc[i] = max(inc[i], dec[j] + arr[i]); } } } return max(inc[n - 1], dec[n - 1]); } static long nc2(long a) { return a*(a-1)/2; } public static int numberOfprimeFactors(int n) { // Print the number of 2s that divide n HashSet<Integer> hs = new HashSet<Integer>(); while (n%2==0) { hs.add(2); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { hs.add(i); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) hs.add(n); return hs.size(); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void reverse(int arr[],int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } static void reverse(long arr[],int start, int end) { long temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int p2(int n) { int k=0; while(n>1) { if(n%2!=0) return k; n/=2; k++; } return k; } static boolean isp2(int n) { while(n>1) { if(n%2==1) return false; n/=2; } return true; } static int binarySearch(int arr[], int first, int last, int key){ int mid = (first + last)/2; while( first <= last ){ if ( arr[mid] < key ){ first = mid + 1; }else if ( arr[mid] == key ){ return mid; }else{ last = mid - 1; } mid = (first + last)/2; } return -1; } static void print(int a[][]) { for(int i=0;i<a.length;i++) { for(int j=0;j<a[0].length;j++) System.out.print(a[i][j]+" "); System.out.println(); } } static int max (int x, int y) { return (x > y)? x : y; } static int search(Pair[] p, Pair pair) { int l=0, r=p.length; while (l <= r) { int m = l + (r - l) / 2; if (p[m].compareTo(pair)==0) return m; if (p[m].compareTo(pair)<0) l = m + 1; else r = m - 1; } return -1; } static void pa(int a[]) { for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } static void pa(long a[]) { for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } static void reverseArray(int arr[], int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } static boolean isPalindrome(String s) { int l=s.length(); for(int i=0;i<l/2;i++) { if(s.charAt(i)!=s.charAt(l-i-1)) return false; } return true; } static long nc2(long n, long m) { return (n*(n-1)/2)%m; } static long c(long a) { return a*(a+1)/2; } static int next(long[] arr, long target) { int start = 0, end = arr.length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to right side if target is // greater. if (arr[mid] < target) { start = mid + 1; } // Move left side. else { ans = mid; end = mid - 1; } } return ans; } static int prev(long[] arr, long target) { int start = 0, end = arr.length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; // Move to left side if target is // lesser. if (arr[mid] > target) { end = mid - 1; } // Move right side. else { ans = mid; start = mid + 1; } } return ans; } static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return power(n, p-2, p); } static long nCrModP(long n, long r, long p) { if(r>n) return 0; if (r == 0) return 1; long[] fac = new long[(int) (n+1)]; fac[0] = 1; for (int i = 1 ;i <= n; i++) fac[i] = fac[i-1] * i % p; return (fac[(int) n]* modInverse(fac[(int) r], p) % p * modInverse(fac[(int) (n-r)], p) % p) % p; } static String reverse(String str) { return new StringBuffer(str).reverse().toString(); } static long fastpow(long x, long y, long m) { if (y == 0) return 1; long p = fastpow(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } static boolean isPerfectSquare(long l) { return Math.pow((long)Math.sqrt(l),2)==l; } static void merge(long[] arr, int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long [n1]; long R[] = new long [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int [n1]; int R[] = new int [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } static class Pair implements Comparable<Pair>{ int a; int b; Pair(int a,int b){ this.a=a; this.b=b; } public int compareTo(Pair p){ if(a>p.a) return 1; if(a==p.a) return (b-p.b); return -1; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[128]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; import java.io.*; public class Deltix { static PrintWriter out; public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); Stack<Integer> s = new Stack<>(); int [] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = sc.nextInt(); for (int i = 0; i < n; i++) { if (a[i] == 1) { s.push(1); } else { while (s.peek() != a[i] - 1) { s.pop(); } s.pop(); s.push(a[i]); } print(s); } } out.close(); } static void print(Stack<Integer> s) { ArrayDeque<Integer> a = new ArrayDeque<>(); while (!s.isEmpty()) { a.addFirst(s.pop()); } while (!a.isEmpty()) { int x = a.pollFirst(); out.print(x); s.push(x); if (a.size() != 0) out.print("."); } out.println(); } static void sort(int[] a) { ArrayList<Integer> q = new ArrayList<>(); for (int i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } static void sort(long[] a) { ArrayList<Long> q = new ArrayList<>(); for (long i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main{ static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextArray(long n) { long[] a = new long[(int) n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } static class FastWriter extends PrintWriter { FastWriter(){ super(System.out); } void println(int[] array) { for(int i=0; i<array.length; i++) { print(array[i]+" "); } println(); } void println(long [] array) { for(int i=0; i<array.length; i++) { print(array[i]+" "); } println(); } } static class Interval { long start,end; Interval(long start, long end) { this.start=start; this.end=end; } } static int MOD=998244353; public static void main(String[] args){ FastScanner in = new FastScanner(); FastWriter out = new FastWriter(); Scanner sc=new Scanner(System.in); int t=in.nextInt(); //int t=1; while (t-->0){ int n=in.nextInt(); int[] ar=in.nextArray(n); int[] level=new int[1005]; int j=1; level[1]=1; out.println(1); for (int i = 1; i < n; i++) { if(ar[i]==1) { j++; level[j] = 1; }else { while (j>=1){ if(level[j]+1!=ar[i]){ j--; }else { break; } } level[j]++; } for (int k = 1; k <= j; k++) { if(k==j){ out.print(level[k]); }else { out.print(level[k]+"."); } } out.println(); } } out.close(); } static int highestPowerOf2(int n) { if (n < 1){ return 0; } int res = 1; for (int i = 0; i < 8 * Integer.BYTES; i++) { int curr = 1 << i; if (curr > n){ break; } res = curr; } return res; } static int reduceFraction(int x, int y) { int d= gcd(x, y); return x/d+y/d; } static boolean subset(int[] ar,int n,int sum){ if(sum==0){ return true; } if(n<0||sum<0){ return false; } return subset(ar,n-1,sum)||subset(ar,n-1,sum-ar[n]); } static boolean isPrime(int n){ if(n<=1) return false; for(int i = 2;i<=Math.sqrt(n);i++){ if (n % i == 0) return false; } return true; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long lcm(long a, long b) { return (a * b) / gcd(a, b); } static int lcm(int a, int b) { return (a * b) / gcd(a, b); } static boolean isPowerOfTwo(int n) { if(n==0||n==1){return false;} double v = Math.log(n) / Math.log(2); return ((int)(Math.ceil(v)) == (int)(Math.floor(v))); } static boolean isPerfectSquare(int x){ if (x >= 0) { int sr = (int)Math.sqrt(x); return ((sr * sr) == x); } return false; } static int lower_bound(int[] arr, int x) { int low_limit = 0, high_limit = arr.length, mid = -1; while (low_limit < high_limit) { mid = (low_limit + high_limit) / 2; if (arr[mid] >= x){ high_limit = mid; }else{ low_limit = mid + 1; } } return low_limit; } static int upper_bound(int[] arr, int x) { int low_limit = 0, high_limit = arr.length, mid = -1; while (low_limit < high_limit) { mid = (low_limit + high_limit) / 2; if (arr[mid] > x){ high_limit = mid; }else{ low_limit = mid + 1; } } return low_limit; } static int binarySearch(int[] ar,int n,int num){ int low=0,high=n-1; while (low<=high){ int mid=(low+high)/2; if(ar[mid]==num){ return mid; }else if(ar[mid]>num){ high=mid-1; }else { low=mid+1; } } return -1; } }
cubic
1523_C. Compression and Expansion
CODEFORCES