src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
import java.io.*; import java.util.*; public class CF1185G2 { static final int MD = 1000000007; static int[][] solve1(int[] aa, int t, int n) { int[][] da = new int[t + 1][n + 1]; da[0][0] = 1; for (int i = 0; i < n; i++) { int a = aa[i]; for (int s = t - 1; s >= 0; s--) for (int m = 0; m < n; m++) { int x = da[s][m]; if (x != 0) { int s_ = s + a; if (s_ <= t) da[s_][m + 1] = (da[s_][m + 1] + x) % MD; } } } return da; } static int[][][] solve2(int[] aa, int[] bb, int t, int na, int nb) { int[][] da = solve1(aa, t, na); int[][][] dab = new int[t + 1][na + 1][nb + 1]; for (int s = 0; s <= t; s++) for (int ma = 0; ma <= na; ma++) dab[s][ma][0] = da[s][ma]; for (int i = 0; i < nb; i++) { int b = bb[i]; for (int s = t - 1; s >= 0; s--) for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb < nb; mb++) { int x = dab[s][ma][mb]; if (x != 0) { int s_ = s + b; if (s_ <= t) dab[s_][ma][mb + 1] = (dab[s_][ma][mb + 1] + x) % MD; } } } return dab; } static long power(int a, int k) { if (k == 0) return 1; long p = power(a, k / 2); p = p * p % MD; if (k % 2 == 1) p = p * a % MD; return p; } static int[] ff, gg; static int ch(int n, int k) { return (int) ((long) ff[n] * gg[n - k] % MD * gg[k] % MD); } static int[][][] init(int n, int na, int nb, int nc) { ff = new int[n + 1]; gg = new int[n + 1]; for (int i = 0, f = 1; i <= n; i++) { ff[i] = f; gg[i] = (int) power(f, MD - 2); f = (int) ((long) f * (i + 1) % MD); } int[][][] dp = new int[na + 1][nb + 1][nc + 1]; for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb <= nb; mb++) for (int mc = 0; mc <= nc; mc++) { int x = (int) ((long) ff[ma + mb + mc] * gg[ma] % MD * gg[mb] % MD * gg[mc] % MD); for (int ma_ = ma == 0 ? 0 : 1; ma_ <= ma; ma_++) { int cha = ma == 0 ? 1 : ch(ma - 1, ma_ - 1); for (int mb_ = mb == 0 ? 0 : 1; mb_ <= mb; mb_++) { int chb = mb == 0 ? 1 : ch(mb - 1, mb_ - 1); for (int mc_ = mc == 0 ? 0 : 1; mc_ <= mc; mc_++) { int chc = mc == 0 ? 1 : ch(mc - 1, mc_ - 1); int y = dp[ma_][mb_][mc_]; if (y == 0) continue; x = (int) ((x - (long) y * cha % MD * chb % MD * chc) % MD); } } } if (x < 0) x += MD; dp[ma][mb][mc] = x; } for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb <= nb; mb++) for (int mc = 0; mc <= nc; mc++) dp[ma][mb][mc] = (int) ((long) dp[ma][mb][mc] * ff[ma] % MD * ff[mb] % MD * ff[mc] % MD); return dp; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st.nextToken()); int[] aa = new int[n]; int[] bb = new int[n]; int[] cc = new int[n]; int na = 0, nb = 0, nc = 0; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int g = Integer.parseInt(st.nextToken()); if (g == 1) aa[na++] = a; else if (g == 2) bb[nb++] = a; else cc[nc++] = a; } int[][][] dp = init(n, na, nb, nc); int[][][] dab = solve2(aa, bb, t, na, nb); int[][] dc = solve1(cc, t, nc); int ans = 0; for (int tab = 0; tab <= t; tab++) { int tc = t - tab; for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb <= nb; mb++) { int xab = dab[tab][ma][mb]; if (xab == 0) continue; for (int mc = 0; mc <= nc; mc++) { int xc = dc[tc][mc]; if (xc == 0) continue; ans = (int) ((ans + (long) xab * xc % MD * dp[ma][mb][mc]) % MD); } } } System.out.println(ans); } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.*; import java.util.*; public class B { static int n, t[], g[], MOD = (int) 1e9 + 7; static int[][][] memo1, memo2[], memo3[]; static int dp1(int idx, int remCnt, int remSum) { if (idx == n) return remSum == 0 && remCnt==0 ? 1 : 0; if (memo1[idx][remCnt][remSum] != -1) return memo1[idx][remCnt][remSum]; int ans = dp1(idx + 1, remCnt, remSum); if (g[idx] == 0 && t[idx] <= remSum && remCnt>0) { ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]); if (ans >= MOD) ans -= MOD; } return memo1[idx][remCnt][remSum] = ans; } static int dp2(int idx, int remCnt1, int remCnt2, int remSum) { int all = remCnt1 + remCnt2; if (all == 0) return remSum == 0 ? 1 : 0; if (idx == n || remSum == 0) return 0; if (memo2[idx][remCnt1][remCnt2][remSum] != -1) return memo2[idx][remCnt1][remCnt2][remSum]; int ans = dp2(idx + 1, remCnt1, remCnt2, remSum); if (t[idx] <= remSum) { if (g[idx] == 1 && remCnt1 > 0) ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]); else if (g[idx] == 2 && remCnt2 > 0) ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]); } return memo2[idx][remCnt1][remCnt2][remSum] = ans; } private static int dp3(int cnt0, int cnt1, int cnt2, int last) { if (cnt0 + cnt1 + cnt2 == 0) return 1; if (memo3[last][cnt0][cnt1][cnt2] != -1) return memo3[last][cnt0][cnt1][cnt2]; long ans = 0; if (cnt0 > 0 && last != 0) ans += dp3(cnt0 - 1, cnt1, cnt2, 0); if (cnt1 > 0 && last != 1) ans += dp3(cnt0, cnt1 - 1, cnt2, 1); if (cnt2 > 0 && last != 2) ans += dp3(cnt0, cnt1, cnt2 - 1, 2); return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); int[] fac = new int[n + 1]; t = new int[n]; g = new int[n]; int[] cnt = new int[3]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (int) (i * 1L * fac[i - 1] % MOD); int T = sc.nextInt(); for (int i = 0; i < n; i++) { t[i] = sc.nextInt(); g[i] = sc.nextInt() - 1; cnt[g[i]]++; } memo1 = new int[n][cnt[0] + 1][T + 1]; memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1]; memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j <= cnt[0]; j++) Arrays.fill(memo1[i][j], -1); for (int j = 0; j <= cnt[1]; j++) for (int k = 0; k <= cnt[2]; k++) Arrays.fill(memo2[i][j][k], -1); } for (int i = 0; i < 4; i++) for (int j = 0; j <= cnt[0]; j++) for (int k = 0; k <= cnt[1]; k++) Arrays.fill(memo3[i][j][k], -1); int ans = 0; for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++) for (int sum0 = 0; sum0 <= T; sum0++) for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++) for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) { long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD; ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD; ways *= fac[cnt0]; ways %= MOD; ways *= fac[cnt1]; ways %= MOD; ways *= fac[cnt2]; ways %= MOD; ans += ways; if (ans >= MOD) ans -= MOD; } out.println(ans); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class template { public static void main(String[] args) throws Exception { new template().run(); } long MOD = 1_000_000_007; public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = f.nextInt(), m = f.nextInt(); int[] t = new int[n], g = new int[n], c = new int[3]; for(int i = 0; i < n; i++) { t[i] = f.nextInt(); c[g[i] = f.nextInt()-1]++; } long[][] dp1 = new long[c[0]+1][m+1]; long[][][] dp2 = new long[c[1]+1][c[2]+1][m+1]; dp1[0][0] = 1; dp2[0][0][0] = 1; for(int i = 0; i < n; i++) { if(g[i] == 0) { for(int j = dp1.length-2; j >= 0; j--) for(int k = m-t[i]; k >= 0; k--) dp1[j+1][k+t[i]] = (dp1[j+1][k+t[i]] + dp1[j][k]) % MOD; } else if(g[i] == 1) { for(int j = dp2.length-2; j >= 0; j--) for(int k = dp2[j].length-1; k >= 0; k--) for(int l = m-t[i]; l >= 0; l--) dp2[j+1][k][l+t[i]] = (dp2[j+1][k][l+t[i]] + dp2[j][k][l]) % MOD; } else { for(int j = dp2.length-1; j >= 0; j--) for(int k = dp2[j].length-2; k >= 0; k--) for(int l = m-t[i]; l >= 0; l--) dp2[j][k+1][l+t[i]] = (dp2[j][k+1][l+t[i]] + dp2[j][k][l]) % MOD; } } long[][][][] combo = new long[c[0]+1][c[1]+1][c[2]+1][3]; if(c[0] != 0) combo[1][0][0][0] = 1; if(c[1] != 0) combo[0][1][0][1] = 1; if(c[2] != 0) combo[0][0][1][2] = 1; for(int i = 0; i <= c[0]; i++) { for(int j = 0; j <= c[1]; j++) { for(int k = 0; k <= c[2]; k++) { for(int a = 0; a < 3; a++) { if(a != 0 && i < c[0]) combo[i+1][j][k][0] = (combo[i+1][j][k][0] + combo[i][j][k][a] * (i+1) % MOD) % MOD; if(a != 1 && j < c[1]) combo[i][j+1][k][1] = (combo[i][j+1][k][1] + combo[i][j][k][a] * (j+1) % MOD) % MOD; if(a != 2 && k < c[2]) combo[i][j][k+1][2] = (combo[i][j][k+1][2] + combo[i][j][k][a] * (k+1) % MOD) % MOD; } } } } long ans = 0; for(int s = 0; s <= m; s++) { for(int x = 0; x <= c[0]; x++) for(int y = 0; y <= c[1]; y++) for(int z = 0;z <= c[2]; z++) { ans = (ans + dp1[x][s] * dp2[y][z][m-s] % MOD * ((combo[x][y][z][0] + combo[x][y][z][1] + combo[x][y][z][2]) % MOD) % MOD) % MOD; } } /* for(int i = 0; i < dp1.length; i++) out.println(Arrays.toString(dp1[i])); out.println("-----"); for(int i = 0; i < dp2.length; i++) { for(int j = 0; j < dp2[i].length; j++) out.println(Arrays.toString(dp2[i][j])); out.println(); } for(int i = 0; i <= c[0]; i++) for(int j = 0; j <= c[1]; j++) for(int k = 0; k <= c[2]; k++) out.printf("%d %d %d: %d%n", i, j, k, combo[i][j][k][0] + combo[i][j][k][1] + combo[i][j][k][2]); */ out.println(ans); /// out.flush(); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.*; import java.util.*; public class B { static int n,t[],g[],MOD=(int)1e9+7; static int [][][]memo1,memo2[],memo3[]; static int dp1(int idx,int remCnt,int remSum) { if(remCnt==0) return remSum==0?1:0; if(remSum==0 || idx==n) return 0; if(memo1[idx][remCnt][remSum]!=-1) return memo1[idx][remCnt][remSum]; int ans=dp1(idx+1,remCnt,remSum); if(g[idx]==0 && t[idx]<=remSum) { ans+=dp1(idx+1,remCnt-1,remSum-t[idx]); if(ans>=MOD) ans-=MOD; } return memo1[idx][remCnt][remSum]=ans; } static int dp2(int idx,int remCnt1,int remCnt2,int remSum) { int all=remCnt1+remCnt2; if(all==0) return remSum==0?1:0; if(idx==n || remSum==0) return 0; if(memo2[idx][remCnt1][remCnt2][remSum]!=-1) return memo2[idx][remCnt1][remCnt2][remSum]; int ans=dp2(idx+1,remCnt1,remCnt2,remSum); if(t[idx]<=remSum) { if(g[idx]==1 && remCnt1>0) ans+=dp2(idx+1,remCnt1-1,remCnt2,remSum-t[idx]); else if(g[idx]==2 && remCnt2>0) ans+=dp2(idx+1,remCnt1,remCnt2-1,remSum-t[idx]); } return memo2[idx][remCnt1][remCnt2][remSum]=ans; } private static int dp3(int cnt0, int cnt1, int cnt2,int last) { if(cnt0+cnt1+cnt2==0) return 1; if(memo3[last][cnt0][cnt1][cnt2]!=-1) return memo3[last][cnt0][cnt1][cnt2]; long ans=0; if(cnt0>0 && last!=0) ans+=dp3(cnt0-1,cnt1,cnt2,0); if(cnt1>0 && last!=1) ans+=dp3(cnt0,cnt1-1,cnt2,1); if(cnt2>0 && last!=2) ans+=dp3(cnt0,cnt1,cnt2-1,2); return memo3[last][cnt0][cnt1][cnt2]=(int) (ans%MOD); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n=sc.nextInt(); int []fac=new int [n+1]; t=new int [n]; g=new int [n]; int []cnt=new int [3]; fac[0]=1; for(int i=1;i<=n;i++) fac[i]=(int) (i*1L*fac[i-1]%MOD); int T=sc.nextInt(); for(int i=0;i<n;i++) { t[i]=sc.nextInt(); g[i]=sc.nextInt()-1; cnt[g[i]]++; } memo1=new int [n][cnt[0]+1][T+1]; memo2=new int [n][cnt[1]+1][cnt[2]+1][T+1]; memo3=new int [4][cnt[0]+1][cnt[1]+1][cnt[2]+1]; for(int i=0;i<n;i++) { for(int j=0;j<=cnt[0];j++) Arrays.fill(memo1[i][j], -1); for(int j=0;j<=cnt[1];j++) for(int k=0;k<=cnt[2];k++) Arrays.fill(memo2[i][j][k], -1); } for(int i=0;i<4;i++) for(int j=0;j<=cnt[0];j++) for(int k=0;k<=cnt[1];k++) Arrays.fill(memo3[i][j][k], -1); int ans=0; for(int cnt0=0;cnt0<=cnt[0];cnt0++) for(int sum0=0;sum0<=T;sum0++) for(int cnt1=0;cnt1<=cnt[1];cnt1++) for(int cnt2=0;cnt2<=cnt[2];cnt2++) { long ways= dp1(0,cnt0,sum0)*1L*dp2(0,cnt1,cnt2,T-sum0)%MOD; ways=ways*dp3(cnt0,cnt1,cnt2,3)%MOD; ways*=fac[cnt0]; ways%=MOD; ways*=fac[cnt1]; ways%=MOD; ways*=fac[cnt2]; ways%=MOD; ans+=ways; if(ans>=MOD) ans-=MOD; } out.println(ans); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.*; import java.util.*; public class B { static int n, t[], g[], MOD = (int) 1e9 + 7; static int[][][] memo1, memo2[], memo3[]; static int dp1(int idx, int remCnt, int remSum) { if (idx == n) return remSum == 0 && remCnt == 0 ? 1 : 0; if (remCnt < 0 || remSum < 0) return 0; if (memo1[idx][remCnt][remSum] != -1) return memo1[idx][remCnt][remSum]; int ans = dp1(idx + 1, remCnt, remSum); if (g[idx] == 0) { ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]); if (ans >= MOD) ans -= MOD; } return memo1[idx][remCnt][remSum] = ans; } static int dp2(int idx, int remCnt1, int remCnt2, int remSum) { if (idx == n) return remSum == 0 && remCnt1 == 0 && remCnt2 == 0 ? 1 : 0; if (remSum < 0 || remCnt1 < 0 || remCnt2 < 0) return 0; if (memo2[idx][remCnt1][remCnt2][remSum] != -1) return memo2[idx][remCnt1][remCnt2][remSum]; int ans = dp2(idx + 1, remCnt1, remCnt2, remSum); if (g[idx] == 1) ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]); else if (g[idx] == 2) ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]); return memo2[idx][remCnt1][remCnt2][remSum] = ans; } private static int dp3(int cnt0, int cnt1, int cnt2, int last) { if (cnt0 < 0 || cnt1 < 0 || cnt2 < 0) return 0; if (cnt0 + cnt1 + cnt2 == 0) return 1; if (memo3[last][cnt0][cnt1][cnt2] != -1) return memo3[last][cnt0][cnt1][cnt2]; long ans = 0; if (last != 0) ans += dp3(cnt0 - 1, cnt1, cnt2, 0); if (last != 1) ans += dp3(cnt0, cnt1 - 1, cnt2, 1); if (last != 2) ans += dp3(cnt0, cnt1, cnt2 - 1, 2); return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); int[] fac = new int[n + 1]; t = new int[n]; g = new int[n]; int[] cnt = new int[3]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (int) (i * 1L * fac[i - 1] % MOD); int T = sc.nextInt(); for (int i = 0; i < n; i++) { t[i] = sc.nextInt(); g[i] = sc.nextInt() - 1; cnt[g[i]]++; } memo1 = new int[n][cnt[0] + 1][T + 1]; memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1]; memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j <= cnt[0]; j++) Arrays.fill(memo1[i][j], -1); for (int j = 0; j <= cnt[1]; j++) for (int k = 0; k <= cnt[2]; k++) Arrays.fill(memo2[i][j][k], -1); } for (int i = 0; i < 4; i++) for (int j = 0; j <= cnt[0]; j++) for (int k = 0; k <= cnt[1]; k++) Arrays.fill(memo3[i][j][k], -1); int ans = 0; for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++) for (int sum0 = 0; sum0 <= T; sum0++) for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++) for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) { long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD; ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD; ways *= fac[cnt0]; ways %= MOD; ways *= fac[cnt1]; ways %= MOD; ways *= fac[cnt2]; ways %= MOD; ans += ways; if (ans >= MOD) ans -= MOD; } out.println(ans); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
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.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskG2 solver = new TaskG2(); solver.solve(1, in, out); out.close(); } static class TaskG2 { static final int MOD = 1000000000 + 7; static final int MAXN = 51; int getWays(int i, int j, int k, int l, int[][][][] ways, boolean[][][][] cached) { if (i + j + k == 0) return l == -1 ? 1 : 0; if (l < 0) return 0; if (cached[i][j][k][l]) return ways[i][j][k][l]; int s = i + j + k; long value = 0; if (l == 0 && i != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i - 1, j, k, x, ways, cached); } } if (l == 1 && j != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i, j - 1, k, x, ways, cached); } } if (l == 2 && k != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i, j, k - 1, x, ways, cached); } } ways[i][j][k][l] = (int) (value % MOD); cached[i][j][k][l] = true; return ways[i][j][k][l]; } int totalWays(int i, int j, int k, int[][][][] ways, boolean[][][][] cached, int[] factorial) { long ret = 0; for (int l = 0; l < 3; l++) ret += getWays(i, j, k, l, ways, cached); ret *= factorial[i]; ret %= MOD; ret *= factorial[j]; ret %= MOD; ret *= factorial[k]; ret %= MOD; return (int) ret; } int add(int type, int value, int[] sizes, int sum, int[][][][] dp) { sizes[type]++; if (type == 0) { for (int s = sum + value; s >= value; s--) { for (int i = 1; i <= sizes[0]; i++) for (int j = 0; j <= sizes[1]; j++) for (int k = 0; k <= sizes[2]; k++) { dp[i][j][k][s] += dp[i - 1][j][k][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } if (type == 1) { for (int s = sum + value; s >= value; s--) { for (int i = 0; i <= sizes[0]; i++) for (int j = 1; j <= sizes[1]; j++) for (int k = 0; k <= sizes[2]; k++) { // System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length); dp[i][j][k][s] += dp[i][j - 1][k][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } if (type == 2) { for (int s = sum + value; s >= value; s--) { for (int i = 0; i <= sizes[0]; i++) for (int j = 0; j <= sizes[1]; j++) for (int k = 1; k <= sizes[2]; k++) { // System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length); dp[i][j][k][s] += dp[i][j][k - 1][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } return sum + value; } public void solve(int testNumber, InputReader in, OutputWriter out) { int[][][][] ways = new int[MAXN][MAXN][MAXN][3]; boolean[][][][] cached = new boolean[MAXN][MAXN][MAXN][3]; // Arrays.fill(ways, -1); int n = in.nextInt(), T = in.nextInt(); ArrayList<Integer>[] ar = new ArrayList[3]; for (int i = 0; i < 3; i++) ar[i] = new ArrayList<Integer>(); int total_sum = 0; for (int i = 0; i < n; i++) { int t = in.nextInt(), g = in.nextInt(); ar[g - 1].add(t); total_sum += t; } if (T > total_sum) { out.println(0); return; } int min_index = 0, mn = 0; for (int i = 0; i < 3; i++) { if (ar[i].size() > mn) { mn = ar[i].size(); min_index = i; } } int[][][][] dp = new int[ar[(1 + min_index) % 3].size() + 1][ar[(2 + min_index) % 3].size() + 1][1][total_sum + 1]; int[][][][] dp2 = new int[1][1][mn + 1][total_sum + 1]; dp[0][0][0][0] = dp2[0][0][0][0] = 1; int[] sizes = {0, 0, 0}; int sum = 0; int[] order = {(min_index + 1) % 3, (min_index + 2) % 3}; int type = 0; for (int i : order) { for (int v : ar[i]) sum = add(type, v, sizes, sum, dp); type++; } sum = 0; sizes[0] = sizes[1] = sizes[2] = 0; for (int i : ar[min_index]) sum = add(2, i, sizes, sum, dp2); int[] factorial = new int[MAXN]; factorial[0] = 1; for (int i = 1; i < MAXN; i++) factorial[i] = (int) ((factorial[i - 1] * 1L * i) % MOD); long answer = 0; for (int i = 0; i < dp.length; i++) for (int j = 0; j < dp[0].length; j++) for (int k = 0; k <= mn; k++) for (int s = 0; s <= T; s++) { long x = (dp[i][j][0][s] * 1L * totalWays(i, j, k, ways, cached, factorial)) % MOD; x *= dp2[0][0][k][T - s]; x %= MOD; answer += x; } out.println(answer % MOD); } } 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); } } 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 println(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.print('\n'); } public void close() { writer.close(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.*; import java.util.*; public class B { static int n, t[], g[], MOD = (int) 1e9 + 7; static int[][][] memo1, memo2[], memo3[]; static int dp1(int idx, int remCnt, int remSum) { if (idx == n) return remSum == 0 && remCnt == 0 ? 1 : 0; if (remCnt < 0 || remSum < 0) return 0; if (memo1[idx][remCnt][remSum] != -1) return memo1[idx][remCnt][remSum]; int ans = dp1(idx + 1, remCnt, remSum); if (g[idx] == 0) { ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]); if (ans >= MOD) ans -= MOD; } return memo1[idx][remCnt][remSum] = ans; } static int dp2(int idx, int remCnt1, int remCnt2, int remSum) { if (idx == n) return remSum == 0 && remCnt1 == 0 && remCnt2 == 0 ? 1 : 0; if (remSum < 0 || remCnt1 < 0 || remCnt2 < 0) return 0; if (memo2[idx][remCnt1][remCnt2][remSum] != -1) return memo2[idx][remCnt1][remCnt2][remSum]; int ans = dp2(idx + 1, remCnt1, remCnt2, remSum); if (g[idx] == 1) ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]); else if (g[idx] == 2) ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]); if (ans >= MOD) ans -= MOD; return memo2[idx][remCnt1][remCnt2][remSum] = ans; } private static int dp3(int cnt0, int cnt1, int cnt2, int last) { if (cnt0 + cnt1 + cnt2 == 0) return 1; if (memo3[last][cnt0][cnt1][cnt2] != -1) return memo3[last][cnt0][cnt1][cnt2]; long ans = 0; if (cnt0 > 0 && last != 0) ans += dp3(cnt0 - 1, cnt1, cnt2, 0); if (cnt1 > 0 && last != 1) ans += dp3(cnt0, cnt1 - 1, cnt2, 1); if (cnt2 > 0 && last != 2) ans += dp3(cnt0, cnt1, cnt2 - 1, 2); return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); int[] fac = new int[n + 1]; t = new int[n]; g = new int[n]; int[] cnt = new int[3]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (int) (i * 1L * fac[i - 1] % MOD); int T = sc.nextInt(); for (int i = 0; i < n; i++) { t[i] = sc.nextInt(); g[i] = sc.nextInt() - 1; cnt[g[i]]++; } memo1 = new int[n][cnt[0] + 1][T + 1]; memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1]; memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j <= cnt[0]; j++) Arrays.fill(memo1[i][j], -1); for (int j = 0; j <= cnt[1]; j++) for (int k = 0; k <= cnt[2]; k++) Arrays.fill(memo2[i][j][k], -1); } for (int i = 0; i < 4; i++) for (int j = 0; j <= cnt[0]; j++) for (int k = 0; k <= cnt[1]; k++) Arrays.fill(memo3[i][j][k], -1); int ans = 0; for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++) for (int sum0 = 0; sum0 <= T; sum0++) for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++) for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) { long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD; ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD; ways *= fac[cnt0]; ways %= MOD; ways *= fac[cnt1]; ways %= MOD; ways *= fac[cnt2]; ways %= MOD; ans += ways; if (ans >= MOD) ans -= MOD; } out.println(ans); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
// Don't place your source in a package import javax.swing.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int T=1; for(int t=0;t<T;t++){ int n=Int(); int k=Int(); int A[][]=new int[n][2]; int a=0,b=0,c=0; for(int i=0;i<A.length;i++){ A[i][0]=Int(); A[i][1]=Int()-1; if(A[i][1]==0)a++; else if(A[i][1]==1)b++; else c++; } Solution sol=new Solution(out); sol.solution(A,k,a,b,c); } out.close(); } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution{ PrintWriter out; public Solution(PrintWriter out){ this.out=out; } int mod=1000000007; long dp3[][][][]; public void solution(int A[][],int T,int x,int y,int z){ long res=0; int n=A.length; long dp1[][]=new long[x+1][T+1];//a long dp2[][][]=new long[y+1][z+1][T+1];//bc dp3=new long[x+2][y+2][z+2][3]; //System.out.println(x+" "+y+" "+z); //init long f[]=new long[n+10]; f[0]=f[1]=1; for(int i=2;i<f.length;i++){ f[i]=f[i-1]*i; f[i]%=mod; } for(int i=0;i<dp3.length;i++){ for(int j=0;j<dp3[0].length;j++){ for(int k=0;k<dp3[0][0].length;k++){ Arrays.fill(dp3[i][j][k],-1); } } } dp1[0][0]=1; long newdp1[][]=new long[dp1.length][dp1[0].length]; for(int i=0;i<A.length;i++){//a int p=A[i][0],type=A[i][1]; if(type==0){ for(int cnt=1;cnt<=x;cnt++){ for(int j=1;j<dp1[0].length;j++){ if(j>=p){ newdp1[cnt][j]+=dp1[cnt-1][j-p]; newdp1[cnt][j]%=mod; } } } for(int cnt=0;cnt<=x;cnt++){ for(int j=0;j<dp1[0].length;j++){ dp1[cnt][j]+=newdp1[cnt][j]; dp1[cnt][j]%=mod; newdp1[cnt][j]=0; } } } } dp2[0][0][0]=1; long newdp2[][][]=new long[dp2.length][dp2[0].length][dp2[0][0].length]; for(int i=0;i<A.length;i++){//b c int p=A[i][0],type=A[i][1]; if(type!=0){ for(int a=0;a<dp2.length;a++){ for(int b=0;b<dp2[0].length;b++){ for(int j=0;j<dp2[0][0].length;j++){ if(j>=p){ if(type==1){ if(a-1>=0){ newdp2[a][b][j]+=dp2[a-1][b][j-p]; } } else{ if(b-1>=0) { newdp2[a][b][j]+=dp2[a][b-1][j-p]; } } } newdp2[a][b][j]%=mod; } } } for(int a=0;a<dp2.length;a++){ for(int b=0;b<dp2[0].length;b++){ for(int j=0;j<dp2[0][0].length;j++){ dp2[a][b][j]+=newdp2[a][b][j]; dp2[a][b][j]%=mod; newdp2[a][b][j]=0; } } } }//type!=0 } dp3[1][0][0][0]=1; dp3[0][1][0][1]=1; dp3[0][0][1][2]=1; for(int i=0;i<dp3.length;i++){ for(int j=0;j<dp3[0].length;j++){ for(int k=0;k<dp3[0][0].length;k++){ for(x=0;x<dp3[0][0][0].length;x++){ if(dp3[i][j][k][x]==-1){ dfs(i,j,k,x); } } } } } for(int i=0;i<dp3.length-1;i++){ for(int j=0;j<dp3[0].length-1;j++){ for(int k=0;k<dp3[0][0].length-1;k++){ for(int cur=0;cur<3;cur++){ for(int t=0;t<=T;t++){//price int aprice=t; int bcprice=T-t; long cnt1=dp1[i][aprice]; long cnt2=dp2[j][k][bcprice]; long combination=dp3[i][j][k][cur]; long p1=(cnt1*f[i])%mod; long p2=(((f[j]*f[k])%mod)*cnt2)%mod; long p3=(p1*p2)%mod; res+=(p3*combination)%mod; res%=mod; } } } } } out.println(res); } public long dfs(int a,int b,int c,int cur){ if(a<0||b<0||c<0){ return 0; } if(a==0&&b==0&&c==0){ return 0; } if(dp3[a][b][c][cur]!=-1)return dp3[a][b][c][cur]; long res=0; if(cur==0){ res+=dfs(a-1,b,c,1); res%=mod; res+=dfs(a-1,b,c,2); res%=mod; } else if(cur==1){ res+=dfs(a,b-1,c,0); res%=mod; res+=dfs(a,b-1,c,2); res%=mod; } else{ res+=dfs(a,b,c-1,0); res%=mod; res+=dfs(a,b,c-1,1); res%=mod; } res%=mod; dp3[a][b][c][cur]=res; return res; } } /* ;\ |' \ _ ; : ; / `-. /: : | | ,-.`-. ,': : | \ : `. `. ,'-. : | \ ; ; `-.__,' `-.| \ ; ; ::: ,::'`:. `. \ `-. : ` :. `. \ \ \ , ; ,: (\ \ :., :. ,'o)): ` `-. ,/,' ;' ,::"'`.`---' `. `-._ ,/ : ; '" `;' ,--`. ;/ :; ; ,:' ( ,:) ,.,:. ; ,:., ,-._ `. \""'/ '::' `:'` ,'( \`._____.-'"' ;, ; `. `. `._`-. \\ ;:. ;: `-._`-.\ \`. '`:. : |' `. `\ ) \ -hrr- ` ;: | `--\__,' '` ,' ,-' free bug dog */ /* 5 3 1 1 2 1 2 1 2 1 2 2 */
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.*; import java.util.*; public class B { static int n, t[], g[], MOD = (int) 1e9 + 7; static int[][][] memo1, memo2[], memo3[]; static int dp1(int idx, int remCnt, int remSum) { if (idx == n) return remSum == 0 && remCnt==0 ? 1 : 0; if(remCnt<0 || remSum<0) return 0; if (memo1[idx][remCnt][remSum] != -1) return memo1[idx][remCnt][remSum]; int ans = dp1(idx + 1, remCnt, remSum); if (g[idx] == 0) { ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]); if (ans >= MOD) ans -= MOD; } return memo1[idx][remCnt][remSum] = ans; } static int dp2(int idx, int remCnt1, int remCnt2, int remSum) { int all = remCnt1 + remCnt2; if (all == 0) return remSum == 0 ? 1 : 0; if (idx == n || remSum == 0) return 0; if (memo2[idx][remCnt1][remCnt2][remSum] != -1) return memo2[idx][remCnt1][remCnt2][remSum]; int ans = dp2(idx + 1, remCnt1, remCnt2, remSum); if (t[idx] <= remSum) { if (g[idx] == 1 && remCnt1 > 0) ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]); else if (g[idx] == 2 && remCnt2 > 0) ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]); } return memo2[idx][remCnt1][remCnt2][remSum] = ans; } private static int dp3(int cnt0, int cnt1, int cnt2, int last) { if (cnt0 + cnt1 + cnt2 == 0) return 1; if (memo3[last][cnt0][cnt1][cnt2] != -1) return memo3[last][cnt0][cnt1][cnt2]; long ans = 0; if (cnt0 > 0 && last != 0) ans += dp3(cnt0 - 1, cnt1, cnt2, 0); if (cnt1 > 0 && last != 1) ans += dp3(cnt0, cnt1 - 1, cnt2, 1); if (cnt2 > 0 && last != 2) ans += dp3(cnt0, cnt1, cnt2 - 1, 2); return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); int[] fac = new int[n + 1]; t = new int[n]; g = new int[n]; int[] cnt = new int[3]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (int) (i * 1L * fac[i - 1] % MOD); int T = sc.nextInt(); for (int i = 0; i < n; i++) { t[i] = sc.nextInt(); g[i] = sc.nextInt() - 1; cnt[g[i]]++; } memo1 = new int[n][cnt[0] + 1][T + 1]; memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1]; memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j <= cnt[0]; j++) Arrays.fill(memo1[i][j], -1); for (int j = 0; j <= cnt[1]; j++) for (int k = 0; k <= cnt[2]; k++) Arrays.fill(memo2[i][j][k], -1); } for (int i = 0; i < 4; i++) for (int j = 0; j <= cnt[0]; j++) for (int k = 0; k <= cnt[1]; k++) Arrays.fill(memo3[i][j][k], -1); int ans = 0; for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++) for (int sum0 = 0; sum0 <= T; sum0++) for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++) for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) { long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD; ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD; ways *= fac[cnt0]; ways %= MOD; ways *= fac[cnt1]; ways %= MOD; ways *= fac[cnt2]; ways %= MOD; ans += ways; if (ans >= MOD) ans -= MOD; } out.println(ans); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.*; import java.util.*; public class B { static int n, t[], g[], MOD = (int) 1e9 + 7; static int[][][] memo1, memo2[], memo3[]; static int dp1(int idx, int remCnt, int remSum) { if (idx == n) return remSum == 0 && remCnt == 0 ? 1 : 0; if (remCnt < 0 || remSum < 0) return 0; if (memo1[idx][remCnt][remSum] != -1) return memo1[idx][remCnt][remSum]; int ans = dp1(idx + 1, remCnt, remSum); if (g[idx] == 0) { ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]); if (ans >= MOD) ans -= MOD; } return memo1[idx][remCnt][remSum] = ans; } static int dp2(int idx, int remCnt1, int remCnt2, int remSum) { if (idx == n) return remSum == 0 && remCnt1 == 0 && remCnt2 == 0 ? 1 : 0; if (remSum < 0 || remCnt1 < 0 || remCnt2 < 0) return 0; if (memo2[idx][remCnt1][remCnt2][remSum] != -1) return memo2[idx][remCnt1][remCnt2][remSum]; int ans = dp2(idx + 1, remCnt1, remCnt2, remSum); if (g[idx] == 1) ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]); else if (g[idx] == 2) ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]); return memo2[idx][remCnt1][remCnt2][remSum] = ans; } private static int dp3(int cnt0, int cnt1, int cnt2, int last) { if (cnt0 < 0 || cnt1 < 0 || cnt2 < 0) return 0; if (cnt0 + cnt1 + cnt2 == 0) return 1; if (memo3[last][cnt0][cnt1][cnt2] != -1) return memo3[last][cnt0][cnt1][cnt2]; long ans = 0; if (last != 0) ans += dp3(cnt0 - 1, cnt1, cnt2, 0); if (last != 1) ans += dp3(cnt0, cnt1 - 1, cnt2, 1); if (last != 2) ans += dp3(cnt0, cnt1, cnt2 - 1, 2); return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); int[] fac = new int[n + 1]; t = new int[n]; g = new int[n]; int[] cnt = new int[3]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (int) (i * 1L * fac[i - 1] % MOD); int T = sc.nextInt(); for (int i = 0; i < n; i++) { t[i] = sc.nextInt(); g[i] = sc.nextInt() - 1; cnt[g[i]]++; } memo1 = new int[n][cnt[0] + 1][T + 1]; memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1]; memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j <= cnt[0]; j++) Arrays.fill(memo1[i][j], -1); for (int j = 0; j <= cnt[1]; j++) for (int k = 0; k <= cnt[2]; k++) Arrays.fill(memo2[i][j][k], -1); } for (int i = 0; i < 4; i++) for (int j = 0; j <= cnt[0]; j++) for (int k = 0; k <= cnt[1]; k++) Arrays.fill(memo3[i][j][k], -1); int ans = 0; for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++) for (int sum0 = 0; sum0 <= T; sum0++) for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++) for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) { long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD; ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD; ways *= fac[cnt0]; ways %= MOD; ways *= fac[cnt1]; ways %= MOD; ways *= fac[cnt2]; ways %= MOD; ans += ways; if (ans >= MOD) ans -= MOD; } out.println(ans); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
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.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskG2 solver = new TaskG2(); solver.solve(1, in, out); out.close(); } static class TaskG2 { static final int MOD = 1000000000 + 7; static final int MAXN = 51; int getWays(int i, int j, int k, int l, int[][][][] ways, boolean[][][][] cached) { if (i + j + k == 0) return l == -1 ? 1 : 0; if (l < 0) return 0; if (cached[i][j][k][l]) return ways[i][j][k][l]; int s = i + j + k; long value = 0; if (l == 0 && i != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i - 1, j, k, x, ways, cached); } } if (l == 1 && j != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i, j - 1, k, x, ways, cached); } } if (l == 2 && k != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i, j, k - 1, x, ways, cached); } } ways[i][j][k][l] = (int) (value % MOD); cached[i][j][k][l] = true; return ways[i][j][k][l]; } int totalWays(int i, int j, int k, int[][][][] ways, boolean[][][][] cached, int[] factorial) { long ret = 0; for (int l = 0; l < 3; l++) ret += getWays(i, j, k, l, ways, cached); ret *= factorial[i]; ret %= MOD; ret *= factorial[j]; ret %= MOD; ret *= factorial[k]; ret %= MOD; return (int) ret; } int add(int type, int value, int[] sizes, int sum, int[][][][] dp) { sizes[type]++; if (type == 0) { for (int s = sum + value; s >= value; s--) { for (int i = 1; i <= sizes[0]; i++) for (int j = 0; j <= sizes[1]; j++) for (int k = 0; k <= sizes[2]; k++) { dp[i][j][k][s] += dp[i - 1][j][k][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } if (type == 1) { for (int s = sum + value; s >= value; s--) { for (int i = 0; i <= sizes[0]; i++) for (int j = 1; j <= sizes[1]; j++) for (int k = 0; k <= sizes[2]; k++) { // System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length); dp[i][j][k][s] += dp[i][j - 1][k][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } if (type == 2) { for (int s = sum + value; s >= value; s--) { for (int i = 0; i <= sizes[0]; i++) for (int j = 0; j <= sizes[1]; j++) for (int k = 1; k <= sizes[2]; k++) { // System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length); dp[i][j][k][s] += dp[i][j][k - 1][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } return sum + value; } public void solve(int testNumber, InputReader in, OutputWriter out) { int[][][][] ways = new int[MAXN][MAXN][MAXN][3]; boolean[][][][] cached = new boolean[MAXN][MAXN][MAXN][3]; // Arrays.fill(ways, -1); int n = in.nextInt(), T = in.nextInt(); ArrayList<Integer>[] ar = new ArrayList[3]; for (int i = 0; i < 3; i++) ar[i] = new ArrayList<Integer>(); int total_sum = 0; for (int i = 0; i < n; i++) { int t = in.nextInt(), g = in.nextInt(); ar[g - 1].add(t); total_sum += t; } if (T > total_sum) { out.println(0); return; } int min_index = 0, mn = 100000000; for (int i = 0; i < 3; i++) { if (ar[i].size() < mn) { mn = ar[i].size(); min_index = i; } } int[][][][] dp = new int[ar[(1 + min_index) % 3].size() + 1][ar[(2 + min_index) % 3].size() + 1][1][total_sum + 1]; int[][][][] dp2 = new int[1][1][mn + 1][total_sum + 1]; dp[0][0][0][0] = dp2[0][0][0][0] = 1; int[] sizes = {0, 0, 0}; int sum = 0; int[] order = {(min_index + 1) % 3, (min_index + 2) % 3}; int type = 0; for (int i : order) { for (int v : ar[i]) sum = add(type, v, sizes, sum, dp); type++; } sum = 0; sizes[0] = sizes[1] = sizes[2] = 0; for (int i : ar[min_index]) sum = add(2, i, sizes, sum, dp2); int[] factorial = new int[MAXN]; factorial[0] = 1; for (int i = 1; i < MAXN; i++) factorial[i] = (int) ((factorial[i - 1] * 1L * i) % MOD); long answer = 0; for (int i = 0; i < dp.length; i++) for (int j = 0; j < dp[0].length; j++) for (int k = 0; k <= mn; k++) for (int s = 0; s <= T; s++) { long x = (dp[i][j][0][s] * 1L * totalWays(i, j, k, ways, cached, factorial)) % MOD; x *= dp2[0][0][k][T - s]; x %= MOD; answer += x; } out.println(answer % MOD); } } 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); } } 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 println(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.print('\n'); } public void close() { writer.close(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.*; import java.util.*; public class CF1185G2 { static final int MD = 1000000007; static int[][] solve1(int[] aa, int t, int n) { int[][] da = new int[t + 1][n + 1]; da[0][0] = 1; for (int i = 0; i < n; i++) { int a = aa[i]; for (int s = t - 1; s >= 0; s--) for (int m = 0; m < n; m++) { int x = da[s][m]; if (x != 0) { int s_ = s + a; if (s_ <= t) da[s_][m + 1] = (da[s_][m + 1] + x) % MD; } } } return da; } static int[][][] solve2(int[] aa, int[] bb, int t, int na, int nb) { int[][] da = solve1(aa, t, na); int[][][] dab = new int[t + 1][na + 1][nb + 1]; for (int s = 0; s <= t; s++) for (int ma = 0; ma <= na; ma++) dab[s][ma][0] = da[s][ma]; for (int i = 0; i < nb; i++) { int b = bb[i]; for (int s = t - 1; s >= 0; s--) for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb < nb; mb++) { int x = dab[s][ma][mb]; if (x != 0) { int s_ = s + b; if (s_ <= t) dab[s_][ma][mb + 1] = (dab[s_][ma][mb + 1] + x) % MD; } } } return dab; } static long power(int a, int k) { if (k == 0) return 1; long p = power(a, k / 2); p = p * p % MD; if (k % 2 == 1) p = p * a % MD; return p; } static int[] ff, gg; static int ch(int n, int k) { return (int) ((long) ff[n] * gg[n - k] % MD * gg[k] % MD); } static int[][][] init(int n, int na, int nb, int nc) { ff = new int[n + 1]; gg = new int[n + 1]; for (int i = 0, f = 1; i <= n; i++) { ff[i] = f; gg[i] = (int) power(f, MD - 2); f = (int) ((long) f * (i + 1) % MD); } int[][][] dp = new int[na + 1][nb + 1][nc + 1]; for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb <= nb; mb++) for (int mc = 0; mc <= nc; mc++) { int x = (int) ((long) ff[ma + mb + mc] * gg[ma] % MD * gg[mb] % MD * gg[mc] % MD); for (int ma_ = ma == 0 ? 0 : 1; ma_ <= ma; ma_++) { int cha = ma == 0 ? 1 : ch(ma - 1, ma_ - 1); for (int mb_ = mb == 0 ? 0 : 1; mb_ <= mb; mb_++) { int chb = mb == 0 ? 1 : ch(mb - 1, mb_ - 1); for (int mc_ = mc == 0 ? 0 : 1; mc_ <= mc; mc_++) { int chc = mc == 0 ? 1 : ch(mc - 1, mc_ - 1); int y = dp[ma_][mb_][mc_]; if (y == 0) continue; x = (int) ((x - (long) y * cha % MD * chb % MD * chc) % MD); } } } if (x < 0) x += MD; dp[ma][mb][mc] = x; } for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb <= nb; mb++) for (int mc = 0; mc <= nc; mc++) dp[ma][mb][mc] = (int) ((long) dp[ma][mb][mc] * ff[ma] % MD * ff[mb] % MD * ff[mc] % MD); return dp; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st.nextToken()); int[] aa = new int[n]; int[] bb = new int[n]; int[] cc = new int[n]; int na = 0, nb = 0, nc = 0; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int g = Integer.parseInt(st.nextToken()); if (g == 1) aa[na++] = a; else if (g == 2) bb[nb++] = a; else cc[nc++] = a; } int[][][] dp = init(n, na, nb, nc); int[][][] dab = solve2(aa, bb, t, na, nb); int[][] dc = solve1(cc, t, nc); int ans = 0; for (int tab = 0; tab <= t; tab++) { int tc = t - tab; for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb <= nb; mb++) { int xab = dab[tab][ma][mb]; if (xab == 0) continue; for (int mc = 0; mc <= nc; mc++) { int xc = dc[tc][mc]; if (xc == 0) continue; ans = (int) ((ans + (long) xab * xc % MD * dp[ma][mb][mc]) % MD); } } } System.out.println(ans); } }
cubic
1185_G2. Playlist for Polycarp (hard version)
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.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskG2 solver = new TaskG2(); solver.solve(1, in, out); out.close(); } static class TaskG2 { static final int MOD = 1000000000 + 7; static final int MAXN = 51; int getWays(int i, int j, int k, int l, int[][][][] ways, boolean[][][][] cached) { if (i + j + k == 0) return l == -1 ? 1 : 0; if (l < 0) return 0; if (cached[i][j][k][l]) return ways[i][j][k][l]; int s = i + j + k; long value = 0; if (l == 0 && i != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i - 1, j, k, x, ways, cached); } } if (l == 1 && j != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i, j - 1, k, x, ways, cached); } } if (l == 2 && k != 0) { for (int x = -1; x < 3; x++) if (x != l) { value += getWays(i, j, k - 1, x, ways, cached); } } ways[i][j][k][l] = (int) (value % MOD); cached[i][j][k][l] = true; return ways[i][j][k][l]; } int totalWays(int i, int j, int k, int[][][][] ways, boolean[][][][] cached, int[] factorial) { long ret = 0; for (int l = 0; l < 3; l++) ret += getWays(i, j, k, l, ways, cached); ret *= factorial[i]; ret %= MOD; ret *= factorial[j]; ret %= MOD; ret *= factorial[k]; ret %= MOD; return (int) ret; } int add(int type, int value, int[] sizes, int sum, int[][][][] dp) { sizes[type]++; if (type == 0) { for (int s = sum + value; s >= value; s--) { for (int i = 1; i <= sizes[0]; i++) for (int j = 0; j <= sizes[1]; j++) for (int k = 0; k <= sizes[2]; k++) { dp[i][j][k][s] += dp[i - 1][j][k][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } if (type == 1) { for (int s = sum + value; s >= value; s--) { for (int i = 0; i <= sizes[0]; i++) for (int j = 1; j <= sizes[1]; j++) for (int k = 0; k <= sizes[2]; k++) { // System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length); dp[i][j][k][s] += dp[i][j - 1][k][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } if (type == 2) { for (int s = sum + value; s >= value; s--) { for (int i = 0; i <= sizes[0]; i++) for (int j = 0; j <= sizes[1]; j++) for (int k = 1; k <= sizes[2]; k++) { // System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length); dp[i][j][k][s] += dp[i][j][k - 1][s - value]; if (dp[i][j][k][s] >= MOD) dp[i][j][k][s] -= MOD; } } } return sum + value; } public void solve(int testNumber, InputReader in, OutputWriter out) { int[][][][] ways = new int[MAXN][MAXN][MAXN][3]; boolean[][][][] cached = new boolean[MAXN][MAXN][MAXN][3]; // Arrays.fill(ways, -1); int n = in.nextInt(), T = in.nextInt(); ArrayList<Integer>[] ar = new ArrayList[3]; for (int i = 0; i < 3; i++) ar[i] = new ArrayList<Integer>(); int total_sum = 0; for (int i = 0; i < n; i++) { int t = in.nextInt(), g = in.nextInt(); ar[g - 1].add(t); total_sum += t; } if (T > total_sum) { out.println(0); return; } int min_index = 0, mn = 100000000; for (int i = 0; i < 3; i++) { if (ar[i].size() < mn) { mn = ar[i].size(); min_index = i; } } int[][][][] dp = new int[ar[(1 + min_index) % 3].size() + 1][ar[(2 + min_index) % 3].size() + 1][mn + 1][total_sum + 1]; dp[0][0][0][0] = 1; int[] sizes = {0, 0, 0}; int sum = 0; int[] order = {(min_index + 1) % 3, (min_index + 2) % 3, min_index}; int type = 0; for (int i : order) { for (int v : ar[i]) sum = add(type, v, sizes, sum, dp); type++; } int[] factorial = new int[MAXN]; factorial[0] = 1; for (int i = 1; i < MAXN; i++) factorial[i] = (int) ((factorial[i - 1] * 1L * i) % MOD); long answer = 0; for (int i = 0; i < dp.length; i++) for (int j = 0; j < dp[0].length; j++) for (int k = 0; k < dp[0][0].length; k++) { answer += dp[i][j][k][T] * 1L * totalWays(i, j, k, ways, cached, factorial); answer %= MOD; } out.println(answer); } } 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); } } 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 println(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.print('\n'); } public void close() { writer.close(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
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 << 27); 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); G2PlaylistForPolycarpHardVersion solver = new G2PlaylistForPolycarpHardVersion(); solver.solve(1, in, out); out.close(); } } static class G2PlaylistForPolycarpHardVersion { Modular mod = new Modular(1e9 + 7); public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int m = in.readInt(); int[][] musics = new int[n][2]; int[] cnts = new int[4]; for (int i = 0; i < n; i++) { musics[i][0] = in.readInt(); musics[i][1] = in.readInt(); cnts[musics[i][1]]++; } int c1 = cnts[1]; int c2 = cnts[2]; int c3 = cnts[3]; int[][][][] comp = new int[c1 + 1][c2 + 1][c3 + 1][4]; for (int i = 0; i <= c1; i++) { for (int j = 0; j <= c2; j++) { for (int k = 0; k <= c3; k++) { for (int t = 0; t < 4; t++) { if (i == 0 && j == 0 && k == 0) { comp[i][j][k][t] = 1; continue; } if (i > 0 && t != 1) { comp[i][j][k][t] = mod.plus(comp[i][j][k][t], mod.mul(comp[i - 1][j][k][1], i)); } if (j > 0 && t != 2) { comp[i][j][k][t] = mod.plus(comp[i][j][k][t], mod.mul(comp[i][j - 1][k][2], j)); } if (k > 0 && t != 3) { comp[i][j][k][t] = mod.plus(comp[i][j][k][t], mod.mul(comp[i][j][k - 1][3], k)); } } } } } int[][][][] last = new int[c1 + 1][c2 + 1][c3 + 1][m + 1]; int[][][][] next = new int[c1 + 1][c2 + 1][c3 + 1][m + 1]; last[0][0][0][0] = 1; int t1 = 0; int t2 = 0; int t3 = 0; for (int[] music : musics) { int m1 = music[1]; int m0 = music[0]; if (m1 == 1) { t1++; } else if (m1 == 2) { t2++; } else { t3++; } for (int i = 0; i <= t1; i++) { for (int j = 0; j <= t2; j++) { for (int k = 0; k <= t3; k++) { for (int t = 0; t <= m; t++) { next[i][j][k][t] = last[i][j][k][t]; if (t < m0) { continue; } if (m1 == 1 && i > 0) { next[i][j][k][t] = mod.plus(next[i][j][k][t], last[i - 1][j][k][t - m0]); } else if (m1 == 2 && j > 0) { next[i][j][k][t] = mod.plus(next[i][j][k][t], last[i][j - 1][k][t - m0]); } else if (m1 == 3 && k > 0) { next[i][j][k][t] = mod.plus(next[i][j][k][t], last[i][j][k - 1][t - m0]); } } } } } int[][][][] tmp = last; last = next; next = tmp; } int ans = 0; for (int i = 0; i <= c1; i++) { for (int j = 0; j <= c2; j++) { for (int k = 0; k <= c3; k++) { ans = mod.plus(ans, mod.mul(last[i][j][k][m], comp[i][j][k][0])); } } } out.println(ans); } } static class Modular { int m; public Modular(int m) { this.m = m; } public Modular(long m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public Modular(double m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public int valueOf(int x) { x %= m; if (x < 0) { x += m; } return x; } public int valueOf(long x) { x %= m; if (x < 0) { x += m; } return (int) x; } public int mul(int x, int y) { return valueOf((long) x * y); } public int plus(int x, int y) { return valueOf(x + y); } public String toString() { return "mod " + m; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c).append('\n'); return this; } public FastOutput flush() { try { 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 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
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
//package prac; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class Round568G { InputStream is; PrintWriter out; String INPUT = ""; // void solve() { int n = ni(), T = ni(); int mod = 1000000007; int[][] a = new int[3][n]; int[] ap = new int[3]; for(int i = 0;i < n;i++){ int t = ni(); int k = ni()-1; a[k][ap[k]++] = t; } for(int i = 0;i < 3;i++)a[i] = Arrays.copyOf(a[i], ap[i]); long[][][][] com = new long[3][ap[0]+2][ap[1]+2][ap[2]+2]; com[0][1][0][0] = com[1][0][1][0] = com[2][0][0][1] = 1; for(int i = 0;i <= ap[0];i++){ for(int j = 0;j <= ap[1];j++){ for(int k = 0;k <= ap[2];k++){ for(int u = 0;u < 3;u++){ if(u != 0){ com[0][i+1][j][k] += com[u][i][j][k]; if(com[0][i+1][j][k] >= mod)com[0][i+1][j][k] -= mod; } if(u != 1){ com[1][i][j+1][k] += com[u][i][j][k]; if(com[1][i][j+1][k] >= mod)com[1][i][j+1][k] -= mod; } if(u != 2){ com[2][i][j][k+1] += com[u][i][j][k]; if(com[2][i][j][k+1] >= mod)com[2][i][j][k+1] -= mod; } } } } } int[][] fif = enumFIF(200, mod); long[][][] dp = new long[3][][]; for(int i = 0;i < 3;i++){ int s = 0; for(int v : a[i])s += v; dp[i] = new long[ap[i]+1][s+1]; dp[i][0][0] = 1; for(int v : a[i]){ for(int j = ap[i]-1;j >= 0;j--){ for(int k = s-v;k >= 0;k--){ dp[i][j+1][k+v] += dp[i][j][k]; if(dp[i][j+1][k+v] >= mod)dp[i][j+1][k+v] -= mod; } } } } long[][][] con = new long[ap[0]+1][ap[1]+1][2501]; for(int i = 0;i <= ap[0];i++){ for(int j = 0;j <= ap[1];j++){ for(int k = 0;k < dp[0][i].length;k++){ if(dp[0][i][k] == 0)continue; for(int l = 0;l < dp[1][j].length;l++){ con[i][j][k+l] += dp[0][i][k] * dp[1][j][l]; con[i][j][k+l] %= mod; } } } } long ans = 0; for(int i = 0;i <= ap[0];i++){ for(int j = 0;j <= ap[1];j++){ for(int k = 0;k <= ap[2];k++){ long base = (com[0][i][j][k] + com[1][i][j][k] + com[2][i][j][k]) * fif[0][i] % mod * fif[0][j] % mod * fif[0][k] % mod; long ls = 0; for(int l = 0;l <= T;l++){ if(T-l < dp[2][k].length){ ls += con[i][j][l] * dp[2][k][T-l]; ls %= mod; } } // if(base > 0 && ls > 0){ // tr(i, j, k, base, ls); // } ans += base * ls; ans %= mod; } } } out.println(ans); } public static int[][] enumFIF(int n, int mod) { int[] f = new int[n + 1]; int[] invf = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; i++) { f[i] = (int) ((long) f[i - 1] * i % mod); } long a = f[n]; long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } invf[n] = (int) (p < 0 ? p + mod : p); for (int i = n - 1; i >= 0; i--) { invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod); } return new int[][] { f, invf }; } void run() throws Exception { // int n = 50, m = 2500; // Random gen = new Random(); // StringBuilder sb = new StringBuilder(); // sb.append(n + " "); // sb.append(m + " "); // for (int i = 0; i < n; i++) { // sb.append(50 + " "); // sb.append(gen.nextInt(3)+1 + " "); // } // INPUT = sb.toString(); is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Round568G().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
// https://codeforces.com/contest/1185/submission/55800229 (rainboy) import java.io.*; import java.util.*; public class CF1185G2 { static final int MD = 1000000007; static int[][] solve1(int[] aa, int t, int n) { int[][] da = new int[t + 1][n + 1]; da[0][0] = 1; for (int i = 0; i < n; i++) { int a = aa[i]; for (int s = t - 1; s >= 0; s--) for (int m = 0; m < n; m++) { int x = da[s][m]; if (x != 0) { int s_ = s + a; if (s_ <= t) da[s_][m + 1] = (da[s_][m + 1] + x) % MD; } } } return da; } static int[][][] solve2(int[] aa, int[] bb, int t, int na, int nb) { int[][] da = solve1(aa, t, na); int[][][] dab = new int[t + 1][na + 1][nb + 1]; for (int s = 0; s <= t; s++) for (int ma = 0; ma <= na; ma++) dab[s][ma][0] = da[s][ma]; for (int i = 0; i < nb; i++) { int b = bb[i]; for (int s = t - 1; s >= 0; s--) for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb < nb; mb++) { int x = dab[s][ma][mb]; if (x != 0) { int s_ = s + b; if (s_ <= t) dab[s_][ma][mb + 1] = (dab[s_][ma][mb + 1] + x) % MD; } } } return dab; } static int[][][] init(int n, int na, int nb, int nc) { int[][][] dp = new int[na + 1][nb + 1][nc + 1]; int[][][][] dq = new int[na + 1][nb + 1][nc + 1][3]; for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb <= nb; mb++) for (int mc = 0; mc <= nc; mc++) if (ma == 0 && mb == 0 && mc == 0) { dp[ma][mb][mc] = 1; dq[ma][mb][mc][0] = dq[ma][mb][mc][1] = dq[ma][mb][mc][2] = 1; } else { int x0 = ma > 0 ? (int) ((long) dq[ma - 1][mb][mc][0] * ma % MD) : 0; int x1 = mb > 0 ? (int) ((long) dq[ma][mb - 1][mc][1] * mb % MD) : 0; int x2 = mc > 0 ? (int) ((long) dq[ma][mb][mc - 1][2] * mc % MD) : 0; dp[ma][mb][mc] = (int) (((long) x0 + x1 + x2) % MD); dq[ma][mb][mc][0] = (x1 + x2) % MD; dq[ma][mb][mc][1] = (x2 + x0) % MD; dq[ma][mb][mc][2] = (x0 + x1) % MD; } return dp; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st.nextToken()); int[] aa = new int[n]; int[] bb = new int[n]; int[] cc = new int[n]; int na = 0, nb = 0, nc = 0; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int g = Integer.parseInt(st.nextToken()); if (g == 1) aa[na++] = a; else if (g == 2) bb[nb++] = a; else cc[nc++] = a; } int[][][] dp = init(n, na, nb, nc); int[][][] dab = solve2(aa, bb, t, na, nb); int[][] dc = solve1(cc, t, nc); int ans = 0; for (int tab = 0; tab <= t; tab++) { int tc = t - tab; for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb <= nb; mb++) { int xab = dab[tab][ma][mb]; if (xab == 0) continue; for (int mc = 0; mc <= nc; mc++) { int xc = dc[tc][mc]; if (xc == 0) continue; ans = (int) ((ans + (long) xab * xc % MD * dp[ma][mb][mc]) % MD); } } } System.out.println(ans); } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.*; import java.util.*; public class B { static int n, t[], g[], MOD = (int) 1e9 + 7; static int[][][] memo1, memo2[], memo3[]; static int dp1(int idx, int remCnt, int remSum) { if (idx == n) return remSum == 0 && remCnt == 0 ? 1 : 0; if (remCnt < 0 || remSum < 0) return 0; if (memo1[idx][remCnt][remSum] != -1) return memo1[idx][remCnt][remSum]; int ans = dp1(idx + 1, remCnt, remSum); if (g[idx] == 0) { ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]); if (ans >= MOD) ans -= MOD; } return memo1[idx][remCnt][remSum] = ans; } static int dp2(int idx, int remCnt1, int remCnt2, int remSum) { if (idx == n) return remSum == 0 && remCnt1 == 0 && remCnt2 == 0 ? 1 : 0; if (remSum < 0 || remCnt1 < 0 || remCnt2 < 0) return 0; if (memo2[idx][remCnt1][remCnt2][remSum] != -1) return memo2[idx][remCnt1][remCnt2][remSum]; int ans = dp2(idx + 1, remCnt1, remCnt2, remSum); if (g[idx] == 1) ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]); else if (g[idx] == 2) ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]); return memo2[idx][remCnt1][remCnt2][remSum] = ans; } private static int dp3(int cnt0, int cnt1, int cnt2, int last) { if (cnt0 + cnt1 + cnt2 == 0) return 1; if (memo3[last][cnt0][cnt1][cnt2] != -1) return memo3[last][cnt0][cnt1][cnt2]; long ans = 0; if (cnt0 > 0 && last != 0) ans += dp3(cnt0 - 1, cnt1, cnt2, 0); if (cnt1 > 0 && last != 1) ans += dp3(cnt0, cnt1 - 1, cnt2, 1); if (cnt2 > 0 && last != 2) ans += dp3(cnt0, cnt1, cnt2 - 1, 2); return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); int[] fac = new int[n + 1]; t = new int[n]; g = new int[n]; int[] cnt = new int[3]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (int) (i * 1L * fac[i - 1] % MOD); int T = sc.nextInt(); for (int i = 0; i < n; i++) { t[i] = sc.nextInt(); g[i] = sc.nextInt() - 1; cnt[g[i]]++; } memo1 = new int[n][cnt[0] + 1][T + 1]; memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1]; memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j <= cnt[0]; j++) Arrays.fill(memo1[i][j], -1); for (int j = 0; j <= cnt[1]; j++) for (int k = 0; k <= cnt[2]; k++) Arrays.fill(memo2[i][j][k], -1); } for (int i = 0; i < 4; i++) for (int j = 0; j <= cnt[0]; j++) for (int k = 0; k <= cnt[1]; k++) Arrays.fill(memo3[i][j][k], -1); int ans = 0; for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++) for (int sum0 = 0; sum0 <= T; sum0++) for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++) for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) { long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD; ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD; ways *= fac[cnt0]; ways %= MOD; ways *= fac[cnt1]; ways %= MOD; ways *= fac[cnt2]; ways %= MOD; ans += ways; if (ans >= MOD) ans -= MOD; } out.println(ans); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import java.awt.Point; public class CFTemplate { static final long MOD = 1000000007L; //static final long MOD2 = 1000000009L; //static final long MOD = 998244353L; //static final long INF = 500000000000L; static final int INF = 1100000000; static final int NINF = -100000; 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); ArrayList<Integer> primes = new ArrayList<Integer>(); for (int i = 2; i <= 3200; i++) { boolean p = true; for (int j = 2; j*j <= i; j++) { if (i%j==0) { p = false; break; } } if (p) primes.add(i); } int Q = sc.ni(); for (int q = 0; q < Q; q++) { int N = sc.ni(); int K = sc.ni(); int[] nums = new int[N+1]; for (int i = 1; i <= N; i++) nums[i] = sc.ni(); for (int i = 1; i <= N; i++) { for (int p: primes) { int c = 0; while (nums[i] % p == 0) { nums[i] /= p; c++; } if (c%2==1) nums[i] *= p; } } TreeSet<Integer> ts = new TreeSet<Integer>(); HashMap<Integer,Integer> last = new HashMap<Integer,Integer>(); int[][] dp = new int[N+1][K+1]; for (int i = 1; i <= N; i++) { if (last.containsKey(nums[i])) { ts.add(last.get(nums[i])); } last.put(nums[i],i); int[] inds = new int[K+1]; int ind = 0; for (int x: ts.descendingSet()) { inds[ind] = x; if (ind==K) break; ind++; } for (int j = 0; j <= K; j++) { dp[i][j] = INF; if (j > 0) dp[i][j] = dp[i][j-1]; for (int k = 0; k <= j; k++) { dp[i][j] = Math.min(dp[i][j],dp[inds[k]][j-k]+1); } } } pw.println(dp[N][K]); } pw.close(); } 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[1]-b[1]; //Ascending order. } }); } 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; } 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
1497E2
CODEFORCES
import java.util.*; import java.io.*; public class Solve{ public static void main(String[] args) throws Exception{ Scanner sc=new Scanner(System.in); PrintWriter out =new PrintWriter(System.out); int size=(int)1e7+1; int[] pr=new int[size]; for(int i=0;i<size;i++){ pr[i]=i; } for(int i=2;i*i<size;i++){ int val=i*i; for(int j=val;j<=size;j+=val){ pr[j]=j/val; } } int t=sc.nextInt(); int[] dp=new int[size]; Arrays.fill(dp,-1); while(t-->0){ int n=sc.nextInt(); int k=sc.nextInt(); int[] ar=new int[n]; for(int i=0;i<n;i++){ int a=sc.nextInt(); ar[i]=pr[a]; } int[] ans=new int[k+1]; int[] ind=new int[k+1]; for(int i=0;i<n;i++){ for(int h=k;h>=0;h--){ if(dp[ar[i]]>=ind[h]){ ans[h]++; ind[h]=i; } if(h>0 && (ans[h-1]<ans[h] ||(ans[h-1]==ans[h] && ind[h-1]>ind[h]))) { ans[h]=ans[h-1]; ind[h]=ind[h-1]; } } dp[ar[i]]=i; } out.println(ans[k]+1); for(int i=0;i<n;i++)dp[ar[i]]=-1; } out.close(); } }
cubic
1497E2
CODEFORCES
import java.io.*; import java.util.*; public class E2 { static ArrayList<Integer> primes; static int[] mind; final static int MAXA = (int) 1e7; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); int t = Integer.parseInt(st.nextToken()); primes = new ArrayList<>(); mind = new int[MAXA + 1]; for (int i = 2; i <= MAXA; i++) { if (mind[i] == 0) { primes.add(i); mind[i] = i; } for (int x : primes) { if (x > mind[i] || x * i > MAXA) break; mind[x * i] = x; } } int[] count = new int[MAXA + 1]; for (int on8y = 0; on8y < t; on8y++) { st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int[] a = new int[n]; Arrays.fill(a, 1); st = new StringTokenizer(f.readLine()); for (int i = 0; i < n; i++) { int x = Integer.parseInt(st.nextToken()); int cnt = 0; int last = 0; while (x > 1) { int p = mind[x]; if (last == p) cnt++; else { if (cnt % 2 == 1) a[i] *= last; last = p; cnt = 1; } x /= p; } if (cnt % 2 == 1) a[i] *= last; } int[][] mnleft = new int[n][k + 1]; for (int j = 0; j < k + 1; j++) { int l = n; int now = 0; for (int i = n - 1; i >= 0; i--) { while (l - 1 >= 0 && now + ((count[a[l - 1]] > 0) ? 1 : 0) <= j) { l--; now += (count[a[l]] > 0) ? 1 : 0; count[a[l]]++; } mnleft[i][j] = l; if (count[a[i]] > 1) now--; count[a[i]]--; } } int[][] dp = new int[n + 1][k + 1]; for (int i = 0; i < n + 1; i++) { Arrays.fill(dp[i], (int) 1e9 + 1); } for (int i = 0; i < k + 1; i++) dp[0][i] = 0; for (int i = 1; i <= n; i++) { for (int j = 0; j <= k; j++) { if (j > 0) dp[i][j] = dp[i][j - 1]; for (int lst = 0; lst <= j; lst++) { dp[i][j] = Math.min(dp[i][j], dp[mnleft[i - 1][lst]][j - lst] + 1); } } } int ans = (int) 1e9 + 1; for (int c : dp[n]) ans = Math.min(ans, c); System.out.println(ans); } } }
cubic
1497E2
CODEFORCES
// https://codeforces.com/contest/1497/submission/110250082 import java.io.*; import java.util.*; public class CF1497E2 extends PrintWriter { CF1497E2() { super(System.out); } static class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; byte[] bb = new byte[1 << 15]; int i, n; byte getc() { if (i == n) { i = n = 0; try { n = in.read(bb); } catch (IOException e) {} } return i < n ? bb[i++] : 0; } int nextInt() { byte c = 0; while (c <= ' ') c = getc(); int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); } return a; } } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1497E2 o = new CF1497E2(); o.main(); o.flush(); } static final int A = 10000000, K = 20; int[] cc = new int[A + 1]; { for (int a = 1; a <= A; a++) cc[a] = a; for (int a = 2; a <= A / a; a++) { int s = a * a; for (int b = s; b <= A; b += s) while (cc[b] % s == 0) cc[b] /= s; } } void main() { int[] pp = new int[A + 1]; Arrays.fill(pp, -1); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int[] aa = new int[n]; for (int i = 0; i < n; i++) aa[i] = cc[sc.nextInt()]; int[] mp = new int[k + 1]; int[] ip = new int[k + 1]; for (int i = 0; i < n; i++) { int a = aa[i]; for (int h = k; h >= 0; h--) { if (pp[a] >= ip[h]) { mp[h]++; ip[h] = i; } if (h > 0 && (mp[h - 1] < mp[h] || mp[h - 1] == mp[h] && ip[h - 1] > ip[h])) { mp[h] = mp[h - 1]; ip[h] = ip[h - 1]; } } pp[a] = i; } println(mp[k] + 1); for (int i = 0; i < n; i++) { int a = aa[i]; pp[a] = -1; } } } }
cubic
1497E2
CODEFORCES
import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Queue; public class E3 { InputStream is; FastWriter out; String INPUT = ""; void solve() { for(int T = ni();T > 0;T--)go(); } int[] lpf = enumLowestPrimeFactors(10000000); void go() { int n = ni(), K = ni(); int[] a = na(n); for(int i = 0;i < n;i++){ a[i] = factorFast(a[i], lpf); } a = shrink(a); int[][] dp = new int[K+1][n+1]; for(int i = 0;i <= K;i++){ Arrays.fill(dp[i], 999999999); } for(int i = 0;i <= K;i++)dp[i][0] = 0; int[] prev = makePrev(a, n+1); int[] imos = new int[n+5]; int[] pp = new int[K+1]; int[] vs = new int[K+1]; for(int i = 0;i < n;i++){ int p = prev[i]; imos[p+1]--; for(int j = 0;j <= K;j++){ vs[j]++; if(pp[j] >= p+1){ vs[j]--; } while(vs[j] > j){ pp[j]++; vs[j] += imos[pp[j]]; } for(int k = 0;k+j <= K;k++){ dp[k+j][i+1] = Math.min(dp[k+j][i+1], dp[k][pp[j]] + 1); } } } out.println(dp[K][n]); } public static int[] shrink(int[] a) { int n = a.length; long[] b = new long[n]; for (int i = 0; i < n; i++) b[i] = (long) a[i] << 32 | i; Arrays.sort(b); int[] ret = new int[n]; int p = 0; for (int i = 0; i < n; i++) { if (i > 0 && (b[i] ^ b[i - 1]) >> 32 != 0) p++; ret[(int) b[i]] = p; } return ret; } public static int[] makePrev(int[] a, int sup) { int n = a.length; int[] mnext = new int[sup]; Arrays.fill(mnext, -1); int[] next = new int[n]; for(int i = 0;i < n;i++){ next[i] = mnext[a[i]]; mnext[a[i]] = i; } return next; } public static int factorFast(int n, int[] lpf) { int ret = 1; int e = 0; int last = -1; while(lpf[n] > 0) { int p = lpf[n]; if (last != p) { if (last > 0 && e % 2 == 1) { ret = ret * last; } last = p; e = 1; } else { e++; } n /= p; } if(last > 0 && e % 2 == 1){ ret *= last; } return ret; } public static int[] enumLowestPrimeFactors(int n) { int tot = 0; int[] lpf = new int[n+1]; int u = n+32; double lu = Math.log(u); int[] primes = new int[(int)(u/lu+u/lu/lu*1.5)]; for(int i = 2;i <= n;i++)lpf[i] = i; for(int p = 2;p <= n;p++){ if(lpf[p] == p)primes[tot++] = p; int tmp; for(int i = 0;i < tot && primes[i] <= lpf[p] && (tmp = primes[i]*p) <= n;i++){ lpf[tmp] = primes[i]; } } return lpf; } 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 E3().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
1497E2
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputStreamReader in = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(in); int t = Integer.parseInt(br.readLine()); // get primes up to 10000 /* boolean[] prime = new boolean[10001]; for (int i = 0; i <= 10000; i++) { prime[i] = true; } for (int p = 2; p * p <= 10000; p++) { if (prime[p]) { for (int i = p * p; i <= 10000; i += p) { prime[i] = false; } } } ArrayList<Integer> primes = new ArrayList<>(); for (int i = 2; i < 10001; i++) { if (prime[i]) { primes.add(i); } } */ int A = 10000000; int[] convert = new int[A+1]; for (int a = 1; a <= A; a++) { convert[a] = a; } for (int a = 2; a <= A/a; a++) { int sq = a*a; for (int b = sq; b <= A; b += sq) { while (convert[b] % sq == 0) { convert[b] /= sq; } } } int[] prevIndex = new int[A+1]; for (int i = 0; i <= A; i++) { prevIndex[i] = -1; } for (int c = 0; c < t; c++) { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int[] a = new int[n]; int maxA = 0; st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { /* int raw = Integer.parseInt(st.nextToken()); for (int p : primes) { if (p*p > raw) { break; } while (raw % (p*p) == 0) { raw /= p*p; } } a[i] = raw; */ a[i] = convert[Integer.parseInt(st.nextToken())]; maxA = Math.max(maxA, a[i]); } // hard version has extra here // better version O(nk) int[] partitions = new int[k+1]; int[] partIndex = new int[k+1]; for (int i = 0; i < n; i++) { int cur = a[i]; for (int j = k; j >= 0; j--) { if (prevIndex[cur] >= partIndex[j]) { partitions[j]++; partIndex[j] = i; } if (j > 0 && (partitions[j-1] < partitions[j] || partitions[j-1] == partitions[j] && partIndex[j-1] > partIndex[j])) { partitions[j] = partitions[j-1]; partIndex[j] = partIndex[j-1]; } } prevIndex[cur] = i; } System.out.println(partitions[k]+1); for (int i = 0; i < n; i++) { int cur = a[i]; prevIndex[cur] = -1; } /* this should work (O(n*k^2)) int[][] minLeftIndex = new int[n][k+1]; for (int j = 0; j <= k; j++) { HashMap<Integer, Integer> interval = new HashMap<>(); int leftIndex = 0; // the right index is i in this case int removed = 0; for (int i = 0; i < n; i++) { if (!interval.containsKey(a[i])) { interval.put(a[i], 0); } interval.put(a[i], interval.get(a[i])+1); if (interval.get(a[i]) > 1) { removed++; } while (removed > j) { interval.put(a[leftIndex], interval.get(a[leftIndex])-1); if (interval.get(a[leftIndex]) > 0) { removed--; } leftIndex++; } minLeftIndex[i][j] = leftIndex; //System.out.println(i + " " + j + " " + leftIndex); } } int[][] dp = new int[n][k+1]; // dp at all i = 0 = 0 for (int i = 0; i < n; i++) { for (int j = 0; j <= k; j++) { int min = Integer.MAX_VALUE; for (int l = 0; l <= j; l++) { if (minLeftIndex[i][l] > 0) { min = Math.min(min, dp[minLeftIndex[i][l]-1][j-l] + 1); // } else { min = 0; } } if (min != Integer.MAX_VALUE) { dp[i][j] = min; } } } System.out.println(dp[n-1][k]+1); */ // easy solution /* HashSet<Integer> hs = new HashSet<>(); int segments = 1; for (int i = 0; i < n; i++) { if (hs.contains(a[i])) { segments++; hs.clear(); } hs.add(a[i]); } System.out.println(segments); */ } } }
cubic
1497E2
CODEFORCES
/** * author: derrick20 * created: 3/20/21 7:13 PM */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class E2_SquareFreeFast { static FastScanner sc = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { // generate(); int T = sc.nextInt(); int MAX = (int) 1e7; int[] canonical = new int[MAX + 1]; canonical[1] = 1; for (int factor = 2; factor <= MAX; factor++) { if (canonical[factor] == 0) { for (int mult = factor; mult <= MAX; mult += factor) { int prev = canonical[mult / factor]; if (prev % factor == 0) { canonical[mult] = prev / factor; } else { canonical[mult] = prev * factor; } } } } int[] last = new int[MAX + 1]; while (T-->0) { int N = sc.nextInt(); int K = sc.nextInt(); int[] a = new int[N + 1]; int[][] dp = new int[2][K + 1]; int[][] start = new int[2][K + 1]; int ptr = 0; for (int i = 1; i <= N; i++) { int nxt = 1 ^ ptr; a[i] = canonical[sc.nextInt()]; for (int k = 0; k <= K; k++) { if (start[ptr][k] > last[a[i]]) { // extend it for free (unique) dp[nxt][k] = dp[ptr][k]; start[nxt][k] = start[ptr][k]; } else { // start anew dp[nxt][k] = dp[ptr][k] + 1; start[nxt][k] = i; } // Use a change (only if existing segment) if (i > 1 && k > 0 && start[ptr][k - 1] <= last[a[i]]) { // if this cost beats the old cost, or if it has a later start point, it's better. if (dp[ptr][k - 1] < dp[nxt][k] || (dp[ptr][k - 1] == dp[nxt][k] && start[ptr][k - 1] > start[nxt][k])) { dp[nxt][k] = dp[ptr][k - 1]; start[nxt][k] = start[ptr][k - 1]; } } } // System.out.println(Arrays.toString(start[nxt])); // System.out.println(Arrays.toString(dp[nxt])); last[a[i]] = i; ptr = nxt; } for (int v : a) { last[v] = 0; } // always allowed to waste initial changes by starting offset, so mono decr out.println(dp[ptr][K]); } out.close(); } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } 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++]; } int nextInt() { return (int) nextLong(); } 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; } double nextDouble() { boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } double cur = nextLong(); if (c != '.') { return neg ? -cur : cur; } else { double frac = nextLong() / cnt; return neg ? -cur - frac : cur + frac; } } String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } }
cubic
1497E2
CODEFORCES
import java.util.*; import java.io.*; public class SolutionC{ public static void main(String[] args) throws Exception{ Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int t=sc.nextInt(); int[] arr=new int[10000002]; for(int i=0;i<arr.length;i++){ arr[i]=i; } for(int i=2;i*i<arr.length;i++){ int b=i*i; for(int j=b;j<arr.length;j+=b){ arr[j]=j/b; } } int[] pp = new int[10000001]; Arrays.fill(pp, -1); while(t-->0){ int n=sc.nextInt(); int k=sc.nextInt(); int[] aa=new int[n]; for(int i=0;i<n;i++){ int a=sc.nextInt(); aa[i]=arr[a]; } int[] mp = new int[k + 1]; int[] ip = new int[k + 1]; for (int i = 0; i < n; i++) { int a = aa[i]; for (int h = k; h >= 0; h--) { if (pp[a] >= ip[h]) { mp[h]++; ip[h] = i; } if (h > 0 && (mp[h - 1] < mp[h] || mp[h - 1] == mp[h] && ip[h - 1] > ip[h])) { mp[h] = mp[h - 1]; ip[h] = ip[h - 1]; } } pp[a] = i; } out.println(mp[k]+1); for (int i = 0; i < n; i++) { pp[aa[i]] = -1; } } out.close(); } }
cubic
1497E2
CODEFORCES
import java.util.*; import java.io.*; public class EdE { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; static ArrayList<Integer> primes; public static void main(String[] omkar) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); int t = sc.nextInt(); primes = new ArrayList<>(); prime(3165); int[] freq = new int[10000001]; while(t--> 0){ int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = readArrayInt(n); for(int j = 0;j<n;j++){ arr[j] = factorize(arr[j]); } int[][] left = new int[n][k+1]; for(int m = 0;m<=k;m++){ int l = 0; int count = 0; for(int i = 0;i<n;i++){ if (freq[arr[i]] > 0){ count++; } freq[arr[i]]++; while(count > m){ freq[arr[l]]--; if (freq[arr[l]] > 0){ count--; } l++; } left[i][m] = l; } while(l < n){ freq[arr[l]]--; l++; } } long[][] dp = new long[n][k+1]; for(int i=0;i<n;i++){ Arrays.fill(dp[i], Integer.MAX_VALUE); } for(int i = 0;i<n;i++){ for(int j = 0;j<=k;j++){ for(int s = 0;s<=j;s++){ if (left[i][s] == 0){ dp[i][j] = 1; continue; } dp[i][j] = Math.min(dp[i][j], dp[left[i][s]-1][j-s]+1); } } } out.println(dp[n-1][k]); } out.close(); } static class MS{ // TreeSet<Long> set; HashMap<Long, Integer> map; public MS() { // set = new TreeSet<Long>(); map = new HashMap<Long, Integer>(); } public void add(long x) { if(map.containsKey(x)){ map.put(x, map.get(x)+1); } else{ map.put(x, 1); // set.add(x); } } public void remove(long x) { if(!map.containsKey(x)) return; if(map.get(x)==1){ map.remove(x); // set.remove(x); } else map.put(x, map.get(x)-1); } // public long getFirst() { // return set.first(); // } // public long getLast() { // return set.last(); // } public int size() { return map.keySet().size(); } public void removeAll(int x) { map.remove(x); } public int getFreq(long x){ if (map.containsKey(x)) return map.get(x); return 0; } } public static void prime(int n){ int[] isPrime = new int[n+1]; Arrays.fill(isPrime, 1); for(long i = 2;i<=n;i++){ if (isPrime[(int)i] == 1){ for(long j = i*i;j<=n;j+=i){ isPrime[(int)j] = 0; } } } for(int j = 3;j<=n;j++){ if (isPrime[j] == 1){ primes.add(j); } } } public static int factorize(long n) { long prod = 1; int count = 0; while (n%2 == 0){ n >>= 1; count++; } if (count > 0 && count%2 == 1) prod *= 2L; for (long i : primes) { if (i*i > n) break; count = 0; while (n % i == 0) { count++; n = n / i; } if (count > 0 && count%2 == 1) prod *= i; } if (n > 2) prod *= n; return (int)prod; } 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
1497E2
CODEFORCES
import java.io.*; import java.util.*; public class CF1497E2 extends PrintWriter { CF1497E2() { super(System.out); } static class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; byte[] bb = new byte[1 << 15]; int i, n; byte getc() { if (i == n) { i = n = 0; try { n = in.read(bb); } catch (IOException e) {} } return i < n ? bb[i++] : 0; } int nextInt() { byte c = 0; while (c <= ' ') c = getc(); int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); } return a; } } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1497E2 o = new CF1497E2(); o.main(); o.flush(); } static final int A = 10000000, K = 20; int[] cc = new int[A + 1]; { boolean[] composite = new boolean[A + 1]; for (int a = 1; a <= A; a++) cc[a] = a; for (int a = 2; a <= A; a++) { if (composite[a]) continue; for (int b = a + a; b <= A; b += a) composite[b] = true; if (a <= A / a) { int a2 = a * a; for (int b = a2; b <= A; b += a2) { int c = cc[b]; while (c % a2 == 0) c /= a2; cc[b] = c; } } } } void main() { int[] pp = new int[A + 1]; Arrays.fill(pp, -1); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int[] aa = new int[n]; for (int i = 0; i < n; i++) aa[i] = cc[sc.nextInt()]; int[] mp = new int[k + 1]; int[] ip = new int[k + 1]; for (int i = 0; i < n; i++) { int a = aa[i]; for (int h = k; h >= 0; h--) { if (pp[a] >= ip[h]) { mp[h]++; ip[h] = i; } if (h > 0 && (mp[h - 1] < mp[h] || mp[h - 1] == mp[h] && ip[h - 1] > ip[h])) { mp[h] = mp[h - 1]; ip[h] = ip[h - 1]; } } pp[a] = i; } println(mp[k] + 1); for (int i = 0; i < n; i++) { int a = aa[i]; pp[a] = -1; } } } }
cubic
1497E2
CODEFORCES
import java.util.*; import java.io.*; public class cf1497_Div2_E2 { static int[] spf; public static int factor(int n) { int val = 1; while (n > 1) { int cnt = 0; int p = spf[n]; while (n % p == 0) { cnt++; n /= p; } if (cnt % 2 == 1) val *= p; } return val; } public static void main(String args[]) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); int max = (int)(1e7) + 1; boolean[] prime = new boolean[max + 1]; Arrays.fill(prime, true); prime[0] = prime[1] = false; spf = new int[max]; for (int i = 2; i < max; i++) spf[i] = i; for (int i = 2; i * i < max; i++) { if (prime[i]) { spf[i] = i; for (int j = i * i; j < max; j += i) { prime[j] = false; spf[j] = i; } } } int[] cnts = new int[max]; for ( ; t > 0; t--) { int n = in.nextInt(); int k = in.nextInt(); int[] vals = new int[n]; for (int i = 0; i < n; i++) vals[i] = factor(in.nextInt()); // left[i][x] = l where al ... ai such that in x moves it is valid subsequence int[][] left = new int[n + 1][k + 1]; // x y z w a b c for (int x = 0; x <= k; x++) { int l = n; int now = 0; for (int i = n - 1; i >= 0; i--) { while (l - 1 >= 0 && now + ((cnts[vals[l - 1]] > 0) ? 1 : 0) <= x) { l--; now += ((cnts[vals[l]] > 0) ? 1 : 0); // System.out.println(now); cnts[vals[l]]++; } // System.out.println(i + " " + x + " " + l + " " + now); left[i][x] = l; if (cnts[vals[i]] > 1) now--; cnts[vals[i]]--; } } // for (int[] x: left) // System.out.println(Arrays.toString(x)); int oo = (int)(1e9); int[][] dp = new int[n + 1][k + 1]; for (int i = 1; i <= n; i++) Arrays.fill(dp[i], oo); for (int i = 1; i <= n; i++) { for (int j = 0; j <= k; j++) { if (j > 0) dp[i][j] = dp[i][j - 1]; for (int x = 0; x <= j; x++) { int l = left[i - 1][x]; dp[i][j] = Math.min(dp[i][j], dp[l][j - x] + 1); } } } int min = Integer.MAX_VALUE; for (int i = 0; i <= k; i++) { min = Math.min(min, dp[n][i]); } out.println(min); } out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = new StringTokenizer(""); } public String next() throws IOException { if(st.hasMoreTokens()) return st.nextToken(); else st = new StringTokenizer(br.readLine()); return next(); } 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()); } //$ } }
cubic
1497E2
CODEFORCES
//stan hu tao //join nct ridin by first year culture reps 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 x1497E { static final int MAX = 10000000; public static void main(String hi[]) throws Exception { int[] prime = new int[MAX+1]; for(int d=2; d <= MAX; d++) if(prime[d] == 0) for(int v=d; v <= MAX; v+=d) if(prime[v] == 0) prime[v] = d; FastScanner infile = new FastScanner(); int T = infile.nextInt(); StringBuilder sb = new StringBuilder(); int[] freq = new int[MAX+1]; int[] ts = new int[MAX+1]; int time = 0; while(T-->0) { int N = infile.nextInt(); int K = infile.nextInt(); int[] arr = infile.nextInts(N); for(int i=0; i < N; i++) { int key = 1; while(arr[i] > 1) { int p = prime[arr[i]]; int cnt = 0; while(arr[i]%p == 0) { arr[i] /= p; cnt ^= 1; } if(cnt == 1) key *= p; } arr[i] = key; } int[][] right = new int[N][K+1]; for(int k=0; k <= K; k++) { int dex = 0; int cnt = 0; for(int i=0; i < N; i++) { while(dex < N && cnt <= k) { if(ts[arr[dex]] == time && freq[arr[dex]] >= 1 && cnt+1 > k) break; if(ts[arr[dex]] == time && freq[arr[dex]] >= 1) cnt++; if(ts[arr[dex]] < time) { ts[arr[dex]] = time; freq[arr[dex]] = 0; } freq[arr[dex]]++; dex++; } right[i][k] = dex; if(freq[arr[i]] >= 2) cnt--; freq[arr[i]]--; } time++; } int[][] dp = new int[N+1][K+1]; for(int i=1; i <= N; i++) Arrays.fill(dp[i], N); for(int i=0; i < N; i++) for(int a=0; a <= K; a++) { dp[i+1][a] = min(dp[i+1][a], dp[i][a]+1); for(int b=0; b <= K-a; b++) dp[right[i][b]][a+b] = min(dp[right[i][b]][a+b], dp[i][a]+1); } int res = dp[N][0]; for(int k=1; k <= K; k++) res = min(res, dp[N][k]); sb.append(res+"\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
1497E2
CODEFORCES
import java.util.*; import java.io.*; public class Solve{ public static void main(String[] args) throws Exception{ Scanner sc=new Scanner(System.in); PrintWriter out =new PrintWriter(System.out); int size=(int)1e7+1; int[] pr=new int[size]; for(int i=0;i<size;i++){ pr[i]=i; } for(int i=2;i*i<size;i++){ if(pr[i]==i){int val=i*i; for(int j=val;j<=size;j+=val){ pr[j]=j/val; } } } int t=sc.nextInt(); int[] dp=new int[size]; Arrays.fill(dp,-1); while(t-->0){ int n=sc.nextInt(); int k=sc.nextInt(); int[] ar=new int[n]; for(int i=0;i<n;i++){ int a=sc.nextInt(); ar[i]=pr[a]; } int[] ans=new int[k+1]; int[] ind=new int[k+1]; for(int i=0;i<n;i++){ for(int h=k;h>=0;h--){ if(dp[ar[i]]>=ind[h]){ ans[h]++; ind[h]=i; } if(h>0 && (ans[h-1]<ans[h] ||(ans[h-1]==ans[h] && ind[h-1]>ind[h]))) { ans[h]=ans[h-1]; ind[h]=ind[h-1]; } } dp[ar[i]]=i; } out.println(ans[k]+1); for(int i=0;i<n;i++)dp[ar[i]]=-1; } out.close(); } }
cubic
1497E2
CODEFORCES
/** * author: derrick20 * created: 3/19/21 11:57 PM */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class E2_SquareFreeDivision2 { static FastScanner sc = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { // generate(); int MAX = (int) 1e7; int[] spf = new int[MAX + 1]; for (int i = 2; i <= MAX; i++) { if (spf[i] == 0) { spf[i] = i; for (int j = i + i; j <= MAX; j += i) { if (spf[j] == 0) { spf[j] = i; } } } } int[] freq = new int[MAX + 1]; int T = sc.nextInt(); while (T-->0) { int N = sc.nextInt(); int K = sc.nextInt(); int[] a = new int[N + 1]; for (int i = 1; i <= N; i++) { a[i] = sc.nextInt(); int canonical = 1; while (a[i] > 1) { int factor = spf[a[i]]; int parity = 0; while (a[i] % factor == 0) { a[i] /= factor; parity ^= 1; } if (parity == 1) { canonical *= factor; } } a[i] = canonical; } int[][] transition = new int[K + 1][N + 1]; // HashMap<Integer, Integer> freq = new HashMap<>(); for (int k = 0; k <= K; k++) { int l = N + 1; int duplicates = 0; for (int r = N; r >= 1; r--) { while (l - 1 >= 1) { int nextDuplicates = duplicates; if (freq[a[l - 1]] >= 1) { nextDuplicates++; } if (nextDuplicates <= k) { duplicates = nextDuplicates; freq[a[l - 1]]++; l--; } else { break; } } transition[k][r] = l; if (--freq[a[r]] >= 1) { duplicates--; } } } int[][] dp = new int[K + 1][N + 1]; int oo = (int) 1e9; for (int[] row : dp) { Arrays.fill(row, oo); } for (int k = 0; k <= K; k++) { dp[k][0] = 0; } for (int r = 1; r <= N; r++) { for (int k = 0; k <= K; k++) { for (int delta = 0; delta <= k; delta++) { dp[k][r] = min(dp[k][r], dp[k - delta][transition[delta][r] - 1] + 1); } } } out.println(dp[K][N]); } out.close(); } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } 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++]; } int nextInt() { return (int) nextLong(); } 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; } double nextDouble() { boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } double cur = nextLong(); if (c != '.') { return neg ? -cur : cur; } else { double frac = nextLong() / cnt; return neg ? -cur - frac : cur + frac; } } String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } }
cubic
1497E2
CODEFORCES
import java.io.*; import java.util.*; public class Main { static final int primeCount = 452; static final int[] prime = new int[primeCount]; static void build_prime() { boolean[] notPrime = new boolean[3200]; for (int i = 2; i < 3200; i++) { if (notPrime[i]) continue; for (int j = i * i; j < 3200; j += i) { notPrime[j] = true; } } int count = 0; for (int i = 2; i < 3200; i++) { if (notPrime[i]) continue; prime[count++] = i; } } private static void run(Reader in, PrintWriter out) throws IOException { int n = in.nextInt(); int m = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = getReal(in.nextInt()); } int[] pre = new int[n]; for (int i = 0; i < n; i++) pre[i] = -1; TreeMap<Integer, Integer> exist = new TreeMap<>(); for (int i = 0; i < n; i++) { Integer result = exist.get(a[i]); if (result != null) { pre[i] = result; } exist.put(a[i], i); } int[][] left = new int[m + 1][n]; for (int i = 0; i <= m; i++) { int start = 0; PriorityQueue<Integer> inSame = new PriorityQueue<>(); for (int j = 0; j < n; j++) { if (pre[j] >= start) { inSame.add(pre[j]); if (inSame.size() > i) { start = inSame.poll() + 1; } } left[i][j] = start; } } int[][] dp = new int[n][m + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j <= m; j++) { if (j == 0) dp[i][0] = Integer.MAX_VALUE; else dp[i][j] = dp[i][j - 1]; for (int k = 0; k <= j; k++) { if (left[k][i] == 0) { dp[i][j] = 1; } else { dp[i][j] = Math.min(dp[i][j], dp[left[k][i] - 1][j - k] + 1); } } } } out.println(dp[n - 1][m]); } static int getReal(int x) { int result = 1; for (int i = 0; i < primeCount; i++) { if (x % prime[i] == 0) { int count = 0; while (x % prime[i] == 0) { count++; x /= prime[i]; } if (count % 2 == 1) { result *= prime[i]; } } } result *= x; return result; } public static void main(String[] args) throws IOException { Reader in = new Reader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); build_prime(); int t = in.nextInt(); for (int i = 0; i < t; i++) { run(in, out); } out.flush(); in.close(); out.close(); } static class Reader { BufferedReader reader; StringTokenizer st; Reader(InputStreamReader stream) { reader = new BufferedReader(stream, 32768); st = null; } void close() throws IOException { reader.close(); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } String nextLine() throws IOException { return reader.readLine(); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
cubic
1497E2
CODEFORCES
import java.io.*; import java.util.*; public class Main { static final int primeCount = 452; static final int[] prime = new int[primeCount]; static void build_prime() { boolean[] notPrime = new boolean[3200]; for (int i = 2; i < 3200; i++) { if (notPrime[i]) continue; for (int j = i * i; j < 3200; j += i) { notPrime[j] = true; } } int count = 0; for (int i = 2; i < 3200; i++) { if (notPrime[i]) continue; prime[count++] = i; } } private static void run(Reader in, PrintWriter out) throws IOException { int n = in.nextInt(); int m = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = getReal(in.nextInt()); } int[] pre = new int[n]; for (int i = 0; i < n; i++) pre[i] = -1; TreeMap<Integer, Integer> exist = new TreeMap<>(); for (int i = 0; i < n; i++) { Integer result = exist.get(a[i]); if (result != null) { pre[i] = result; } exist.put(a[i], i); } int[][] left = new int[m + 1][n]; for (int i = 0; i <= m; i++) { int start = 0; PriorityQueue<Integer> inSame = new PriorityQueue<>(); for (int j = 0; j < n; j++) { if (pre[j] >= start) { inSame.add(pre[j]); if (inSame.size() > i) { start = inSame.poll() + 1; } } left[i][j] = start; } } int[][] dp = new int[n][m + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j <= m; j++) { dp[i][j] = Integer.MAX_VALUE; } for (int j = 0; j <= m; j++) { for (int k = 0; k <= j; k++) { if (left[k][i] == 0) { dp[i][j] = 1; } else { dp[i][j] = Math.min(dp[i][j], dp[left[k][i] - 1][j - k] + 1); } } } } out.println(dp[n - 1][m]); } static int getReal(int x) { int result = 1; for (int i = 0; i < primeCount; i++) { if (x % prime[i] == 0) { int count = 0; while (x % prime[i] == 0) { count++; x /= prime[i]; } if (count % 2 == 1) { result *= prime[i]; } } } result *= x; return result; } public static void main(String[] args) throws IOException { Reader in = new Reader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); build_prime(); int t = in.nextInt(); for (int i = 0; i < t; i++) { run(in, out); } out.flush(); in.close(); out.close(); } static class Reader { BufferedReader reader; StringTokenizer st; Reader(InputStreamReader stream) { reader = new BufferedReader(stream, 32768); st = null; } void close() throws IOException { reader.close(); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } String nextLine() throws IOException { return reader.readLine(); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
cubic
1497E2
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.stream.IntStream; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.TreeSet; 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) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); SquareFreeDivisionHardVersion solver = new SquareFreeDivisionHardVersion(); solver.solve(1, in, out); out.close(); } static class SquareFreeDivisionHardVersion { static final int MAX = 10000001; public void solve(int testNumber, InputReader in, OutputWriter out) { int t = in.nextInt(); int[] d = PrimesAndDivisors.generateDivisors(MAX); int[] reduced = new int[MAX]; for (int i = 1; i < MAX; i++) { int val = i; reduced[i] = 1; while (val != 1) { int prime = d[val], exponent = 0; while (val % prime == 0) { val /= prime; exponent ^= 1; } if (exponent > 0) reduced[i] *= prime; } } int counter = 0; int[] seen = new int[MAX]; for (int jjjj = 0; jjjj < t; jjjj++) { int n = in.nextInt(), k = in.nextInt(); int[] a = in.readIntArray(n); for (int x : a) seen[reduced[x]] = -1; int[][] dp = new int[n + 1][k + 1]; TreeSet<Integer> ts = new TreeSet<>(); int num = 0; for (int i = 0; i < n; i++) { int R = reduced[a[i]]; if (seen[R] != -1) { ts.add(-seen[R]); if (ts.size() > k + 1) ts.remove(ts.last()); num++; } Arrays.fill(dp[i], n + 1); for (int j = num; j <= k; j++) dp[i][j] = 1; seen[R] = i; int u = 0; for (int r : ts) { for (int j = u; j <= k; j++) dp[i][j] = Integer.min(dp[i][j], dp[-r][j - u] + 1); u++; } // System.out.println(i + " " + Arrays.toString(dp[i])); // System.out.println("Treeset : " + ts); } out.println(dp[n - 1][k]); } } } 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[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } 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 int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class PrimesAndDivisors { public static int[] generateDivisors(int n) { int[] divisors = IntStream.range(0, n + 1).toArray(); for (int i = 2; i * i <= n; i++) if (divisors[i] == i) for (int j = i * i; j <= n; j += i) divisors[j] = i; return divisors; } } 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 println(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.print('\n'); } public void close() { writer.close(); } } }
cubic
1497E2
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class SolutionE extends Thread { 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; } } private static final FastReader scanner = new FastReader(); private static final PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { new Thread(null, new SolutionE(), "Main", 1 << 26).start(); } static final int[] primeFactors = getSmallestPrimeFactorInIntervalInclusive(10_000_000); public void run() { int t = scanner.nextInt(); for (int i = 0; i < t; i++) { solve(); } out.close(); } //runs in roughly O(maxN * lg^2(maxN))) public static int[] getSmallestPrimeFactorInIntervalInclusive(int maxN) { int[] result = new int[maxN + 1]; result[1] = 1; for (int i = 2; i <= maxN; i++) { if (result[i] == 0) { for (int j = i; j <= maxN; j += i) { result[j] = (result[j / i] % i == 0) ? (result[j/i]/i) : (result[j/i]*i); } } } return result; } private static void solve() { int n = scanner.nextInt(); int k = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = primeFactors[scanner.nextInt()]; } Map<Integer, Integer> lastSeenIndex = new HashMap<>(); int[] revertPointers = new int[n]; for (int i = 0; i < n; i++) { if (lastSeenIndex.get(a[i]) != null) { revertPointers[i] = lastSeenIndex.get(a[i]); } else { revertPointers[i] = -1; } lastSeenIndex.put(a[i], i); } int[][] maxSegment = new int[n][k+1]; for (int j = 0; j <= k; j++) { int pointerLeft = 0; int pointerRight = 0; boolean[] changed = new boolean[n]; int amountChanged = 0; while (pointerLeft < n) { if (pointerRight < n && revertPointers[pointerRight] < pointerLeft) { pointerRight++; } else if (pointerRight < n && revertPointers[pointerRight] >= pointerLeft && amountChanged < j) { changed[revertPointers[pointerRight]] = true; pointerRight++; amountChanged++; } else { if (changed[pointerLeft]) { amountChanged--; } maxSegment[pointerLeft][j] = pointerRight; pointerLeft++; } } } int[][] dp = new int[n+1][k+1]; for (int j = 0; j <= k; j++) { dp[n][j] = 0; } for (int i = n - 1; i >= 0; i--) { for (int j = 0; j <= k; j++) { dp[i][j] = n + 1; for (int x = 0; x <= j; x++) { int nextJumpTo = maxSegment[i][x]; dp[i][j] = Math.min(dp[i][j], dp[nextJumpTo][j - x] + 1); } } } out.println(dp[0][k]); } //REMINDERS: //- CHECK FOR INTEGER-OVERFLOW BEFORE SUBMITTING //- CAN U BRUTEFORCE OVER SOMETHING, TO MAKE IT EASIER TO CALCULATE THE SOLUTION }
cubic
1497E2
CODEFORCES
// Don't place your source in a package import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner {//scanner from SecondThread BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(System.out); int primes[]=new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999}; int T=Int(); for(int t=0;t<T;t++){ int n=Int(); int k=Int(); int A[]=new int[n]; for(int i=0;i<n;i++){ A[i]=Int(); } Sol sol=new Sol(); sol.solution(out,A,k,primes); } out.flush(); } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Sol{ int dp[][]; public void solution(PrintWriter out,int A[],int K,int primes[]){ int n=A.length; int id=0; int dp[][]=new int[n+1][K+1]; for(int i=0;i<dp.length;i++){ Arrays.fill(dp[i],n); } //pre-processing Map<String,Integer>f=new HashMap<>(); for(int i=0;i<A.length;i++){ String h=hash(A[i],primes); if(!f.containsKey(h)){ f.put(h,id); A[i]=id; id++; } else{ A[i]=f.get(h); } } int dis[][]=new int[A.length][K+1]; for(int k=0;k<=K;k++){//how far it can go int r=n-1; Map<Integer,Integer>ff=new HashMap<>(); for(int i=n-1;i>=0;i--){ put(ff,A[i]); while(ff.size()+k<(r-i+1)){ remove(ff,A[r]); dis[r][k]=i+1; r--; } } } for(int i=0;i<n;i++){ for(int j=0;j<=K;j++){ if(j>=i+1){ dp[i][j]=1; continue; } for(int k=0;k<=j;k++){//take k change int reach=dis[i][k];//the maximum place I can reach if(reach==0)dp[i][j]=1; else dp[i][j]=Math.min(dp[i][j],1+dp[reach-1][j-k]); } } } out.println(dp[n-1][K]); } public void put(Map<Integer,Integer>f,int key){ if(!f.containsKey(key))f.put(key,1); else f.put(key,f.get(key)+1); } public void remove(Map<Integer,Integer>f,int key){ f.put(key,f.get(key)-1); if(f.get(key)==0)f.remove(key); } public String hash(int n,int primes[]){ StringBuilder str=new StringBuilder("a,"); for(int i:primes){ if(i*i>n)break; int cnt=0; while(n%i==0){ n/=i; cnt++; } cnt%=2; if(cnt!=0)str.append(i+","); } if(n!=1)str.append(n+","); return str.toString(); } }
cubic
1497E2
CODEFORCES
/** * author: derrick20 * created: 3/19/21 11:57 PM */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class E2_SquareFreeDivision2 { static FastScanner sc = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { // generate(); int T = sc.nextInt(); int MAX = (int) 1e7; int[] canonical = new int[MAX + 1]; canonical[1] = 1; for (int factor = 2; factor <= MAX; factor++) { if (canonical[factor] == 0) { for (int mult = factor; mult <= MAX; mult += factor) { int prev = canonical[mult / factor]; if (prev % factor == 0) { canonical[mult] = prev / factor; } else { canonical[mult] = prev * factor; } } } } // System.out.println(Arrays.toString(canonical)); int[] freq = new int[MAX + 1]; while (T-->0) { int N = sc.nextInt(); int K = sc.nextInt(); int[] a = new int[N + 1]; for (int i = 1; i <= N; i++) { a[i] = canonical[sc.nextInt()]; } int[][] transition = new int[K + 1][N + 1]; // HashMap<Integer, Integer> freq = new HashMap<>(); for (int k = 0; k <= K; k++) { int l = N + 1; int duplicates = 0; for (int r = N; r >= 1; r--) { while (l - 1 >= 1) { int nextDuplicates = duplicates; if (freq[a[l - 1]] >= 1) { nextDuplicates++; } if (nextDuplicates <= k) { duplicates = nextDuplicates; freq[a[l - 1]]++; l--; } else { break; } } transition[k][r] = l; if (--freq[a[r]] >= 1) { duplicates--; } } } int[][] dp = new int[K + 1][N + 1]; int oo = (int) 1e9; for (int[] row : dp) { Arrays.fill(row, oo); } for (int k = 0; k <= K; k++) { dp[k][0] = 0; } for (int r = 1; r <= N; r++) { for (int k = 0; k <= K; k++) { for (int delta = 0; delta <= k; delta++) { dp[k][r] = min(dp[k][r], dp[k - delta][transition[delta][r] - 1] + 1); } } } out.println(dp[K][N]); } out.close(); } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } 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++]; } int nextInt() { return (int) nextLong(); } 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; } double nextDouble() { boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } double cur = nextLong(); if (c != '.') { return neg ? -cur : cur; } else { double frac = nextLong() / cnt; return neg ? -cur - frac : cur + frac; } } String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } }
cubic
1497E2
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; import java.text.*; public class Main { static PrintWriter out; static Reader in; public static void main(String[] args) throws IOException { input_output(); Main solver = new Main(); solver.solve(); out.close(); out.flush(); } static long INF = (long)1e18; static int MAXN = (int)1e7+5; static int mod = 998_244_353; static int n, m, q, t; static double pi = Math.PI; void solve() throws IOException{ t = in.nextInt(); int[] div = new int[MAXN]; Arrays.fill(div, 1); for (int i = 2; i < MAXN; i++) { if (div[i] == 1) { for (int j = i; j < MAXN; j+=i) { div[j] = i; } } } while (t --> 0) { n = in.nextInt(); int k = in.nextInt(); int[] arr = new int[n+1]; for (int i = 1; i <= n; i++) { arr[i] = in.nextInt(); int tmp = arr[i], newn = 1; while (div[arr[i]] != 1) { int elm = div[arr[i]], cnt = 0; while (div[arr[i]] == elm) { cnt++; arr[i] /= elm; } if (cnt%2 == 1) newn *= elm; } newn *= arr[i]; arr[i] = newn; } int[] close = new int[n+1]; List<Node> list = new ArrayList<>(); for (int i = 1; i <= n; i++) list.add(new Node(arr[i], i)); Collections.sort(list); for (int i = 0; i < n; i++) { if (i == n-1 || list.get(i+1).val != list.get(i).val) { close[list.get(i).idx] = -1; } else { close[list.get(i).idx] = list.get(i+1).idx; } } int[][] next = new int[n+1][k+1]; List<Integer> upd = new ArrayList<>(); List<Integer> nupd = new ArrayList<>(); for (int i = 0; i <= k; i++) next[n][i] = n; for (int i = n-1; i >= 1; i--) { nupd.clear(); if (close[i] == -1) { for (int j = 0; j <= k; j++) next[i][j] = next[i+1][j]; } else { int tmp = close[i]-1, cnt = 0; if (upd.size() == 0 || tmp < upd.get(0)) { nupd.add(tmp); tmp = -1; } for (int j = 0; j < upd.size(); j++) { if (nupd.size() < k+1 && tmp != -1 && tmp < upd.get(j)) { nupd.add(tmp); tmp = -1; } if (nupd.size() < k+1) nupd.add(upd.get(j)); } if (tmp != -1 && nupd.size() < k+1) nupd.add(tmp); for (int j = 0; j < nupd.size(); j++) next[i][j] = nupd.get(j); for (int j = nupd.size(); j <= k; j++) next[i][j] = n; upd.clear(); for (int j = 0; j < nupd.size(); j++) upd.add(nupd.get(j)); } } int[][] dp = new int[n+1][k+1]; for (int i = 1; i <= n; i++) for (int j = 0; j <= k; j++) dp[i][j] = n; for (int i = 0; i < n; i++) { for (int cur = 0; cur <= k; cur++) { for (int ncur = cur; ncur <= k; ncur++) { dp[next[i+1][ncur-cur]][ncur] = Math.min(dp[next[i+1][ncur-cur]][ncur], dp[i][cur]+1); } } } int ans = n; for (int i = 0; i <= k; i++) ans = Math.min(ans, dp[n][i]); out.println(ans); } } //<> static class Node implements Comparable<Node> { int val, idx; Node (int val, int idx) { this.val = val; this.idx = idx; } public int compareTo(Node o) { if (this.val != o.val) return this.val - o.val; return this.idx - o.idx; } } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static void input_output() throws IOException { File f = new File("in.txt"); if(f.exists() && !f.isDirectory()) { in = new Reader(new FileInputStream("in.txt")); } else in = new Reader(); f = new File("out.txt"); if(f.exists() && !f.isDirectory()) { out = new PrintWriter(new File("out.txt")); } else out = new PrintWriter(System.out); } }
cubic
1497E2
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.util.*; import java.math.*; /* 50 873 838 288 87 889 364 720 410 565 651 577 356 740 99 549 592 994 385 777 435 486 118 887 440 749 533 356 790 413 681 267 496 475 317 88 660 374 186 61 437 729 860 880 538 277 301 667 180 60 393 6 2 2 3 3 5 5 4 2 2 3 3 */ public class C429 { static InputStream is; static int[] counts; static int[] sufsum; static long mod = (long)(1e9+7); static long[][] choose; static long[][] memo; public static void main(String[] args) throws IOException { is = System.in; int n = ni(); int[] a = na(n); long[] fact = new long[n+2]; fact[0] = 1; for (int i = 1; i < fact.length; i++) { fact[i] = (fact[i-1]*i)%mod; } HashMap<Integer,ArrayList<Integer>> hm = new HashMap<>(); for (int i = 0; i < a.length; i++) { int cp = a[i]; int sfree = 1; for(int p = 2; p*p <= a[i] && cp > 1; p++){ int count = 0; while(cp % p == 0){ cp /= p; count++; } if(count % 2 == 1) sfree *= p; } if(cp != 1) sfree *= cp; if(!hm.containsKey(sfree)) hm.put(sfree, new ArrayList<Integer>()); hm.get(sfree).add(a[i]); } counts = new int[hm.size()]; int dex = 0; //System.out.println(hm); long bigmult = 1; for(Integer key : hm.keySet()){ ArrayList<Integer> list = hm.get(key); counts[dex++] = list.size(); bigmult = bigmult*fact[list.size()] % mod; // HashMap<Integer,Integer> dups = new HashMap<>(); // for(int x : list){ // if(!dups.containsKey(x)){ // dups.put(x, 0); // } // dups.put(x, dups.get(x)+1); // } // for (int k : dups.keySet()) { // int amount = dups.get(k); // long tomult = new BigInteger(fact[amount]+"").modInverse(new BigInteger(mod+"")).longValue(); // bigmult*= tomult; // bigmult %= mod; // } } Arrays.sort(counts); sufsum = new int[counts.length]; for(int i = counts.length-2; i >= 0; i--){ sufsum[i] = sufsum[i+1]+counts[i+1]; } choose = new long[2*n+3][2*n+3]; for(int i = 0; i < choose.length; i++){ choose[i][0] = 1; for(int j = 1; j <=i; j++){ choose[i][j] = (choose[i-1][j]+choose[i-1][j-1])%mod; } } memo = new long[counts.length][700]; for (int i = 0; i < memo.length; i++) { Arrays.fill(memo[i], -1); } //System.out.println("bigmult: " + bigmult); System.out.println((bigmult*dp(counts.length-2,counts[counts.length-1]-1))%mod); } static long dp(int dex, int need){ if(dex == -1){ if(need == 0) return 1; return 0; } //System.out.println("dex: " + dex + " need " + need); if(memo[dex][need] != -1) return memo[dex][need]; int numspots = sufsum[dex]+1; long ret = 0; int c = counts[dex]; for(int numdivs = 1; numdivs <= c; numdivs++) { long toadd = 0; for(int gotoneed =0; gotoneed <= need && gotoneed <= numdivs; gotoneed++) { long temp = choose[need][gotoneed]; temp *= choose[numspots-need][numdivs-gotoneed]; //System.out.println("dex: " + dex + " need: "+ need + " numdivs: " + numdivs + " c1: " + choose[need][gotoneed] + " c2 " + choose[numspots-need][numdivs-gotoneed]); temp %= mod; temp *= dp(dex-1,need-gotoneed+c-numdivs); temp %= mod; toadd += temp; toadd %= mod; } toadd *= choose[c-1][numdivs-1]; toadd %= mod; ret += toadd; ret %= mod; } //System.out.println("dex: " + dex + " need: "+ need + " ret: " + ret); return memo[dex][need]=ret; } private static byte[] inbuf = new byte[1024]; public static int lenbuf = 0, ptrbuf = 0; private static 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 static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double nd() { return Double.parseDouble(ns()); } private static char nc() { return (char)skip(); } private static 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 static 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 static 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 static int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private static int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static 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(); } } }
cubic
840_C. On the Bench
CODEFORCES
//package round429; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; // 203530 public class C { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); for(int i = 0;i < n;i++){ int v = a[i]; for(int j = 2;j*j <= v;j++){ while(v % (j*j) == 0){ v /= j*j; } } a[i] = v; } Arrays.sort(a); int[] f = new int[n]; int p = 0; for(int i= 0;i < n;i++){ if(i > 0 && a[i] != a[i-1]){ p++; } f[p]++; } f = Arrays.copyOf(f, p+1); int mod = 1000000007; int[][] fif = enumFIF(1000, mod); long[] res = countSameNeighborsSequence(f, fif, mod); long ans = res[0]; for(int v : f){ ans = ans * fif[0][v] % mod; } out.println(ans); } public static int[][] enumFIF(int n, int mod) { int[] f = new int[n + 1]; int[] invf = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; i++) { f[i] = (int) ((long) f[i - 1] * i % mod); } long a = f[n]; long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } invf[n] = (int) (p < 0 ? p + mod : p); for (int i = n - 1; i >= 0; i--) { invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod); } return new int[][] { f, invf }; } public static long[] countSameNeighborsSequence(int[] a, int[][] fif, int mod) { int all = 0; for(int v : a)all += v; int len = 0; long[] dp = new long[all+1]; dp[0] = 1; for(int v : a){ long[][] pre = new long[all+1][v+1]; for(int j = 0;j <= all;j++)pre[j][0] = dp[j]; for(int j = 0;j < v;j++){ for(int k = 0;k <= all;k++){ for(int L = j;L >= 0;L--){ if(pre[k][L] == 0)continue; int ca = 2*(j-L); int ab = len+j+1-k-ca-L; if(ab < 0)continue; if(k-1 >= 0){ pre[k-1][L] += pre[k][L]*k; // aca pre[k-1][L] %= mod; } if(L+1 <= v){ pre[k][L+1] += pre[k][L]*(ca+L); pre[k][L+1] %= mod; } pre[k][L] = pre[k][L]*ab%mod; } } } Arrays.fill(dp, 0); for(int k = 0;k <= all;k++){ for(int L = 0;L <= v && k+L <= all;L++){ dp[k+L] += pre[k][L]; } } for(int k = 0;k <= all;k++){ dp[k] %= mod; } // for(int k = 0;k <= all;k++){ // dp[k] = dp[k] % mod * fif[1][v] % mod; // } len += v; } long fifs = 1; for(int v : a)fifs = fifs * fif[1][v] % mod; for(int k = 0;k <= all;k++)dp[k] = dp[k] * fifs % mod; return dp; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new C().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.*; import java.util.*; public class C { int removeSq(int x) { for (int i = 2; i * i <= x; i++) { while (x % (i * i) == 0) { x /= i * i; } } return x; } void submit() { int n = nextInt(); HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { int x = removeSq(nextInt()); map.merge(x, 1, Integer::sum); } int[] a = new int[map.size()]; int ptr = 0; for (Integer x : map.values()) { a[ptr++] = x; } int ret = go(a); for (int x : a) { ret = (int)((long)ret * fact[x] % P); } out.println(ret); } int go(int[] a) { int[] dp = new int[a[0]]; dp[a[0] - 1] = 1; int places = a[0] + 1; int toInsert = 0; for (int x : a) { toInsert += x; } toInsert -= a[0]; for (int i =1; i < a.length; i++) { int here = a[i]; if (here == 0) { continue; } int[] nxt = new int[dp.length + here]; for (int wasSame = 0; wasSame < dp.length; wasSame++) { if (wasSame > toInsert) { continue; } if (dp[wasSame] == 0) { continue; } int wasDiff = places - wasSame; for (int runsSame = 0; runsSame <= wasSame && runsSame <= here; runsSame++) { for (int runsDiff = 0; runsDiff <= wasDiff && runsSame + runsDiff <= here; runsDiff++) { if (runsSame + runsDiff == 0) { continue; } int delta = (int) ((long) dp[wasSame] * ways[wasSame][runsSame] % P * ways[wasDiff][runsDiff] % P * ways[here - 1][runsSame + runsDiff - 1] % P); if (delta == 0) { continue; } int nxtIdx = (wasSame - runsSame) + (here - runsSame - runsDiff); nxt[nxtIdx] += delta; if (nxt[nxtIdx] >= P) { nxt[nxtIdx] -= P; } } } } dp = nxt; places += here; toInsert -= here; } // System.err.println(Arrays.toString(a) + " " + idx); // System.err.println(Arrays.toString(dp)); return dp[0]; } int[][] ways; int[] fact; static final int N = 350; static final int P = 1_000_000_007; void preCalc() { ways = new int[N][]; for (int i = 0; i < N; i++) { ways[i] = new int[i + 1]; ways[i][0] = ways[i][i] = 1; for (int j = 1; j < i; j++) { ways[i][j] = ways[i - 1][j] + ways[i - 1][j - 1]; if (ways[i][j] >= P) { ways[i][j] -= P; } } } fact = new int[N]; fact[0] = 1; for (int i = 1; i < N; i++) { fact[i] = (int)((long)fact[i - 1] * i % P); } } void stress() { } void test() { } C() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); preCalc(); submit(); //stress(); //test(); out.close(); } static final Random rng = new Random(); static int rand(int l, int r) { return l + rng.nextInt(r - l + 1); } public static void main(String[] args) throws IOException { new C(); } BufferedReader br; PrintWriter out; StringTokenizer st; String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { final int MOD = (int) (1e9 + 7); long[][] C; long[] fact; public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); precalc(n); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); a[i] = removeSquares(a[i]); } int[] g = getGroupSizes(a); long ans = solve(g); for (int x : g) { ans = ans * fact[x] % MOD; } out.println(ans); } private long solve(int[] a) { // For a description, see http://petr-mitrichev.blogspot.com/2017/07/a-week7.html long[] d = new long[1]; d[0] = 1; int totalPositions = 1; for (int x : a) { long[] nd = new long[d.length + x + 1]; for (int s = 0; s < d.length; s++) { if (d[s] == 0) { continue; } for (int m = 1; m <= x; m++) { for (int p = 0; p <= s && p <= m; p++) { long cur = d[s]; cur = cur * C[s][p] % MOD; cur = cur * C[totalPositions - s][m - p] % MOD; cur = cur * f(x, m) % MOD; int ns = s + x - m - p; nd[ns] += cur; if (nd[ns] >= MOD) { nd[ns] -= MOD; } } } } totalPositions += x; d = nd; } return d[0]; } private long f(int n, int k) { if (n < k) { return 0; } n -= k; return C[n + k - 1][k - 1]; } private void precalc(int n) { fact = new long[n + 1]; fact[0] = 1; for (int i = 1; i < fact.length; i++) { fact[i] = i * fact[i - 1] % MOD; } C = new long[1000][1000]; C[0][0] = 1; for (int i = 1; i < C.length; i++) { C[i][0] = 1; for (int j = 1; j < C.length; j++) { C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; if (C[i][j] >= MOD) { C[i][j] -= MOD; } } } } private int[] getGroupSizes(int[] a) { Arrays.sort(a); List<Integer> res = new ArrayList<>(); for (int i = 0; i < a.length; ) { int j = i; while (j < a.length && a[i] == a[j]) { ++j; } res.add(j - i); i = j; } int[] r = new int[res.size()]; for (int i = 0; i < r.length; i++) { r[i] = res.get(i); } return r; } private int removeSquares(int n) { int res = 1; for (int d = 2; d * d <= n; d++) { if (n % d == 0) { int cur = 0; while (n % d == 0) { n /= d; ++cur; } if (cur % 2 == 1) { res *= d; } } } if (n > 1) { res *= n; } return res; } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class Div1_429C { static final long MOD = 1_000_000_007; static long[] fact = new long[305]; static long[] iFact = new long[305]; static final long I304 = 904487323; public static void main(String[] args) throws IOException { fact[0] = 1; for (int i = 1; i < 305; i++) { fact[i] = fact[i - 1] * i % MOD; } iFact[304] = I304; for (int i = 303; i >= 0; i--) { iFact[i] = iFact[i + 1] * (i + 1) % MOD; } BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int len = Integer.parseInt(reader.readLine()); long[] groups = new long[len + 1]; int[] gSizes = new int[len + 1]; int nG = 0; StringTokenizer inputData = new StringTokenizer(reader.readLine()); iLoop: for (int i = 0; i < len; i++) { long nxt = Integer.parseInt(inputData.nextToken()); for (int j = 1; j <= nG; j++) { if (isSquare(nxt * groups[j])) { gSizes[j]++; continue iLoop; } } groups[++nG] = nxt; gSizes[nG] = 1; } long[][] dp = new long[nG + 1][len]; dp[0][0] = 1; int fTotal = 0; for (int fG = 0; fG < nG; fG++) { for (int fB = 0; fB < len; fB++) { if (dp[fG][fB] == 0) { continue; } int nGSize = gSizes[fG + 1]; for (int nS = 1; nS <= Math.min(nGSize, fTotal + 1); nS++) { for (int nBR = 0; nBR <= Math.min(fB, nS); nBR++) { long nW = dp[fG][fB] * fact[nGSize] % MOD * comb(nGSize - 1, nS - 1) % MOD * comb(fB, nBR) % MOD * comb(fTotal + 1 - fB, nS - nBR) % MOD; dp[fG + 1][fB - nBR + nGSize - nS] = (dp[fG + 1][fB - nBR + nGSize - nS] + nW) % MOD; } } } fTotal += gSizes[fG + 1]; } printer.println(dp[nG][0]); printer.close(); } static long comb(int a, int b) { if(b > a) { return 0; } return fact[a] * iFact[a - b] % MOD * iFact[b] % MOD; } static boolean isSquare(long inp) { long sqrt = (long) Math.sqrt(inp); return inp == sqrt * sqrt; } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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 int mod = 1000000007; public int MAXN = 333; public int[][] w1; public long[] fact; public long[] ifact; public void solve(int testNumber, InputReader in, OutputWriter out) { long[][] e = Factorials.getFIF(MAXN, mod); fact = e[0]; ifact = e[1]; w1 = new int[MAXN][MAXN]; w1[0][0] = 1; for (int i = 1; i < MAXN; i++) { for (int j = 1; j < MAXN; j++) { for (int k = 1; k <= i; k++) { w1[i][j] += w1[i - k][j - 1]; if (w1[i][j] >= mod) w1[i][j] -= mod; } } } int n = in.nextInt(); int[] arr = in.readIntArray(n); boolean[] marked = new boolean[n]; int[] fs = new int[n]; int fidx = 0; for (int i = 0; i < n; i++) { if (marked[i]) continue; int count = 0; for (int j = 0; j < n; j++) { if (isSquare(1L * arr[i] * arr[j])) { if (marked[j]) System.exit(1); marked[j] = true; count++; } } fs[fidx++] = count; } fs = Arrays.copyOf(fs, fidx); long x = 1; for (int j : fs) x = x * fact[j] % mod; x = x * solve(fs) % mod; out.println(x); } public boolean isSquare(long x) { long d = (long) (Math.sqrt(x)); while (d * d < x) d++; while (d * d > x) d--; return d * d == x; } public int solve(int[] freq) { int d = AUtils.sum(freq); int b = AUtils.max(freq); if (d == 0) return 1; if (b + b - 1 > d) return 0; int[] dp = new int[1]; dp[0] = 1; for (int j = 0; j < freq.length; j++) { if (freq[j] == 0) continue; int[] nxt = new int[dp.length + freq[j]]; for (int pgr = 0; pgr < dp.length; pgr++) { for (int cgr = 1; cgr <= freq[j]; cgr++) { nxt[pgr + cgr] += 1L * dp[pgr] * w1[freq[j]][cgr] % mod * ifact[cgr] % mod; if (nxt[pgr + cgr] >= mod) nxt[pgr + cgr] -= mod; } } dp = nxt; } int res = 0; for (int i = 0; i < dp.length; i++) { long x = 1L * dp[i] * fact[i] % mod; if ((d - i) % 2 == 0) res += x; else res -= x; if (res >= mod) res -= mod; if (res < 0) res += mod; } return res; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int tokens) { int[] ret = new int[tokens]; for (int i = 0; i < tokens; i++) { ret[i] = nextInt(); } return ret; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class AUtils { public static int max(int[] arr) { int res = arr[0]; for (int x : arr) res = Math.max(res, x); return res; } public static int sum(int[] arr) { int sum = 0; for (int x : arr) { sum += x; } return sum; } } static class Factorials { public static long[][] getFIF(int max, int mod) { long[] fact = new long[max]; long[] ifact = new long[max]; long[] inv = new long[max]; inv[1] = 1; for (int i = 2; i < max; i++) { inv[i] = (mod - mod / i) * inv[mod % i] % mod; } fact[0] = 1; ifact[0] = 1; for (int i = 1; i < max; i++) { fact[i] = fact[i - 1] * i % mod; ifact[i] = ifact[i - 1] * inv[i] % mod; } return new long[][]{fact, ifact, inv}; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; 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 << 27); 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); COnTheBench solver = new COnTheBench(); solver.solve(1, in, out); out.close(); } } static class COnTheBench { Modular mod = new Modular(1e9 + 7); Factorial fact = new Factorial(1000, mod); Combination comb = new Combination(fact); Debug debug = new Debug(true); public int f(int i, int j) { int ans = mod.mul(fact.fact(i), comb.combination(i + j - 1 - j, j - 1)); ans = mod.mul(ans, fact.invFact(j)); return ans; } public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); DSU dsu = new DSU(n); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = in.readInt(); } for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if (square(a[j] * a[i])) { dsu.merge(j, i); break; } } } IntegerList list = new IntegerList(); for (int i = 0; i < n; i++) { if (dsu.find(i) == i) { list.add(dsu.size[dsu.find(i)]); } } int[] cnts = list.toArray(); debug.debug("cnts", cnts); int m = cnts.length; int[][] dp = new int[m + 1][n + 1]; dp[0][0] = 1; for (int i = 1; i <= m; i++) { int way = cnts[i - 1]; for (int j = 0; j <= n; j++) { dp[i][j] = 0; for (int k = 1; k <= j && k <= way; k++) { int contrib = mod.mul(f(way, k), dp[i - 1][j - k]); dp[i][j] = mod.plus(dp[i][j], contrib); } } } debug.debug("dp", dp); int ans = 0; for (int i = 0; i <= n; i++) { int local = mod.mul(dp[m][i], fact.fact(i)); if ((n - i) % 2 == 1) { local = mod.valueOf(-local); } ans = mod.plus(ans, local); } out.println(ans); } public boolean square(long x) { long l = 1; long r = (long) 1e9; while (l < r) { long m = (l + r) / 2; if (m * m < x) { l = m + 1; } else { r = m; } } return l * l == x; } } static class IntegerList implements Cloneable { private int size; private int cap; private int[] data; private static final int[] EMPTY = new int[0]; public IntegerList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } } public IntegerList(IntegerList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public IntegerList() { this(0); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } public void add(int x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(int[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(IntegerList list) { addAll(list.data, 0, list.size); } public int[] toArray() { return Arrays.copyOf(data, size); } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof IntegerList)) { return false; } IntegerList other = (IntegerList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Integer.hashCode(data[i]); } return h; } public IntegerList clone() { IntegerList ans = new IntegerList(); ans.addAll(this); return ans; } } static class Combination implements IntCombination { final Factorial factorial; final Modular modular; public Combination(Factorial factorial) { this.factorial = factorial; this.modular = factorial.getModular(); } public Combination(int limit, Modular modular) { this(new Factorial(limit, modular)); } public int combination(int m, int n) { if (n > m) { return 0; } return modular.mul(modular.mul(factorial.fact(m), factorial.invFact(n)), factorial.invFact(m - n)); } } 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 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; } } static interface IntCombination { } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; 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; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(int c) { cache.append(c); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { 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 InverseNumber { int[] inv; public InverseNumber(int[] inv, int limit, Modular modular) { this.inv = inv; inv[1] = 1; int p = modular.getMod(); for (int i = 2; i <= limit; i++) { int k = p / i; int r = p % i; inv[i] = modular.mul(-k, inv[r]); } } public InverseNumber(int limit, Modular modular) { this(new int[limit + 1], limit, modular); } } static class Debug { private boolean offline; private PrintStream out = System.err; static int[] empty = new int[0]; public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public Debug debug(String name, Object x) { return debug(name, x, empty); } public Debug debug(String name, Object x, int... indexes) { if (offline) { if (x == null || !x.getClass().isArray()) { out.append(name); for (int i : indexes) { out.printf("[%d]", i); } out.append("=").append("" + x); out.println(); } else { indexes = Arrays.copyOf(indexes, indexes.length + 1); if (x instanceof byte[]) { byte[] arr = (byte[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof short[]) { short[] arr = (short[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof boolean[]) { boolean[] arr = (boolean[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof char[]) { char[] arr = (char[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof int[]) { int[] arr = (int[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof float[]) { float[] arr = (float[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof double[]) { double[] arr = (double[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof long[]) { long[] arr = (long[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else { Object[] arr = (Object[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } } } return this; } } static class Factorial { int[] fact; int[] inv; Modular modular; public Modular getModular() { return modular; } public Factorial(int[] fact, int[] inv, InverseNumber in, int limit, Modular modular) { this.modular = modular; this.fact = fact; this.inv = inv; fact[0] = inv[0] = 1; for (int i = 1; i <= limit; i++) { fact[i] = modular.mul(fact[i - 1], i); inv[i] = modular.mul(inv[i - 1], in.inv[i]); } } public Factorial(int limit, Modular modular) { this(new int[limit + 1], new int[limit + 1], new InverseNumber(limit, modular), limit, modular); } public int fact(int n) { return fact[n]; } public int invFact(int n) { return inv[n]; } } static class DSU { protected int[] p; protected int[] rank; int[] size; public DSU(int n) { p = new int[n]; rank = new int[n]; size = new int[n]; reset(); } public final void reset() { for (int i = 0; i < p.length; i++) { p[i] = i; rank[i] = 0; size[i] = 1; } } public final int find(int a) { if (p[a] == p[p[a]]) { return p[a]; } return p[a] = find(p[a]); } public final void merge(int a, int b) { a = find(a); b = find(b); if (a == b) { return; } if (rank[a] == rank[b]) { rank[a]++; } if (rank[a] < rank[b]) { int tmp = a; a = b; b = tmp; } size[a] += size[b]; p[b] = a; } } static class Modular { int m; public int getMod() { return m; } public Modular(int m) { this.m = m; } public Modular(long m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public Modular(double m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public int valueOf(int x) { x %= m; if (x < 0) { x += m; } return x; } public int valueOf(long x) { x %= m; if (x < 0) { x += m; } return (int) x; } public int mul(int x, int y) { return valueOf((long) x * y); } public int plus(int x, int y) { return valueOf(x + y); } public String toString() { return "mod " + m; } } static class SequenceUtils { public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } }
cubic
840_C. On the Bench
CODEFORCES
/** * author: derrick20 * created: 11/11/20 1:03 PM */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class OnTheBench { public static void main(String[] args) { setupCombo(301); FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); long[] a = sc.nextLongs(N); boolean[] vis = new boolean[N]; int[] groups = new int[N + 1]; int G = 0; for (int i = 0; i < N; i++) { if (!vis[i]) { vis[i] = true; int elems = 1; for (int j = i + 1; j < N; j++) { long prod = a[i] * a[j]; long root = (long) Math.sqrt(prod); if (!vis[j] && prod == root * root) { vis[j] = true; elems++; } } groups[++G] = elems; } } long[][] dp = new long[G + 1][N + 1]; // dp[g][bad] = ways to interleave first g groups for a given # of bad pairs dp[0][0] = 1; // dp[0][k] = 0, k != 0 int total = 0; for (int prefix = 1; prefix <= G; prefix++) { int amt = groups[prefix]; for (int prevBad = 0; prevBad <= max(0, total - 1); prevBad++) { for (int fixed = 0; fixed <= min(prevBad, amt); fixed++) { for (int slots = max(1, fixed); slots <= min(amt, total + 1); slots++) { int introduced = amt - slots; long ways = mult( choose[prevBad][fixed], choose[total + 1 - prevBad][slots - fixed], choose[amt - 1][slots - 1], fact[amt], dp[prefix - 1][prevBad] ); int currBad = prevBad + introduced - fixed; dp[prefix][currBad] = (dp[prefix][currBad] + ways) % mod; } } } total += amt; // System.out.println(Arrays.toString(dp[prefix])); } out.println(dp[G][0]); out.close(); } static long mod = (long) 1e9 + 7; static long[][] choose; static long[] fact; static long mult(long... multiplicands) { long ans = 1; for (long v : multiplicands) { ans = (ans * v) % mod; } return ans; } static void setupCombo(int MAX) { choose = new long[MAX + 1][MAX + 1]; fact = new long[MAX + 1]; choose[0][0] = 1; fact[0] = 1; for (int i = 1; i <= MAX; i++) { fact[i] = (long) i * fact[i - 1] % mod; choose[i][0] = 1; for (int j = 1; j < i; j++) { choose[i][j] = (choose[i - 1][j - 1] + choose[i - 1][j]) % mod; } choose[i][i] = 1; } } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public 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; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } }
cubic
840_C. On the Bench
CODEFORCES
/** * author: derrick20 * created: 11/11/20 1:45 PM */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class OnTheBenchAlt { public static void main(String[] args) { setupCombo(301); FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); long[] a = new long[N]; HashMap<Long, Integer> clusters = new HashMap<>(); for (int i = 0; i < N; i++) { a[i] = removeSquares(sc.nextLong()); clusters.merge(a[i], 1, Integer::sum); } int G = clusters.size(); int[] groups = new int[G + 1]; int ptr = 1; for (int amt : clusters.values()) { groups[ptr++] = amt; } long[][] dp = new long[G + 1][N + 1]; // dp[g][bad] = ways to interleave first g groups for a given # of bad pairs dp[0][0] = 1; // dp[0][k] = 0, k != 0 int total = 0; /* intuition for runtime analysis: Say there were k groups, each size n / k The outer loop is k, 2nd loop is n worst case, and the inner 2 are bounded by n / k (amt per group) k * n * (n / k) * (n / k) = n^3 / k, which works despite 4 loops!! Seems hard to convert into pull-dp since prevBad has a more direct meaning in the arrangements, so using that as our variable makes more sense */ for (int prefix = 1; prefix <= G; prefix++) { int amt = groups[prefix]; // key bugs here and there: USE THE CORRECT BOUNDS for (int prevBad = 0; prevBad <= max(0, total - 1); prevBad++) { for (int fixed = 0; fixed <= min(prevBad, amt); fixed++) { for (int slots = max(1, fixed); slots <= min(amt, total + 1); slots++) { int introduced = amt - slots; long ways = mult( choose[prevBad][fixed], choose[total + 1 - prevBad][slots - fixed], choose[amt - 1][slots - 1], fact[amt], dp[prefix - 1][prevBad] // key bug: NEED TO RELATE PREVIOUS DP ); int currBad = prevBad + introduced - fixed; dp[prefix][currBad] = (dp[prefix][currBad] + ways) % mod; } } } total += amt; // System.out.println(Arrays.toString(dp[prefix])); } out.println(dp[G][0]); out.close(); } static long mod = (long) 1e9 + 7; static long[][] choose; static long[] fact; static long removeSquares(long x) { long curr = x; for (long v = 2; v * v <= x && curr > 1; v++) { int cnt = 0; while (curr % v == 0) { curr /= v; cnt ^= 1; } if (cnt == 1) curr *= v; } return curr; } static long choose(int n, int k) { return k < 0 || k > n ? 0 : choose[n][k]; } static long mult(long... multiplicands) { long ans = 1; for (long v : multiplicands) { ans = (ans * v) % mod; } return ans; } static void setupCombo(int MAX) { choose = new long[MAX + 1][MAX + 1]; fact = new long[MAX + 1]; choose[0][0] = 1; fact[0] = 1; for (int i = 1; i <= MAX; i++) { fact[i] = (long) i * fact[i - 1] % mod; choose[i][0] = 1; for (int j = 1; j < i; j++) { choose[i][j] = (choose[i - 1][j - 1] + choose[i - 1][j]) % mod; } choose[i][i] = 1; } } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public 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; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.HashMap; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); OnTheBench solver = new OnTheBench(); solver.solve(1, in, out); out.close(); } static class OnTheBench { long MOD = (long) (1e9) + 7; long[][] C = new long[333][333]; public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); DisjointSet dsu = new DisjointSet(N); long[] arr = new long[N]; setC(); for (int i = 0; i < N; i++) { arr[i] = in.nextInt(); } for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { long sqrt = (long) (Math.sqrt(arr[i] * arr[j])); long sqrt2 = (long) (Math.ceil(Math.sqrt(arr[i] * arr[j]))); if (sqrt * sqrt == arr[i] * arr[j] || sqrt2 * sqrt2 == arr[i] * arr[j]) { dsu.merge(i, j); } } } ArrayList<Integer> sz = new ArrayList<>(); sz.add(0); HashMap<Integer, Integer> seen = new HashMap<>(); long mult = 1; for (int i = 0; i < N; i++) { if (!seen.containsKey(dsu.find(i))) { seen.put(dsu.find(i), sz.size()); sz.add(0); } sz.set(seen.get(dsu.find(i)), sz.get(seen.get(dsu.find(i))) + 1); } for (int i : sz) { // if (arr[0] == 285) { // out.println(i); // } mult *= fact(i); mult %= MOD; } long[][] dp = new long[sz.size()][333]; int sum = 0; dp[0][0] = 1; for (int n = 1; n < dp.length; n++) { for (int ij = 1; ij <= sz.get(n); ij++) { for (int y = 0; y <= sum; y++) { for (int j = 0; j <= Math.min(y, ij); j++) { int i = ij - j; dp[n][y - j + sz.get(n) - ij] += ((((dp[n - 1][y] * C[sum + 1 - y][i]) % MOD * C[y][j]) % MOD) * C[sz.get(n) - 1][ij - 1]) % MOD; dp[n][y - j + sz.get(n) - ij] %= MOD; } } } sum += sz.get(n); } out.println((dp[sz.size() - 1][0] * mult) % MOD); } void setC() { for (int i = 0; i <= 332; i++) { C[i][0] = 1; for (int j = 1; j <= i; j++) { C[i][j] = C[i - 1][j] + C[i - 1][j - 1]; C[i][j] %= MOD; } } } long fact(int i) { long res = 1; while (i > 0) { res *= i; res %= MOD; i--; } return res; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class DisjointSet { int[] rank; int[] par; public DisjointSet(int N) { rank = new int[N]; par = new int[N]; for (int i = 0; i < N; i++) { rank[i] = 1; par[i] = i; } } public int find(int x) { if (x == par[x]) { return x; } return (par[x] = find(par[x])); } public void merge(int x, int y) { int parX = find(x); int parY = find(y); if (parX != parY) { if (rank[parX] > rank[parY]) { par[parY] = parX; rank[parX] += rank[parY]; } else { par[parX] = parY; rank[parY] += rank[parX]; } } } } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Iterator; import java.io.IOException; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { private static final int MOD = (int) 1e9 + 7; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] primes = getPrimes(40_000); int[][] a = new int[n][]; for (int i = 0; i < n; ++i) { int x = in.nextInt(); IntList divs = new IntList(); for (int j : primes) { if (j * j > x) { break; } int cnt = 0; while (x % j == 0) { cnt++; x /= j; } if (cnt % 2 == 1) { divs.add(j); } } if (x > 1) { divs.add(x); } a[i] = divs.toArray(); } Comparator<int[]> cmp = ((o1, o2) -> { for (int i = 0; i < o1.length && i < o2.length; ++i) { if (o1[i] < o2[i]) { return -1; } else if (o2[i] < o1[i]) { return 1; } } return Integer.compare(o1.length, o2.length); }); Arrays.sort(a, cmp); IntList freqsList = new IntList(); int cnt = 1; for (int i = 1; i < n; ++i) { if (cmp.compare(a[i], a[i - 1]) == 0) { cnt++; } else { freqsList.add(cnt); cnt = 1; } } freqsList.add(cnt); int[][] comb = new int[2 * n + 1][2 * n + 1]; for (int i = 0; i < comb.length; ++i) { comb[i][0] = 1; for (int j = 1; j <= i; ++j) { comb[i][j] = (comb[i - 1][j] + comb[i - 1][j - 1]) % MOD; } } int[] dp = new int[n]; int[] ndp = new int[n]; dp[0] = 1; int total = 0; int ans = 1; for (int x : freqsList.toArray()) { Arrays.fill(ndp, 0); for (int bad = 0; bad < n; ++bad) { if (dp[bad] == 0) { continue; } for (int putSeparately = 1; putSeparately <= x; ++putSeparately) { for (int breakEq = 0; breakEq <= putSeparately; ++breakEq) { int nState = bad + x - putSeparately - breakEq; if (nState < 0 || nState >= n) { continue; } int rem = total + 1 - bad; int notBreak = putSeparately - breakEq; if (breakEq > bad || notBreak > rem) { continue; } int add = (int) ((long) comb[bad][breakEq] * comb[rem][notBreak] % MOD * comb[x - 1][putSeparately - 1] % MOD * dp[bad] % MOD); ndp[nState] += add; ndp[nState] %= MOD; } } } total += x; int[] aux = dp; dp = ndp; ndp = aux; ans = (int) ((long) ans * fact(x) % MOD); } ans = (int) ((long) ans * dp[0] % MOD); out.println(ans); } private int fact(int n) { int res = 1; for (int i = 2; i <= n; ++i) { res = (int) ((long) res * i % MOD); } return res; } private int[] getPrimes(int n) { boolean[] isPrime = new boolean[n + 1]; Arrays.fill(isPrime, 2, isPrime.length, true); for (int i = 2; i * i <= n; ++i) { if (isPrime[i]) { for (int j = i * i; j <= n; j += i) { isPrime[j] = false; } } } IntList primes = new IntList(); for (int i = 2; i <= n; ++i) { if (isPrime[i]) { primes.add(i); } } return primes.toArray(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { return Integer.parseInt(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static interface IntIterator extends Iterator<Integer> { } static class IntList implements Iterable<Integer> { int[] elem; int size; public IntList() { this(0, 0, 1); } public IntList(int size) { this(size, 0, Math.max(1, size)); } public IntList(int size, int value) { this(size, value, Math.max(1, size)); } public IntList(int size, int value, int capacity) { elem = new int[capacity]; Arrays.fill(elem, 0, size, value); this.size = size; } private IntList(int... e) { elem = e.clone(); size = e.length; } public void add(int e) { if (size + 1 > elem.length) { increaseCapacity(); } elem[size++] = e; } private void increaseCapacity() { changeCapacity(3 * elem.length / 2 + 1); } private void changeCapacity(int newCapacity) { int[] nElem = new int[newCapacity]; System.arraycopy(elem, 0, nElem, 0, Math.min(elem.length, newCapacity)); elem = nElem; } public IntIterator iterator() { return new IntIterator() { int pos = 0; public Integer next() { return IntList.this.elem[pos++]; } public boolean hasNext() { return pos < IntList.this.size; } public int nextInt() { return IntList.this.elem[pos++]; } }; } public int[] toArray() { return Arrays.copyOf(elem, size); } public int hashCode() { int hashCode = 0; for (int i = 0; i < size; ++i) { hashCode = 31 * hashCode + elem[i]; } return hashCode; } } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { final int MOD = (int) (1e9 + 7); long[][] C; long[] fact; public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); precalc(n); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); a[i] = removeSquares(a[i]); } int[] g = getGroupSizes(a); long ans = solve(g); for (int x : g) { ans = ans * fact[x] % MOD; } out.println(ans); } private long solve(int[] a) { // For a description, see http://petr-mitrichev.blogspot.com/2017/07/a-week7.html long[] d = new long[1]; d[0] = 1; int totalPositions = 1; for (int x : a) { long[] nd = new long[d.length + x + 1]; for (int s = 0; s < d.length; s++) { if (d[s] == 0) { continue; } for (int m = 1; m <= x; m++) { for (int p = 0; p <= s && p <= m; p++) { long cur = d[s]; cur = cur * C[s][p] % MOD; cur = cur * C[totalPositions - s][m - p] % MOD; cur = cur * f(x, m) % MOD; int ns = s + x - m - p; if (ns >= 0 && ns < nd.length) { nd[ns] += cur; if (nd[ns] >= MOD) { nd[ns] -= MOD; } } } } } if (totalPositions == 1) { totalPositions = x + 1; } else { totalPositions += x; } d = nd; } return d[0]; } private long f(int n, int k) { if (n < k) { return 0; } n -= k; return C[n + k - 1][k - 1]; } private void precalc(int n) { fact = new long[n + 1]; fact[0] = 1; for (int i = 1; i < fact.length; i++) { fact[i] = i * fact[i - 1] % MOD; } C = new long[1000][1000]; C[0][0] = 1; for (int i = 1; i < C.length; i++) { C[i][0] = 1; for (int j = 1; j < C.length; j++) { C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; if (C[i][j] >= MOD) { C[i][j] -= MOD; } } } } private int[] getGroupSizes(int[] a) { Arrays.sort(a); List<Integer> res = new ArrayList<>(); for (int i = 0; i < a.length; ) { int j = i; while (j < a.length && a[i] == a[j]) { ++j; } res.add(j - i); i = j; } int[] r = new int[res.size()]; for (int i = 0; i < r.length; i++) { r[i] = res.get(i); } return r; } private int removeSquares(int n) { int res = 1; for (int d = 2; d * d <= n; d++) { if (n % d == 0) { int cur = 0; while (n % d == 0) { n /= d; ++cur; } if (cur % 2 == 1) { res *= d; } } } if (n > 1) { res *= n; } return res; } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
cubic
840_C. On the Bench
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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { static final int MODULO = (int) (1e9 + 7); public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = removeSquares(in.nextInt()); Arrays.sort(a); int[][] c = new int[n + 1][n + 1]; c[0][0] = 1; for (int i = 1; i < c.length; ++i) { c[i][0] = 1; for (int j = 1; j < c.length; ++j) { c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % MODULO; } } int[] fact = new int[n + 1]; fact[0] = 1; for (int i = 1; i < fact.length; ++i) { fact[i] = (int) (i * (long) fact[i - 1] % MODULO); } int i = 0; int[] ways = new int[]{1}; while (i < n) { int j = i; while (j < n && a[j] == a[i]) ++j; int m = j - i; int[] nways = new int[j + 1]; for (int old = 0; old < ways.length; ++old) { long w = ways[old]; for (int blocks = 1; blocks <= m; ++blocks) { for (int intoOld = 0; intoOld <= old && intoOld <= blocks; ++intoOld) { nways[old - intoOld + (m - blocks)] = (int) ((nways[old - intoOld + (m - blocks)] + w * c[old][intoOld] % MODULO * c[i + 1 - old][blocks - intoOld] % MODULO * c[m - 1][blocks - 1] % MODULO * fact[m] % MODULO) % MODULO); } } } i = j; ways = nways; } out.println(ways[0]); } private int removeSquares(int x) { for (int i = 2; i * i <= x; ++i) { while (x % (i * i) == 0) { x /= i * i; } } return x; } } 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()); } } }
cubic
840_C. On the Bench
CODEFORCES
//package round429; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class C2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); for(int i = 0;i < n;i++){ int v = a[i]; for(int j = 2;j*j <= v;j++){ while(v % (j*j) == 0){ v /= j*j; } } a[i] = v; } Arrays.sort(a); int[] f = new int[n]; int p = 0; for(int i= 0;i < n;i++){ if(i > 0 && a[i] != a[i-1]){ p++; } f[p]++; } f = Arrays.copyOf(f, p+1); int mod = 1000000007; int[][] fif = enumFIF(1000, mod); long[] res = countSameNeighborsSequence(f, fif, mod); long ans = res[0]; for(int v : f){ ans = ans * fif[0][v] % mod; } out.println(ans); } public static int[][] enumFIF(int n, int mod) { int[] f = new int[n + 1]; int[] invf = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; i++) { f[i] = (int) ((long) f[i - 1] * i % mod); } long a = f[n]; long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } invf[n] = (int) (p < 0 ? p + mod : p); for (int i = n - 1; i >= 0; i--) { invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod); } return new int[][] { f, invf }; } public static long[] countSameNeighborsSequence(int[] a, int[][] fif, int mod) { int n = a.length; int bef = a[0]; int aft = a[0]; long[] dp = new long[bef]; dp[bef-1] = 1; for(int u = 1;u < n;u++){ int v = a[u]; aft += v; long[][] ldp = new long[bef][aft]; for(int i = 0;i < dp.length;i++){ ldp[i][0] = dp[i]; } for(int i = 0;i < v;i++){ long[][] ndp = new long[bef][aft]; for(int j = 0;j < bef;j++){ for(int k = 0;j+k < aft;k++){ if(ldp[j][k] == 0)continue; // XX -> XCX if(j > 0){ ndp[j-1][k] += ldp[j][k] * j; ndp[j-1][k] %= mod; } // CC -> CCC if(k > 0){ ndp[j][k+1] += ldp[j][k] * k; ndp[j][k+1] %= mod; } // XC -> XCC // #XC = 2*(i-k) if(2*(i-k) > 0){ ndp[j][k+1] += ldp[j][k] * (2*(i-k)); ndp[j][k+1] %= mod; } // XY -> XCY // #XY = bef+i+1-#XC-#CC-#XX if(bef+i+1-j-k-2*(i-k) > 0){ ndp[j][k] += ldp[j][k] * (bef+i+1-j-k-2*(i-k)); ndp[j][k] %= mod; } } } ldp = ndp; } dp = new long[aft]; for(int j = 0;j < bef;j++){ for(int k = 0;j+k < aft;k++){ dp[j+k] += ldp[j][k]; if(dp[j+k] >= mod)dp[j+k] -= mod; } } for(int j = 0;j < aft;j++)dp[j] = dp[j] * fif[1][v] % mod; bef = aft; } return dp; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new C2().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import java.util.concurrent.*; public final class on_the_bench { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); static int[] parent,size; static int maxn=(int)500; static long mod=(long)(1e9+7); static int[] fact,inv_fact; static int getParent(int u) { if(u==parent[u]) { return u; } else { int val=getParent(parent[u]);parent[u]=val; return val; } } static void merge(int u,int v) { int x=getParent(u),y=getParent(v); if(x!=y) { parent[y]=x; size[x]+=size[y];size[y]=0; } } static int add(long a,long b) { long ret=a+b; if(ret>=mod) { ret%=mod; } return (int)ret; } static int mul(long a,long b) { long ret=a*b; if(ret>=mod) { ret%=mod; } return (int)ret; } static int pow(long a,long b) { long x=1,y=a; while(b>0) { if(b%2==1) { x=mul(x,y); } y=mul(y,y);b=b/2; } return (int)(x%mod); } static void build() { fact=new int[maxn];inv_fact=new int[maxn];fact[0]=1; for(int i=1;i<maxn;i++) { fact[i]=mul(fact[i-1],i); } inv_fact[maxn-1]=pow(fact[maxn-1],mod-2); for(int i=maxn-2;i>=0;i--) { inv_fact[i]=mul(inv_fact[i+1],(i+1)); } } static int[] mul_poly(int[] a,int[] b,int deg1,int deg2) { int[] ret=new int[deg1+deg2+1]; for(int i=0;i<=deg1;i++) { for(int j=0;j<=deg2;j++) { int curr=mul(a[i],b[j]); ret[i+j]=add(ret[i+j],curr); } } return ret; } static int C(int n,int r) { if(n-r<0 || Math.min(n,r)<0) { return 0; } int val1=fact[n],val2=inv_fact[r],val3=inv_fact[n-r]; int mul=mul(val2,val3); return mul(val1,mul); } public static void main(String args[]) throws Exception { int n=sc.nextInt();build(); int[] a=new int[n];parent=new int[n];size=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); parent[i]=i; size[i]=1; } for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { long curr=a[i]*1L*a[j],now=(long)Math.sqrt(curr); if(now*now==curr) { merge(i,j); } } } List<Integer> list=new ArrayList<>(); for(int i=0;i<n;i++) { if(getParent(i)==i) { list.add(size[i]); } } // out.println(list); int res=0;int[] poly=new int[1];poly[0]=1; for(int i=0;i<list.size();i++) { int size=list.get(i); int[] arr=new int[size];arr[0]=1; for(int j=1;j<size;j++) { int now1=C(size,j),now2=mul(fact[size-1],inv_fact[size-1-j]); int qq=mul(now1,now2); arr[j]=qq; } poly=mul_poly(poly,arr,poly.length-1,size-1); } for(int i=1,x=1;i<poly.length;i++,x*=-1) { int now=add(x,mod); int curr=mul(fact[n-i],poly[i]); curr=mul(curr,now); res=add(res,curr); } // out.println(res); int zz=mul(res,mod-1);res=add(fact[n],zz); out.println(res);out.close(); } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; /* 2 3 5 2 6 5 1 11 -10 12 3 3 6 2 1 8 5 3 -7 9 5 3 -7 4 14 3 1 8 5 3 1 3 13 3 -2 4 13 3 3 1 3 6 3 3 6 5 12 -7 19 3 5 7 11 13 -2 8 5 9 5 9 3 6 7 -3 9 7 6 3 7 */ public class c { static int n; static int[] fs; static int[] cfs; static long[][] choose = chooseTable(1001); static long[] fact; static final long MOD = (long) (1e9 + 7); static long[][] memo; public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); n = in.nextInt(); fact = new long[301]; fact[0] = 1; for (int i = 1; i < fact.length; i++) { fact[i] = fact[i - 1] * i; fact[i] %= MOD; } HashMap<Long, Integer> map = new HashMap<Long, Integer>(); fs = new int[n]; for (int i = 0; i < n; i++) { long v = in.nextLong(); long r = 1; for (int d = 2; d * d <= v; d++) { int cnt = 0; while (v % d == 0) { v /= d; cnt ^= 1; } if (cnt == 1) { r *= d; } } r *= v; if (!map.containsKey(r)) { map.put(r, map.size()); } fs[map.get(r)]++; } cfs = new int[n]; for (int i = 1; i < n; i++) { cfs[i] = cfs[i - 1] + fs[i - 1]; } memo = new long[n+1][n+1]; for(long[] arr : memo) Arrays.fill(arr, -1); System.out.println(go(0, 0)); } static long go(int color, int priorities) { if (color == n) return priorities == 0 ? 1 : 0; // System.out.println(color + " "+ priorities); if(memo[color][priorities] != -1) return memo[color][priorities]; int nonpriorities = cfs[color] - priorities + 1; long ans = 0; for (int cntPrio = 0; cntPrio <= priorities && cntPrio <= fs[color]; cntPrio++) { for (int cntNonPrio = 0; cntNonPrio <= nonpriorities && cntNonPrio + cntPrio <= fs[color]; cntNonPrio++) { if(cntPrio + cntNonPrio == 0 && fs[color] != 0) continue; int cntExtra = fs[color] - cntPrio - cntNonPrio; long tmp = choose(priorities, cntPrio); tmp *= choose(nonpriorities, cntNonPrio); tmp %= MOD; tmp *= multichoose(cntPrio + cntNonPrio, cntExtra); tmp %= MOD; tmp *= go(color + 1, priorities - cntPrio + cntExtra); tmp %= MOD; tmp *= fact[fs[color]]; tmp %= MOD; ans += tmp; ans %= MOD; } } return memo[color][priorities] = ans; } static long[][] chooseTable(int n) { long[][] table = new long[n][]; for (int x = 0; x < n; x++) { table[x] = new long[x + 1]; table[x][0] = table[x][x] = 1; for (int y = 1; y < x; y++) { table[x][y] = table[x - 1][y - 1] + table[x - 1][y]; table[x][y] %= MOD; } } return table; } static long choose(int n, int k) { if (k == 0) return 1; if (k >= choose[n].length) { return 0; } return choose[n][k]; } static long multichoose(int n, int k) { return choose(n + k - 1, k); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); } 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()); } } }
cubic
840_C. On the Bench
CODEFORCES
//package round429; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class C2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); for(int i = 0;i < n;i++){ int v = a[i]; for(int j = 2;j*j <= v;j++){ while(v % (j*j) == 0){ v /= j*j; } } a[i] = v; } Arrays.sort(a); int[] f = new int[n]; int p = 0; for(int i= 0;i < n;i++){ if(i > 0 && a[i] != a[i-1]){ p++; } f[p]++; } f = Arrays.copyOf(f, p+1); int mod = 1000000007; int[][] fif = enumFIF(1000, mod); long[] res = countSameNeighborsSequence(f, fif, mod); long ans = res[0]; for(int v : f){ ans = ans * fif[0][v] % mod; } out.println(ans); } public static int[][] enumFIF(int n, int mod) { int[] f = new int[n + 1]; int[] invf = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; i++) { f[i] = (int) ((long) f[i - 1] * i % mod); } long a = f[n]; long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } invf[n] = (int) (p < 0 ? p + mod : p); for (int i = n - 1; i >= 0; i--) { invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod); } return new int[][] { f, invf }; } public static long[] countSameNeighborsSequence(int[] a, int[][] fif, int mod) { int n = a.length; int bef = a[0]; int aft = a[0]; long[] dp = new long[bef]; dp[bef-1] = 1; for(int u = 1;u < n;u++){ int v = a[u]; aft += v; long[][] ldp = new long[bef][aft]; for(int i = 0;i < dp.length;i++){ ldp[i][0] = dp[i]; } for(int i = 0;i < v;i++){ long[][] ndp = new long[bef][aft]; for(int j = 0;j < bef;j++){ for(int k = 0;j+k < aft;k++){ if(ldp[j][k] == 0)continue; // XX -> XCX if(j > 0){ ndp[j-1][k] += ldp[j][k] * j; ndp[j-1][k] %= mod; } // CC -> CCC // XC -> XCC // #XC = 2*(i-k) ndp[j][k+1] += ldp[j][k] * (2*i-k); ndp[j][k+1] %= mod; // XY -> XCY // #XY = bef+i+1-#XC-#CC-#XX ndp[j][k] += ldp[j][k] * (bef+i+1-j-k-2*(i-k)); ndp[j][k] %= mod; } } ldp = ndp; } dp = new long[aft]; for(int j = 0;j < bef;j++){ for(int k = 0;j+k < aft;k++){ dp[j+k] += ldp[j][k]; if(dp[j+k] >= mod)dp[j+k] -= mod; } } for(int j = 0;j < aft;j++)dp[j] = dp[j] * fif[1][v] % mod; bef = aft; } return dp; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new C2().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
cubic
840_C. On the Bench
CODEFORCES
//package round429; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class C2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); for(int i = 0;i < n;i++){ int v = a[i]; for(int j = 2;j*j <= v;j++){ while(v % (j*j) == 0){ v /= j*j; } } a[i] = v; } Arrays.sort(a); int[] f = new int[n]; int p = 0; for(int i= 0;i < n;i++){ if(i > 0 && a[i] != a[i-1]){ p++; } f[p]++; } f = Arrays.copyOf(f, p+1); int mod = 1000000007; int[][] fif = enumFIF(1000, mod); long[] res = countSameNeighborsSequence(f, fif, mod); long ans = res[0]; for(int v : f){ ans = ans * fif[0][v] % mod; } out.println(ans); } public static int[][] enumFIF(int n, int mod) { int[] f = new int[n + 1]; int[] invf = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; i++) { f[i] = (int) ((long) f[i - 1] * i % mod); } long a = f[n]; long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } invf[n] = (int) (p < 0 ? p + mod : p); for (int i = n - 1; i >= 0; i--) { invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod); } return new int[][] { f, invf }; } public static long[] countSameNeighborsSequence(int[] a, int[][] fif, int mod) { int n = a.length; int bef = a[0]; int aft = a[0]; long[] dp = new long[bef]; dp[bef-1] = 1; for(int u = 1;u < n;u++){ int v = a[u]; aft += v; long[][] ldp = new long[bef][aft]; for(int i = 0;i < dp.length;i++){ ldp[i][0] = dp[i]; } for(int i = 0;i < v;i++){ long[][] ndp = new long[bef][aft]; for(int j = 0;j < bef;j++){ for(int k = 0;j+k < aft;k++){ if(ldp[j][k] == 0)continue; // XX -> XCX if(j > 0){ ndp[j-1][k] += ldp[j][k] * j; ndp[j-1][k] %= mod; } // CC -> CCC // XC -> XCC // #XC = 2*(i-k) ndp[j][k+1] += ldp[j][k] * (2*i-k); ndp[j][k+1] %= mod; // XY -> XCY // #XY = bef+i+1-#XC-#CC-#XX ndp[j][k] += ldp[j][k] * (bef+i+1-j-k-2*(i-k)); ndp[j][k] %= mod; } } ldp = ndp; } dp = new long[aft]; for(int j = 0;j < bef;j++){ for(int k = 0;j+k < aft;k++){ dp[j+k] += ldp[j][k]; } } for(int j = 0;j < aft;j++)dp[j] = dp[j] % mod * fif[1][v] % mod; bef = aft; } return dp; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new C2().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.*; import java.util.*; public class MainD { static final StdIn in = new StdIn(); static final PrintWriter out = new PrintWriter(System.out); static final long M=(long)1e9+7; static long[] fac, faci; public static void main(String[] args) { int n=in.nextInt(); fac = new long[n+1]; faci = new long[n+1]; fac[0]=faci[0]=1; for(int i=1; i<=n; ++i) faci[i]=modI(fac[i]=fac[i-1]*i%M, M); List<List<Integer>> grps = new ArrayList<List<Integer>>(); for(int i=0; i<n; ++i) { int ai=in.nextInt(); for(int j=0; ; ++j) { if(j>=grps.size()) grps.add(new ArrayList<Integer>()); if(grps.get(j).size()>0&&!ps((long)grps.get(j).get(0)*ai)) continue; grps.get(j).add(ai); break; } } long[][] dp = new long[grps.size()][n-grps.size()+1]; dp[0][grps.get(0).size()-1]=fac[grps.get(0).size()]; int ad=grps.get(0).size(); for(int i=1; i<grps.size(); ++i) { for(int j=0; j<dp[i-1].length; ++j) { if(dp[i-1][j]==0) continue; for(int k=0; k<grps.get(i).size(); ++k) for(int l=Math.max(grps.get(i).size()+j-k-ad-1, 0); l<=Math.min(grps.get(i).size()-k, j); ++l) dp[i][j+k-l]=(fac[grps.get(i).size()]*nck(j, l)%M*nck(ad+1-j, grps.get(i).size()-k-l)%M*nck(grps.get(i).size()-1, k)%M*dp[i-1][j]+dp[i][j+k-l])%M; } ad+=grps.get(i).size(); } //out.println(Arrays.deepToString(dp)); out.println(dp[grps.size()-1][0]); out.close(); } static long modI(long a, long m) { return (a%=m)<=1?1:((1-modI(m%a, a)*m)/a+m)%m; } static long nck(int n, int k) { return fac[n]*faci[k]%M*faci[n-k]%M; } static boolean ps(long x) { long lb=1, rb=M; while(lb<=rb) { long mb=(lb+rb)/2; if(mb*mb==x) return true; if(mb*mb<x) lb=mb+1; else rb=mb-1; } return false; } static class StdIn { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public StdIn() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public StdIn(InputStream in) { try{ din = new DataInputStream(in); } catch(Exception e) { throw new RuntimeException(); } buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == ' ' || c == '\n'||c=='\r') break; s.append((char)c); c=read(); } return s.toString(); } public String nextLine() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == '\n'||c=='\r') break; s.append((char)c); c = read(); } return s.toString(); } public int nextInt() { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public int[] readIntArray(int n, int os) { int[] ar = new int[n]; for(int i=0; i<n; ++i) ar[i]=nextInt()+os; return ar; } public long nextLong() { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long[] readLongArray(int n, long os) { long[] ar = new long[n]; for(int i=0; i<n; ++i) ar[i]=nextLong()+os; return ar; } public double nextDouble() { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() { try{ if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } catch(IOException e) { throw new RuntimeException(); } } public void close() throws IOException { if (din == null) return; din.close(); } } }
cubic
840_C. On the Bench
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(); 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"); } PW.print(solution.toString()); PW.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.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import static java.lang.Double.parseDouble; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.in; import static java.lang.System.out; public class SolutionD extends Thread { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(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 parseInt(next()); } long nextLong() { return parseLong(next()); } double nextDouble() { return parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } private static final FastReader scanner = new FastReader(); private static final PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { solve(); out.close(); } private static void solve() { int n = scanner.nextInt(); int m = scanner.nextInt(); int k = scanner.nextInt(); int[][] hori = new int[n][m-1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m-1; j++) { int xij = scanner.nextInt(); hori[i][j] = xij; } } int[][] vert = new int[n-1][m]; for (int i = 0; i < n-1; i++) { for (int j = 0; j < m; j++) { int xij = scanner.nextInt(); vert[i][j] = xij; } } if (k % 2 != 0) { for (int i = 0; i < n; i++) { StringBuilder s = new StringBuilder(); for (int j = 0; j < m; j++) { s.append("-1 "); } out.println(s); } return; } k /= 2; long[][][] dp = new long[n][m][k+1]; for (int kTmp = 1; kTmp <= k; kTmp++) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dp[i][j][kTmp] = Integer.MAX_VALUE; if (i > 0) { dp[i][j][kTmp] = Math.min(dp[i][j][kTmp], dp[i-1][j][kTmp-1] + 2L * vert[i - 1][j]); } if (j > 0) { dp[i][j][kTmp] = Math.min(dp[i][j][kTmp], dp[i][j-1][kTmp-1] + 2L * hori[i][j - 1]); } if (i + 1 < n) { dp[i][j][kTmp] = Math.min(dp[i][j][kTmp], dp[i+1][j][kTmp-1] + 2L * vert[i][j]); } if (j + 1 < m) { dp[i][j][kTmp] = Math.min(dp[i][j][kTmp], dp[i][j+1][kTmp-1] + 2L * hori[i][j]); } } } } for (int i = 0; i < n; i++) { StringBuilder s = new StringBuilder(); for (int j = 0; j < m; j++) { s.append(dp[i][j][k]).append(" "); } out.println(s); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class D { static byte[] buf = new byte[1<<26]; static int bp = -1; public static void main(String[] args) throws IOException { /**/ DataInputStream in = new DataInputStream(System.in); /*/ DataInputStream in = new DataInputStream(new FileInputStream("src/d.in")); /**/ in.read(buf, 0, 1<<26); int n = nni(); int m = nni(); int k = nni(); if (k%2==1) { for (int i = 0; i < n; ++i) { StringBuilder ans = new StringBuilder(); String sp = ""; for (int j = 0; j < m; ++j) { ans.append(sp+"-1"); sp = " "; } System.out.println(ans); } return; } int[][] lr = new int[n][m-1]; int[][] ud = new int[n-1][m]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m-1; ++j) { lr[i][j] = nni(); } } for (int i = 0; i < n-1; ++i) { for (int j = 0; j < m; ++j) { ud[i][j] = nni(); } } int[][][] ans = new int[k/2+1][n][m]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { for (int q = 1; q <= k/2; ++q) { ans[q][i][j] = 123456789; } } } for (int uq = 0; uq < k/2; ++uq) { for (int ui = 0; ui < n; ++ui) { for (int uj = 0; uj < m; ++uj) { int w = ans[uq][ui][uj]; if (ui>0 && w+ud[ui-1][uj]<ans[uq+1][ui-1][uj]) { ans[uq+1][ui-1][uj] = w+ud[ui-1][uj]; } if (ui<n-1 && w+ud[ui][uj]<ans[uq+1][ui+1][uj]) { ans[uq+1][ui+1][uj] = w+ud[ui][uj]; } if (uj>0 && w+lr[ui][uj-1]<ans[uq+1][ui][uj-1]) { ans[uq+1][ui][uj-1] = w+lr[ui][uj-1]; } if (uj<m-1 && w+lr[ui][uj]<ans[uq+1][ui][uj+1]) { ans[uq+1][ui][uj+1] = w+lr[ui][uj]; } } } } for (int i = 0; i < n; ++i) { StringBuilder as = new StringBuilder(); String sp = ""; for (int j = 0; j < m; ++j) { as.append(sp+ans[k/2][i][j]*2); sp = " "; } System.out.println(as); } } public static int nni() { int ret = 0; byte b = buf[++bp]; while (true) { ret = ret*10+b-'0'; b = buf[++bp]; if (b<'0'||b>'9') { while (buf[bp+1]=='\r'||buf[bp+1]=='\n'||buf[bp+1]==' ') {++bp;} break; } } return ret; } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; public class D { static FastIO f; static long ve[][], he[][]; public static void main(String args[]) throws IOException { f = new FastIO(); int n = f.ni(), m = f.ni(), k = f.ni(), i, j; ve = new long[n-1][]; he = new long[n][]; long[][] ans = new long[n][m], pans = new long[n][m], temp; for(i = 0; i < n; i++) he[i] = f.nla(m-1); for(i = 0; i < n-1; i++) ve[i] = f.nla(m); if(k%2 == 1) { for(i = 0; i < n; i++) Arrays.fill(ans[i], -1L); } else { k /= 2; while(k-->0) { for(i = 0; i < n; i++) { for(j = 0; j < m; j++) { ans[i][j] = Integer.MAX_VALUE; if(i != 0) ans[i][j] = Math.min(ans[i][j], pans[i-1][j] + 2*edge(i, j, i-1, j)); if(i != n-1) ans[i][j] = Math.min(ans[i][j], pans[i+1][j] + 2*edge(i, j, i+1, j)); if(j != 0) ans[i][j] = Math.min(ans[i][j], pans[i][j-1] + 2*edge(i, j, i, j-1)); if(j != m-1) ans[i][j] = Math.min(ans[i][j], pans[i][j+1] + 2*edge(i, j, i, j+1)); } } // f.err(k + "\n"); // errorprint(ans, n, m); temp = pans; pans = ans; ans = temp; } temp = pans; pans = ans; ans = temp; } for(i = 0; i < n; i++) { for(j = 0; j < m; j++) { f.out(ans[i][j] + " "); } f.out("\n"); } f.flush(); } public static void errorprint(long[][] p, int n, int m) throws IOException { int i, j; for(i = 0; i < n; i++) { for(j = 0; j < m; j++) { f.err(p[i][j] + " "); } f.err("\n"); } f.err("\n"); } public static long edge(int i, int j, int x, int y) { if(i == x) return he[i][Math.min(j, y)]; else return ve[Math.min(i, x)][j]; } 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
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; public class D { public static int dir[][]={{-1,0},{1,0},{0,-1},{0,1}}; public static void main(String[] args) { // Scanner sc=new Scanner(System.in); FastScanner sc = new FastScanner(); FastOutput out = new FastOutput(System.out); int n=sc.nextInt(); int m=sc.nextInt(); int k=sc.nextInt(); int ans[][][]=new int[n][m][11]; int arr[][]=new int[n*m][4]; for(int i=0;i<n;i++){ for(int j=0;j<m-1;j++){ int x=sc.nextInt(); arr[i*m+j][3]=x; arr[i*m+j+1][2]=x; } } for(int i=0;i<n-1;i++){ for(int j=0;j<m;j++){ int x=sc.nextInt(); arr[i*m+j][1]=x; arr[(i+1)*m+j][0]=x; } } if(k%2==1){ for(int i=0;i<n;i++){ StringBuilder sb=new StringBuilder(""); for(int j=0;j<m;j++){ ans[i][j][10]=-1; sb.append(ans[i][j][10]+" "); } out.println(sb.toString()); } }else{ for(int ceng=1;ceng<=k/2;ceng++){ for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ ans[i][j][ceng]=Integer.MAX_VALUE/3; for(int dr=0;dr<4;dr++){ int nx=i+dir[dr][0]; int ny=j+dir[dr][1]; if(nx<n&&ny<m&&nx>=0&&ny>=0){ ans[i][j][ceng]=Math.min(ans[i][j][ceng], ans[nx][ny][ceng-1]+arr[i*m+j][dr]); } } } } } for(int i=0;i<n;i++){ StringBuilder sb=new StringBuilder(""); for(int j=0;j<m;j++){ sb.append(ans[i][j][k/2]*2+" "); } out.println(sb.toString()); } } 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[] readIntArray(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()); } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 1 << 13; 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 append(String c) { cache.append(c); afterWrite(); return this; } public FastOutput println(String c) { return append(c).println(); } public FastOutput println() { return append(System.lineSeparator()); } public FastOutput flush() { try { 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
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; public final class Solution { static PrintWriter out = new PrintWriter(System.out); static FastReader in = new FastReader(); static long mod = (long) 1e9 + 7; static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(1, 0), new Pair(0, -1), new Pair(0, 1)}; //6 3 //2 3 10 7 5 14 //1 6 //2 4 //3 5 public static void main(String[] args) { int n = i(); int m = i(); int k = i(); int[][] a = new int[n][m - 1]; for (int i = 0; i < n; i++) { a[i] = input(m - 1); } int[][] b = new int[n - 1][m]; for (int i = 0; i < n - 1; i++) { b[i] = input(m); } if (k % 2 > 0) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(-1 + " "); } out.println(); } out.flush(); return; } int[][][] f = new int[n][m][k / 2 + 1]; for (int s = 1; s <= k / 2; s++) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int ans = -1; if (j > 0) { ans = f[i][j - 1][s - 1] + a[i][j - 1]; } if (i > 0) { int t = f[i - 1][j][s - 1] + b[i - 1][j]; ans = ans == -1 ? t : Math.min(ans, t); } if (i < n - 1) { int t = f[i + 1][j][s - 1] + b[i][j]; ans = ans == -1 ? t : Math.min(ans, t); } if (j < m - 1) { int t = f[i][j + 1][s - 1] + a[i][j]; ans = ans == -1 ? t : Math.min(ans, t); } f[i][j][s] = ans; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(f[i][j][k / 2] * 2 + " "); } out.println(); } out.flush(); } static int sd(long i) { int d = 0; while (i > 0) { d += i % 10; i = i / 10; } return d; } static Set<Integer> getFactors(int x) { Set<Integer> res = new HashSet<>(); if (x <= 3) { res.add(x); } else { int t = x; for (int f = 2; f <= x / 2; f++) { if (t == 1) { break; } if (t % f == 0) { res.add(f); while (t % f == 0) { t = t / f; } } } if (t > 1) { res.add(t); } } return res; } static int lower(long A[], long x) { int l = -1, r = A.length; while (r - l > 1) { int m = (l + r) / 2; if (A[m] >= x) { r = m; } else { l = m; } } return r; } static int upper(long A[], long x) { int l = -1, r = A.length; while (r - l > 1) { int m = (l + r) / 2; if (A[m] <= x) { l = m; } else { r = m; } } return l; } static void swap(int A[], int a, int b) { int t = A[a]; A[a] = A[b]; A[b] = t; } static int lowerBound(int A[], int low, int high, int x) { if (low > high) { if (x >= A[high]) { return A[high]; } } int mid = (low + high) / 2; if (A[mid] == x) { return A[mid]; } if (mid > 0 && A[mid - 1] <= x && x < A[mid]) { return A[mid - 1]; } if (x < A[mid]) { return lowerBound(A, low, mid - 1, x); } return lowerBound(A, mid + 1, high, x); } static long pow(long a, long b) { long pow = 1; long x = a; while (b != 0) { if ((b & 1) != 0) { pow = (pow * x) % mod; } x = (x * x) % mod; b /= 2; } return pow; } 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 void print(char A[]) { for (char c : A) { out.print(c); } out.println(); } static void print(boolean A[]) { for (boolean c : A) { out.print(c + " "); } out.println(); } static void print(int A[]) { for (int c : A) { out.print(c + " "); } out.println(); } static void print(long A[]) { for (long i : A) { out.print(i + " "); } out.println(); } static void print(List<Integer> A) { for (int a : A) { out.print(a + " "); } } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static String s() { return in.nextLine(); } static int[] input(int N) { int A[] = new int[N]; for (int i = 0; i < N; i++) { A[i] = in.nextInt(); } return A; } static long[] inputLong(int N) { long A[] = new long[N]; for (int i = 0; i < A.length; i++) { A[i] = in.nextLong(); } return A; } static int GCD(int a, int b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static long GCD(long a, long b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } } class SegmentTree { long[] t; public SegmentTree(int n) { t = new long[n + n]; Arrays.fill(t, Long.MIN_VALUE); } public long get(int i) { return t[i + t.length / 2]; } public void add(int i, long value) { i += t.length / 2; t[i] = value; for (; i > 1; i >>= 1) { t[i >> 1] = Math.max(t[i], t[i ^ 1]); } } // max[a, b] public long max(int a, int b) { long res = Long.MIN_VALUE; for (a += t.length / 2, b += t.length / 2; a <= b; a = (a + 1) >> 1, b = (b - 1) >> 1) { if ((a & 1) != 0) { res = Math.max(res, t[a]); } if ((b & 1) == 0) { res = Math.max(res, t[b]); } } return res; } } class Pair { int i, j; Pair(int i, int j) { this.i = i; this.j = j; } } 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
//package round718; import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Queue; public class D2 { InputStream is; FastWriter out; String INPUT = "";//2 5 9 9 9 9 9 8 8 8 8 5 6 7 8 9"; void solve() { int n = ni(), m = ni(), K = ni(); int[][] a = new int[2*n+1][2*m+1]; for(int i = 0;i < n;i++){ int[] u = na(m-1); for(int j = 0;j < m-1;j++){ a[2*i][2*j+1] = u[j]; } } for(int i = 0;i < n-1;i++){ int[] u = na(m); for(int j = 0;j < m;j++){ a[2*i+1][2*j] = u[j]; } } if(K % 2 == 1){ for(int i = 0;i < n;i++){ for(int j = 0;j < m;j++){ out.print(-1 + " "); } out.println(); } return; } int[][][] dp = new int[K/2+1][n][m]; int[] dr = {1, 0, -1, 0}; int[] dc = {0, 1, 0, -1}; for(int i = 1;i <= K/2;i++){ for(int j = 0;j < n;j++){ for(int k = 0;k < m;k++){ dp[i][j][k] = Integer.MAX_VALUE; for(int l = 0;l < 4;l++){ int jj = j + dr[l], kk = k + dc[l]; if(jj >= 0 && jj < n && kk >= 0 && kk < m){ dp[i][j][k] = Math.min(dp[i][j][k], dp[i-1][jj][kk] + a[j+jj][k+kk]); } } } } } for(int i = 0;i < n;i++){ for(int j = 0;j < m;j++){ out.print(dp[K/2][i][j] * 2 + " "); } out.println(); } } void run() throws Exception { // int n = 500, m = 500; // Random gen = new Random(); // StringBuilder sb = new StringBuilder(); // sb.append(n + " "); // sb.append(n + " "); // sb.append(20 + " "); // for (int i = 0; i < n; i++) { // for(int j = 0;j < m-1;j++) { // sb.append(gen.nextInt(200000) + " "); // } // } // for (int i = 0; i < n-1; i++) { // for(int j = 0;j < m;j++) { // sb.append(gen.nextInt(200000) + " "); // } // } // INPUT = sb.toString(); 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 D2().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
1517_D. Explorer Space
CODEFORCES
// Don't place your source in a package import javax.swing.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int T=1; for(int t=0;t<T;t++){ int n=Int(),m=Int(),k=Int(); List<int[]>g[]=new ArrayList[n*m+1]; for(int i=0;i<g.length;i++){ g[i]=new ArrayList<>(); } for(int i=0;i<n;i++){ for(int j=0;j<m-1;j++){ int w=Int(); int u=i*m+j; int v=i*m+(j+1); g[u].add(new int[]{v,w}); g[v].add(new int[]{u,w}); } } for(int i=0;i<n-1;i++){ for(int j=0;j<m;j++){ int w=Int(); int u=i*m+j; int v=(i+1)*m+j; g[u].add(new int[]{v,w}); g[v].add(new int[]{u,w}); } } Solution sol=new Solution(out); sol.solution(n,m,k,g); } out.close(); } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution{ PrintWriter out; public Solution(PrintWriter out){ this.out=out; } List<int[]>g[]; int n,m; long INF=10000000000000000l; int curr=-1,curc=-1; long mn=Long.MAX_VALUE; long dp[][]; public void solution(int n,int m,int k,List<int[]>g[]){ //edge : 4 directions. this.n=n; this.m=m; long res[][]=new long[n][m]; if(k%2==1){ for(int i=0;i<n;i++){ Arrays.fill(res[i],-1); } print(res); return; } this.g=g; dp=new long[n*m+1][k/2+2]; for(int i=0;i<dp.length;i++){ Arrays.fill(dp[i],-1); } for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ int id=i*m+j; dfs(id,k/2); } } for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ int id=i*m+j; res[i][j]=dp[id][k/2]; } } print(res); } public long dfs(int id,int cnt){ if(cnt==0){ return 0; } if(dp[id][cnt]!=-1)return dp[id][cnt]; int r=id/m; int c=id%m; long res=Long.MAX_VALUE; for(int p[]:g[id]){ int next=p[0],w=p[1]; res=Math.min(res,w*2+dfs(next,cnt-1)); } dp[id][cnt]=res; return res; } public int dis(int x1,int y1,int x2,int y2){ return Math.abs(x1-x2)+Math.abs(y1-y2); } public void print(long A[][]){ for(int i=0;i<A.length;i++){ for(int j=0;j<A[0].length;j++){ out.print(A[i][j]+" "); } out.println(); } } } class Solution1{ PrintWriter out; public Solution1(PrintWriter out){ this.out=out; } public void solution(int A[]){ } } /* ;\ |' \ _ ; : ; / `-. /: : | | ,-.`-. ,': : | \ : `. `. ,'-. : | \ ; ; `-.__,' `-.| \ ; ; ::: ,::'`:. `. \ `-. : ` :. `. \ \ \ , ; ,: (\ \ :., :. ,'o)): ` `-. ,/,' ;' ,::"'`.`---' `. `-._ ,/ : ; '" `;' ,--`. ;/ :; ; ,:' ( ,:) ,.,:. ; ,:., ,-._ `. \""'/ '::' `:'` ,'( \`._____.-'"' ;, ; `. `. `._`-. \\ ;:. ;: `-._`-.\ \`. '`:. : |' `. `\ ) \ -hrr- ` ;: | `--\__,' '` ,' ,-' free bug dog */
cubic
1517_D. Explorer Space
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 NINF = -1000000000000000000L; static FastScanner sc; static PrintWriter pw; static final int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}}; static final int MO = 1200; public static void main(String[] args) { sc = new FastScanner(); pw = new PrintWriter(System.out); int N = sc.ni(); int M = sc.ni(); int K = sc.ni(); int[][] LR = new int[N][M-1]; for (int i = 0; i < N; i++) { LR[i] = sc.intArray(M-1,0); } int[][] UD = new int[N-1][M]; for (int i = 0; i < N-1; i++) { UD[i] = sc.intArray(M,0); } if (K%2==0) { int T = K/2; int[][] dist = new int[N][M]; for (int step = 1; step <= T; step++) { int[][] newDist = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { newDist[i][j] = INF; //up if (i > 0) { newDist[i][j] = Math.min(newDist[i][j],UD[i-1][j]+dist[i-1][j]); } //down if (i < N-1) { newDist[i][j] = Math.min(newDist[i][j],UD[i][j]+dist[i+1][j]); } //left if (j > 0) { newDist[i][j] = Math.min(newDist[i][j],LR[i][j-1]+dist[i][j-1]); } //right if (j < M-1) { newDist[i][j] = Math.min(newDist[i][j],LR[i][j]+dist[i][j+1]); } } } dist = newDist; } for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { pw.print((2*dist[i][j]) + " "); } pw.println(); } } else { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { pw.print("-1 "); } pw.println(); } } pw.close(); } 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) { int ablock = a[0]/MO; int bblock = b[0]/MO; if (ablock != bblock) return ablock-bblock; else return a[1]-b[1]; } }); } 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; } 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
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class Main { static PrintWriter pw; static _Scanner sc; public static void main(String[] args) throws Exception { sc = new _Scanner(System.in); pw = new PrintWriter(System.out); //long startTime = System.currentTimeMillis(); //int t = sc.nextInt(); int t = 1; while (t-- > 0) { solve(); } pw.flush(); //System.out.println("time: " + (System.currentTimeMillis() - startTime)); } private static void solve() throws Exception { int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt(); int[][] h = new int[n][m - 1]; int[][] v = new int[n - 1][m]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m - 1; ++j) { h[i][j] = sc.nextInt(); } } for (int i = 0; i < n - 1; ++i) { for (int j = 0; j < m; ++j) { v[i][j] = sc.nextInt(); } } if (k % 2 == 1) { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (j > 0) { pw.print(" "); } pw.print(-1); } pw.println(); } return; } k = k / 2; long[][] d = new long[n][m]; for (int ki = 0; ki < k; ++ki) { long[][] dk = new long[n][m]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { long val = Integer.MAX_VALUE; if (j < m - 1) { val = Math.min(val, d[i][j + 1] + h[i][j]); } if (i < n - 1) { val = Math.min(val, d[i + 1][j] + v[i][j]); } if (j > 0) { val = Math.min(val, d[i][j - 1] + h[i][j - 1]); } if (i > 0) { val = Math.min(val, d[i - 1][j] + v[i - 1][j]); } dk[i][j] = val; } } d = dk; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (j > 0) { pw.print(" "); } pw.print(d[i][j] * 2); } pw.println(); } } static class Shuffle { static void run(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * in.length); int tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } static void run(long[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * in.length); long tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } static <T> void run(List<T> in) { for (int i = 0; i < in.size(); i++) { int idx = (int) (Math.random() * in.size()); T tmp = in.get(i); in.set(i, in.get(idx)); in.set(idx, tmp); } } } static class _Scanner { StringTokenizer st; BufferedReader br; _Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } _Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int[] intArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } long[] longArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } int[] intArrSorted(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); Shuffle.run(in); Arrays.sort(in); return in; } long[] longArrSorted(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); Shuffle.run(in); Arrays.sort(in); return in; } Integer[] IntegerArr(int n) throws IOException { Integer[] in = new Integer[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } Long[] LongArr(int n) throws IOException { Long[] in = new Long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return nextToken().charAt(0); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } boolean ready() throws IOException { return br.ready(); } } }
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.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); DExplorerSpace solver = new DExplorerSpace(); solver.solve(1, in, out); out.close(); } static class DExplorerSpace { static final int oo = 1000000000; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(); int[][] right = new int[n][m - 1]; int[][] down = new int[n - 1][m]; for (int i = 0; i < n; i++) right[i] = in.readIntArray(m - 1); for (int i = 0; i + 1 < n; i++) down[i] = in.readIntArray(m); if (k % 2 == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) out.print(-1 + " "); out.println(); } return; } 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], oo); for (int i = 0; i < n; i++) for (int j = 0; j < m - 1; 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++) { out.print(2 * dp[k / 2][i][j] + " "); } out.println(); } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.print('\n'); } public void close() { writer.close(); } } 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[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } 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 int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
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.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { static int n; static int m; static int steps; static long[][] distJ; static long[][] distI; static long[][][] memo; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); m = in.nextInt(); steps = in.nextInt(); memo = new long[n][m][steps]; distJ = new long[n][m - 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { distJ[i][j] = in.nextLong(); } } distI = new long[n - 1][m]; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { distI[i][j] = in.nextLong(); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (steps % 2 != 0) { out.print(-1 + " "); } else { out.print(2 * lowestCost(i, j, steps / 2) + " "); } } out.println(); } } private long lowestCost(int i, int j, int distance) { if (distance == 0) { return 0; } if (memo[i][j][distance] > 0) { return memo[i][j][distance]; } long minDist = Long.MAX_VALUE; //j + 1 and j -1 if (j < m - 1) { // move forward on j minDist = Math.min(minDist, distJ[i][j] + lowestCost(i, j + 1, distance - 1)); } if (j > 0) { // move backward on j minDist = Math.min(minDist, distJ[i][j - 1] + lowestCost(i, j - 1, distance - 1)); } if (i < n - 1) { // move forward on i minDist = Math.min(minDist, distI[i][j] + lowestCost(i + 1, j, distance - 1)); } if (i > 0) { // move backward on i minDist = Math.min(minDist, distI[i - 1][j] + lowestCost(i - 1, j, distance - 1)); } //memoize memo[i][j][distance] = minDist; return minDist; } } 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(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.PrintWriter; import java.util.*; public class D { static Scanner sc; static PrintWriter out; public static void main(String[] args) throws Exception { sc = new Scanner(System.in); out = new PrintWriter(System.out); //int t = sc.nextInt(); for(int i=0; i<1; i++) { solve(); } out.flush(); } static void solve() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int[][] a = new int[n][m-1]; int[][] b = new int[n-1][m]; for(int i=0 ;i<n; i++) { for(int j=0; j<m-1; j++) { a[i][j] = sc.nextInt(); } } for(int i=0 ;i<n-1; i++) { for(int j=0; j<m; j++) { b[i][j] = sc.nextInt(); } } if(k % 2 == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (j > 0) out.print(" "); out.print("-1"); } out.println(); } return; } int[][] prev = new int[n][m]; k /= 2; for(int l=0; l<k; l++) { int[][] next = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { next[i][j] = Integer.MAX_VALUE; if(i>0) { next[i][j] = Math.min(next[i][j], prev[i-1][j] + b[i-1][j]); } if(i+1<n) { next[i][j] = Math.min(next[i][j], prev[i+1][j] + b[i][j]); } if(j>0) { next[i][j] = Math.min(next[i][j], prev[i][j-1] + a[i][j-1]); } if(j+1<m) { next[i][j] = Math.min(next[i][j], prev[i][j+1] + a[i][j]); } } } prev = next; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (j > 0) out.print(" "); out.print(prev[i][j] * 2); } out.println(); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; public class EdE { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; static long[][][] paths; static long[] powers501; public static void main(String[] havish) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); paths = new long[n+1][m+1][4]; //up down left right; powers501 = new long[5]; powers501[0] = 1; for(int j = 1;j<5;j++){ powers501[j] = 501L*powers501[j-1]; } long[][][]dp = new long[n+1][m+1][k/2+2]; for(int i = 1;i<=n;i++){ for(int j = 1;j<=m-1;j++){ int val = sc.nextInt(); paths[i][j][3] = val; paths[i][j+1][2] = val; // paths.put(powers501[3]*i + powers501[2]*j + powers501[1]*i + powers501[0]*(j+1), val); // paths.put(powers501[3]*i + powers501[2]*(j+1) + powers501[1]*i + powers501[0]*j, val); } } for(int i = 1;i<=n-1;i++){ for(int j = 1;j<=m;j++){ int val = sc.nextInt(); // paths.put(powers501[3]*(i+1) + powers501[2]*j + powers501[1]*i + powers501[0]*j, val); // paths.put(powers501[3]*i + powers501[2]*j + powers501[1]*(i+1) + powers501[0]*j, val); paths[i][j][1] = val; paths[i+1][j][0] = val; } } for(int j = 1;j<=n;j++){ for(int i = 1;i<=m;i++){ Arrays.fill(dp[j][i], Integer.MAX_VALUE); dp[j][i][0] = 0; } } for(int steps = 1;steps<k/2+2;steps++){ for(int i = 1;i<=n;i++){ for(int j = 1;j<=m;j++){ if (i-1 > 0) { dp[i][j][steps] = Math.min(dp[i-1][j][steps-1] + getVal(i, j, i-1, j), dp[i][j][steps]); } if (j-1 > 0) { dp[i][j][steps] = Math.min(dp[i][j-1][steps-1] + getVal(i, j, i, j-1), dp[i][j][steps]); } if (i+1 <= n) { dp[i][j][steps] = Math.min(dp[i+1][j][steps-1] + getVal(i, j, i+1, j), dp[i][j][steps]); } if (j+1 <= m) { dp[i][j][steps] = Math.min(dp[i][j+1][steps-1] + getVal(i, j, i, j+1), dp[i][j][steps]); } } } } if (k%2 == 1){ for(int j = 1;j<=n;j++){ for(int s = 1;s<=m;s++){ out.print(-1 + " "); } out.println(); } } else{ for(int j = 1;j<=n;j++){ for(int s = 1;s<=m;s++){ out.print(dp[j][s][k/2]*2L + " "); } out.println(); } } out.close(); } public static long getVal(int x1, int y1, int x2, int y2) { if (x2 == x1+1) return paths[x1][y1][1]; else if (x1 == x2+1) return paths[x1][y1][0]; else if (y2 == y1 + 1) return paths[x1][y1][3]; else return paths[x1][y1][2]; } 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
1517_D. Explorer Space
CODEFORCES
import java.util.Scanner; public class D { static long[][][] dp; static int[][] hor, ver; static int n, m; static int[][] dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; public static boolean isValid (int row, int col) { return row >= 0 && col >= 0 && row < n && col < m; } public static void minCost (int row, int col, int k) { if (k == 0) return; if (k == 2) { long min = Long.MAX_VALUE; for (int i = 0; i < 4; i++) { if (isValid(row + dir[i][0], col + dir[i][1])) { if ((row + dir[i][0]) == row) { if ((col + dir[i][1]) > col) { min = Math.min(min, hor[row][col]); } else { min = Math.min(min, hor[row][col - 1]); } } else { if ((row + dir[i][0]) > row) { min = Math.min(min, ver[row][col]); } else { min = Math.min(min, ver[row - 1][col]); } } } } dp[row][col][k] = 2 * min; return; } if (dp[row][col][k] != Long.MAX_VALUE) return; long min = Long.MAX_VALUE; for (int i = 0; i < 4; i++) { if (isValid(row + dir[i][0], col + dir[i][1])) { if (k >= 4) { minCost(row + dir[i][0], col + dir[i][1], k - 2); int edge = 0; if ((row + dir[i][0]) == row) { if ((col + dir[i][1]) > col) { edge = hor[row][col]; } else { edge = hor[row][col - 1]; } } else { if ((row + dir[i][0]) > row) { edge = ver[row][col]; } else { edge = ver[row - 1][col]; } } min = Math.min(min, 2 * edge + dp[row + dir[i][0]][col + dir[i][1]][k - 2]); } } } dp[row][col][k] = min; } public static void main(String[] args) { Scanner input = new Scanner(System.in); n = input.nextInt(); m = input.nextInt(); int k = input.nextInt(); hor = new int[n][m - 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { hor[i][j] = input.nextInt(); } } ver = new int[n - 1][m]; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { ver[i][j] = input.nextInt(); } } if (k % 2 != 0) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print(-1 + " "); } System.out.println(""); } } else { dp = new long[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++) { dp[i][j][x] = Long.MAX_VALUE; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { minCost(i, j, k); System.out.print(dp[i][j][k] + " "); } System.out.println(""); } } input.close(); } }
cubic
1517_D. Explorer Space
CODEFORCES
//Utilities import java.io.*; import java.util.*; public class Main { static int n, m, k; static int[][] horW, verW; static int[][][] dp = new int[505][505][15]; public static void main(String[] args) throws IOException { for (int i = 0; i < 505; i++) { for (int j = 0; j < 505; j++) { for (int k = 0; k < 15; k++) { dp[i][j][k] = -1; } } } n = in.iscan(); m = in.iscan(); k =in.iscan(); horW = new int[n+1][m]; verW = new int[n][m+1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m-1; j++) { horW[i][j] = in.iscan(); } } for (int i = 1; i <= n-1; i++) { for (int j = 1; j <= m; j++) { verW[i][j] = in.iscan(); } } int min = Integer.MAX_VALUE; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (k % 2 == 1) { out.print(-1 + " "); continue; } out.print(dfs(i, j, k/2) * 2 + " "); } out.println(); } out.close(); } static int dfs(int r, int c, int k) { if (dp[r][c][k] != -1) { return dp[r][c][k]; } if (k == 0) { return dp[r][c][k] = 0; } int min = Integer.MAX_VALUE; if (r - 1 >= 1) { min = Math.min(min, verW[r-1][c] + dfs(r-1, c, k-1)); } if (r + 1 <= n) { min = Math.min(min, verW[r][c] + dfs(r+1, c, k-1)); } if (c - 1 >= 1) { min = Math.min(min, horW[r][c-1] + dfs(r, c-1, k-1)); } if (c + 1 <= m) { min = Math.min(min, horW[r][c] + dfs(r, c+1, k-1)); } return dp[r][c][k] = min; } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static long gcd (long a, long b) { return b == 0 ? a : gcd (b, a % b); } public static long lcm (long a, long b) { return a * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static int fast_pow (int b, int x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; public class Main { public static void deal(int n,int m,int k,int[][] d1,int[][] d2) { 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; } int[][][] dp = new int[k/2+1][n][m]; for(int i=0;i<k/2;i++) { for(int j=0;j<n;j++) { for(int l=0;l<m;l++) { int min = Integer.MAX_VALUE; if(j>0) min = Math.min(min,d2[j-1][l]+dp[i][j-1][l]); if(j<n-1) min = Math.min(min,d2[j][l]+dp[i][j+1][l]); if(l>0) min = Math.min(min,d1[j][l-1]+dp[i][j][l-1]); if(l<m-1) min = Math.min(min,d1[j][l]+dp[i][j][l+1]); dp[i+1][j][l] = min; } } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { System.out.print(dp[k/2][i][j]*2); System.out.print(" "); } System.out.println(); } } public static void main(String[] args) { MyScanner scanner = new MyScanner(); int n = scanner.nextInt(); int m = scanner.nextInt(); int k = scanner.nextInt(); int[][] d1 = new int[n][m-1]; int[][] d2 = new int[n-1][m]; for(int i=0;i<n;i++) { for(int j=0;j<m-1;j++) { d1[i][j] = scanner.nextInt(); } } for(int i=0;i<n-1;i++) { for(int j=0;j<m;j++) { d2[i][j] = scanner.nextInt(); } } deal(n,m,k,d1,d2); } 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
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; public class D { 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]; } } static int n,m,k,uu[][],rr[][],dd[][],ll[][],dp[][][]; public static void main(String args[]) throws IOException { Scan input=new Scan(); StringBuilder ans=new StringBuilder(""); n=input.scanInt(); m=input.scanInt(); k=input.scanInt(); dp=new int[n][m][k]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { for(int kk=0;kk<k;kk++) { dp[i][j][kk]=-1; } } } uu=new int[n][m]; rr=new int[n][m]; dd=new int[n][m]; ll=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m-1;j++) { int tmp=input.scanInt(); rr[i][j]=tmp; ll[i][j+1]=tmp; } } for(int i=0;i<n-1;i++) { for(int j=0;j<m;j++) { int tmp=input.scanInt(); dd[i][j]=tmp; uu[i+1][j]=tmp; } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(k%2!=0) { ans.append(-1+" "); continue; } ans.append((2*solve(i,j,k/2))+" "); } ans.append("\n"); } System.out.println(ans); } public static int solve(int x,int y,int rem) { if(rem==0) { return 0; } if(dp[x][y][rem]!=-1) { return dp[x][y][rem]; } int ans=Integer.MAX_VALUE/10; if(uu[x][y]!=0) { ans=Math.min(ans,uu[x][y]+solve(x-1,y,rem-1)); } if(rr[x][y]!=0) { ans=Math.min(ans,rr[x][y]+solve(x,y+1,rem-1)); } if(dd[x][y]!=0) { ans=Math.min(ans,dd[x][y]+solve(x+1,y,rem-1)); } if(ll[x][y]!=0) { ans=Math.min(ans,ll[x][y]+solve(x,y-1,rem-1)); } dp[x][y][rem]=ans; return ans; } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; public class CF1517D extends PrintWriter { CF1517D() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1517D o = new CF1517D(); o.main(); o.flush(); } static final int INF = 0x3f3f3f3f; void main() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); if (k % 2 == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) print("-1 "); println(); } return; } k /= 2; int[][] hh = new int[n][m - 1]; for (int i = 0; i < n; i++) for (int j = 0; j < m - 1; j++) hh[i][j] = sc.nextInt(); int[][] vv = new int[n - 1][m]; for (int i = 0; i < n - 1; i++) for (int j = 0; j < m; j++) vv[i][j] = sc.nextInt(); int[][] dp = new int[n][m]; int[][] dq = new int[n][m]; while (k-- > 0) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int x = INF; if (i > 0) x = Math.min(x, dp[i - 1][j] + vv[i - 1][j]); if (j > 0) x = Math.min(x, dp[i][j - 1] + hh[i][j - 1]); if (i + 1 < n) x = Math.min(x, dp[i + 1][j] + vv[i][j]); if (j + 1 < m) x = Math.min(x, dp[i][j + 1] + hh[i][j]); dq[i][j] = x; } int[][] tmp = dp; dp = dq; dq = tmp; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) print(dp[i][j] * 2 + " "); println(); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.Array; 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 int x,y; public static void main(String[] args){ FastScanner in = new FastScanner(); FastWriter out = new FastWriter(); int n=in.nextInt(); int m=in.nextInt(); int k=in.nextInt(); int[][] right=new int[n][m-1]; int[][] down=new int[n-1][m]; for (int i = 0; i < n; i++) { right[i]=in.nextArray(m-1); } for (int i = 0; i < n - 1; i++) { down[i]=in.nextArray(m); } if(k%2!=0){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print("-1 "); } out.println(); } }else { int[][] dp=new int[n][m]; int[][] dp1=new int[n][m]; for (int i = 0; i < k / 2; i++) { for (int j = 0; j < n; j++) { for (int l = 0; l < m; l++) { int ans=Integer.MAX_VALUE; if(j>0){ ans=Math.min(ans,dp[j-1][l]+down[j-1][l]); } if(l>0){ ans=Math.min(ans,dp[j][l-1]+right[j][l-1]); } if(j!=n-1){ ans=Math.min(ans,dp[j+1][l]+down[j][l]); } if(l!=m-1){ ans=Math.min(ans,dp[j][l+1]+right[j][l]); } dp1[j][l]=ans; } } dp=dp1; dp1=new int[n][m]; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.println((2*dp[i][j])+" "); } out.println(); } } out.close(); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; public class D1517 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int[][] costRight = new int[n][m - 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { costRight[i][j] = sc.nextInt(); } } int[][] costDown = new int[n - 1][m]; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { costDown[i][j] = sc.nextInt(); } } if (k % 2 == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { pw.print(-1 + " "); } pw.println(); } pw.close(); return; } int[][][] dp = new int[k + 1][n][m]; for (int w = 2; w <= k; w += 2) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dp[w][i][j] = (int) 1e9; if (i + 1 < n) dp[w][i][j] = Math.min(dp[w][i][j], 2 * costDown[i][j] + dp[w - 2][i + 1][j]); if (i - 1 >= 0) dp[w][i][j] = Math.min(dp[w][i][j], 2 * costDown[i - 1][j] + dp[w - 2][i - 1][j]); if (j + 1 < m) dp[w][i][j] = Math.min(dp[w][i][j], 2 * costRight[i][j] + dp[w - 2][i][j + 1]); if (j - 1 >= 0) dp[w][i][j] = Math.min(dp[w][i][j], 2 * costRight[i][j - 1] + dp[w - 2][i][j - 1]); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { pw.print(dp[k][i][j] + " "); } pw.println(); } 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
1517_D. Explorer Space
CODEFORCES
import java.util.*; public class Main { public static Scanner scan = new Scanner(System.in); int n, m; int[][] x; int[][] y; int k, k2; int[][] sol0; int[][] sol1; public Main(int[][] x, int[][] y, int k) { this.x = x; this.y = y; this.k = k; this.n = x.length; this.m = x[0].length; } void go() { if(k%2 != 0) { for(int i=0; i<n; ++i) { for(int j=0; j<m; ++j) { System.out.print(-1 + " "); } System.out.println(); } return; } k2 = k/2; sol0 = new int[n][m]; sol1 = new int[n][m]; for(int d=0; d<k2; ++d) { var zzz = sol1; sol1 = sol0; sol0 = zzz; for(int i=0; i<n; ++i) for(int j=0; j<m; ++j) { update(i,j); } } for(int i=0; i<n; ++i) { for(int j=0; j<m; ++j) { System.out.print(sol1[i][j]*2 + " "); } System.out.println(); } } void update(int i, int j) { int ret = Integer.MAX_VALUE; if(i>0) ret = Math.min(ret, sol0[i-1][j] + y[i-1][j]); if(j>0) ret = Math.min(ret, sol0[i][j-1] + x[i][j-1]); if(i < n-1) ret = Math.min(ret, sol0[i+1][j] + y[i][j]); if(j < m-1) ret = Math.min(ret, sol0[i][j+1] + x[i][j]); sol1[i][j] = ret; } public static void main(String[] args) { int n = scan.nextInt(); int m = scan.nextInt(); int k = scan.nextInt(); int x[][] = new int[n][m]; int y[][] = new int[n][m]; for(int i=0; i<n; ++i) { for(int j=0; j<m-1; ++j) { x[i][j] = scan.nextInt(); } } for(int i=0; i<n-1; ++i) { for(int j=0; j<m; ++j) { y[i][j] = scan.nextInt(); } } Main mm = new Main(x,y,k); mm.go(); } }
cubic
1517_D. Explorer Space
CODEFORCES
// Main Code at the Bottom import java.util.*; import java.io.*; public class Main{ //Fast IO class static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { boolean env=System.getProperty("ONLINE_JUDGE") != null; //env=true; if(!env) { try { br=new BufferedReader(new FileReader("src\\input.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } } 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()); } 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 long MOD=(long)1e9+7; //debug static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); //Global variables and functions static int code(int x,int y) { return 505*x+y; } static class pair{ int x,y; pair(int a,int b){ this.x=a; this.y=b; } public boolean equals(Object obj) { if(obj == null || obj.getClass()!= this.getClass()) return false; pair p = (pair) obj; return (this.x==p.x && this.y==p.y); } public int hashCode() { return Objects.hash(x,y); } } static int hor[][],ver[][]; static int moves[][]= {{-1,0},{1,0},{0,-1},{0,1}}; static int n,m; static int dp[][][]; static int solve(int x,int y,int k) { if(k==0) { return 0; } if(dp[x][y][k]!=0) return dp[x][y][k]; int min=(int)MOD; for(int mo[]: moves) { int X=x+mo[0],Y=y+mo[1]; if(X<0 || X>=n || Y<0 || Y>=m) continue; int val=0; if(mo[0]==1) val=ver[x][y]; else if(mo[0]==-1) val=ver[x-1][y]; else if(mo[1]==1) val=hor[x][y]; else val=hor[x][y-1]; min=Math.min(min, 2*val+solve(X,Y,k-2)); } return dp[x][y][k]=min; } //Main function(The main code starts from here) public static void main (String[] args) throws java.lang.Exception { int test=1; //test=sc.nextInt(); while(test-->0) { n=sc.nextInt();m=sc.nextInt(); int k=sc.nextInt(); if(k%2!=0) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) out.print(-1+" "); out.println(); } continue; } 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(); } } dp=new int[n][m][k+1]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { out.print(solve(i,j,k)+" "); } out.println(); } } out.flush(); out.close(); } }
cubic
1517_D. Explorer Space
CODEFORCES
//created by Whiplash99 import java.io.*; import java.util.*; public class D { private static ArrayDeque<Integer>[][] edge; private static long[][] dp[],w1,w2; private static int N,M,K; private static void answer() { StringBuilder sb=new StringBuilder(); for(int i=0;i<N;i++) { for (int j = 0; j < M; j++) sb.append(dp[i][j][K]).append(" "); sb.append("\n"); } System.out.println(sb); } private static long solve(int i, int j, int pos) { if(pos==0) return 0; if(dp[i][j][pos]!=-1) return dp[i][j][pos]; long a=Long.MAX_VALUE/100; if(i-1>=0) a=Math.min(a,solve(i-1,j,pos-1)+w2[i-1][j]); if(i<N-1) a=Math.min(a,solve(i+1,j,pos-1)+w2[i][j]); if(j-1>=0) a=Math.min(a,solve(i,j-1,pos-1)+w1[i][j-1]); if(j<M-1) a=Math.min(a,solve(i,j+1,pos-1)+w1[i][j]); return dp[i][j][pos]=a; } public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i; String[] s=br.readLine().trim().split(" "); N=Integer.parseInt(s[0]); M=Integer.parseInt(s[1]); K=Integer.parseInt(s[2]); edge=new ArrayDeque[N][M]; for(i=0;i<N;i++) { for(int j=0;j<M;j++) edge[i][j]=new ArrayDeque<>(); } w1=new long[N][M-1]; w2=new long[N-1][M]; dp=new long[N][M][K/2+1]; for(i=0;i<N;i++) { s=br.readLine().trim().split(" "); for(int j=0;j<M-1;j++) w1[i][j]=Integer.parseInt(s[j])*2L; } for(i=0;i<N-1;i++) { s=br.readLine().trim().split(" "); for(int j=0;j<M;j++) w2[i][j]=Integer.parseInt(s[j])*2L; } for(i=0;i<N;i++) { for(int j=0;j<M;j++) Arrays.fill(dp[i][j],-1); } if(K%2==1) { K/=2; answer(); System.exit(0); } K/=2; for(i=0;i<N;i++) { for(int j=0;j<M;j++) solve(i,j,K); } answer(); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Main { static FastReader sc=new FastReader(); static long dp[][][]; static int mod=1000000007; public static void main(String[] args) throws IOException { //CHECK FOR N=1 //CHECK FOR N=1 //CHECK FOR N=1 //CHECK FOR N=1 PrintWriter out=new PrintWriter(System.out); // StringBuffer sb=new StringBuffer(""); int ttt=1; // ttt =i(); outer :while (ttt-- > 0) { int n=i(); int m=i(); int k=i(); int A[][]=input(n,m-1); int B[][]=input(n-1, m); dp=new long[n+1][m+1][k+1]; for(int ii=0;ii<n;ii++) { for(int jj=0;jj<m;jj++) { Arrays.fill(dp[ii][jj],-1); } } if(k%2!=0) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { System.out.print("-1 "); } System.out.println(); } } else { go(A, B, 0, 0, k/2, n, m); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { System.out.print(dp[i][j][k/2]*2+" "); } System.out.println(); } } } out.close(); //System.out.println(sb.toString()); //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 //CHECK FOR N=1 //CHECK FOR N=1 } static long go(int A[][],int B[][],int i,int j,int k,int l,int p) { if(k==0) return 0; if(i>=l || j>=p) return Integer.MAX_VALUE; if(dp[i][j][k]!=-1) return dp[i][j][k]; // if(i==m && j==n && k<org) { // return Integer.MAX_VALUE; // } long op1=Long.MAX_VALUE; if(i+1<l) op1=Math.min(op1,go(A, B, i+1, j, k-1,l,p)+B[i][j]); if(i-1>=0) op1=Math.min(op1,go(A, B, i-1, j, k-1,l,p)+B[i-1][j]); if(j+1<p) op1=Math.min(op1,go(A, B, i, j+1, k-1,l,p)+A[i][j]); if(j-1>=0) op1=Math.min(op1,go(A, B, i, j-1, k-1,l,p)+A[i][j-1]); go(A, B, i+1, j, k, l, p); go(A, B, i, j+1, k, l, p); return dp[i][j][k]=op1; } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static long sum(int A[]) { long sum=0; for(int i : A) { sum+=i; } return sum; } static long sum(long A[]) { long sum=0; for(long i : A) { sum+=i; } return sum; } static void reverse(long A[]) { int n=A.length; long B[]=new long[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void reverse(int A[]) { int n=A.length; int B[]=new int[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void input(int A[],int B[]) { for(int i=0;i<A.length;i++) { A[i]=sc.nextInt(); B[i]=sc.nextInt(); } } static int[][] input(int n,int m){ int A[][]=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { A[i][j]=i(); } } return A; } static char[][] charinput(int n,int m){ char A[][]=new char[n][m]; for(int i=0;i<n;i++) { String s=s(); for(int j=0;j<m;j++) { A[i][j]=s.charAt(j); } } return A; } static int max(int A[]) { int max=Integer.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static int min(int A[]) { int min=Integer.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long max(long A[]) { long max=Long.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static long min(long A[]) { long min=Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long [] prefix(long A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] prefix(int A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] suffix(long A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static long [] suffix(int A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static void print(int A[]) { for(int i : A) { System.out.print(i+" "); } System.out.println(); } static void print(long A[]) { for(long i : A) { System.out.print(i+" "); } System.out.println(); } static long mod(long x) { int mod=1000000007; return ((x%mod + mod)%mod); } static String reverse(String s) { StringBuffer p=new StringBuffer(s); p.reverse(); return p.toString(); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static void sort(long[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static String sort(String s) { Character ch[]=new Character[s.length()]; for(int i=0;i<s.length();i++) { ch[i]=s.charAt(i); } Arrays.sort(ch); StringBuffer st=new StringBuffer(""); for(int i=0;i<s.length();i++) { st.append(ch[i]); } return st.toString(); } static HashMap<Integer,Integer> hash(int A[]){ HashMap<Integer,Integer> map=new HashMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Integer,Integer> tree(int A[]){ TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean prime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 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 class Pair implements Comparable<Pair> { int x; int y; int z; Pair(int x,int y,int z){ this.x=x; this.y=y; this.z=z; } @Override // public int compareTo(Pair o) { // if(this.x>o.x) // return 1; // else if(this.x<o.x) // return -1; // else { // if(this.y>o.y) // return 1; // else if(this.y<o.y) // return -1; // else // return 0; // } // } public int compareTo(Pair o) { int p=this.x-this.y; int q=o.x-o.y; if(p>q) return 1; else if(p<q) return -1; return 0; } } 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.io.*; public class B{ static int[][] hor; static int[][] ver; static int n; static int m; static int k; static long[][][] dp; static long dist(int row, int col) { if(k%2==1)return Integer.MAX_VALUE; return 2*make(row,col,k/2); } static long make(int row, int col, int moves) { if(moves == 0) { return 0; } if(dp[row][col][moves]!=-1)return dp[row][col][moves]; long ans = Long.MAX_VALUE; if(col-1>=0) { ans = Math.min(ans, hor[row][col-1]+make(row,col-1,moves-1)); } if(col+1<m) { ans = Math.min(ans, hor[row][col]+make(row,col+1,moves-1)); } if(row-1>=0) { ans = Math.min(ans, ver[row-1][col]+make(row-1,col,moves-1)); } if(row+1<n) { ans = Math.min(ans, ver[row][col]+make(row+1,col,moves-1)); } dp[row][col][moves] = ans; return ans; } public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); n = fs.nextInt(); m = fs.nextInt(); k = fs.nextInt(); hor = new int[n][m]; ver = new int[n][m]; dp = new long[505][505][24]; for(int i=0;i<505;i++)for(int j=0;j<505;j++)for(int k=0;k<24;k++)dp[i][j][k] = -1; for(int i=0;i<n;i++) { for(int j=0;j<m-1;j++) { int a = fs.nextInt(); hor[i][j] = a; } } for(int row=0;row<n-1;row++) { for(int col =0;col<m;col++) { int a = fs.nextInt(); ver[row][col] = a; } } for(int row=0;row<n;row++) { for(int col=0;col<m;col++) { long d = dist(row,col); if(d<Integer.MAX_VALUE) { out.print(d+" "); } else out.print("-1 "); } out.println(); } 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
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; /** * * @Har_Har_Mahadev */ public class D { private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; private static long[][][] dp; private static long[][] ff; private static long[][] ss; public static void process() throws IOException { int n = sc.nextInt(),m = sc.nextInt(),k = sc.nextInt(); ff = new long[n][m]; ss = new long[n][m]; for(int i = 0; i<n; i++) { for(int j = 0; j<m-1; j++) { ff[i][j] = sc.nextLong(); } } for(int i = 0; i<n-1; i++) { for(int j = 0; j<m; j++) { ss[i][j] = sc.nextLong(); } } 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; } dp = new long[n+1][m+1][11]; for(int i = 0; i<=n; i++) { for(int j = 0; j<=m; j++)Arrays.fill(dp[i][j], -1); } for(int i = 0; i<=n; i++) { for(int j = 0; j<=m; j++) { dp[i][j][0] = 0; } } k/=2; long ans[][] = new long[n][m]; for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) { ans[i][j] = solve(i,j,k,n,m)*2L; } } for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++)print(ans[i][j]+" "); println(); } } private static long solve(int i, int j, int k, int n, int m) { if(dp[i][j][k] != -1)return dp[i][j][k]; long ans = Long.MAX_VALUE; if(i+1<n) { ans = min(ans,ss[i][j] + solve(i+1, j, k-1, n, m)); } if(i-1>=0) { ans = min(ans,ss[i-1][j] + solve(i-1, j, k-1, n, m)); } if(j+1<m) { ans = min(ans,ff[i][j] + solve(i, j+1, k-1, n, m)); } if(j-1>=0) { ans = min(ans,ff[i][j-1] + solve(i, j-1, k-1, n, m)); } return dp[i][j][k] = ans; } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= static FastScanner sc; static PrintWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new PrintWriter(System.out); } else { sc = new FastScanner(100); out = new PrintWriter("output.txt"); } int t = 1; // t = sc.nextInt(); while (t-- > 0) { process(); } out.flush(); out.close(); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Pair)) return false; // Pair key = (Pair) o; // return x == key.x && y == key.y; // } // // @Override // public int hashCode() { // int result = x; // result = 31 * result + y; // return result; // } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static void println(Object o) { out.println(o); } static void println() { out.println(); } static void print(Object o) { out.print(o); } static void pflush(Object o) { out.println(o); out.flush(); } static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static int max(int x, int y) { return Math.max(x, y); } static int min(int x, int y) { return Math.min(x, y); } static int abs(int x) { return Math.abs(x); } static long abs(long x) { return Math.abs(x); } static long sqrt(long z) { long sqz = (long) Math.sqrt(z); while (sqz * 1L * sqz < z) { sqz++; } while (sqz * 1L * sqz > z) { sqz--; } return sqz; } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } static long max(long x, long y) { return Math.max(x, y); } static long min(long x, long y) { return Math.min(x, y); } public static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } public static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(System.in)); } FastScanner(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; } int[] readArray(int n) throws IOException { int[] A = new int[n]; for (int i = 0; i != n; i++) { A[i] = sc.nextInt(); } return A; } long[] readArrayLong(int n) throws IOException { long[] A = new long[n]; for (int i = 0; i != n; i++) { A[i] = sc.nextLong(); } return A; } } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; public class D { static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; static void solve() { in = new InputReader(System.in); out = new PrintWriter(System.out); int t = 1; while(t-- > 0) { int n = in.nextInt(); int m = in.nextInt(); int K = in.nextInt(); long[][] x = new long[n][]; for(int i = 0; i < n; i++) { x[i] = in.nextLongArray(m - 1); } long[][] y = new long[n - 1][]; for(int i = 0; i < n - 1; i++) { y[i] = in.nextLongArray(m); } if(K % 2 != 0) { for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { out.print("-1 "); } out.println(); } continue; } K /= 2; long[][][] dp = new long[K + 1][n][m]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { for(int k = 1; k <= K; k++) { dp[k][i][j] = Integer.MAX_VALUE; } } } for(int k = 1; k <= K; k++) { for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(i + 1 < n) { dp[k][i][j] = Math.min(dp[k][i][j], dp[k - 1][i + 1][j] + 2 * y[i][j]); } if(i - 1 >= 0) { dp[k][i][j] = Math.min(dp[k][i][j], dp[k - 1][i - 1][j] + 2 * y[i - 1][j]); } if(j + 1 < m) { dp[k][i][j] = Math.min(dp[k][i][j], dp[k - 1][i][j + 1] + 2 * x[i][j]); } if(j - 1 >= 0) { dp[k][i][j] = Math.min(dp[k][i][j], dp[k - 1][i][j - 1] + 2 * x[i][j - 1]); } } } } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { out.print(dp[K][i][j] + " "); } out.println(); } } out.close(); } public static void main(String[] args) { new Thread(null ,new Runnable(){ public void run() { try{ solve(); } catch(Exception e){ e.printStackTrace(); } } },"1",1<<26).start(); } static int[][] graph(int from[], int to[], int n) { int g[][] = new int[n][]; int cnt[] = new int[n]; for (int i = 0; i < from.length; i++) { cnt[from[i]]++; cnt[to[i]]++; } for (int i = 0; i < n; i++) { g[i] = new int[cnt[i]]; } Arrays.fill(cnt, 0); for (int i = 0; i < from.length; i++) { g[from[i]][cnt[from[i]]++] = to[i]; g[to[i]][cnt[to[i]]++] = from[i]; } return g; } static class Pair implements Comparable<Pair>{ int x,y,z; Pair (int x,int y,int z){ this.x=x; this.y=y; this.z=z; } public int compareTo(Pair o) { if (this.x == o.x) return Integer.compare(this.y,o.y); return Integer.compare(this.x,o.x); //return 0; } 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 Integer(x).hashCode() * 31 + new Integer(y).hashCode(); } @Override public String toString() { return x + " " + y; } } static String rev(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return sb.toString(); } static long gcd(long x, long y) { if (y == 0) { return x; } else { return gcd(y, x % y); } } static int gcd(int x, int y) { if (y == 0) { return x; } else { return gcd(y, x % y); } } static int abs(int a, int b) { return (int) Math.abs(a - b); } static long abs(long a, long b) { return (long) Math.abs(a - b); } static int max(int a, int b) { if (a > b) { return a; } else { return b; } } static int min(int a, int b) { if (a > b) { return b; } else { return a; } } static long max(long a, long b) { if (a > b) { return a; } else { return b; } } static long min(long a, long b) { if (a > b) { return b; } else { return a; } } static long pow(long n, long p, long m) { long result = 1; if (p == 0) { return 1; } while (p != 0) { if (p % 2 == 1) { result *= n; } if (result >= m) { result %= m; } p >>= 1; n *= n; if (n >= m) { n %= m; } } return result; } static long pow(long n, long p) { long result = 1; if (p == 0) { return 1; } if (p == 1) { return n; } while (p != 0) { if (p % 2 == 1) { result *= n; } p >>= 1; n *= n; } return result; } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=1; while(T-->0) { int n=input.nextInt(); int m=input.nextInt(); int k=input.nextInt(); int arr1[][]=new int[n+1][m]; for(int i=1;i<=n;i++) { for(int j=1;j<m;j++) { arr1[i][j]=input.nextInt(); } } int arr2[][]=new int[n][m+1]; for(int i=1;i<n;i++) { for(int j=1;j<=m;j++) { arr2[i][j]=input.nextInt(); } } if(k%2==0) { int dp[][][]=new int[n+1][m+1][k+1]; for(int l=2;l<=k;l+=2) { for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { int min=Integer.MAX_VALUE; if(j+1<=m) { min=Math.min(min,dp[i][j+1][l-2]+2*arr1[i][j]); } if(i+1<=n) { min=Math.min(min,dp[i+1][j][l-2]+2*arr2[i][j]); } if(j-1>=1) { min=Math.min(min,dp[i][j-1][l-2]+2*arr1[i][j-1]); } if(i-1>=1) { min=Math.min(min,dp[i-1][j][l-2]+2*arr2[i-1][j]); } dp[i][j][l]=min; } } } for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { out.print(dp[i][j][k]+" "); } out.println(); } } else { for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { out.print(-1+" "); } out.println(); } } } 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
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; // Created by @thesupremeone on 23/04/21 public class ExplorerSpace { int[][] horizontal, vertical; int n, m; long[][][] dp; int large = Integer.MAX_VALUE; boolean isValid(int i, int j){ return i>=0 && j>=0 && i<n && j<m; } long getMin(int i, int j, int k){ if(k==0) return 0; if(dp[i][j][k]!=-1) return dp[i][j][k]; long ans = large; for (int a = 0; a < 2; a++) { for (int d = 0; d < 2; d++) { int dx = a==0 ? (d==0 ? +1 : -1) : 0; int dy = a==1 ? (d==0 ? +1 : -1) : 0; int x = i+dx; int y = j+dy; if(isValid(x, y)){ if(dx==0){ ans = Math.min(horizontal[i][Math.min(j, y)]+getMin(x, y, k-1), ans); }else { ans = Math.min(vertical[Math.min(i, x)][j]+getMin(x, y, k-1), ans); } } } } dp[i][j][k] = ans; return ans; } void solve() throws IOException { n = getInt(); m = getInt(); dp = new long[n+1][m+1][11]; for (int i = 0; i < n+1; i++) { for (int j = 0; j < m+1; j++) { for (int k = 0; k < 11; k++) { dp[i][j][k] = -1; } } } int k = getInt(); horizontal = new int[n][m-1]; vertical = new int[n-1][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m - 1; j++) { horizontal[i][j] = getInt(); } } for (int i = 0; i < n - 1; i++) { for (int j = 0; j < m; j++) { vertical[i][j] = getInt(); } } if(k%2!=0){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { print("-1 "); } println(""); } }else { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { long ans = 2*getMin(i, j, k/2); print(ans+" "); } println(""); } } } public static void main(String[] args) throws Exception { if (isOnlineJudge()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); new ExplorerSpace().solve(); out.flush(); } else { Thread judge = new Thread(); in = new BufferedReader(new FileReader("input.txt")); out = new BufferedWriter(new FileWriter("output.txt")); judge.start(); new ExplorerSpace().solve(); out.flush(); judge.suspend(); } } static boolean isOnlineJudge(){ try { return System.getProperty("ONLINE_JUDGE")!=null || System.getProperty("LOCAL")==null; }catch (Exception e){ return true; } } // Fast Input & Output static BufferedReader in; static StringTokenizer st; static BufferedWriter out; static String getLine() throws IOException{ return in.readLine(); } static String getToken() throws IOException{ if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(getLine()); return st.nextToken(); } static int getInt() throws IOException { return Integer.parseInt(getToken()); } static long getLong() throws IOException { return Long.parseLong(getToken()); } static void print(Object s) throws IOException{ out.write(String.valueOf(s)); } static void println(Object s) throws IOException{ out.write(String.valueOf(s)); out.newLine(); } }
cubic
1517_D. Explorer Space
CODEFORCES
// package com.company.codeforces; import java.util.*; public class Solution { static int n,m,h[][],v[][]; public static void main(String[] args) { Scanner input=new Scanner(System.in); n=input.nextInt(); m=input.nextInt(); int k=input.nextInt(); h=new int[n][m-1]; for (int i = 0; i <n ; i++) { for (int j = 0; j <m-1 ; j++) { h[i][j]=input.nextInt(); } } v=new int[n][m]; for (int i = 0; i <n-1 ; i++) { for (int j = 0; j <m ; j++) { v[i][j]=input.nextInt(); } } int ans[][]=new int[n][m]; dp=new int[501][501][11]; for (int aa[]:ans ) { Arrays.fill(aa,-1); } if (k%2==0) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ans[i][j] = dfs(i, j, k / 2) * 2; } } } for (int i = 0; i <n ; i++) { for (int j = 0; j <m ; j++) { System.out.print(ans[i][j]+" "); } System.out.println(); } } static int dp[][][]; private static int dfs(int i, int j, int k) { if (k==0) return 0; if (dp[i][j][k]!=0){ // System.out.println("hit"); return dp[i][j][k]; } //left int ans=Integer.MAX_VALUE; if (j-1>=0) ans=dfs(i, j-1, k-1)+h[i][j-1]; if (i<n-1) ans=Math.min(ans,dfs(i+1, j, k-1)+v[i][j]); if (i>0) ans=Math.min(ans,dfs(i-1, j, k-1)+v[i-1][j]); if (j<m-1) ans=Math.min(ans,dfs(i, j+1, k-1)+h[i][j]); return dp[i][j][k]= ans; } }
cubic
1517_D. Explorer Space
CODEFORCES
//package Codeforces.Round718Div1_2; import java.io.*; import java.util.*; public class D { static boolean isValid(int n, int m, int i, int j){ return 0<=i && i<n && 0<=j && j<m; } public static void main(String[] args) throws IOException { Soumit sc = new Soumit(); int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); StringBuilder sb = new StringBuilder(); if(k%2==1){ for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ sb.append("-1 "); } sb.append("\n"); } System.out.println(sb); System.exit(0); } k/=2; long[][] horizontaledge = new long[n][m-1]; long[][] verticaledge = new long[n-1][m]; for(int i=0;i<n;i++) horizontaledge[i] = sc.nextLongArray(m-1); for(int i=0;i<n-1;i++) verticaledge[i] = sc.nextLongArray(m); long[][][] dp = new long[11][n][m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ dp[0][i][j] = 0; } } for(int i=1;i<=k;i++){ for(int j1=0;j1<n;j1++){ for(int j2=0;j2<m;j2++){ long min = Long.MAX_VALUE/2000; //for up if(isValid(n, m, j1-1, j2)){ min = Math.min(dp[i-1][j1-1][j2]+verticaledge[j1-1][j2], min); } //for down if(isValid(n, m, j1+1, j2)){ min = Math.min(min, dp[i-1][j1+1][j2]+verticaledge[j1][j2]); } //for left if(isValid(n, m, j1, j2-1)){ min = Math.min(min, dp[i-1][j1][j2-1]+horizontaledge[j1][j2-1]); } //for right if(isValid(n, m, j1, j2+1)){ min = Math.min(min, dp[i-1][j1][j2+1]+horizontaledge[j1][j2]); } dp[i][j1][j2] = min; } } } for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ sb.append(dp[k][i][j]*2).append(" "); } sb.append("\n"); } System.out.println(sb); sc.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } 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;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
cubic
1517_D. Explorer Space
CODEFORCES
//Template with FastScanner // jzzhao import java.util.*; import java.io.*; public class Solution { 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++) { solve(sc,pw); //pw.println(solve(sc,pw)); } pw.close(); } /* FS Methods: - next(): next element in string - nextLine(): nextline in string - ni(): next Integer - nd(): next Double - nl(): next Long - intArray(n): - longArray(n): - to2di(m,n): - to2dl(m,n): */ public static void solve(FastScanner sc, PrintWriter pw) { int n = sc.ni(); int m = sc.ni(); int k = sc.ni(); int[][] arr = sc.to2di(n,m-1); int[][] arr2 = sc.to2di(n-1,m); if(k%2==1){ String s =""; for(int j = 0;j<m;j++){ s+="-1"; if(j!=m-1){ s+=" "; } } for(int i = 0;i<n;i++){ pw.println(s); } return; } Integer[][][] dp = new Integer[n][m][k+1]; // edge info // for(int i= 0;i<n;i++){ // for(int j = 0;j<m-1;j++){ // int l = i*1000+j; // int r = i*1000+j+1; // String cur = l+" "+r; // String cur2 = r+" "+l; // map.put(cur,arr[i][j]); // map.put(cur2,arr[i][j]); // } // } // for(int i= 0;i<n-1;i++){ // for(int j = 0;j<m;j++){ // int l = i*1000+j; // int r = (i+1)*1000+j; // String cur = l+" "+r; // String cur2 = r+" "+l; // map.put(cur,arr2[i][j]); // map.put(cur2,arr2[i][j]); // } // } //dp fill for(int i= 0;i<n;i++){ for(int j = 0;j<m;j++){ fill(dp,i,j,k,n,m,arr,arr2); } } for(int i= 0;i<n;i++){ String s = ""; for(int j = 0;j<m;j++){ s+=dp[i][j][k]; if(j!=m-1){ s+=" "; } } pw.println(s); } } public static int fill(Integer[][][] dp, int x, int y, int k, int n,int m,int[][] arr, int[][] arr2){ if(dp[x][y][k]!=null){ return dp[x][y][k]; } if(k==0){ dp[x][y][k]= 0; return 0; } int min = Integer.MAX_VALUE; if(x>0){ int curVal = 2*arr2[x-1][y]+fill(dp,x-1,y,k-2,n,m,arr,arr2); min = Math.min(min,curVal); } if(y>0){ int curVal = 2*arr[x][y-1]+fill(dp,x,y-1,k-2,n,m,arr,arr2); min = Math.min(min,curVal); } if(x<n-1){ int curVal = 2*arr2[x][y]+fill(dp,x+1,y,k-2,n,m,arr,arr2); min = Math.min(min,curVal); } if(y<m-1){ int curVal = 2*arr[x][y]+fill(dp,x,y+1,k-2,n,m,arr,arr2); min = Math.min(min,curVal); } dp[x][y][k]=min; return min; } /* - The following are helping method so pls do not do anything to them. */ // public static int[][] to2d(Scanner scanner, int m, int n){ // int[][] ans = new int[m][n]; // for(int i = 0;i<m;i++){ // String[] r = scanner.nextLine().split("[ ]"); // for(int j = 0;j<n;j++){ // ans[i][j] = stoi(r[j]); // } // } // return ans; // } // public static int[] toArray(Scanner scanner, int m){ // int[] ans = new int[m]; // String[] r = scanner.nextLine().split("[ ]"); // for(int i = 0;i<m;i++){ // ans[i] = stoi(r[i]); // } // return ans; // } public static void printArr(PrintWriter pw,int[] a){ for(int i = 0;i<a.length;i++){ pw.print(a[i]); if(i!=a.length-1){ pw.print(" "); } } pw.println(); } public static void print2d(PrintWriter pw,int[][] a){ for(int j=0;j<a.length;j++){ for(int i = 0;i<a[j].length;i++){ pw.print(a[j][i]); if(i!=a[j].length-1){ pw.print(" "); } } pw.println(" "); } pw.println(); } public static int stoi(String s){ return Integer.parseInt(s); } } 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; } int[][] to2di(int m, int n){ int[][] ans = new int[m][n]; for(int i = 0;i<m;i++){ String[] r = nextLine().split("[ ]"); for(int j = 0;j<n;j++){ ans[i][j] = Integer.parseInt(r[j]); } } return ans; } long[][] to2dl(int m, int n){ long[][] ans = new long[m][n]; for(int i = 0;i<m;i++){ String[] r = nextLine().split("[ ]"); for(int j = 0;j<n;j++){ ans[i][j] = Long.parseLong(r[j]); } } return ans; } 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
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; public class Main{ static int[][][]memo; static int inf=(int)1e9; static int n,m,down[][],right[][]; static int dp(int i,int j,int k) { if(k<=0)return 0; if(memo[i][j][k]!=-1)return memo[i][j][k]; int ans=inf; if(i+1<n) { ans=Math.min(ans, down[i][j]+dp(i+1, j, k-1)); } if(i-1>=0) { ans=Math.min(ans, down[i-1][j]+dp(i-1, j, k-1)); } if(j+1<m) { ans=Math.min(ans, right[i][j]+dp(i, j+1, k-1)); } if(j-1>=0) { ans=Math.min(ans, right[i][j-1]+dp(i, j-1, k-1)); } return memo[i][j][k]=ans; } static void main() throws Exception{ n=sc.nextInt();m=sc.nextInt();int k=sc.nextInt(); if((k&1)==1) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { pw.print((-1)+" "); } pw.println(); } return; } k>>=1; right=new int[n][]; down=new int[n-1][]; for(int i=0;i<n;i++) { right[i]=sc.intArr(m-1); } for(int i=0;i<n-1;i++) { down[i]=sc.intArr(m); } memo = new int[n][m][k+1]; int inf=(int)1e9; for(int i=0;i<=k;i++) { for(int j=0;j<n;j++) { for(int o=0;o<m;o++) { memo[j][o][i]=-1; } } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { pw.print((dp(i, j, k)<<1)+" "); } pw.println(); } } public static void main(String[] args) throws Exception{ sc=new MScanner(System.in); pw = new PrintWriter(System.out); int tc=1; // tc=sc.nextInt(); for(int i=1;i<=tc;i++) { // pw.printf("Case #%d:", i); main(); } pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void sort(int[]in) { shuffle(in); Arrays.sort(in); } static void sort(long[]in) { shuffle(in); Arrays.sort(in); } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.math.*; import java.text.*; import java.util.*; public class Main { static PrintWriter out; static Reader in; public static void main(String[] args) throws IOException { input_output(); Main solver = new Main(); solver.solve(); out.close(); out.flush(); } static int INF = (int)1e9; static int MAXN = (int)4e5 + 5; static int MOD = (int)1e9+7; static int q, t, n, m, k; static double pi = Math.PI; void solve() throws IOException { n = in.nextInt(); m = in.nextInt(); k = in.nextInt(); int[][] right = new int[n][m], left = new int[n][m], up = new int[n][m], down = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m-1; j++) { right[i][j] = in.nextInt(); left[i][j+1] = right[i][j]; } } for (int i = 0; i < n-1; i++) { for (int j = 0; j < m; j++) { down[i][j] = in.nextInt(); up[i+1][j] = down[i][j]; } } if (k%2 == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print("-1 "); } out.println(); } return; } int[][][] dp = new int[n][m][k+1]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int kk = 1; kk <= k; kk++) { dp[i][j][kk] = INF; } } } for (int step = 2; step <= k; step+=2) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i != 0) { dp[i][j][step] = Math.min(dp[i][j][step], dp[i-1][j][step-2]+up[i][j]*2); } if (i != n-1) { dp[i][j][step] = Math.min(dp[i][j][step], dp[i+1][j][step-2]+down[i][j]*2); } if (j != 0) { dp[i][j][step] = Math.min(dp[i][j][step], dp[i][j-1][step-2]+left[i][j]*2); } if (j != m-1) { dp[i][j][step] = Math.min(dp[i][j][step], dp[i][j+1][step-2]+right[i][j]*2); } } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(dp[i][j][k]+" "); } out.println(); } } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static void input_output() throws IOException { File f = new File("in.txt"); if (f.exists() && !f.isDirectory()) { in = new Reader(new FileInputStream("in.txt")); } else in = new Reader(); f = new File("out.txt"); if (f.exists() && !f.isDirectory()) { out = new PrintWriter(new File("out.txt")); } else out = new PrintWriter(System.out); } }
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(); List<List<Integer>> horizontalEdgeWeights = new ArrayList<List<Integer>>(rows); for (int r = 0; r < rows; r++) { horizontalEdgeWeights.add(new ArrayList<Integer>(cols-1)); for (int c = 0; c < cols - 1; c++) { horizontalEdgeWeights.get(r).add(FR.nextInt()); } } List<List<Integer>> verticalEdgeWeights = new ArrayList<List<Integer>>(rows-1); for (int r = 0; r < rows - 1; r++) { verticalEdgeWeights.add(new ArrayList<Integer>(cols)); for (int c = 0; c < cols; c++) { verticalEdgeWeights.get(r).add(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"); } PW.print(solution.toString()); PW.close(); } static List<List<Integer>> getResult(int rows, int cols, int moves, List<List<Integer>> horizontalEdgeWeights, List<List<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); 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(r-1).get(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(r).get(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(r).get(c); 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(r).get(c); 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 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.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.PriorityQueue; import java.util.Set; //@Japanese /* PriorityQueueは拡張for文で出すとsortされてない順番で出てくる * longのbit演算は1L<<posに注意 * JOIはMLEが厳しい。最悪shortを使う。 * ArrayListはオートボクシングが遅いから、最悪自作listを使う */ /*略語 * 2-to, 4-for, 8-from * -L -long(型), -P -素数Pを法とした余り * a,b -任意の引数, n,m -自然数, p -素数 * pos -postition * abs -絶対値 * min -minimum, max -maximum, ave -average * div -divide * pow -power(累乗) * ceil -ceiling(天井関数) * dt -data * ln -length * sc -scanner * INF -INFINITY * e97 -10E9+7=1000000007(prime often used) */ public class Main { public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int h = sc.nexI(); int w = sc.nexI(); int k = sc.nexI(); Graph grid = new Graph(h*w); for(int i=0; i<h; i++) { for(int j=1; j<w; j++) { long w1 = sc.nexL(); grid.add2(getad(w, i, j-1), getad(w, i, j), w1); } } for(int i=1; i<h; i++) { for(int j=0; j<w; j++) { long w1 = sc.nexL(); grid.add2(getad(w, i-1, j), getad(w, i, j), w1); } } if(k%2 != 0) { int[][] anss = new int[h][w]; fill(anss,-1); for(int i=0; i<h; i++) { prtspas(anss[i]); } return; } if((h*w) == 1) { System.out.println(-1); return; } long[][] mincos = new long[(k/2)+1][h*w]; fill(mincos[0],0L); for(int t=1; t<=(k/2); t++) { fill(mincos[t], INFL); for(int i=0; i<h; i++) { for(int j=0; j<w; j++) { int ad = getad(w, i, j); for(Edge e: grid.get(ad)) { mincos[t][ad] = min(mincos[t][ad], mincos[t-1][e.v2]+e.w); } } } } for(int i=0; i<(h*w); i++) { mincos[k/2][i]*=2L; } for(int i=0; i<h; i++) { prtspas(Arrays.copyOfRange(mincos[k/2], i*w, i*w + w)); } out.flush(); return; } public static int getad(int w, int i, int j) { return (i*w + j); } static class Graph { // @Japanese 重み付きグラフ private ArrayList<Node> dt = new ArrayList<>(); Graph(int sz) { for (int i = 0; i < sz; i++) { Node node1 = new Node(); dt.add(node1); } } public void add(int v8, int cnct2, long w) { dt.get(v8).add(new Edge(v8, cnct2, w)); } public void add2(int v1, int v2, long w) { dt.get(v1).add(new Edge(v1, v2, w)); dt.get(v2).add(new Edge(v2, v1, w)); } public Set<Edge> get(int v) { return dt.get(v).getAll(); } public int size() { return dt.size(); } public int sizeOf(int v) { return dt.get(v).size(); } public void clear() { for (int i = 0; i < dt.size(); i++) dt.get(i).clear(); } public void clear(int v) { dt.get(v).clear(); } private void add_v(Node v_new) { dt.add(v_new); } public void show2() { for (int i = 0; i < dt.size(); i++) { System.out.print(i + ":"); for (Edge e : dt.get(i).getAll()) e.show2(); System.out.println(); } } public static Graph make_Graph(int vn, int en, FastScanner sc) { Graph g = new Graph(vn); for (int i = 0; i < en; i++) { int s1 = sc.nexI() - 1; int g1 = sc.nexI() - 1; long w = sc.nexL(); g.add2(s1, g1, w); } return g; } public static Graph make_tree(int vn, FastScanner sc) { Graph g = new Graph(vn); for (int i = 1; i < vn; i++) { int s1 = sc.nexI() - 1; int g1 = sc.nexI() - 1; long w = sc.nexL(); g.add2(s1, g1, w); } return g; } private long[] dijkstra(int from) { PriorityQueue<Edge> dijk = new PriorityQueue<>(new CompEdge_float()); long[] d8i = new long[this.dt.size()]; fill(d8i, INFL); dijk.add(new Edge(from, 0L)); while (!dijk.isEmpty()) { Edge dw = dijk.poll(); if (d8i[dw.v2] > dw.w) { d8i[dw.v2] = dw.w; for (Edge e : this.get(dw.v2)) { long w2 = dw.w + e.w; if (d8i[e.v2] > w2) dijk.add(new Edge(e.v2, w2)); } } } return d8i; } } static class Node { // 重みつきグラフの頂点 private Set<Edge> next_vs = new HashSet<>(); public void add(Edge cnct2) { next_vs.add(cnct2); } public Set<Edge> getAll() { return next_vs; } public int size() { return next_vs.size(); } public void clear() { next_vs.clear(); } public void addAll(Node list2add) { this.next_vs.addAll(list2add.next_vs); } } static class Edge { // @Japanese 重み着きのグラフの辺 int from = -1, v2 = -1; long w; public Edge(int going2, long weight_route) { this.v2 = going2; this.w = weight_route; } public Edge(int come8, int going2, long weight_route) { this.from = come8; this.v2 = going2; this.w = weight_route; } public void show2() { System.out.println(this.from + "->" + this.v2 + " :w=" + this.w); } } static class CompEdge_float implements Comparator<Edge> { // 今は小さいのが前に出てくる public int compare(Edge a, Edge b) { if (a.w > b.w) return 1; else if (a.w < b.w) return -1; else return a.v2 - b.v2; } } private static final int INF = (int) 3e8; private static final long INFL = (long) 1e17; private static final int INTMAX = Integer.MAX_VALUE; private static final long LONGMAX = Long.MAX_VALUE; private static final long e97 = 1000000007L; private static final long e99 = 998244353L; private static final double PI = Math.PI; private static void assertion(boolean should_true) { // throw Error if should_true is not true @Japanese「断言」 if (!should_true) throw new AssertionError(); } private static int abs(int a) { return (a >= 0) ? a : -a; } private static long abs(long a) { return (a >= 0L) ? a : -a; } private static double abs(double a) { return (a >= 0.0) ? a : -a; } private static int min(int a, int b) { return (a < b) ? a : b; } private static long min(long a, long b) { return (a < b) ? a : b; } private static double min(double a, double b) { return (a < b) ? a : b; } private static int max(int a, int b) { return (a > b) ? a : b; } private static long max(long a, long b) { return (a > b) ? a : b; } private static double max(double a, double b) { return (a > b) ? a : b; } private static int pow2(int num2pow) { if (num2pow > 4e4) throw new IllegalArgumentException("Input is to Large. Use Long."); return num2pow * num2pow; } private static long pow2(long num2pow) { if (num2pow > 1e8) throw new IllegalArgumentException("Input is to Large. Use PowP."); return num2pow * num2pow; } private static int pow(int num_powered, int index) { int ans = 1; for (int i = 0; i < index; i++) { if (ans >= (INTMAX / num_powered)) throw new IllegalArgumentException("Input is to Large. Use Long."); ans *= num_powered; } return ans; } private static long pow(long num_powered, int index) { long ans = 1L; for (int i = 0; i < index; i++) { if (ans >= (LONGMAX / num_powered)) throw new IllegalArgumentException("Input is to Large. Use PowP."); ans *= num_powered; } return ans; } private static long powP(long num_powered, long index, long p) { // O(log(index)) // @Japanese 繰り返し二乗法 if (num_powered == 0L) return 0L; if (index == 0L) return 1L; if (index == 2L) { return (pow2(num_powered) % p); } int d = getDigit2(index); long[] num_done_by2 = new long[d + 1]; num_done_by2[0] = num_powered; for (int i = 1; i <= d; i++) { num_done_by2[i] = num_done_by2[i - 1] * num_done_by2[i - 1]; num_done_by2[i] %= p; } long ans = 1L; for (int i = d; i >= 0; i--) { long cf = (1L << (long) i); if (index >= cf) { index -= cf; ans = ans * num_done_by2[i]; ans %= p; } } return ans; } private static double hypod(double a, double b) { return Math.sqrt(a * a + b * b); } private static int getDigit2(long num2know) { // O(log(n)) long compare4 = 1L; int digit = 0; while (num2know >= compare4) { digit++; compare4 = (1L << (long) digit); } return digit; // num < 2^digit } private static int getDigit10(long num2know) { // O(log10(n)) long compare4 = 1L; int digit = 0; while (num2know >= compare4) { digit++; compare4 *= 10L; } return digit; // @Japanese num は digit桁の数で、10^digit未満 } private static int divceil(int numerator, int denominator) { return (numerator + denominator - 1) / denominator; } private static long divceil(long numerator, long denominator) { return (numerator + denominator - 1L) / denominator; } private static long factorial(int n) { // O(n) long ans = 1L; for (long i = 2; i <= n; i++) { if (ans >= (LONGMAX / i)) throw new IllegalArgumentException("Input is to Large. Use facP."); ans *= i; } return ans; } private static long facP(int n, long p) { // O(n) see also PermulationCombination:O(max_sz)+Q long ans = 1L; for (long i = 2; i <= n; i++) { ans *= i; ans %= p; } return ans; } private static long lcm(long m, long n) { long ans = m / gcd(m, n); if (ans >= (LONGMAX / n)) throw new IllegalArgumentException("Input is to Large."); ans *= n; return ans; } private static long gcd(long m, long n) { // O(log(m+n)) if ((m <= 0L) || (n <= 0L)) throw new IllegalArgumentException("m and n should be natural."); while ((m > 0L) && (n > 0L)) { if (m >= n) m %= n; else n %= m; } if (m > 0L) return m; else return n; } private static boolean is_prime(long n2check) { // O(√n) if (n2check == 1L) return false; for (long i = 2L; i <= Math.sqrt(n2check); i++) { if (n2check % i == 0L) return false; } return true; } private static int safe_mod(int n, int p) { n %= p; if (n >= 0) return n; return (n + p); } private static long safe_mod(long n, long p) { n %= p; if (n >= 0L) return n; return (n + p); } private static long modinv(long n, long p) { // @Japanese 逆元を求める // O(10log(n)) // pは素数でなくてもよい // ネットから拾ってきたのが理解不能だったので、行列計算を用いて非効率的アルゴリズムを書いた n %= p; if ((p == 1L) || (gcd(n, p) != 1L)) throw new IllegalArgumentException("n and p should be coprime."); // @Japanese // yn≡1(mod p) // <-> xp+yn=1; (n<p) // ...(sx+ty)a+(ux+vy)b=1 (|sv-tu|=1) // ...(sx+ty)a+(ux+vy)=1 // <- sx+ty=0, ux+vy=1 long a = p, b = n, s = 1L, t = 0L, u = 0L, v = 1L; while (b > 1) { long quo = a / b, rem = a % b; a = b; b = rem; long s2 = s * quo + u, t2 = t * quo + v; u = s; v = t; s = s2; t = t2; } long det = s * v - t * u; if (abs(det) != 1L) throw new ArithmeticException("My algorithm was Wrong!!"); s /= det; s %= p; if (s < 0L) s += p; return s; } private static int minAll(int[] dt4min) { // O(n) int min = INF; for (int element : dt4min) { if (element < min) min = element; } return min; } private static long minAll(long[] dt4min) { // O(n) long min = INFL; for (long element : dt4min) { if (element < min) min = element; } return min; } private static int maxAll(int[] dt4max) { // O(n) int max = -INF; for (int element : dt4max) { if (element > max) max = element; } return max; } private static long maxAll(long[] dt4max) { // O(n) long max = -INFL; for (long element : dt4max) { if (element > max) max = element; } return max; } private static int sumAll(int[] dt4sum) { // O(n) int sum_of_dt = 0; for (int element : dt4sum) { if (sum_of_dt > (INTMAX - element)) throw new IllegalArgumentException("Input is to Large. Use Long."); sum_of_dt += element; } return sum_of_dt; } private static long sumAll(long[] dt4sum) { // O(n) long sum_of_dt = 0L; for (long element : dt4sum) { if (sum_of_dt > (LONGMAX - element)) throw new IllegalArgumentException("Input is to Large."); sum_of_dt += element; } return sum_of_dt; } private static int sumAll(ArrayList<Integer> dt4sum) { int sum_of_dt = 0; for (long element : dt4sum) { if (sum_of_dt > (INTMAX - element)) throw new IllegalArgumentException("Input is to Large. Use Long."); sum_of_dt += element; } return sum_of_dt; } private static int[] reverse(int[] as) { int ln = as.length; int[] bs = new int[ln]; for (int i = 0; i < ln; i++) bs[i] = as[ln - i - 1]; return bs; } private static void reverseSub(int[] as, int S_include, int Gnot_include) { // O(G-S) int ln = Gnot_include - S_include; int[] bs = new int[ln]; for (int i = S_include; i < Gnot_include; i++) bs[i - S_include] = as[i]; for (int i = 0; i < ln; i++) as[i + S_include] = bs[ln - i - 1]; } private static boolean is_in_area(int y, int x, int height, int width) { if (y < 0) return false; if (x < 0) return false; if (y >= height) return false; if (x >= width) return false; return true; } private static boolean is_in_area(Vector v, int height, int width) { if (v.y < 0) return false; if (v.x < 0) return false; if (v.y >= height) return false; if (v.x >= width) return false; return true; } private static int nC2(int n) { return ((n * (n - 1)) / 2); } private static long nC2(long n) { return ((n * (n - 1L)) / 2L); } private static int iflag(int pos) { if (pos >= 32) throw new IllegalArgumentException("Input is to Large. Use Long."); return (1 << pos); } private static long flag(int pos) { if (pos >= 64) throw new IllegalArgumentException("Input is to Large. Use Long."); return (1L << (long) pos); } private static boolean isFlaged(int bit, int pos) { if (pos >= 32) throw new IllegalArgumentException("Input is to Large."); return ((bit & (1 << pos)) != 0); } private static boolean isFlaged(long bit, int pos) { if (pos >= 64) throw new IllegalArgumentException("Input is to Large."); return ((bit & (1L << (long) pos)) != 0L); } private static int deflag(int bit, int pos) { return (bit & (~(1 << pos))); } private static int countFlaged(int bit) { int ans = 0; for (int i = 0; i < 31; i++) { if ((bit & (1 << i)) != 0) ans++; } return ans; } private static int countFlaged(long bit) { int ans = 0; for (long i = 0L; i < 63L; i++) { if ((bit & (1L << i)) != 0L) ans++; } return ans; } private static int[] Xdir4 = { 1, 0, 0, -1 }; private static int[] Ydir4 = { 0, 1, -1, 0 }; private static int[] Xdir8 = { 1, 1, 1, 0, 0, -1, -1, -1 }; private static int[] Ydir8 = { 1, 0, -1, 1, -1, 1, 0, -1 }; public static int biSearch(int[] dt, int target) { // O(log(dt.length)) // dt should be sorted in 0->INF // return adress of target int left = 0, right = dt.length - 1; int mid = -1; while (left <= right) { mid = ((right + left) / 2); if (dt[mid] == target) return mid; if (dt[mid] < target) left = (mid + 1); else right = (mid - 1); } return -1; } public static int biSearchMax(long[] dt, long target) { // O(log(dt.length)) // dt should be sorted in 0->INF int left = -1, right = dt.length, mid = -1; while ((right - left) > 1) { mid = ((right + left) / 2); if (dt[mid] <= target) left = mid; else right = mid; } return left; // @Japanese target以下の最大のaddress } public static int biSearchMin(long[] dt, long target) { // O(log(dt.length)) // dt should be sorted in 0->INF int left = -1, right = dt.length, mid = -1; while ((right - left) > 1) { mid = ((right + left) / 2); if (dt[mid] <= target) left = mid; else right = mid; } return right; // @Japanese targetより大きい最小のaddress } private static void fill(boolean[] target, boolean reset) { for (int i = 0; i < target.length; i++) target[i] = reset; } private static void fill(int[] target, int reset) { for (int i = 0; i < target.length; i++) target[i] = reset; } private static void fill(long[] target, long reset) { for (int i = 0; i < target.length; i++) target[i] = reset; } private static void fill(char[] target, char reset) { for (int i = 0; i < target.length; i++) target[i] = reset; } private static void fill(double[] target, double reset) { for (int i = 0; i < target.length; i++) target[i] = reset; } private static void fill(boolean[][] target, boolean reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { target[i][j] = reset; } } } private static void fill(int[][] target, int reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { target[i][j] = reset; } } } private static void fill(long[][] target, long reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { target[i][j] = reset; } } } private static void fill(char[][] target, char reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { target[i][j] = reset; } } } private static void fill(double[][] target, double reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { target[i][j] = reset; } } } private static void fill(int[][][] target, int reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { for (int k = 0; k < target[i][j].length; k++) { target[i][j][k] = reset; } } } } private static void fill(long[][][] target, long reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { for (int k = 0; k < target[i][j].length; k++) { target[i][j][k] = reset; } } } } private static void fill_parent(int[] parent) { for (int i = 0; i < parent.length; i++) { parent[i] = i; } } private static void showBit(int bit) { for (int i = 0; i < getDigit2(bit); i++) { if (isFlaged(bit, i)) System.out.print("O"); else System.out.print("."); } System.out.println(); } private static void showBit(long bit) { for (int i = 0; i < getDigit2(bit); i++) { if (isFlaged(bit, i)) System.out.print("O"); else System.out.print("."); } System.out.println(); } static void show2(boolean[][] dt, String cmnt) { for (int i = 0; i < dt.length; i++) { for (int j = 0; j < dt[i].length; j++) { if (dt[i][j]) System.out.print("O"); else System.out.print("."); } if (!cmnt.equals("")) System.out.print("<-" + cmnt); System.out.println(" :" + i); } } static void show2(int[][] dt, String cmnt) { for (int i = 0; i < dt.length; i++) { for (int j = 0; j < dt[i].length; j++) System.out.print(dt[i][j] + ","); if (!cmnt.equals("")) System.out.print("<-" + cmnt); System.out.println(" :" + i); } } static void show2(long[][] dt, String cmnt) { for (int i = 0; i < dt.length; i++) { for (int j = 0; j < dt[i].length; j++) System.out.print(dt[i][j] + ","); if (!cmnt.equals("")) System.out.print("<-" + cmnt); System.out.println(" :" + i); } } static void show2(ArrayDeque<Long> dt) { long element = 0; while (dt.size() > 0) { element = dt.removeFirst(); System.out.print(element); } System.out.println("\n"); } static void show2(List<Object> dt) { for (int i = 0; i < dt.size(); i++) System.out.print(dt.get(i) + ","); System.out.println("\n"); } private static void prtlnas(int[] array) { PrintWriter out = new PrintWriter(System.out); for (int e: array) out.println(e); out.flush(); } private static void prtlnas(long[] array) { PrintWriter out = new PrintWriter(System.out); for (long e: array) out.println(e); out.flush(); } private static void prtlnas(ArrayList<Object> array) { PrintWriter out = new PrintWriter(System.out); for (Object e: array) out.println(e); out.flush(); } private static void prtspas(int[] array) { PrintWriter out = new PrintWriter(System.out); out.print(array[0]); for (int i = 1; i < array.length; i++) out.print(" " + array[i]); out.println(); out.flush(); } private static void prtspas(long[] array) { PrintWriter out = new PrintWriter(System.out); out.print(array[0]); for (int i = 1; i < array.length; i++) out.print(" " + array[i]); out.println(); out.flush(); } private static void prtspas(double[] array) { PrintWriter out = new PrintWriter(System.out); out.print(array[0]); for (int i = 1; i < array.length; i++) out.print(" " + array[i]); out.println(); out.flush(); } private static void prtspas(ArrayList<Integer> array) { if (array.isEmpty()) return; PrintWriter out = new PrintWriter(System.out); out.print(array.get(0)); for (int i = 1; i < array.size(); i++) out.print(" " + array.get(i)); out.println(); out.flush(); } static class Vector { int x, y; public Vector(int sx, int sy) { this.x = sx; this.y = sy; } public boolean equals(Vector v) { return (this.x == v.x && this.y == v.y); } public void show2() { System.out.println(this.x + ", " + this.y); } public static int dist2(Vector a, Vector b) { int dx = abs(a.x - b.x); int dy = abs(a.y - b.y); if (dx > 3e4) throw new IllegalArgumentException("Input is to Large. Use Long."); if (dy > 3e4) throw new IllegalArgumentException("Input is to Large. Use Long."); return (dx * dx + dy * dy); } } static class CompVector implements Comparator<Vector> { public int compare(Vector a, Vector b) { if (a.x == b.x) return a.y - b.y; else return a.x - b.x; } } static class FastScanner { //@Japanese ネットから拾ってきた。よく分からん。 private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return (33 <= c) && (c <= 126); } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nexL() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b) || b == ':') { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nexI() { long nl = nexL(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) { throw new NumberFormatException(); } return (int) nl; } public double nexD() { return Double.parseDouble(next()); } // a means array public void ai(int[]... array) { for (int i = 0; i < array[0].length; i++) { for (int j = 0; j < array.length; j++) { array[j][i] = nexI(); } } return; } public void al(long[]... array) { for (int i = 0; i < array[0].length; i++) { for (int j = 0; j < array.length; j++) { array[j][i] = nexL(); } } return; } public void aimin1(int[] array) { for (int i = 0; i < array.length; i++) { array[i] = nexI() - 1; } return; } public void aD(double[] array) { for (int i = 0; i < array.length; i++) { array[i] = nexD(); } return; } public void ai2d(int[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { array[i][j] = nexI(); } } return; } public void al2d(long[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { array[i][j] = nexL(); } } return; } } } // END OF THE CODE
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.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, FastScanner in, PrintWriter out) { final int[] dr = {-1, 0, 1, 0}; final int[] dc = {0, -1, 0, 1}; int height = in.nextInt(); int width = in.nextInt(); int k = in.nextInt(); int[][][] cost = new int[4][height][width]; for (int r = 0; r < height; r++) { for (int c = 0; c + 1 < width; c++) { int x = in.nextInt(); cost[3][r][c] = x; cost[1][r][c + 1] = x; } } for (int r = 0; r + 1 < height; r++) { for (int c = 0; c < width; c++) { int x = in.nextInt(); cost[2][r][c] = x; cost[0][r + 1][c] = x; } } boolean odd = (k % 2 != 0); k /= 2; int[][][] d = new int[k + 1][height][width]; for (int len = 1; len <= k; len++) { for (int r = 0; r < height; r++) { for (int c = 0; c < width; c++) { d[len][r][c] = Integer.MAX_VALUE; for (int dir = 0; dir < 4; dir++) { int nr = r + dr[dir]; int nc = c + dc[dir]; if (nr < 0 || nr >= height || nc < 0 || nc >= width) { continue; } d[len][r][c] = Math.min(d[len][r][c], d[len - 1][nr][nc] + cost[dir][r][c]); } } } } for (int r = 0; r < height; r++) { for (int c = 0; c < width; c++) { if (c > 0) { out.print(" "); } out.print(odd ? -1 : 2 * d[k][r][c]); } out.println(); } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(), "Main", 1 << 27).start(); } static class Pair { int f; int s; int p; PrintWriter w; // int t; Pair(int f, int s) { // Pair(int f,int s, PrintWriter w){ this.f = f; this.s = s; // this.p = p; // this.w = w; // this.t = t; } public static Comparator<Pair> wc = new Comparator<Pair>() { public int compare(Pair e1,Pair e2){ // 1 for swap if(Math.abs(e1.f)-Math.abs(e2.f)!=0){ // e1.w.println("**"+e1.f+" "+e2.f); return -1*(Math.abs(e1.f)-Math.abs(e2.f)); } else{ // e1.w.println("##"+e1.f+" "+e2.f); return(Math.abs(e1.s)-Math.abs(e2.s)); } }}; } public Integer[] sort(Integer[] a) { Arrays.sort(a); return a; } public Long[] sort(Long[] a) { Arrays.sort(a); return a; } public static ArrayList<Integer> sieve(int N) { int i, j, flag; ArrayList<Integer> p = new ArrayList<Integer>(); for (i = 1; i < N; i++) { if (i == 1 || i == 0) continue; flag = 1; for (j = 2; j <= i / 2; ++j) { if (i % j == 0) { flag = 0; break; } } if (flag == 1) { p.add(i); } } return p; } public static long gcd(long a, long b) { if (b == 0) return a; else return gcd(b, a % b); } public static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } //// recursive dfs public static int dfs(int s, ArrayList<Integer>[] g, long[] dist, boolean[] v, PrintWriter w, int p) { v[s] = true; int ans = 1; // int n = dist.length - 1; int t = g[s].size(); // int max = 1; for (int i = 0; i < t; i++) { int x = g[s].get(i); if (!v[x]) { // dist[x] = dist[s] + 1; ans = Math.min(ans, dfs(x, g, dist, v, w, s)); } else if (x != p) { // w.println("* " + s + " " + x + " " + p); ans = 0; } } // max = Math.max(max,(n-p)); return ans; } //// iterative BFS public static int bfs(int s, ArrayList<Integer>[] g, long[] dist, boolean[] b, PrintWriter w, int p) { b[s] = true; int siz = 1; // dist--; Queue<Integer> q = new LinkedList<>(); q.add(s); while (q.size() != 0) { int i = q.poll(); Iterator<Integer> it = g[i].listIterator(); int z = 0; while (it.hasNext()) { z = it.next(); if (!b[z]) { b[z] = true; // dist--; dist[z] = dist[i] + 1; // siz++; q.add(z); } else if (z != p) { siz = 0; } } } return siz; } public static int lower(int a[], int x) { // x is the target value or key int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] >= x) r = m; else l = m; } return r; } public static int upper(int a[], int x) {// x is the key or target value int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] <= x) l = m; else r = m; } return l + 1; } public static int lower(ArrayList<Integer> a, int x) { // x is the target value or key int l = -1, r = a.size(); while (l + 1 < r) { int m = (l + r) >>> 1; if (a.get(m) >= x) r = m; else l = m; } return r; } public static int upper(ArrayList<Integer> a, int x) {// x is the key or target value int l = -1, r = a.size(); while (l + 1 < r) { int m = (l + r) >>> 1; if (a.get(m) <= x) l = m; else r = m; } return l + 1; } public static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } public void yesOrNo(boolean f){ if(f){ w.println("YES"); } else{ w.println("NO"); } } ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// // code here int oo = (int) 1e9; int[] parent; int[] dist; int[] height; boolean[] vis; // ArrayList<Integer>[] g; //int[] col; //HashMap<Long, Boolean>[] dp; char[][] g; // boolean[][] v; //long[] a; // ArrayList<Integer[]> a; // int[][] ans; long[][][] dp; long mod; int n; int m; int k; long[][] pre; // StringBuilder[] a; // StringBuilder[] b; //StringBuilder ans; int[][] col; int[][] row; PrintWriter w = new PrintWriter(System.out); public void run() { InputReader sc = new InputReader(System.in); int defaultValue = 0; mod = 1000000007; int test = 1; //test = sc.nextInt(); while (test-- > 0) { n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt(); col = new int[n][m-1]; row = new int[n-1][m]; dp = new long[n][m][21]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ Arrays.fill(dp[i][j],oo); } } for(int i=0;i<n;i++){ for(int j=0;j<m-1;j++){ col[i][j] = sc.nextInt(); } } for(int i=0;i<n-1;i++){ for(int j=0;j<m;j++){ row[i][j] = sc.nextInt(); } } if(k%2!=0){ for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ w.print(-1+" "); } w.println(""); } } else{ for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ long ans = sol(i,j,k/2); w.print((ans*2)+" "); } w.println(""); } } } w.flush(); w.close(); } public long sol(int i, int j, int steps){ if(steps == 0)return 0; else if(dp[i][j][steps]!=oo)return dp[i][j][steps]; else{ long ans = oo; if(i-1>-1){ ans = Math.min(ans,sol(i-1,j,steps-1)+row[i-1][j]); } if(i+1<n){ ans = Math.min(ans,sol(i+1,j,steps-1)+row[i][j]); } if(j-1>-1){ ans = Math.min(ans,sol(i,j-1,steps-1)+col[i][j-1]); } if(j+1<m){ ans = Math.min(ans,sol(i,j+1,steps-1)+col[i][j]); } dp[i][j][steps] = Math.min(dp[i][j][steps],ans); return dp[i][j][steps]; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*;import java.io.*;import java.math.*; public class Main { static int[][] l,r,u,d; static int[][][]dist; static int inf=Integer.MAX_VALUE; static class Node{ int x,y,len,dis; Node(int x,int y,int len,int dis){ this.x=x;this.y=y;this.len=len;this.dis=dis; } } public static void process()throws IOException { int n=ni(); int m=ni(); int k=ni(); dist=new int[n][m][k/2+1]; l=new int[n][m]; r=new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m-1;j++) l[i][j]=r[i][j+1]=ni(); u=new int[n][m]; d=new int[n][m]; for(int i=0;i<n-1;i++) for(int j=0;j<m;j++) d[i][j]=u[i+1][j]=ni(); if(k%2==1) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) p("-1 "); pn(""); } return; } k/=2; for(int kk=1;kk<=k;kk++) for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { dist[i][j][kk]=inf; if(i!=0) dist[i][j][kk]=Math.min(dist[i][j][kk],dist[i-1][j][kk-1]+u[i][j]); if(i!=n-1) dist[i][j][kk]=Math.min(dist[i][j][kk],dist[i+1][j][kk-1]+d[i][j]); if(j!=0) dist[i][j][kk]=Math.min(dist[i][j][kk],dist[i][j-1][kk-1]+r[i][j]); if(j!=m-1) dist[i][j][kk]=Math.min(dist[i][j][kk],dist[i][j+1][kk-1]+l[i][j]); } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) p(2*dist[i][j][k]+" "); pn(""); } } 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
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.io.*; public class D { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); 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] = sc.nextInt(); } } 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] = sc.nextInt(); } } if(k % 2 == 1) { StringBuilder sb = new StringBuilder(); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ sb.append(-1+" "); } sb.replace(sb.length()-1, sb.length(), "\n"); } PrintWriter pw = new PrintWriter(System.out); pw.println(sb.toString().trim()); pw.flush(); } else { int[][] dir = {{0,1},{0,-1},{1,0},{-1,0}}; long[][][] dp = new long[k/2+1][n][m]; for(int s = 1; s <= k/2; s++) { for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ dp[s][i][j] = Long.MAX_VALUE; for(int[] d: dir) { int u = i + d[0], v = j + d[1]; if(u >= 0 && u < n && v >= 0 && v < m) { long w = calc(i, j, u, v, lr, ud); dp[s][i][j] = Math.min(dp[s][i][j], dp[s-1][u][v] + 2*w); } } } } } StringBuilder sb = new StringBuilder(); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ sb.append(dp[k/2][i][j]+" "); } sb.replace(sb.length()-1, sb.length(), "\n"); } PrintWriter pw = new PrintWriter(System.out); pw.println(sb.toString().trim()); pw.flush(); } } static long calc(int i, int j, int u, int v, int[][] lr, int[][] ud) { if(i == u) { return lr[i][Math.min(j, v)]; } else { return ud[Math.min(i, u)][j]; } } static class Pair implements Comparable<Pair>{ int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair p) { if(x == p.x) return y - p.y; else return x - p.x; } public String toString() { return x+" "+y; } } 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
1517_D. Explorer Space
CODEFORCES
import java.util.*; import java.awt.image.BandedSampleModel; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.Scanner; public class D{ static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } public static void main(String args[]) { Scanner sc=new Scanner(System.in); //int cases = sc.nextInt(); //for(int i=0;i<cases;i++) { int n = sc.nextInt(); int m=sc.nextInt(); int steps=sc.nextInt(); long arr[][][] = new long[n][m][5]; for(int j=0;j<n;j++) { for(int k=0;k<m-1;k++) { long num=sc.nextLong(); arr[j][k][1]=num; arr[j][k+1][3]=num; } } for(int j=0;j<n-1;j++) { for(int k=0;k<m;k++) { long num=sc.nextLong(); arr[j][k][2]=num; arr[j+1][k][4]=num; } } long temp[][]=new long[n][m]; long ans[][]=new long[n][m]; for(int i=0;i<steps/2;i++) { for(int j=0;j<n;j++) { for(int k=0;k<m;k++) { long min=Long.MAX_VALUE; if(k>0) { long f=arr[j][k][3]+ans[j][k-1]; min=Math.min(min,f); } if(k<m-1) { long f=arr[j][k][1]+ans[j][k+1]; min=Math.min(min,f); } if(j>0) { long f=arr[j][k][4]+ans[j-1][k]; min=Math.min(min,f); } if(j<n-1) { long f=arr[j][k][2]+ans[j+1][k]; min=Math.min(min,f); } temp[j][k]=min; } } for(int j=0;j<n;j++) { for(int k=0;k<m;k++) { ans[j][k]=temp[j][k]; } } } StringBuilder p=new StringBuilder(); for(int j=0;j<n;j++) { for(int k=0;k<m;k++) { if(steps%2!=0) { p.append(-1+" "); } else { p.append(2*ans[j][k]+" ");} } p.append("\n"); } System.out.println(p); } } }
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[] dp = new long[k+1]; for(int l = 1; l <= k; l++){ dp[l] = cal(i,j,l); } for(int l = 1; l <= k; l++){ for(int g = 1; g < l; g++){ dp[l] = Math.min(dp[l],dp[g]+dp[l-g]); } } out.print(2*dp[k]+" "); } 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