src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class P111C{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int h, w; void run(){ h=sc.nextInt(); w=sc.nextInt(); solve(); } void shuffle(int[] is){ Random rand=new Random(); for(int i=is.length-1; i>=1; i--){ int j=rand.nextInt(i+1); int t=is[i]; is[i]=is[j]; is[j]=t; } } void solve(){ n=w*h; g=new long[n]; int[] dx={0, 0, -1, 1}; int[] dy={-1, 1, 0, 0}; int[] _=new int[n]; for(int i=0; i<n; i++){ _[i]=i; } shuffle(_); HashMap<Integer, Integer> map=new HashMap<Integer, Integer>(); for(int i=0; i<n; i++){ map.put(_[i], i); } for(int y=0; y<h; y++){ for(int x=0; x<w; x++){ for(int k=0; k<4; k++){ int x2=x+dx[k]; int y2=y+dy[k]; if(x2>=0&&x2<w&&y2>=0&&y2<h){ // g[y*w+x]|=1L<<(y2*w+x2); g[map.get(y*w+x)]|=1L<<(map.get(y2*w+x2)); } } } } mds=(1L<<n)-1; mds(0, 0, 0); println((n-Long.bitCount(mds))+""); } int n; long[] g; long mds; long[] candidate; void mds(long choosed, long removed, long covered){ if(Long.bitCount(choosed)>=Long.bitCount(mds)) return; if(covered==((1L<<n)-1)){ if(Long.bitCount(choosed)<Long.bitCount(mds)) mds=choosed; return; } int k=-1; // ArrayList<Integer> list=new ArrayList<Integer>(); for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){ int i=Long.numberOfTrailingZeros(remained); if((covered>>>i&1)==1){ if(Long.bitCount(g[i]&~covered)==0){ mds(choosed, removed|(1L<<i), covered); return; }else if(Long.bitCount(g[i]&~covered)==1 &&(g[i]&~covered&~removed)!=0){ mds(choosed, removed|(1L<<i), covered); return; } }else{ if(Long.bitCount(g[i]&~removed)==0){ mds(choosed|(1L<<i), removed|(1L<<i), covered|(1L<<i)|g[i]); return; }else if(Long.bitCount(g[i]&~removed)==1 &&((g[i]&~removed)|(g[i]&~covered))==(g[i]&~removed)){ int j=Long.numberOfTrailingZeros(g[i]&~removed); mds(choosed|(1L<<j), removed|(1L<<i)|(1L<<j), covered |(1L<<j)|g[j]); return; } } if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)) k=i; if(false){ /* if(k==-1 ||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k] &~covered)){ list.clear(); list.add(i); k=i; }else if(Long.bitCount(g[i]&~covered)==Long.bitCount(g[k] &~covered)) list.add(i); */ } } if(k==-1) return; // k=list.get((int)(list.size()*random())); mds(choosed|(1L<<k), removed|(1L<<k), covered|(1L<<k)|g[k]); mds(choosed, removed|(1L<<k), covered); } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } public static void main(String[] args){ Locale.setDefault(Locale.US); new P111C().run(); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class P111C{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int h, w; void run(){ h=sc.nextInt(); w=sc.nextInt(); solve(); } void shuffle(int[] is){ Random rand=new Random(); for(int i=is.length-1; i>=1; i--){ int j=rand.nextInt(i+1); int t=is[i]; is[i]=is[j]; is[j]=t; } } void solve(){ n=w*h; g=new long[n]; int[] dx={0, 0, -1, 1}; int[] dy={-1, 1, 0, 0}; for(int y=0; y<h; y++){ for(int x=0; x<w; x++){ for(int k=0; k<4; k++){ int x2=x+dx[k]; int y2=y+dy[k]; if(x2>=0&&x2<w&&y2>=0&&y2<h){ g[y*w+x]|=1L<<(y2*w+x2); } } } } candidate=new int[n]; mds=(1L<<n)-1; mds(0, 0, 0); println((n-Long.bitCount(mds))+""); } int n; long[] g; long mds; int[] candidate; void mds(long choosed, long removed, long covered){ if(Long.bitCount(choosed)>=Long.bitCount(mds)) return; if(covered==((1L<<n)-1)){ if(Long.bitCount(choosed)<Long.bitCount(mds)) mds=choosed; return; } long s=covered; for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){ int i=Long.numberOfTrailingZeros(remained); s|=(1L<<i)|g[i]; } if(s!=((1L<<n)-1)) return; int k=-1; for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){ int i=Long.numberOfTrailingZeros(remained); if((covered>>>i&1)==1){ if(Long.bitCount(g[i]&~covered)==0){ mds(choosed, removed|(1L<<i), covered); return; }else if(Long.bitCount(g[i]&~covered)==1 &&(g[i]&~covered&~removed)!=0){ mds(choosed, removed|(1L<<i), covered); return; } }else{ if(Long.bitCount(g[i]&~removed)==0){ mds(choosed|(1L<<i), removed|(1L<<i), covered|(1L<<i)|g[i]); return; }else if(Long.bitCount(g[i]&~removed)==1 &&((g[i]&~removed)|(g[i]&~covered))==(g[i]&~removed)){ int j=Long.numberOfTrailingZeros(g[i]&~removed); mds(choosed|(1L<<j), removed|(1L<<i)|(1L<<j), covered |(1L<<j)|g[j]); return; } } if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)) k=i; } if(k==-1) return; mds(choosed|(1L<<k), removed|(1L<<k), covered|(1L<<k)|g[k]); mds(choosed, removed|(1L<<k), covered); } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } public static void main(String[] args){ Locale.setDefault(Locale.US); new P111C().run(); } }
np
111_C. Petya and Spiders
CODEFORCES
/** * @author derrick20 */ import java.io.*; import java.util.*; public class PetyaSpiders implements Runnable { public static void main(String[] args) throws Exception { new Thread(null, new PetyaSpiders(), ": )", 1 << 28).start(); } public void run() { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); M = sc.nextInt(); if (N > M) { int temp = N; N = M; M = temp; } // if the max is 1, then 1x1. Else, one dimension is at least 2, so // our idea of sliding forward a 2xN window works if (M == 1) { out.println(0); } else { int[][][] dp = new int[M][1 << N][1 << N]; // N, M are at least 2. N <= 6 // base case: try all prev and curr masks, let next = 0 for (int prev = 0; prev < 1 << N; prev++) { // we cannot allow the previous to have anything except for 0's. // this matters for M = 2, since at the end of the dp we are // doing a special case for the final column where we need to // ensure both curr AND next are validly covered if (prev == 0) { for (int curr = 0; curr < 1 << N; curr++) { // all of these will satisfy the nonexistent columns, of course dp[0][prev][curr] = Integer.bitCount(curr); } } else { // not allowed to have nonzero previous spiders Arrays.fill(dp[0][prev], oo); } } for (int prev = 0; prev < 1 << N; prev++) { for (int curr = 0; curr < 1 << N; curr++) { if (isValid(0, prev, curr)) { dp[1][prev][curr] = Integer.bitCount(prev) + Integer.bitCount(curr); } else { dp[1][prev][curr] = oo; } } } for (int col = 2; col <= M - 2; col++) { for (int next = 0; next < 1 << N; next++) { for (int curr = 0; curr < 1 << N; curr++) { dp[col][curr][next] = oo; for (int prev = 0; prev < 1 << N; prev++) { if (dp[col - 1][prev][curr] != oo && isValid(prev, curr, next)) { dp[col][curr][next] = Math.min(dp[col][curr][next], dp[col - 1][prev][curr] + Integer.bitCount(next)); } } } } } // to get the answer, we need to act on the last column by trying to // ensure that both the prev row AND the current row are valid // basically, isValid(prev, curr, next) && isValid(curr, next, 0) int ans = oo; for (int next = 0; next < 1 << N; next++) { for (int curr = 0; curr < 1 << N; curr++) { dp[M - 1][curr][next] = oo; for (int prev = 0; prev < 1 << N; prev++) { if (dp[M - 2][prev][curr] != oo && isValid(prev, curr, next) && isValid(curr, next, 0)) { dp[M - 1][curr][next] = Math.min(dp[M - 1][curr][next], dp[M - 2][prev][curr] + Integer.bitCount(next)); ans = Math.min(ans, dp[M - 1][curr][next]); } } } } // for (int c = 1; c < M; c++) { // System.out.println("For col = " + c); // for (int prev = 0; prev < 1 << N; prev++) { // System.out.println("Prev = " + Integer.toBinaryString(prev)); // for (int curr = 0; curr < 1 << N; curr++) { // System.out.println("Curr = " + Integer.toBinaryString(curr) + " gives " + dp[c][prev][curr] + " "); // } // } // } out.println(N * M - ans); } out.close(); } static int N, M; static int oo = 999; static int[] dr = {1, 0, -1, 0}, dc = {0, 1, 0, -1}; static boolean isValid(int prev, int curr, int next) { boolean[][] grid = new boolean[N][3]; int[] subsets = {prev, curr, next}; for (int r = 0; r < N; r++) { for (int c = 0; c < 3; c++) { if ((subsets[c] & 1) > 0) { grid[r][c] = true; for (int k = 0; k < 4; k++) { int r2 = r + dr[k]; int c2 = c + dc[k]; if (0 <= r2 && r2 <= N - 1 && 0 <= c2 && c2 <= 2) { grid[r2][c2] = true; } } } subsets[c] >>= 1; } } for (int r = 0; r < N; r++) { if (!grid[r][1]) { // we only need to ensure the middle is safe return false; } } return true; } 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(); } }
np
111_C. Petya and Spiders
CODEFORCES
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* I'm working for the day I will surpass you https://www.a2oj.com/Ladder16.html */ import java.util.*; import java.io.*; import java.math.*; public class x111C { public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int R = Integer.parseInt(st.nextToken()); int C = Integer.parseInt(st.nextToken()); if(R > C) { int t = R; R = C; C = t; } //dp[c][m1][m2] = min spoders in first c columns int[][][] dp = new int[C+1][1 << R][1 << R]; for(int i=0; i <= C; i++) for(int mask=0; mask < (1<<R); mask++) Arrays.fill(dp[i][mask], 69); for(int mask=0; mask < (1<<R); mask++) dp[0][0][mask] = 0; for(int c=1; c <= C; c++) for(int mask1=0; mask1 < (1<<R); mask1++) for(int mask2=0; mask2 < (1<<R); mask2++) for(int mask3=0; mask3 < (1<<R); mask3++) { boolean works = true; for(int b=0; b < R; b++) if((mask2&(1<<b)) == 0) { if(b > 0 && (mask2&(1<<(b-1))) > 0); else if(b+1 < R && (mask2&(1<<(b+1))) > 0); else if((mask1&(1<<b)) > 0); else if((mask3&(1<<b)) > 0); else works = false; } if(works) dp[c][mask2][mask3] = Math.min(dp[c][mask2][mask3], dp[c-1][mask1][mask2]+Integer.bitCount(mask1)); } int res = 0; for(int mask=0; mask < (1<<R); mask++) res = Math.max(res, R*C-(dp[C][mask][0]+Integer.bitCount(mask))); System.out.println(res); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class P111C{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int h, w; void run(){ h=sc.nextInt(); w=sc.nextInt(); solve(); } void shuffle(int[] is){ Random rand=new Random(); for(int i=is.length-1; i>=1; i--){ int j=rand.nextInt(i+1); int t=is[i]; is[i]=is[j]; is[j]=t; } } void solve(){ n=w*h; g=new long[n]; int[] dx={0, 0, -1, 1}; int[] dy={-1, 1, 0, 0}; for(int y=0; y<h; y++){ for(int x=0; x<w; x++){ for(int k=0; k<4; k++){ int x2=x+dx[k]; int y2=y+dy[k]; if(x2>=0&&x2<w&&y2>=0&&y2<h){ g[y*w+x]|=1L<<(y2*w+x2); } } } } candidate=new int[n]; xs=new Xorshift(); mds=(1L<<n)-1; mds(0, 0, 0); println((n-Long.bitCount(mds))+""); } int n; long[] g; long mds; int[] candidate; Xorshift xs; void mds(long choosed, long removed, long covered){ if(Long.bitCount(choosed)>=Long.bitCount(mds)) return; if(covered==((1L<<n)-1)){ if(Long.bitCount(choosed)<Long.bitCount(mds)) mds=choosed; return; } { long s=covered; for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){ int i=Long.numberOfTrailingZeros(remained); s|=(1L<<i)|g[i]; } if(s!=((1L<<n)-1)){ return; } } int index=0; int k=-1; for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){ int i=Long.numberOfTrailingZeros(remained); if((covered>>>i&1)==1){ if(Long.bitCount(g[i]&~covered)==0){ mds(choosed, removed|(1L<<i), covered); return; }else if(Long.bitCount(g[i]&~covered)==1 &&(g[i]&~covered&~removed)!=0){ mds(choosed, removed|(1L<<i), covered); return; } }else{ if(Long.bitCount(g[i]&~removed)==0){ mds(choosed|(1L<<i), removed|(1L<<i), covered|(1L<<i)|g[i]); return; }else if(Long.bitCount(g[i]&~removed)==1 &&((g[i]&~removed)|(g[i]&~covered))==(g[i]&~removed)){ int j=Long.numberOfTrailingZeros(g[i]&~removed); mds(choosed|(1L<<j), removed|(1L<<i)|(1L<<j), covered |(1L<<j)|g[j]); return; } } // if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)) // k=i; if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)){ index=0; candidate[index++]=i; k=i; }else if(Long.bitCount(g[i]&~covered)==Long.bitCount(g[k]&~covered)){ candidate[index++]=i; } } if(k==-1) return; // k=candidate[xs.nextInt(index)]; mds(choosed|(1L<<k), removed|(1L<<k), covered|(1L<<k)|g[k]); mds(choosed, removed|(1L<<k), covered); } class Xorshift{ int x, y, z, w; public Xorshift(){ x=123456789; y=362436069; z=521288629; w=88675123; } public Xorshift(int seed){ x=_(seed, 0); y=_(x, 1); z=_(y, 2); w=_(z, 3); } int _(int s, int i){ return 1812433253*(s^(s>>>30))+i+1; } // 32bit signed public int nextInt(){ int t=x^(x<<11); x=y; y=z; z=w; return w=w^(w>>>19)^t^(t>>>8); } // error = O(n*2^-32) public int nextInt(int n){ return (int)(n*nextDouble()); } // [0, 1) (53bit) public double nextDouble(){ int a=nextInt()>>>5, b=nextInt()>>>6; return (a*67108864.0+b)*(1.0/(1L<<53)); } } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } public static void main(String[] args){ Locale.setDefault(Locale.US); new P111C().run(); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.io.*; import java.awt.geom.Point2D; import java.text.*; import java.math.*; import java.util.*; public class Main implements Runnable { final String filename = ""; public void solve() throws Exception { int n = iread(), m = iread(); int INF = -1; if (m > n) { int t = m; m = n; n = t; } int[][][] d = new int[2][1 << m][1 << m]; for (int i = 0; i < 1 << m; i++) Arrays.fill(d[0][i], INF); int[] cnt = new int[1 << m]; for (int i = 0; i < 1 << m; i++) cnt[i] = cnt[i / 2] + i % 2; int step = 0; d[0][0][0] = 0; for (int u = 0; u < n; u++) { for (int i = 0; i < 1 << m; i++) Arrays.fill(d[step ^ 1][i], INF); for (int mask1 = 0; mask1 < 1 << m; mask1++) for (int mask2 = 0; mask2 < 1 << m; mask2++) { int t = d[step][mask1][mask2]; if (t == INF) continue; for (int mask = 0; mask < 1 << m; mask++) { if ((mask1 & mask) != mask1) continue; int mask01 = ((1 << m) - 1) & ~mask2; for (int j = 0; j < m; j++) if ((mask & (1 << j)) != 0) { if (j > 0) mask01 &= ~(1 << (j - 1)); mask01 &= ~(1 << j); if (j + 1 < m) mask01 &= ~(1 << (j + 1)); } int mask02 = mask; int t2 = t + cnt[((1 << m) - 1) & ~mask]; if (d[step ^ 1][mask01][mask02] < t2) { d[step ^ 1][mask01][mask02] = t2; } } } step ^= 1; } int ans = INF; for (int mask = 0; mask < 1 << m; mask++) { ans = Math.max(ans, d[step][0][mask]); } out.write(ans + "\n"); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); // in = new BufferedReader(new FileReader(filename+".in")); // out = new BufferedWriter(new FileWriter(filename+".out")); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public int iread() throws Exception { return Integer.parseInt(readword()); } public double dread() throws Exception { return Double.parseDouble(readword()); } public long lread() throws Exception { return Long.parseLong(readword()); } BufferedReader in; BufferedWriter out; public String readword() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) { try { Locale.setDefault(Locale.US); } catch (Exception e) { } // new Thread(new Main()).start(); new Thread(null, new Main(), "1", 1 << 25).start(); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.util.*; import java.io.*; public class EdC { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; static char[][] grid; static int n; static int t; static int[][] dp; static int[] times; static int[] genre; public static void main(String[] omkar) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); n = sc.nextInt(); t = sc.nextInt(); times = new int[n]; genre = new int[n]; for(int j =0 ;j<n;j++){ times[j] = sc.nextInt(); genre[j] = sc.nextInt(); } dp = new int[1<<n][4]; for(int j = 0;j<1<<n;j++) Arrays.fill(dp[j], -1); int ans = 0; for(int j=0;j<1<<n;j++){ int time = 0; for(int k = 0;k<n;k++){ if (((1<<k) & j) != 0){ time+=times[k]; } } if (time == t){ letsgodp(j, 1); letsgodp(j, 2); letsgodp(j, 3); ans+=dp[j][1]; ans%=mod; ans+=dp[j][2]; ans%=mod; ans+=dp[j][3]; ans%=mod; } } out.println(ans); out.close(); } public static void letsgodp(int mask, int dg){ if (dp[mask][dg] != -1) return; dp[mask][dg] = 0; for(int j = 0;j<n;j++){ if (((1<<j) & mask) != 0 && genre[j] == dg){ int submask = mask - (1<<j); int og1 = genre[j]+1 > 3 ? genre[j]-2 : genre[j]+1; int og2 = genre[j]+2 > 3 ? genre[j]-1 : genre[j]+2; if (submask != 0){ letsgodp(submask, og1); letsgodp(submask, og2); dp[mask][dg] +=(dp[submask][og1] + dp[submask][og2]); dp[mask][dg] %=mod; } else{ dp[mask][dg] = 1; } } } } public static void sort(int[] array){ ArrayList<Integer> copy = new ArrayList<Integer>(); 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
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
/** * BaZ :D */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class ACMIND { static FastReader scan; static PrintWriter pw; static long MOD = 1_000_000_007; static long INF = 1_000_000_000_000_000_000L; static long inf = 2_000_000_000; public static void main(String[] args) { new Thread(null,null,"BaZ",1<<25) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static int n, g[], t[], T; static int dp[][]; static void solve() throws IOException { scan = new FastReader(); pw = new PrintWriter(System.out,true); StringBuilder fast = new StringBuilder(); n = ni(); T = ni(); g = new int[n]; t = new int[n]; for(int i=0;i<n;++i) { t[i] = ni(); g[i] = ni(); } int MAX = (1<<n); dp = new int[MAX][4]; for(int i=0;i<MAX;++i) { for(int j=0;j<4;++j) { dp[i][j] = -1; } } pl(f((1<<n)-1,0)); pw.flush(); pw.close(); } static int f(int mask, int prev) { if(dp[mask][prev]!=-1) { return dp[mask][prev]; } int left = T; for(int i=0;i<n;++i) { if((mask&(1<<i))==0) { left-=t[i]; } } if(left==0) { return 1; } int cnt = 0; for(int i=0;i<n;++i) { if((mask&(1<<i))!=0) { if(g[i]!=prev && left>=t[i]) { cnt+=f(mask^(1<<i), g[i]); if(cnt>=MOD) { cnt-=MOD; } } } } return dp[mask][prev] = cnt; } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } static class FastReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class G1 { static int n, T, duration[], type[]; static long dp[][][], mod = (long) 1e9 + 7; public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { solveIt(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }, "Main", 1 << 28).start(); } public static void solveIt() throws Exception { Scanner in = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); n = in.nextInt(); T = in.nextInt(); dp = new long[3][T + 1][1 << n]; duration = new int[n]; type = new int[n]; for (int i = 0; i < n; i++) { duration[i] = in.nextInt(); type[i] = in.nextInt() - 1; } for (long a[][] : dp) for (long b[] : a) Arrays.fill(b, -1); pw.println(solve(0, T, 0)); pw.close(); } static long solve(int lastType, int rem, int mask) { if (rem == 0) return 1; if (rem < 0) return 0; if (dp[lastType][rem][mask] != -1) return dp[lastType][rem][mask]; long res = 0; for (int i = 0; i < n; i++) { if (!check(mask, i) && (lastType != type[i] || mask == 0) && rem - duration[i] >= 0) { res += solve(type[i], rem - duration[i], set(mask, i)); if (res >= mod) res -= mod; } } return dp[lastType][rem][mask] = res; } static boolean check(int N, int pos) { return (N & (1 << pos)) != 0; } static int set(int N, int pos) { return N = N | (1 << pos); } static int reset(int N, int pos) { return N = N & ~(1 << pos); } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } }
np
1185_G1. Playlist for Polycarp (easy 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 * dp[ma][mb][mc]) % MD); } } } System.out.println(ans); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; @SuppressWarnings("unused") public class Solution{ static long inf = (long)1e18+100; static final long mod = (long)1e9+7; @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int tt = 1; outer: while(tt-->0) { int n = fs.nextInt(), T = fs.nextInt(); int[] t = new int[n], g = new int[n]; for(int i=0;i<n;i++) { t[i] = fs.nextInt(); g[i] = fs.nextInt(); } //dp[mask][pre] -- number of ways to order mask songs last song has prev genre long[][] dp = new long[1<<n][4]; dp[0][0] = 1; long ans = 0; for(int mask=0;mask<(1<<n);mask++) { for(int pre=0;pre<=3;pre++) { for(int i=0;i<n;i++) if((mask&(1<<i))==0 && g[i]!=pre) dp[mask^(1<<i)][g[i]] = add(dp[mask^(1<<i)][g[i]], dp[mask][pre]); int sum = 0; for(int i=0;i<n;i++) { if((mask&(1<<i))!=0) sum += t[i]; } if(sum==T) ans = add(ans, dp[mask][pre]); } } out.println(ans); } out.close(); } static long add(long a, long b) { a += b; if(a>mod) return a - mod; return a; } static final Random random=new Random(); static <T> void shuffle(T[] arr) { int n = arr.length; for(int i=0;i<n;i++ ) { int k = random.nextInt(n); T temp = arr[k]; arr[k] = arr[i]; arr[i] = temp; } } static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); int temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static void reverse(int[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++){ int temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static void reverse(long[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++){ long temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static <T> void reverse(T[] arr, int l, int r) { for(int i=l;i<l+(r-l)/2;i++) { T temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp; } } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().toCharArray()[0]; } } }
np
1185_G1. Playlist for Polycarp (easy 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(),k=Int(); int A[][]=new int[n][2]; for(int i=0;i<n;i++){ A[i][0]=Int(); A[i][1]=Int(); } Solution sol=new Solution(out); sol.solution(A,k); } 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; } long dp[][]; int mod=1000000007; int time; public void solution(int A[][],int t){ this.time=t; dp=new long[4][1<<A.length+2]; for(int i=0;i<dp.length;i++){ Arrays.fill(dp[i],-1); } long a=dfs(A,0,(1<<A.length)-1); out.println(a); } public long dfs(int A[][],int pre,int state){ int use=cal(A,state); if(time-use==0){ return 1; } if(time<use||state==0){ return 0; } if(dp[pre][state]!=-1)return dp[pre][state]; long res=0; for(int i=0;i<A.length;i++){ if(((state&(1<<i))!=0)&&A[i][1]!=pre){ res+=dfs(A,A[i][1],(state^(1<<i))); res%=mod; } } dp[pre][state]=res; return res; } public int cal(int A[][],int state){ int t=0; for(int i=0;i<A.length;i++){ if((state&(1<<i))==0){ t+=A[i][0]; } } return t; } } /* ;\ |' \ _ ; : ; / `-. /: : | | ,-.`-. ,': : | \ : `. `. ,'-. : | \ ; ; `-.__,' `-.| \ ; ; ::: ,::'`:. `. \ `-. : ` :. `. \ \ \ , ; ,: (\ \ :., :. ,'o)): ` `-. ,/,' ;' ,::"'`.`---' `. `-._ ,/ : ; '" `;' ,--`. ;/ :; ; ,:' ( ,:) ,.,:. ; ,:., ,-._ `. \""'/ '::' `:'` ,'( \`._____.-'"' ;, ; `. `. `._`-. \\ ;:. ;: `-._`-.\ \`. '`:. : |' `. `\ ) \ -hrr- ` ;: | `--\__,' '` ,' ,-' free bug dog */
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class q5 { static NoD[] arr; static int index,count,zc; static ArrayList<NoD> pos,neg; static long[][][][] dp; static long solve(int a,int b, int c,int d, long mod) { long[][][][] a2=dp; int p=-1; if(a==0 && b==0 && c==0) return 1; if(dp[a][b][c][d]!=-1) return dp[a][b][c][d]; long tr=0; if(a>0 && d!=1) { tr=+a*solve(a-1,b,c,1,mod); tr%=mod; } if(b >0 && d!=2) { tr+=b*solve(a,b-1,c,2,mod); tr%=mod; } if(c>0 && d!=3) { tr+=c*solve(a,b,c-1,3,mod); tr%=mod; } tr%=mod; return dp[a][b][c][d]=tr; } public static void main(String[] args) throws IOException { Reader.init(System.in); PrintWriter out=new PrintWriter(System.out); int n=Reader.nextInt(),t=Reader.nextInt(); long mod=(long)1e9+7,fact[]=new long[16]; dp=new long[16][16][16][4]; for(int i=0;i<16;i++) { for(int j=0;j<16;j++) { for(int k=0;k<16;k++) Arrays.fill(dp[i][j][k], -1); } } fact[0]=1; for(int i=1;i<=15;i++) { fact[i]=i*fact[i-1]; fact[i]%=mod; } NoD[] arr=new NoD[n]; for(int i=0;i<n;i++) { int a=Reader.nextInt(),b=Reader.nextInt(); arr[i]=new NoD(a,b); } long ans=0; for(int i=0;i<(1<<n);i++) { int time=0; int prev=-1; int t1=0,t2=0,t3=0; long[] c= {i}; BitSet b=BitSet.valueOf(c); for(int j=0;j<n;j++) { if(b.get(j)) { time+=arr[j].val; prev=arr[j].index; if(arr[j].index==1) t1++; else if(arr[j].index==2) t2++; else t3++; } } if(time==t) { long v=1; long v2=1; v*=solve(t1,t2,t3,0,mod); v%=mod; ans+=v; ans%=mod; } } out.println(ans); out.flush(); } } class NoD{ int val, index; NoD(int v,int i){ val=v;index=i; } } class Pair{ NoD a, b; Pair(NoD aa,NoD bb){ a=aa;b=bb; } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String nextLine() throws IOException{ return reader.readLine(); } static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.*; public class G { static int n,t; static int[]a; static int[]g; static long[][][]dp; static final long MOD=1000000007; public static void main(String[]args){ Scanner sc=new Scanner(System.in); n=sc.nextInt(); t=sc.nextInt(); a=new int[n]; g=new int[n]; for(int i=0;i<n;i++) { a[i] = sc.nextInt(); g[i] = sc.nextInt(); } dp=new long[4][1<<(n-1)+1][t+1]; for(int i=0;i<4;i++) for(int j=0;j<1<<(n-1)+1;j++) for(int k=0;k<=t;k++) dp[i][j][k]=-1; System.out.println(dp(0,0,t)); } private static long dp(int genre,int mask,int time){ if(time<0) return 0; if(dp[genre][mask][time]!=-1) return dp[genre][mask][time]; if(time==0) return 1; dp[genre][mask][time]=0; for(int i=0;i<n;i++) { if (g[i] != genre && ((1 << i) & mask) == 0) dp[genre][mask][time] = (dp[genre][mask][time]+dp(g[i], mask | (1 << i), time - a[i]))%MOD; } return dp[genre][mask][time]; } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; /** * * @author Dstoical */ public class G { private static int M = 1000000007, MM = 998244353; private static int N = 15,n,T; private static int[] time,gi; private static int[][][] dp; public static void process() throws IOException { n = sc.nextInt();T = sc.nextInt(); time = new int[n+1]; gi = new int[n+1]; for(int i=0; i<n; i++) { int a = sc.nextInt(),b = sc.nextInt(); time[i] = a; gi[i] = b-1; } dp = new int[1<<n][T+1][3]; for(int i=0; i<1<<n; i++) { for(int j=0; j<T+1; j++) { for(int k=0; k<3; k++)dp[i][j][k] = -1; } } int ans = 0; for(int i=0; i<n; i++) { if(time[i] <= T) { ans = (ans + solve(1<<i,time[i],gi[i]))%M; } } println(ans); } private static int solve(int mask, int tim, int code) { if(tim == T)return 1; if(dp[mask][tim][code] != -1)return dp[mask][tim][code]; int ans = 0; for(int i=0; i<n; i++) { if((mask>>i & 1) > 0)continue; if(code == gi[i])continue; if(tim + time[i] > T)continue; ans = (ans + solve(mask|(1<<i), time[i]+tim, gi[i]))%M; } return dp[mask][tim][code] = (ans%M); } //============================================================================= //--------------------------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); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// 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 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(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// 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); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; public class Main { static final int MOD = (int)1e9 + 7; static int n; static int[] t; static int[] g; static int[][] memo; static int dp(int mask, int rem, int last) { if(rem == 0) return 1; if(memo[last][mask] != -1) return memo[last][mask]; int ans = 0; for(int i = 0; i < n; i++) { if((mask & (1 << i)) == 0 && rem >= t[i] && g[i] != last) ans += dp(mask | 1 << i, rem - t[i], g[i]); if(ans >= MOD) ans -= MOD; } return memo[last][mask] = ans; } public static void main (String[] args) throws java.lang.Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); n = in.nextInt(); int T = in.nextInt(); t = new int[n]; g = new int[n]; for(int i = 0; i < n; i++) { t[i] = in.nextInt(); g[i] = in.nextInt() - 1; } memo = new int[4][1 << n]; for(int []x : memo) { Arrays.fill(x, -1); } out.println(dp(0, T, 3)); out.close(); } static class InputReader { BufferedReader reader; 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()); } } }
np
1185_G1. Playlist for Polycarp (easy 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); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jeel Vaishnav */ 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); G1PlaylistForPolycarpEasyVersion solver = new G1PlaylistForPolycarpEasyVersion(); solver.solve(1, in, out); out.close(); } static class G1PlaylistForPolycarpEasyVersion { public void solve(int testNumber, InputReader sc, PrintWriter out) { int n = sc.nextInt(); int T = sc.nextInt(); int mod = (int) 1e9 + 7; int dp[][][] = new int[1 << n][226][3]; int t[] = new int[n]; int g[] = new int[n]; for (int i = 0; i < n; ++i) { t[i] = sc.nextInt(); g[i] = sc.nextInt() - 1; dp[1 << i][t[i]][g[i]] = 1; } for (int i = 0; i < (1 << n); ++i) { for (int j = 0; j < n; ++j) { if ((i >> j & 1) == 1) { int newMask = i ^ (1 << j); for (int k = t[j]; k <= T; ++k) { for (int l = 0; l < 3; ++l) { if (l == g[j]) continue; dp[i][k][g[j]] = (dp[i][k][g[j]] + dp[newMask][k - t[j]][l]) % mod; } } } } } long ans = 0; for (int i = 0; i < (1 << n); ++i) { for (int j = 0; j < 3; ++j) { ans += dp[i][T][j]; } } ans %= mod; out.print(ans); } } 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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
np
1185_G1. Playlist for Polycarp (easy 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++; } Arrays.sort(A,(x,y)->{ return x[0]-y[0]; }); 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+2][T+1];//a long dp2[][][]=new long[y+2][z+2][T+2];//bc dp3=new long[x+2][y+2][z+2][3]; //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; for(int i=0;i<A.length;i++){//a int p=A[i][0],type=A[i][1]; if(type==0){ long newdp[][]=new long[dp1.length][dp1[0].length]; for(int cnt=1;cnt<=x;cnt++){ for(int j=1;j<dp1[0].length;j++){ if(j>=p){ newdp[cnt][j]+=dp1[cnt-1][j-p]; newdp[cnt][j]%=mod; } } } for(int cnt=0;cnt<=x;cnt++){ for(int j=0;j<dp1[0].length;j++){ newdp[cnt][j]+=dp1[cnt][j]; newdp[cnt][j]%=mod; } } dp1=newdp; } } dp2[0][0][0]=1; for(int i=0;i<A.length;i++){//b c int p=A[i][0],type=A[i][1]; if(type!=0){ long newdp[][][]=new long[dp2.length][dp2[0].length][dp2[0][0].length]; 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){ newdp[a][b][j]+=dp2[a-1][b][j-p]; } } else{ if(b-1>=0) { newdp[a][b][j]+=dp2[a][b-1][j-p]; } } } newdp[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++){ newdp[a][b][j]+=dp2[a][b][j]; newdp[a][b][j]%=mod; } } } dp2=newdp; } } 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;i++){ for(int j=0;j<dp3[0].length;j++){ for(int k=0;k<dp3[0][0].length;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]; ///if(combination==-1)combination=0; 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; } } } } } //System.out.println(dp2[1][0][2]+" "+dp3[1][1][0][0]); // for(long p[]:dp1){ // System.out.println(Arrays.toString(p)); //} 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 */
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; import java.math.BigInteger; import java.util.Map.Entry; import static java.lang.Math.*; public class G extends PrintWriter { void run() { long mod = 1_000_000_000 + 7; int n = nextInt(); int m = nextInt(); int[] t = new int[n]; int[] g = new int[n]; for (int i = 0; i < n; i++) { t[i] = nextInt(); g[i] = nextInt() - 1; } int k = 1 << n; long[][] dp = new long[k][n]; for (int i = 0; i < n; i++) { dp[1 << i][i] = 1; } for (int mask = 0; mask < k; mask++) { if (Integer.bitCount(mask) <= 1) { continue; } for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) { for (int j = 0; j < n; j++) { if ((mask & (1 << j)) == 0 || g[i] == g[j]) { continue; } dp[mask][i] = (dp[mask][i] + dp[mask ^ (1 << i)][j]) % mod; } } } } long ans = 0; for (int mask = 0; mask < k; mask++) { int sum = 0; for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) { sum += t[i]; } } if (sum == m) { for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) { ans = (ans + dp[mask][i]) % mod; } } } } println(ans); } boolean skip() { while (hasNext()) { next(); } return true; } int[][] nextMatrix(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) matrix[i][j] = nextInt(); return matrix; } String next() { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String line = nextLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } int[] nextArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return reader.readLine(); } catch (IOException err) { return null; } } public G(OutputStream outputStream) { super(outputStream); } static BufferedReader reader; static StringTokenizer tokenizer = new StringTokenizer(""); static Random rnd = new Random(); static boolean OJ; public static void main(String[] args) throws IOException { OJ = System.getProperty("ONLINE_JUDGE") != null; G solution = new G(System.out); if (OJ) { reader = new BufferedReader(new InputStreamReader(System.in)); solution.run(); } else { reader = new BufferedReader(new FileReader(new File(G.class.getName() + ".txt"))); long timeout = System.currentTimeMillis(); while (solution.hasNext()) { solution.run(); solution.println(); solution.println("----------------------------------"); } solution.println("time: " + (System.currentTimeMillis() - timeout)); } solution.close(); reader.close(); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.util.NoSuchElementException; public class Main { private static FastScanner sc = new FastScanner(); private static long mod = 1000000007; public static void main(String[] args) { int n = sc.nextInt(); int T = sc.nextInt(); int[] t = new int[n]; int[] g = new int[n]; for(int i=0; i<n; i++) { t[i] = sc.nextInt(); g[i] = sc.nextInt() - 1; } long[][][] dp = new long[T+1][3][1 << 15]; for(int i=1; i<=T; i++) { for(int j=0; j<n; j++) { if(i - t[j] == 0) { dp[i][g[j]][1 << j] = (dp[i][g[j]][1 << j] + 1) % mod; } else if(i - t[j] > 0) { for(int k=0; k<(1 << 15); k++) { if((k >> j & 1) == 1) { continue; } dp[i][g[j]][k + (1 << j)] = (dp[i][g[j]][k + (1 << j)] + dp[i - t[j]][(g[j] + 1) % 3][k] + dp[i - t[j]][(g[j] + 2) % 3][k]) % mod; } } } } long ans = 0; for(int j=0; j<3; j++) { for(int k=0; k<(1 << 15); k++) { ans = (ans + dp[T][j][k]) % mod; } } System.out.println(ans); } static long power(long m , long n){ if(n == 0) { return 1; }else if(n == 1){ return m; }else if(n % 2 == 0){ long s = power(m, n/2); return ( (s % mod) * (s % mod) ) % mod; }else{ return ( (m % mod) * (power(m, n-1) % mod) ) % mod; } } static class FastScanner { 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;} private void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;} public boolean hasNext() { skipUnprintable(); return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt(){ return Integer.parseInt(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import sun.reflect.generics.tree.Tree; import java.io.*; import java.math.BigInteger; import java.net.Inet4Address; import java.util.*; public class l { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////// ///////// //////// ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE ///////// //////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE ///////// //////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE ///////// //////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE ///////// //////// ///////// //////// ///////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static long mod = (int) (1e9 + 7); static int n; static StringBuilder sol; static class pair implements Comparable<pair> { int L,R; public pair( int x,int y) { L=x;R=y; } public int compareTo(pair o) { if (L!=o.L)return L-o.L; return o.R-R; } public String toString(){ return L+" "+R; } } static boolean is; static int [][][]memo; static int[]val,gen; static int dp(int last,int rem,int msk){ if (rem==0)return 1; if (memo[last][rem][msk]!=-1)return memo[last][rem][msk]; int ans =0; for (int i =0;i<n;i++){ if ((msk&1<<i)==0){ if (gen[i]!=last&&val[i]<=rem){ ans+=dp(gen[i],rem-val[i],msk|1<<i); ans%=mod; } } } return memo[last][rem][msk]=ans; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); //FileWriter f = new FileWriter("C:\\Users\\Ibrahim\\out.txt"); PrintWriter pw = new PrintWriter(System.out); n = sc.nextInt(); int t = sc.nextInt(); gen= new int[n]; val= new int[n]; for (int i =0;i<n;i++){ val[i]=sc.nextInt(); gen[i]=sc.nextInt(); } memo= new int[4][t+1][1<<n]; for (int[][]x:memo)for (int[]a:x)Arrays.fill(a,-1); pw.println(dp(0,t,0)); pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Vaibhav Pulastya */ 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); G1PlaylistForPolycarpEasyVersion solver = new G1PlaylistForPolycarpEasyVersion(); solver.solve(1, in, out); out.close(); } static class G1PlaylistForPolycarpEasyVersion { long mod = (int) 1e9 + 7; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int T = in.nextInt(); int[] t = new int[n]; int[] g = new int[n]; for (int i = 0; i < n; i++) { t[i] = in.nextInt(); g[i] = in.nextInt(); } long[] fact = new long[n + 1]; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = (fact[i - 1] * i) % mod; } ArrayList<Integer> masks = new ArrayList<>(); long val = 0; for (int i = 1; i < (1 << n); i++) { int time = 0; int[] count = new int[3]; for (int j = 0; j < n; j++) { if ((i & (1 << j)) != 0) { time += t[j]; count[g[j] - 1]++; } } if (time == T) { masks.add(i); Arrays.sort(count); long v = ((fact[count[0]] * fact[count[1]]) % mod * fact[count[2]]) % mod; val += ((countUtil(count[0], count[1], count[2])) * v) % mod; } } out.println(val%mod); } long countWays(int p, int q, int r, int last) { // if number of balls of any // color becomes less than 0 // the number of ways arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // if last ball required is P // and the number of ways is // the sum of number of ways // to form sequence with 'p-1' P // balls, q Q Balls and r R balls // ending with Q and R. if (last == 0) return (countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2)) % mod; // Same as above case for 'q' and 'r' if (last == 1) return (countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2)) % mod; if (last == 2) return (countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1)) % mod; return 0; } long countUtil(int p, int q, int r) { // Three cases arise: return ((countWays(p, q, r, 0) + countWays(p, q, r, 1)) % mod + countWays(p, q, r, 2)) % mod; } } 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 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; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int MOD = 1000000007; // After writing solution, quick scan for: // array out of bounds // special cases e.g. n=1? // npe, particularly in maps // // Big numbers arithmetic bugs: // int overflow // sorting, or taking max, after MOD void solve() throws IOException { int[] nT = ril(2); int n = nT[0]; int T = nT[1]; int[][] tg = new int[n][]; for (int i = 0; i < n; i++) tg[i] = ril(2); // dp[t][m][g] is the number of sequences possible to be formed from // songs indicated by mask m, having total time t, and whose last song // is genre g. int[][][] dp = new int[T+1][1 << n][3]; for (int ti = 1; ti <= T; ti++) { for (int mask = 1; mask <= (1 << n); mask++) { // Iterate over the possible last song. It's genre will determine // what the third dimension should be for (int j = 0; j < n; j++) { if (((1 << j) & mask) == 0) continue; int time = tg[j][0]; int genre = tg[j][1]-1; if (ti - time < 0) continue; long base = dp[ti][mask][genre]; long add = 0; if (ti - time == 0) { // Base case: there is always one way regardless of what songs are available. // The empty playlist add = 1; } else { for (int g = 0; g < 3; g++) add += dp[ti-time][mask ^ (1 << j)][g]; add -= dp[ti-time][mask ^ (1 << j)][genre]; } dp[ti][mask][genre] = (int) ((base + add) % MOD); } } } long ans = 0; for (int g = 0; g < 3; g++) ans += dp[T][(1 << n)-1][g]; pw.println(ans % MOD); } // IMPORTANT // DID YOU CHECK THE COMMON MISTAKES ABOVE? // Template code below BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { Main m = new Main(); m.solve(); m.close(); } void close() throws IOException { pw.flush(); pw.close(); br.close(); } int ri() throws IOException { return Integer.parseInt(br.readLine().trim()); } long rl() throws IOException { return Long.parseLong(br.readLine().trim()); } int[] ril(int n) throws IOException { int[] nums = new int[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } long[] rll(int n) throws IOException { long[] nums = new long[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); long x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } int[] rkil() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return ril(x); } long[] rkll() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return rll(x); } char[] rs() throws IOException { return br.readLine().toCharArray(); } void sort(int[] A) { Random r = new Random(); for (int i = A.length-1; i > 0; i--) { int j = r.nextInt(i+1); int temp = A[i]; A[i] = A[j]; A[j] = temp; } Arrays.sort(A); } void printDouble(double d) { pw.printf("%.16f", d); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.TreeSet; public class r568p8{ private static InputReader sc; private static PrintWriter pw; private static long mod; static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; InputReader(InputStream stream) { this.stream = stream; } 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++]; } 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; } 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; } 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(); } 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(); } 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 { boolean isSpaceChar(int ch); } } public static void main(String args[]) { sc = new InputReader(System.in); pw = new PrintWriter(System.out); int t = 1; while(t-->0) solve(); pw.flush(); pw.close(); } private static void fill_matrix(long dp[][][][], int a, int b, int c, int end){ if((a == 0 && b == 0 && c == 0) || (a == 0 && end == 0) || (b == 0 && end == 1) || (c == 0 && end == 2)){ dp[a][b][c][end] = 0; return; } if(a > 1 && b == 0 && c == 0){ dp[a][b][c][end] = 0; return; } if(b > 1 && a == 0 && c == 0){ dp[a][b][c][end] = 0; return; } if(c > 1 && a == 0 && b == 0){ dp[a][b][c][end] = 0; return; } if(a == 1 && end == 0 && b == 0 && c == 0){ dp[a][b][c][end] = 1; return; } if(b == 1 && end == 1 && a == 0 && c == 0){ dp[a][b][c][end] = 1; return; } if(c == 1 && end == 2 && b == 0 && a == 0){ dp[a][b][c][end] = 1; return; } if(end == 0){ fill_matrix(dp, a-1, b, c, 1); fill_matrix(dp, a-1, b, c, 2); dp[a][b][c][0] = (dp[a-1][b][c][1]%mod + dp[a-1][b][c][2]%mod)%mod; } else if(end == 1){ fill_matrix(dp, a, b-1, c, 0); fill_matrix(dp, a, b-1, c, 2); dp[a][b][c][1] = (dp[a][b-1][c][0]%mod + dp[a][b-1][c][2]%mod)%mod; } else{ fill_matrix(dp, a, b, c-1, 0); fill_matrix(dp, a, b, c-1, 1); dp[a][b][c][2] = (dp[a][b][c-1][0]%mod + dp[a][b][c-1][1]%mod)%mod; } } private static long cal(int count[]){ int a = count[0], b = count[1], c = count[2]; long dp[][][][] = new long[a+1][b+1][c+1][3]; long factorial[] = new long[20]; factorial[0] = 1; factorial[1] = 1; for(int i=2; i<20; i++) factorial[i] = (factorial[i-1]%mod*i%mod)%mod; fill_matrix(dp, a, b, c, 0); fill_matrix(dp, a, b, c, 1); fill_matrix(dp, a, b, c, 2); long p = (dp[a][b][c][0]%mod + dp[a][b][c][1]%mod + dp[a][b][c][2]%mod)%mod; long ans = (((p%mod * factorial[a]%mod)%mod * factorial[b]%mod)%mod * factorial[c]%mod)%mod; return ans; } private static void solve(){ int n = sc.nextInt(), T = sc.nextInt(); int len[] = new int[n], genre[] = new int[n]; for(int i=0; i<n; i++){ len[i] = sc.nextInt(); genre[i] = sc.nextInt(); } int sum[] = new int[(1<<n)]; mod = (long)1e9 + 7; long ans = 0; for(int i=1; i<(1<<n); i++){ for(int j=0; j<15; j++){ if((i&(1<<j)) != 0){ sum[i] = sum[i^(1<<j)] + len[j]; break; } } if(sum[i] == T) { int count[] = {0, 0, 0}; for (int j = 0; j < 15; j++) { if ((i & (1 << j)) != 0) count[genre[j] - 1]++; } ans = (ans % mod + cal(count) % mod) % mod; } } pw.println(+ans); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); G1playlist solver = new G1playlist(); solver.solve(1, in, out); out.close(); } static class G1playlist { int mod = 1000000007; public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int T = in.scanInt(); int[][] song = new int[n][2]; for (int i = 0; i < n; i++) { song[i][0] = in.scanInt(); song[i][1] = in.scanInt() - 1; } int[][][] dp = new int[T + 1][(1 << n)][3]; for (int i = 0; i < n; i++) if (song[i][0] <= T) { dp[song[i][0]][(1 << i)][song[i][1]] = 1; } for (int t = 0; t <= T; t++) { for (int i = 0; i < (1 << n); i++) { for (int j = 0; j < 3; j++) { if (dp[t][i][j] == 0) continue; for (int k = 0; k < n; k++) { if (((1 << k) & i) == 0 && t + song[k][0] <= T && song[k][1] != j) dp[t + song[k][0]][(1 << k) | i][song[k][1]] = (dp[t + song[k][0]][(1 << k) | i][song[k][1]] + dp[t][i][j]) % mod; } } } } long ans = 0; for (int i = 0; i < (1 << n); i++) { for (int j = 0; j < 3; j++) { ans = (ans + dp[T][i][j]) % mod; } } out.println(ans); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int 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(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1185g1_3 { public static void main(String[] args) throws IOException { int n = rni(), t = ni(), song[][] = new int[n][2]; for (int i = 0; i < n; ++i) { song[i][0] = rni(); song[i][1] = ni() - 1; } int dp[][] = new int[1 << n][4], sum[] = new int[1 << n], ans = 0; dp[0][3] = 1; for (int i = 0; i < 1 << n; ++i) { for (int j = 0; j < 4; ++j) { for (int k = 0; k < n; ++k) { if ((i & (1 << k)) == 0 && song[k][1] != j) { dp[i | (1 << k)][song[k][1]] = madd(dp[i | (1 << k)][song[k][1]], dp[i][j]); sum[i | (1 << k)] = sum[i] + song[k][0]; } } } } for (int i = 0; i < 1 << n; ++i) { if (sum[i] == t) { ans = madd(ans, dp[i][0], dp[i][1], dp[i][2]); } } prln(ans); close(); } static int mmod = 1000000007; static int madd(int a, int b) { return (a + b) % mmod; } static int madd(int... a) { int ans = a[0]; for (int i = 1; i < a.length; ++i) { ans = madd(ans, a[i]); } return ans; } static int msub(int a, int b) { return (a - b + mmod) % mmod; } static int mmul(int a, int b) { return (int) ((long) a * b % mmod); } static int mmul(int... a) { int ans = a[0]; for (int i = 1; i < a.length; ++i) { ans = mmul(ans, a[i]); } return ans; } static int minv(int x) { // return mpow(x, mmod - 2); return (exgcd(x, mmod)[0] % mmod + mmod) % mmod; } static int mpow(int a, long b) { if (a == 0) { return 0; } int ans = 1; while (b > 0) { if ((b & 1) > 0) { ans = mmul(ans, a); } a = mmul(a, a); b >>= 1; } return ans; } static BufferedReader __i = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __o = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __r = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final long LMAX = 9223372036854775807L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int[] exgcd(int a, int b) {if (b == 0) return new int[] {1, 0}; int[] y = exgcd(b, a % b); return new int[] {y[1], y[0] - y[1] * (a / b)};} static long[] exgcd(long a, long b) {if (b == 0) return new long[] {1, 0}; long[] y = exgcd(b, a % b); return new long[] {y[1], y[0] - y[1] * (a / b)};} static int randInt(int min, int max) {return __r.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __i.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} // output static void pr(int i) {__o.print(i);} static void prln(int i) {__o.println(i);} static void pr(long l) {__o.print(l);} static void prln(long l) {__o.println(l);} static void pr(double d) {__o.print(d);} static void prln(double d) {__o.println(d);} static void pr(char c) {__o.print(c);} static void prln(char c) {__o.println(c);} static void pr(char[] s) {__o.print(new String(s));} static void prln(char[] s) {__o.println(new String(s));} static void pr(String s) {__o.print(s);} static void prln(String s) {__o.println(s);} static void pr(Object o) {__o.print(o);} static void prln(Object o) {__o.println(o);} static void prln() {__o.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;}; static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;} static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__o.flush();} static void close() {__o.close();} }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class B { static int n,t[],g[],MOD=(int)1e9+7; static int [][]memo; static int dp(int msk,int rem,int lastG) { if(rem==0) return 1; if(memo[lastG][msk]!=-1) return memo[lastG][msk]; int ans=0; for(int i=0;i<n;i++) { if((msk & (1<<i))==0 && rem>=t[i] && g[i]!=lastG) ans+=dp(msk|1<<i,rem-t[i],g[i]); if(ans>=MOD) ans-=MOD; } return memo[lastG][msk]=ans; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); n=sc.nextInt(); int T=sc.nextInt(); t=new int [n]; g=new int [n]; for(int i=0;i<n;i++) { t[i]=sc.nextInt(); g[i]=sc.nextInt()-1; } memo=new int [4][1<<n]; for(int []x:memo) Arrays.fill(x, -1); out.println(dp(0, T, 3)); 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(); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.regex.*; public class Main{ static long dp[][][][]=new long [16][16][16][4]; static void ini() { for(int i=0;i<16;i++) { for(int j=0;j<16;j++) { for(int k=0;k<16;k++) { for(int l=0;l<4;l++) { dp[i][j][k][l]=-1L; } } } } } static int chk(long i) { if(i==0L) return 1; else return 0; } static long f(long a,long b,long c,int taken) { int got=(int) (a+b+c); int have=chk(a)+chk(b)+chk(c); if(have==2) { if(got==1) return 1L; else return 0L; } if(dp[(int) a][(int) b][(int) c][taken]!=-1) { return dp[(int) a][(int) b][(int) c][taken]; } long ans=0L; if(taken == 0) { if(a!=0) ans+=(a*f(a-1,b,c,1))%mod; ans%=mod; if(b!=0) ans+=(b*f(a,b-1,c,2))%mod; ans%=mod; if(c!=0) ans+=(c*f(a,b,c-1,3))%mod; ans%=mod; } else { ans+=((taken==1 || a==0)?0L:(a*f(a-1,b,c,1))%mod)%mod; ans%=mod; ans+=((taken==2 || b==0)?0L:(b*f(a,b-1,c,2))%mod)%mod; ans%=mod; ans+=((taken==3 || c==0)?0L:(c*f(a,b,c-1,3))%mod)%mod; ans%=mod; } dp[(int) a][(int) b][(int) c][taken]=ans; return ans; } public static void main(String[] args) { InputReader in=new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n=in.nextInt(); int total=in.nextInt(); int t[]=new int[n]; int g[]=new int[n]; for(int i=0;i<n;i++) { t[i]=in.nextInt(); g[i]=in.nextInt(); } long ans=0L; for(int i=0;i<(1<<n);i++) { int sum=0; int a[]=new int[4]; for(int j=0;j<n;j++) { if(((i>>j)&1)==1) { sum+=t[j]; a[g[j]]++; } } if(sum==total) { ini(); ans=(ans+f(a[1],a[2],a[3],0))%mod; } } pw.println(ans); pw.flush(); pw.close(); } private static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } static class tri implements Comparable<tri> { int p, c, l; tri(int p, int c, int l) { this.p = p; this.c = c; this.l = l; } public int compareTo(tri o) { return Integer.compare(l, o.l); } } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } /* public static long primeFactorization(long n) { HashSet<Integer> a =new HashSet<Integer>(); long cnt=0; for(int i=2;i*i<=n;i++) { while(a%i==0) { a.add(i); a/=i; } } if(a!=1) cnt++; //a.add(n); return cnt; }*/ public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x%M*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result%M * x%M)%M; x=(x%M * x%M)%M; n=n/2; } return result; } public static long modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } public static long[] shuffle(long[] a, Random gen){ for(int i = 0, n = a.length;i < n;i++){ int ind = gen.nextInt(n-i)+i; long d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } static class pair implements Comparable<pair>{ Long x; Long y; Integer z; pair(long l,long y2,int z){ this.x=l; this.y=y2; this.z=z; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString(){ return (x+" "+y); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.*; import java.io.*; public class Songs { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static int findPos(int x, int ar[]){ for(int i=0;i<ar.length;i++){ if(ar[i]==x) return (i+1); } return -20; } public static void main(String args[])throws IOException{ Reader sc=new Reader(); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int i,j; int n=sc.nextInt(); int tt=sc.nextInt(); int t[]=new int[n]; int g[]=new int[n]; int last=0; int M=1000000007; long sum=0; for(i=0;i<n;i++){ t[i]=sc.nextInt(); g[i]=sc.nextInt()-1; } int d[][]=new int[1<<n][4]; d[0][3]=1; for(i=0;i<(1<<n);i++){ for(last=0;last<4;last++){ for(j=0;j<n;j++){ if(g[j]!=last&&((i&(1<<j)))==0){ d[i^(1<<j)][g[j]]=(d[i^(1<<j)][g[j]]+d[i][last])%M; // System.out.println((i|(1<<j))+" "+(g[j])+" "+d[i|(1<<j)][g[j]]); } } } int dur=0; for(j=0;j<n;j++){ if((i&(1<<j))>0){ dur+=t[j]; } } if(dur==tt){ // System.out.println(i); sum=(sum+d[i][0]+d[i][1]+d[i][2])%M; } } pw.println(sum); pw.close(); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class G1_PlaylistForPolycarp { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader inp = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(inp, out); out.close(); } private static class Solver { private void solve(InputReader inp, PrintWriter out) { int n = inp.nextInt(), t = inp.nextInt(); int[][] tracks = new int[n][2]; long MOD = 1000000007; for (int i = 0; i < n; i++) { tracks[i][0] = inp.nextInt(); tracks[i][1] = inp.nextInt() - 1; } long[][] dp = new long[2 << n][4]; dp[0][3] = 1; // amount of 1's in the mask int curr = 1; while (curr <= n) { int mask = 0; for (int i = 0; i < curr; i++) mask |= (1 << i); // while it is a possible mask while (mask < 2 << n) { // for each track for (int i = 0; i < n; i++) { // if mask contains track i if ((mask & (1 << i)) != 0) { // for each genre for (int j = 0; j < 4; j++) { if (j == tracks[i][1]) continue; dp[mask][tracks[i][1]] += dp[mask - (1 << i)][j]; } } } // update mask mask = nextNumberXBits(mask); } curr++; } long res = 0; for (int i = 0; i < (2 << n); i++) { int time = 0; for (int j = 0; j < n; j++) { if ((i & (1 << j)) != 0) time += tracks[j][0]; } if (time == t) { for (int j = 0; j < 4; j++) { res += dp[i][j]; } res %= MOD; } } out.print(res); } private static int nextNumberXBits(int mask) { int c = mask & -mask; int r = mask + c; return (((r ^ mask) >> 2) / c) | r; } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
// Problem : G1. Playlist for Polycarp (easy version) // Contest : Codeforces - Codeforces Round #568 (Div. 2) // URL : https://codeforces.com/contest/1185/problem/G1 // Memory Limit : 256 MB // Time Limit : 5000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) import java.io.*; import java.util.*; import java.util.stream.*; public class a implements Runnable{ public static void main(String[] args) { new Thread(null, new a(), "process", 1<<26).start(); } public void run() { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); //PrintWriter out = new PrintWriter("file.out"); Task solver = new Task(); //int t = scan.nextInt(); int t = 1; for(int i = 1; i <= t; i++) solver.solve(i, scan, out); out.close(); } static class Task { static final int inf = Integer.MAX_VALUE; public void solve(int testNumber, FastReader sc, PrintWriter pw) { //CHECK FOR QUICKSORT TLE //***********************// //CHECK FOR INT OVERFLOW //***********************// int n = sc.nextInt(); int m = sc.nextInt(); tup[] arr = new tup[n]; for(int i = 0; i < n; i++) { arr[i] = new tup(sc.nextInt(), sc.nextInt()-1); } List<Integer>[] arr2 = Stream.generate(ArrayList::new).limit(16).toArray(List[]::new); for(int i = 1; i < (1<<n); i++) { int t = i; int bits = 0; while(t > 0) { if((t & 1) == 1) bits ++; t>>=1; } arr2[bits].add(i); } int[][] dp = new int[1<<n][3]; dp[0] = new int[]{1, 1, 1}; long c = 0; for(int i = 1; i <= n; i++) { for(int x : arr2[i]) { int totallen = 0; ArrayList<Integer> active = new ArrayList<>(); for(int j = 0; j < n; j++) { if((x & (1 << j)) > 0){ active.add(j); totallen += arr[j].a; } } for(int y : active) { if(i == 1) dp[x][arr[y].b]++; else dp[x][arr[y].b] += dp[x - (1<<y)][(arr[y].b+1)%3] + dp[x - (1<<y)][(arr[y].b+2)%3]; dp[x][arr[y].b] %= 1000000007; } if(totallen == m) { c += dp[x][0] + dp[x][1] + dp[x][2]; c %= 1000000007; } } } pw.println(c); } } static long binpow(long a, long b, long m) { a %= m; long res = 1; while (b > 0) { if ((b & 1) == 1) res = res * a % m; a = a * a % m; b >>= 1; } return res; } static void sort(int[] x){ shuffle(x); Arrays.sort(x); } static void sort(long[] x){ shuffle(x); Arrays.sort(x); } static class tup implements Comparable<tup>{ int a, b; tup(int a,int b){ this.a=a; this.b=b; } @Override public int compareTo(tup o){ return Integer.compare(o.b,b); } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(i + 1); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(i + 1); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
np
1185_G1. Playlist for Polycarp (easy 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]; for(int i=0;i<A.length;i++){ A[i][0]=Int(); A[i][1]=Int()-1; } Arrays.sort(A,(a,b)->{ return a[1]-b[1]; }); Solution sol=new Solution(out); sol.solution(A,k); } 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){ long res=0; int n=A.length; long dp1[][]=new long[n+1][T+1];//a long dp2[][][]=new long[n+1][n+1][T+1];//bc dp3=new long[n+1][n+1][n+1][3]; //init long f[]=new long[n+1]; 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; for(int i=0;i<A.length;i++){//a int p=A[i][0],type=A[i][1]; if(type==0){ long newdp[][]=new long[dp1.length][dp1[0].length]; for(int cnt=1;cnt<=n;cnt++){ for(int j=1;j<dp1[0].length;j++){ if(j>=p){ newdp[cnt][j]+=dp1[cnt-1][j-p]; newdp[cnt][j]%=mod; } } } for(int cnt=0;cnt<=n;cnt++){ for(int j=0;j<dp1[0].length;j++){ newdp[cnt][j]+=dp1[cnt][j]; newdp[cnt][j]%=mod; } } dp1=newdp; } else{ break; } } dp2[0][0][0]=1; for(int i=0;i<A.length;i++){//b c int p=A[i][0],type=A[i][1]; if(type!=0){ long newdp[][][]=new long[dp2.length][dp2[0].length][dp2[0][0].length]; 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){ newdp[a][b][j]+=dp2[a-1][b][j-p]; } } else{ if(b-1>=0) { newdp[a][b][j]+=dp2[a][b-1][j-p]; } } } newdp[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++){ newdp[a][b][j]+=dp2[a][b][j]; newdp[a][b][j]%=mod; } } } dp2=newdp; } } dp3[1][0][0][0]=1; dp3[0][1][0][1]=1; dp3[0][0][1][2]=1; dfs(n,n,n,0);dfs(n,n,n,1);dfs(n,n,n,2); 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(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; } } } } } /*System.out.println(dp3[1][0][0][0]+" "+dp2[0][0][0]); for(long p[]:dp1){ System.out.println(Arrays.toString(p)); }*/ 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 */
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.*; public class CFContest { public static void main(String[] args) throws Exception { boolean local = System.getProperty("ONLINE_JUDGE") == null; boolean async = false; Charset charset = Charset.forName("ascii"); FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset); Task task = new Task(io, new Debug(local)); if (async) { Thread t = new Thread(null, task, "dalt", 1 << 27); t.setPriority(Thread.MAX_PRIORITY); t.start(); t.join(); } else { task.run(); } if (local) { io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M"); } io.flush(); } public static class Task implements Runnable { final FastIO io; final Debug debug; int inf = (int) 1e9 + 2; BitOperator bitOperator = new BitOperator(); Modular modular = new Modular((int) 1e9 + 7); public Task(FastIO io, Debug debug) { this.io = io; this.debug = debug; } @Override public void run() { solve(); } int[][][] f; int n; int t; int[] songTimes; int[] songTypes; int mask; public void solve() { n = io.readInt(); t = io.readInt(); mask = 1 << n; f = new int[4][mask][t + 1]; for (int i = 0; i < 4; i++) { for (int j = 0; j < mask; j++) { for (int k = 0; k <= t; k++) { f[i][j][k] = -1; } } } songTimes = new int[n + 1]; songTypes = new int[n + 1]; for (int i = 1; i <= n; i++) { songTimes[i] = io.readInt(); songTypes[i] = io.readInt(); } int ans = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < mask; j++) { ans = modular.plus(ans, f(i, j, t)); } } io.cache.append(ans); } int f(int i, int j, int k) { if (j == 0) { return k == 0 && i == 0 ? 1 : 0; } if (k < 0) { return 0; } if (f[i][j][k] == -1) { f[i][j][k] = 0; for (int x = 1; x <= n; x++) { if (songTypes[x] != i || bitOperator.bitAt(j, x - 1) == 0) { continue; } for (int y = 0; y < 4; y++) { if (y == i) { continue; } f[i][j][k] = modular.plus(f[i][j][k], f(y, bitOperator.setBit(j, x - 1, false), k - songTimes[x])); } } } return f[i][j][k]; } } /** * 模运算 */ public static class Modular { int m; public Modular(int m) { this.m = m; } 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); } @Override public String toString() { return "mod " + m; } } public static class BitOperator { public int bitAt(int x, int i) { return (x >> i) & 1; } public int bitAt(long x, int i) { return (int) ((x >> i) & 1); } public int setBit(int x, int i, boolean v) { if (v) { x |= 1 << i; } else { x &= ~(1 << i); } return x; } public long setBit(long x, int i, boolean v) { if (v) { x |= 1L << i; } else { x &= ~(1L << i); } return x; } /** * Determine whether x is subset of y */ public boolean subset(long x, long y) { return intersect(x, y) == x; } /** * Merge two set */ public long merge(long x, long y) { return x | y; } public long intersect(long x, long y) { return x & y; } public long differ(long x, long y) { return x - intersect(x, y); } } public static class Randomized { static Random random = new Random(); public static double nextDouble(double min, double max) { return random.nextDouble() * (max - min) + min; } public static void randomizedArray(int[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); int tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static void randomizedArray(long[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); long tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static void randomizedArray(double[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); double tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static void randomizedArray(float[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); float tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static <T> void randomizedArray(T[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); T tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static int nextInt(int l, int r) { return random.nextInt(r - l + 1) + l; } } public static class Splay implements Cloneable { public static final Splay NIL = new Splay(); static { NIL.left = NIL; NIL.right = NIL; NIL.father = NIL; NIL.size = 0; NIL.key = Integer.MIN_VALUE; NIL.sum = 0; } Splay left = NIL; Splay right = NIL; Splay father = NIL; int size = 1; int key; long sum; public static void splay(Splay x) { if (x == NIL) { return; } Splay y, z; while ((y = x.father) != NIL) { if ((z = y.father) == NIL) { y.pushDown(); x.pushDown(); if (x == y.left) { zig(x); } else { zag(x); } } else { z.pushDown(); y.pushDown(); x.pushDown(); if (x == y.left) { if (y == z.left) { zig(y); zig(x); } else { zig(x); zag(x); } } else { if (y == z.left) { zag(x); zig(x); } else { zag(y); zag(x); } } } } x.pushDown(); x.pushUp(); } public static void zig(Splay x) { Splay y = x.father; Splay z = y.father; Splay b = x.right; y.setLeft(b); x.setRight(y); z.changeChild(y, x); y.pushUp(); } public static void zag(Splay x) { Splay y = x.father; Splay z = y.father; Splay b = x.left; y.setRight(b); x.setLeft(y); z.changeChild(y, x); y.pushUp(); } public void setLeft(Splay x) { left = x; x.father = this; } public void setRight(Splay x) { right = x; x.father = this; } public void changeChild(Splay y, Splay x) { if (left == y) { setLeft(x); } else { setRight(x); } } public void pushUp() { if (this == NIL) { return; } size = left.size + right.size + 1; sum = left.sum + right.sum + key; } public void pushDown() { } public static int toArray(Splay root, int[] data, int offset) { if (root == NIL) { return offset; } offset = toArray(root.left, data, offset); data[offset++] = root.key; offset = toArray(root.right, data, offset); return offset; } public static void toString(Splay root, StringBuilder builder) { if (root == NIL) { return; } root.pushDown(); toString(root.left, builder); builder.append(root.key).append(','); toString(root.right, builder); } public Splay clone() { try { return (Splay) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public static Splay cloneTree(Splay splay) { if (splay == NIL) { return NIL; } splay = splay.clone(); splay.left = cloneTree(splay.left); splay.right = cloneTree(splay.right); return splay; } public static Splay add(Splay root, Splay node) { if (root == NIL) { return node; } Splay p = root; while (root != NIL) { p = root; root.pushDown(); if (root.key < node.key) { root = root.right; } else { root = root.left; } } if (p.key < node.key) { p.setRight(node); } else { p.setLeft(node); } p.pushUp(); splay(node); return node; } /** * Make the node with the minimum key as the root of tree */ public static Splay selectMinAsRoot(Splay root) { if (root == NIL) { return root; } root.pushDown(); while (root.left != NIL) { root = root.left; root.pushDown(); } splay(root); return root; } /** * Make the node with the maximum key as the root of tree */ public static Splay selectMaxAsRoot(Splay root) { if (root == NIL) { return root; } root.pushDown(); while (root.right != NIL) { root = root.right; root.pushDown(); } splay(root); return root; } /** * delete root of tree, then merge remain nodes into a new tree, and return the new root */ public static Splay deleteRoot(Splay root) { root.pushDown(); Splay left = splitLeft(root); Splay right = splitRight(root); return merge(left, right); } /** * detach the left subtree from root and return the root of left subtree */ public static Splay splitLeft(Splay root) { root.pushDown(); Splay left = root.left; left.father = NIL; root.setLeft(NIL); root.pushUp(); return left; } /** * detach the right subtree from root and return the root of right subtree */ public static Splay splitRight(Splay root) { root.pushDown(); Splay right = root.right; right.father = NIL; root.setRight(NIL); root.pushUp(); return right; } public static Splay merge(Splay a, Splay b) { if (a == NIL) { return b; } if (b == NIL) { return a; } a = selectMaxAsRoot(a); a.setRight(b); a.pushUp(); return a; } public static Splay selectKthAsRoot(Splay root, int k) { if (root == NIL) { return NIL; } Splay trace = root; Splay father = NIL; while (trace != NIL) { father = trace; trace.pushDown(); if (trace.left.size >= k) { trace = trace.left; } else { k -= trace.left.size + 1; if (k == 0) { break; } else { trace = trace.right; } } } splay(father); return father; } public static Splay selectKeyAsRoot(Splay root, int k) { if (root == NIL) { return NIL; } Splay trace = root; Splay father = NIL; Splay find = NIL; while (trace != NIL) { father = trace; trace.pushDown(); if (trace.key > k) { trace = trace.left; } else { if (trace.key == k) { find = trace; trace = trace.left; } else { trace = trace.right; } } } splay(father); if (find != NIL) { splay(find); return find; } return father; } public static Splay bruteForceMerge(Splay a, Splay b) { if (a == NIL) { return b; } else if (b == NIL) { return a; } if (a.size < b.size) { Splay tmp = a; a = b; b = tmp; } a = selectMaxAsRoot(a); int k = a.key; while (b != NIL) { b = selectMinAsRoot(b); if (b.key >= k) { break; } Splay kickedOut = b; b = deleteRoot(b); a = add(a, kickedOut); } return merge(a, b); } public static Splay[] split(Splay root, int key) { if (root == NIL) { return new Splay[]{NIL, NIL}; } Splay p = root; while (root != NIL) { p = root; root.pushDown(); if (root.key > key) { root = root.left; } else { root = root.right; } } splay(p); if (p.key <= key) { return new Splay[]{p, splitRight(p)}; } else { return new Splay[]{splitLeft(p), p}; } } @Override public String toString() { StringBuilder builder = new StringBuilder().append(key).append(":"); toString(cloneTree(this), builder); return builder.toString(); } } public static class FastIO { public final StringBuilder cache = new StringBuilder(); private final InputStream is; private final OutputStream os; private final Charset charset; private StringBuilder defaultStringBuf = new StringBuilder(1 << 8); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastIO(InputStream is, OutputStream os, Charset charset) { this.is = is; this.os = os; this.charset = charset; } public FastIO(InputStream is, OutputStream os) { this(is, os, Charset.forName("ascii")); } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } 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; } public long readLong() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } long 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; } public double readDouble() { boolean sign = true; skipBlank(); if (next == '+' || next == '-') { sign = next == '+'; next = read(); } long val = 0; while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } if (next != '.') { return sign ? val : -val; } next = read(); long radix = 1; long point = 0; while (next >= '0' && next <= '9') { point = point * 10 + next - '0'; radix = radix * 10; next = read(); } double result = val + (double) point / radix; return sign ? result : -result; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } public int readLine(char[] data, int offset) { int originalOffset = offset; while (next != -1 && next != '\n') { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(byte[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (byte) next; next = read(); } return offset - originalOffset; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } public void flush() { try { os.write(cache.toString().getBytes(charset)); os.flush(); cache.setLength(0); } catch (IOException e) { throw new RuntimeException(e); } } public boolean hasMore() { skipBlank(); return next != -1; } } public static class Debug { private boolean allowDebug; public Debug(boolean allowDebug) { this.allowDebug = allowDebug; } public void assertTrue(boolean flag) { if (!allowDebug) { return; } if (!flag) { fail(); } } public void fail() { throw new RuntimeException(); } public void assertFalse(boolean flag) { if (!allowDebug) { return; } if (flag) { fail(); } } private void outputName(String name) { System.out.print(name + " = "); } public void debug(String name, int x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, long x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, double x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, int[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, long[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, double[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, Object x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, Object... x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.deepToString(x)); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class G1 { static int n, T, duration[], type[]; static long dp[][][], mod = (long) 1e9 + 7; public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { solveIt(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }, "Main", 1 << 28).start(); } public static void solveIt() throws Exception { Scanner in = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); n = in.nextInt(); T = in.nextInt(); dp = new long[4][T + 1][1 << n]; duration = new int[n]; type = new int[n]; for (int i = 0; i < n; i++) { duration[i] = in.nextInt(); type[i] = in.nextInt() - 1; } for (long a[][] : dp) for (long b[] : a) Arrays.fill(b, -1); pw.println(solve(3, T, 0)); pw.close(); } static long solve(int lastType, int rem, int mask) { if (rem == 0) return 1; if (rem < 0) return 0; if (dp[lastType][rem][mask] != -1) return dp[lastType][rem][mask]; long res = 0; for (int i = 0; i < n; i++) { if (!check(mask, i) && lastType != type[i] && rem - duration[i] >= 0) { res += solve(type[i], rem - duration[i], set(mask, i)); if (res >= mod) res -= mod; } } return dp[lastType][rem][mask] = res; } static boolean check(int N, int pos) { return (N & (1 << pos)) != 0; } static int set(int N, int pos) { return N = N | (1 << pos); } static int reset(int N, int pos) { return N = N & ~(1 << pos); } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
/* Roses are red Memes are neat All my test cases time out Lmao yeet */ import java.util.*; import java.io.*; public class x1185G1b { static long MOD = 1000000007L; public static void main(String args[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int T = Integer.parseInt(st.nextToken()); Song[] arr = new Song[N]; for(int i=0; i < N; i++) { st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken())-1; arr[i] = new Song(a, b); } //bitmask long[][] dp = new long[1 << N][3]; Arrays.fill(dp[0], 1L); for(int mask=0; mask < dp.length; mask++) { for(int i=0; i < N; i++) if((mask & (1 << i)) == 0) { Song c = arr[i]; //continue all dp if mask == 0 if(mask == 0 && c.t <= T) { dp[mask|(1 << i)][c.g]++; dp[mask|(1 << i)][c.g] %= MOD; } //continue dp if not same genre else { for(int gen=0; gen < 3; gen++) if(gen != c.g) { dp[mask|(1 << i)][c.g] += dp[mask][gen]; dp[mask|(1 << i)][c.g] %= MOD; } //optimize? } } } long res = 0L; for(int mask=1; mask < dp.length; mask++) for(int i=0; i < 3; i++) { int sum = 0; for(int b=0; b < N; b++) if((mask & (1 << b)) > 0) sum += arr[b].t; if(sum == T) res = (res+dp[mask][i])%MOD; } System.out.println(res); } } class Song { public int t; public int g; public Song(int a, int b) { t = a; g = b; } } //cheerios are good for your heart, but are they good for your brain?
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author beginner1010 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskG1 solver = new TaskG1(); solver.solve(1, in, out); out.close(); } static class TaskG1 { final int mod = (int) 1e9 + 7; int[][][] dp; int rec(int mask, int time, int T, int genre, int[] ts, int[] gs) { if (time > T) return 0; if (time == T) return 1; if (mask == (1 << ts.length) - 1) return 0; int res = dp[genre][time][mask]; if (res != -1) return res; res = 0; for (int i = 0; i < ts.length; i++) { if ((mask & (1 << i)) == 0 && (mask == 0 || gs[i] != genre)) { res += rec(mask | (1 << i), time + ts[i], T, gs[i], ts, gs); if (res >= mod) res -= mod; } } return dp[genre][time][mask] = res; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] ts = new int[n]; int[] gs = new int[n]; int T = in.nextInt(); for (int i = 0; i < n; i++) { ts[i] = in.nextInt(); gs[i] = in.nextInt() - 1; } dp = new int[3][T][1 << n]; for (int[][] aux : dp) { for (int[] aux2 : aux) Arrays.fill(aux2, -1); } int ans = rec(0, 0, T, 0, ts, gs); out.println(ans); } } static class InputReader { private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isWhitespace(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isWhitespace(c)); return res * sgn; } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.util.Map.Entry; public class cf2{ static int x0; static int y0; static int x1; static int y1; static HashMap<Integer,HashSet<Integer>>allowed; static HashMap<Integer,HashMap<Integer,Integer>>cost; static int []dx= {-1,-1,-1,0,0,0,1,1,1}; static int []dy= {-1,0,1,-1,0,1,-1,0,1}; static int highbound=(int)1e9; static boolean valid(int i,int j) { if(i>=1 && i<=highbound && j>=1 && j<=highbound && allowed.containsKey(i) && allowed.get(i).contains(j))return true; return false; } static long ans; static class Triple implements Comparable<Triple> { int i,j,cost; Triple(int x, int y, int z){i = x; j = y; cost = z;} public int compareTo(Triple t) { return this.cost - t.cost; } public String toString() { return i+" "+j+" "+cost; } } public static int dijkstra() { PriorityQueue<Triple> q = new PriorityQueue<Triple>(); q.add(new Triple(x0,y0,0)); HashMap<Integer,Integer>z=new HashMap<Integer,Integer>();z.put(y0,0); cost.put(x0,z); while(!q.isEmpty()) { Triple cur = q.remove(); //if(cur.i==x1 && cur.j==y1)continue; if(cur.cost > cost.getOrDefault(cur.i,new HashMap<Integer,Integer>()).getOrDefault(cur.j,1000000000)) continue; for(int k = 0; k < 9; k++) { int x = cur.i + dx[k]; int y = cur.j + dy[k]; int c=cost.getOrDefault(x,new HashMap<Integer,Integer>()).getOrDefault(y,1000000000); if(valid(x,y) && cur.cost +1 < c) { HashMap<Integer,Integer>zz=new HashMap<Integer,Integer>();zz.put(y,cur.cost+1); cost.put(x,zz); q.add(new Triple(x,y,cur.cost+1)); } } } return cost.getOrDefault(x1,new HashMap<Integer,Integer>()).getOrDefault(y1,-1); } static int t;static int n; static int []ds; static int []gs; static int [][]memo; static int dp(int lastg,int msk,int sum) { if(sum==t)return 1; if(msk==(1<<n)-1) { return 0; } if(memo[lastg][msk]!=-1)return memo[lastg][msk]; int tot=0; for(int i=0;i<n;i++) { if(((1<<i)&msk)==0 && gs[i]!=lastg) { tot=(tot+dp(gs[i],msk|(1<<i),sum+ds[i]))%(1000000007); } } return memo[lastg][msk]=tot; } public static void main(String[] args) throws IOException{ MScanner sc = new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); n=sc.nextInt(); t=sc.nextInt(); ds=new int[n];gs=new int[n]; for(int i=0;i<n;i++) { ds[i]=sc.nextInt();gs[i]=sc.nextInt(); } memo=new int[4][1<<n]; for(int []i:memo)Arrays.fill(i,-1); pw.println(dp(0, 0,0)); pw.flush(); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static int[]primes; static int sizeofp=0; static int[] isComposite; static void sieve(int N) // O(N log log N) { isComposite = new int[N+1]; isComposite[0] = isComposite[1] = 1; primes = new int[N]; for (int i = 2; i <= N; ++i) if (isComposite[i] == 0) { primes[sizeofp++]=i;; if(1l * i * i <= N) for (int j = i * i; j <= N; j += i) isComposite[j] = 1; } } static class pair implements Comparable<pair>{ int num;int idx; pair(int x,int y){ num=x;idx=y; } @Override public int compareTo(pair o) { if(num!=o.num) { return num-o.num; } return idx-o.idx; } @Override public int hashCode() { return Objects.hash(num,idx) ; } public boolean equals(pair o) { if(this.compareTo(o)==0)return true; return false; } public String toString() { return "("+0+" "+0+")"; } } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); G1PleilistDlyaPolikarpaUproshennayaVersiya solver = new G1PleilistDlyaPolikarpaUproshennayaVersiya(); solver.solve(1, in, out); out.close(); } static class G1PleilistDlyaPolikarpaUproshennayaVersiya { static final int MOD = (int) 1e9 + 7; int n; int t; int[][] a = new int[15][2]; long[][] mem = new long[1 << 15][4]; public void solve(int testNumber, InputReader in, PrintWriter out) { for (int i = 0; i < (1 << 15); i++) { for (int h = 0; h < 4; h++) { mem[i][h] = -1; } } n = in.nextInt(); t = in.nextInt(); for (int i = 0; i < n; i++) { a[i][0] = in.nextInt(); a[i][1] = in.nextInt(); } out.println(doit(0, 0, 0)); } private long doit(int mask, int genre, int sum) { if (mem[mask][genre] != -1) { return mem[mask][genre]; } if (sum > t) { mem[mask][genre] = 0; return mem[mask][genre]; } if (sum == t) { mem[mask][genre] = 1; return mem[mask][genre]; } long ct = 0; for (int i = 0; i < n; i++) { if ((mask & (1 << i)) > 0 || genre == a[i][1]) { continue; } ct = (ct + doit(mask | (1 << i), a[i][1], sum + a[i][0])) % MOD; } mem[mask][genre] = ct; return mem[mask][genre]; } } 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()); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); G1PlaylistForPolycarpEasyVersion solver = new G1PlaylistForPolycarpEasyVersion(); solver.solve(1, in, out); out.close(); } static class G1PlaylistForPolycarpEasyVersion { public static final int GENRES_COUNT = 3; private int songsCount; private int totalDuration; private Song[] songs; private int[][][] mem; static final int mod = 1000000007; public void solve(int testNumber, InputReader in, PrintWriter out) { songsCount = in.nextInt(); totalDuration = in.nextInt(); songs = new Song[songsCount]; for (int i = 0; i < songsCount; i++) { songs[i] = new Song(in.nextInt(), in.nextInt() - 1); } long ret = 0; int chosenSongs = 0; mem = new int[GENRES_COUNT + 1][][]; for (int i = 0; i < GENRES_COUNT; i++) { mem[i] = new int[totalDuration + 1][]; for (int j = 0; j <= totalDuration; j++) { mem[i][j] = new int[1 << songsCount]; for (int k = 0; k < 1 << songsCount; k++) { mem[i][j][k] = -1; } } } for (int i = 0; i < songsCount; i++) { chosenSongs = 1 << i; ret += search(totalDuration - songs[i].duration, songs[i].genre, chosenSongs); } out.println(ret % mod); } private long search(int timeLeft, int lastGenre, int chosen) { if (timeLeft < 0) { return 0; } if (timeLeft == 0) { return 1; } if (mem[lastGenre][timeLeft][chosen] != -1) { return mem[lastGenre][timeLeft][chosen]; } long ret = 0; for (int i = 0; i < songsCount; i++) { if (((1 << i) & chosen) == 0 && songs[i].genre != lastGenre) { ret += search(timeLeft - songs[i].duration, songs[i].genre, chosen | 1 << i); if (ret > mod) { ret = ret % mod; } } } mem[lastGenre][timeLeft][chosen] = (int) (ret % mod); return mem[lastGenre][timeLeft][chosen]; } class Song { public int duration; public int genre; public Song(int duration, int genre) { this.duration = duration; this.genre = genre; } } } 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()); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; import java.util.concurrent.ThreadLocalRandom; public class Main2 { static int mod = 1000000007; static FastScanner scanner; public static void main(String[] args) { scanner = new FastScanner(); int n = scanner.nextInt(); int T = scanner.nextInt(); int[][] songs = new int[n][2]; for (int i = 0; i < n; i++) { songs[i][0] = scanner.nextInt(); songs[i][1] = scanner.nextInt() - 1; } int[] mapping = new int[65536]; int mask = 1; for (int k = 0; k < n; k++) { for (int i = 1; i < mapping.length; i++) { if ((i & mask) != 0) mapping[i] += songs[k][0]; } mask <<= 1; } int[][][] dp = new int[17][65536][3]; mask = 1; for (int i = 0; i < n; i++) { dp[1][mask][songs[i][1]] = 1; mask <<= 1; } for (int i = 1; i < n; i++) { mask = 1; for (int k = 0; k < n; k++) { int cg = songs[k][1]; int g1,g2; if (cg == 0) {g1 = 1; g2 = 2;} else if (cg == 1) {g1 = 0; g2 = 2;} else {g1 = 0; g2 = 1;} for (int j = 1; j < 65536; j++) { if ((j & mask) != 0) continue; dp[i + 1][j | mask][cg] = (dp[i + 1][j | mask][cg] + (dp[i][j][g1] + dp[i][j][g2]) % mod) % mod; } mask <<= 1; } } int res = 0; for (int k = 0; k < 17; k++) for (int i = 1; i < 65536; i++) { if (mapping[i] == T) res = (res + dp[k][i][0] + dp[k][i][1] + dp[k][i][2]) % mod; } System.out.println(res); } static long test(long[] b, long c, int maxSkipped, int startWith) { int skipped = 0; long lastSkipped = b[0]; for (int i = startWith; i < b.length; i++) { long expected = b[0] + c * (i - skipped); if (b[i] != expected) { skipped++; lastSkipped = b[i]; if (skipped > maxSkipped) { return Long.MAX_VALUE; } } } return lastSkipped; } static boolean test2(long[] b, long c) { for (int i = 1; i < b.length; i++) { long expected = b[1] + c * (i - 1); if (b[i] != expected) { return false; } } return true; } // 5 5 // 1 1 5 2 3 static class WithIdx implements Comparable<WithIdx> { int val; int idx; public WithIdx(int val, int idx) { this.val = val; this.idx = idx; } @Override public int compareTo(WithIdx o) { if (val == o.val) { return Integer.compare(idx, o.idx); } return -Integer.compare(val, o.val); } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] nextLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } String[] nextStringArray(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = nextToken(); return res; } } static class PrefixSums { long[] sums; public PrefixSums(long[] sums) { this.sums = sums; } public long sum(int fromInclusive, int toExclusive) { if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value"); return sums[toExclusive] - sums[fromInclusive]; } public static PrefixSums of(int[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } public static PrefixSums of(long[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } } static class ADUtils { static void sort(int[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } static void reverse(int[] arr) { int last = arr.length / 2; for (int i = 0; i < last; i++) { int tmp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = tmp; } } static void sort(long[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap long a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } } static class MathUtils { static long[] FIRST_PRIMES = { 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}; static long[] primes(int to) { long[] all = new long[to + 1]; long[] primes = new long[to + 1]; all[1] = 1; int primesLength = 0; for (int i = 2; i <= to; i ++) { if (all[i] == 0) { primes[primesLength++] = i; all[i] = i; } for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j]; j++) { all[(int) (i * primes[j])] = primes[j]; } } return Arrays.copyOf(primes, primesLength); } static long modpow(long b, long e, long m) { long result = 1; while (e > 0) { if ((e & 1) == 1) { /* multiply in this bit's contribution while using modulus to keep * result small */ result = (result * b) % m; } b = (b * b) % m; e >>= 1; } return result; } static long submod(long x, long y, long m) { return (x - y + m) % m; } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class G1 { public static void main(String[] args) throws Exception { new G1().run(); } int MOD = 1_000_000_007; public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = f.nextInt(), t = f.nextInt(); int[][] dp = new int[1 << n][3]; int[] tarr = new int[n]; int[] garr = new int[n]; for(int i = 0; i < n; i++) { tarr[i] = f.nextInt(); garr[i] = f.nextInt()-1; if(tarr[i] <= t) dp[1 << i][garr[i]] = 1; } int[] time = new int[1 << n]; for(int i = 0; i < dp.length; i++) { for(int bi = 0; bi < n; bi++) if((i & 1 << bi) != 0) time[i] += tarr[bi]; } for(int i = 0; i < dp.length; i++) { int j = time[i]; for(int k = 0; k < 3; k++) { if(dp[i][k] == 0) continue; for(int bi = 0; bi < n; bi++) if(tarr[bi] + j <= t && (i & 1 << bi) == 0 && garr[bi] != k) { dp[i | 1 << bi][garr[bi]] = (dp[i | 1 << bi][garr[bi]] + dp[i][k]) % MOD; } } } long ans = 0; for(int i = 0; i < dp.length; i++) for(int j = 0; j < 3; j++) if(time[i] == t) ans = (ans + dp[i][j]) % MOD; 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); } } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.*; import java.io.*; import java.text.*; public class Main{ //SOLUTION BEGIN //Into the Hardware Mode void pre() throws Exception{} int n, t; void solve(int TC) throws Exception{ n = ni();t = ni(); int[][] song = new int[n][]; for(int i = 0; i< n; i++)song[i] = new int[]{ni(), ni()-1}; long[][] dp = new long[1<<n][3]; for(int i = 0; i< dp.length; i++) for(int j = 0; j< dp[i].length; j++) dp[i][j] = -1; pn(start(dp, song, 0, -1)); } long start(long[][] dp, int[][] song, int mask, int prev){ long ti = 0; for(int i = 0; i< n; i++){ if(((mask>>i)&1)==1)ti+=song[i][0]; } if(ti==t)return 1; if(prev != -1 && dp[mask][prev] != -1)return dp[mask][prev]; long ans = 0; for(int i = 0; i< n; i++){ if(((mask>>i)&1)==0 && song[i][1] != prev && ti+song[i][0] <= t) ans = (ans+start(dp, song, mask|(1<<i), song[i][1]))%mod; } if(prev!= -1)dp[mask][prev] = ans; return ans; } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} long mod = (long)1e9+7, IINF = (long)1e18; final int INF = (int)1e9, MX = (int)2e5+5; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8; static boolean multipleTC = false, memory = false; FastReader in;PrintWriter out; void run() throws Exception{ in = new FastReader(); out = new PrintWriter(System.out); //Solution Credits: Taranpreet Singh int T = (multipleTC)?ni():1; pre();for(int t = 1; t<= T; t++)solve(t); out.flush(); out.close(); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str = ""; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class G1 { static final int mod = (int) (1e9 + 7); static final int UNCALC = -1; static int[][][] memo; static int n, t[], genre[]; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); t = new int[n]; int T = sc.nextInt(); genre = new int[n]; for (int i = 0; i < n; i++) { t[i] = sc.nextInt(); genre[i] = sc.nextInt(); } memo = new int[4][1 << n][T+1]; for (int[][] a : memo) for (int[] b : a) Arrays.fill(b, UNCALC); out.println(dp(0, 0, T)); out.flush(); out.close(); } static int dp(int last, int mask, int rem) { if (rem==0) return 1; if (memo[last][mask][rem] != UNCALC) return memo[last][mask][rem]; int cnt = 0; for (int i = 0; i < n; i++) { if (genre[i] == last || t[i] > rem || (mask & 1 << i) != 0) continue; cnt = (cnt + dp(genre[i], mask | 1 << i, rem - t[i]))%mod; } return memo[last][mask][rem] = cnt; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.*; import java.io.*; public class EdC { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; static char[][] grid; static int n; static int t; static int[][] dp; static int[] times; static int[] genre; public static void main(String[] omkar) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); n = sc.nextInt(); t = sc.nextInt(); times = new int[n]; genre = new int[n]; for(int j =0 ;j<n;j++){ times[j] = sc.nextInt(); genre[j] = sc.nextInt(); } dp = new int[1<<n][4]; for(int j = 0;j<1<<n;j++) Arrays.fill(dp[j], -1); for(int j=0;j<1<<n;j++){ letsgodp(j, 1); letsgodp(j, 2); letsgodp(j, 3); } int ans = 0; for(int j=0;j<1<<n;j++){ int time = 0; for(int k = 0;k<n;k++){ if (((1<<k) & j) != 0){ time+=times[k]; } } if (time == t){ ans+=dp[j][1]; ans%=mod; ans+=dp[j][2]; ans%=mod; ans+=dp[j][3]; ans%=mod; } } out.println(ans); out.close(); } public static void letsgodp(int mask, int dg){ if (dp[mask][dg] != -1) return; dp[mask][dg] = 0; for(int j = 0;j<n;j++){ if (((1<<j) & mask) != 0 && genre[j] == dg){ int submask = mask - (1<<j); int og1 = genre[j]+1 > 3 ? genre[j]-2 : genre[j]+1; int og2 = genre[j]+2 > 3 ? genre[j]-1 : genre[j]+2; if (submask != 0){ letsgodp(submask, og1); letsgodp(submask, og2); dp[mask][dg] +=(dp[submask][og1] + dp[submask][og2]); dp[mask][dg] %=mod; } else{ dp[mask][dg] = 1; } } } } public static void sort(int[] array){ ArrayList<Integer> copy = new ArrayList<Integer>(); 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
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
//package cf568d2; import java.util.*; public class G { static int n,t; static int[]a; static int[]g; static long[][][]dp; static final long MOD=1000000007; public static void main(String[]args){ Scanner sc=new Scanner(System.in); n=sc.nextInt(); t=sc.nextInt(); a=new int[n]; g=new int[n]; for(int i=0;i<n;i++) { a[i] = sc.nextInt(); g[i] = sc.nextInt(); } dp=new long[4][1<<(n-1)+1][t+1]; for(int i=0;i<4;i++) for(int j=0;j<1<<(n-1)+1;j++) for(int k=0;k<=t;k++) dp[i][j][k]=-1; System.out.println(dp(0,0,t)); } private static long dp(int genre,int mask,int time){ if(time<0) return 0; if(dp[genre][mask][time]!=-1) return dp[genre][mask][time]; if(time==0) return 1; dp[genre][mask][time]=0; for(int i=0;i<n;i++) { if (g[i] != genre && ((1 << i) & mask) == 0) dp[genre][mask][time] = (dp[genre][mask][time]+dp(g[i], mask | (1 << i), time - a[i]))%MOD; } return dp[genre][mask][time]; } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Solution{ public static long mod = 1000000007; public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st.nextToken()); int[] d = new int[n]; int[] g = new int[n]; for(int i=0;i<n;i++){ st = new StringTokenizer(br.readLine()); d[i] = Integer.parseInt(st.nextToken()); g[i] = Integer.parseInt(st.nextToken())-1; } long[][] dp = new long[(1<<n)][3]; for(int i=0;i<n;i++){ dp[(1<<i)][g[i]] = 1; } long res = 0; for(int i=1;i<(1<<n);i++){ int k = i; int sum = 0; for(int j=n-1;j>=0;j--){ if(k>=(1<<j)){ k-=(1<<j); sum += d[j]; } else{ for(int r=0;r<3;r++) if(r!=g[j]) dp[i+(1<<j)][g[j]] += dp[i][r]; dp[i+(1<<j)][g[j]] %= mod; } } if(sum==t){ res += dp[i][0] +dp[i][1] +dp[i][2]; res %= mod; } } out.println(res); out.flush(); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.NoSuchElementException; public class Main { static PrintWriter out; static InputReader ir; static void solve() { int n = ir.nextInt(); int t = ir.nextInt(); int[][] a = new int[n][]; for (int i = 0; i < n; i++) a[i] = ir.nextIntArray(2); long[] f = fact(15); long res = 0; for (int i = 0; i < 1 << n; i++) { int[] ct = new int[4]; int tot = 0; for (int j = 0; j < n; j++) { if (((1 << j) & i) != 0) { tot += a[j][0]; ct[a[j][1]]++; } } if (tot != t) continue; long[][][][] dp = new long[ct[1] + 1][ct[2] + 1][ct[3] + 1][4]; dp[0][0][0][0] = 1; for (int j = 0; j < ct[1] + ct[2] + ct[3]; j++) { for (int k = 0; k <= ct[1]; k++) { for (int l = 0; l <= ct[2]; l++) { if (k + l > j || j - k - l > ct[3]) continue; for (int m = 0; m <= 3; m++) { for (int o = 0; o <= 3; o++) { if (m == o) continue; if (o == 1 && k == ct[1]) continue; if (o == 2 && l == ct[2]) continue; if (o == 3 && j - k - l == ct[3]) continue; if (o == 1) { dp[k + 1][l][j - k - l][1] = add(dp[k + 1][l][j - k - l][1], dp[k][l][j - k - l][m]); } if (o == 2) { dp[k][l + 1][j - k - l][2] = add(dp[k][l + 1][j - k - l][2], dp[k][l][j - k - l][m]); } if (o == 3) { dp[k][l][j - k - l + 1][3] = add(dp[k][l][j - k - l + 1][3], dp[k][l][j - k - l][m]); } } } } } } for (int m = 0; m <= 3; m++) res = add(res, mul(mul(f[ct[1]], f[ct[2]]), mul(f[ct[3]], dp[ct[1]][ct[2]][ct[3]][m]))); } out.println(res); } static long mod = (long) 1e9 + 7; static long add(long a, long b) { return (a + b) % mod; } static long sub(long a, long b) { long d = a - b; while (d < 0) d += mod; return d; } static long mul(long a, long b) { return a * b % mod; } static long div(long a, long b) { return a * mod_inverse(b) % mod; } private static long[] fact(int n) { long[] ret = new long[n + 1]; ret[0] = 1 % mod; for (int i = 1; i <= n; i++) { ret[i] = mul(ret[i - 1], i); } return ret; } private static long[] factInv(int n) { long[] ret = new long[n + 1]; ret[0] = 1; for (int i = 1; i <= n; i++) { ret[i] = div(ret[i - 1], i); } return ret; } public static long comb(int n, int m, long[] fact, long[] factInv) { long ret = fact[n]; ret = mul(ret, factInv[m]); ret = mul(ret, factInv[n - m]); return ret; } public static long[][] stirling(int n) { long[][] ret = new long[n + 1][n + 1]; ret[0][0] = 1; for (int i = 1; i <= n; i++) for (int j = 1; j <= i; j++) ret[i][j] = add(ret[i - 1][j - 1], mul(ret[i - 1][j], j)); return ret; } public static long mod_inverse(long a) { long[] ret = extgcd(a, mod); return add(mod, ret[0] % mod); } public static long[] extgcd(long a, long b) { long[] ret = new long[3]; ret[2] = _extgcd(a, b, ret); return ret; } private static long _extgcd(long a, long b, long[] x) { long g = a; x[0] = 1; x[1] = 0; if (b != 0) { g = _extgcd(b, a % b, x); long temp = x[0]; x[0] = x[1]; x[1] = temp; x[1] -= (a / b) * x[0]; } return g; } static long modpow(long a, long n) { long res = 1; while (n > 0) { if ((n & 1) != 0) res = res * a % mod; a = a * a % mod; n >>= 1; } return res; } public static void main(String[] args) { ir = new InputReader(System.in); out = new PrintWriter(System.out); solve(); out.flush(); } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } static void tr(Object... o) { out.println(Arrays.deepToString(o)); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class realfast implements Runnable { private static final int INF = (int) 1e9; int time[]= new int[15]; int g[]= new int [15]; public void solve() throws IOException { int n = readInt(); int t = readInt(); for(int i=0;i<n;i++) { time[i]=readInt(); g[i]=readInt(); } long dp[][]= new long [(int)Math.pow(2,n)][4]; for(int i =0;i<(int)Math.pow(2,n);i++) { for(int j=0;j<=3;j++) dp[i][j]=-1; } long val = cal(dp,0,0,0,t); out.println(val); } public long cal(long dp[][], int mask , int genre , int t ,int T ) { int val = dp.length; if(t>T) { return 0; } if(t==T) { return 1; } if(dp[mask][genre]!=-1) return dp[mask][genre]; dp[mask][genre]=0; int i=1; int count=0; while(i<val) { if((i&mask)==0&&g[count]!=genre) { dp[mask][genre] = ((dp[mask][genre]%1000000007)+ cal(dp,mask|i,g[count],t+time[count],T)%1000000007)%1000000007; } i=2*i; count++; } return dp[mask][genre]; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int u ; int v ; int val; edge(int u1, int v1 , int val1) { this.u=u1; this.v=v1; this.val=val1; } public int compareTo(edge e) { return this.val-e.val; } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class codeforces { public static long cnt = 0; public static void f(int g1, int g2, int g3, int last) { if (g1 == 0 && g2 == 0 && g3 == 0) cnt++; if (g1 > 0 && last != 1) f(g1 - 1, g2, g3, 1); if (g2 > 0 && last != 2) f(g1, g2 - 1, g3, 2); if (g3 > 0 && last != 3) f(g1, g2, g3 - 1, 3); } public static void main(String[] args) throws IOException { BufferedReader scan = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(scan.readLine()); int n = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st.nextToken()); int T[] = new int[n]; int G[] = new int[n]; for (int i = 0; i < n; i++) { st = new StringTokenizer(scan.readLine()); T[i] = Integer.parseInt(st.nextToken()); G[i] = Integer.parseInt(st.nextToken()); } long ans = 0; for (int mask = 1; mask < (1 << n); mask++) { int sum = 0; int g1 = 0; int g2 = 0; int g3 = 0; for (int i = 0; i < n; i++) { if (((1 << i) & mask) > 0) { sum += T[i]; if (G[i] == 1) g1++; if (G[i] == 2) g2++; if (G[i] == 3) g3++; } } cnt = 0; if (sum == t) f(g1, g2, g3, -1); for (long i = 1; i <= g1; i++) cnt *= i; for (long i = 1; i <= g2; i++) cnt *= i; for (long i = 1; i <= g3; i++) cnt *= i; ans += cnt; } System.out.println(ans % 1000000007); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Washoum */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; inputClass in = new inputClass(inputStream); PrintWriter out = new PrintWriter(outputStream); G1PlaylistForPolycarpEasyVersion solver = new G1PlaylistForPolycarpEasyVersion(); solver.solve(1, in, out); out.close(); } static class G1PlaylistForPolycarpEasyVersion { static final int mod = (int) 1e9 + 7; public void solve(int testNumber, inputClass sc, PrintWriter out) { int n = sc.nextInt(); int t = sc.nextInt(); G1PlaylistForPolycarpEasyVersion.Song[] songs = new G1PlaylistForPolycarpEasyVersion.Song[n]; for (int i = 0; i < n; i++) { songs[i] = new G1PlaylistForPolycarpEasyVersion.Song(sc.nextInt(), sc.nextInt()); } long ans = 0; for (int mask = 1; mask < (1 << n); mask++) { int nb = 0; int tot = 0; int type1 = 0; int type2 = 0; int type3 = 0; for (int j = 0; j < n; j++) { if (((1 << j) & mask) > 0) { nb++; tot += songs[j].l; if (songs[j].type == 1) { type1++; } else if (songs[j].type == 2) { type2++; } else { type3++; } } } if (tot == t) { long[][][][][] dp = new long[nb + 1][3][type1 + 1][type2 + 1][type3 + 1]; boolean[][][][][] go = new boolean[nb + 1][3][type1 + 1][type2 + 1][type3 + 1]; if (type1 > 0) { go[1][0][type1 - 1][type2][type3] = true; dp[1][0][type1 - 1][type2][type3] = type1; } if (type2 > 0) { go[1][1][type1][type2 - 1][type3] = true; dp[1][1][type1][type2 - 1][type3] = type2; } if (type3 > 0) { go[1][2][type1][type2][type3 - 1] = true; dp[1][2][type1][type2][type3 - 1] = type3; } for (int i = 0; i < nb; i++) { for (int m = 0; m < 3; m++) { for (int j = 0; j <= type1; j++) { for (int k = 0; k <= type2; k++) { for (int l = 0; l <= type3; l++) { if (go[i][m][j][k][l]) { if (m == 0) { if (k > 0) { dp[i + 1][1][j][k - 1][l] += dp[i][m][j][k][l] * k; dp[i + 1][1][j][k - 1][l] %= mod; go[i + 1][1][j][k - 1][l] = true; } if (l > 0) { dp[i + 1][2][j][k][l - 1] += dp[i][m][j][k][l] * l; dp[i + 1][2][j][k][l - 1] %= mod; go[i + 1][2][j][k][l - 1] = true; } } else if (m == 1) { if (j > 0) { dp[i + 1][0][j - 1][k][l] += dp[i][m][j][k][l] * j; dp[i + 1][0][j - 1][k][l] %= mod; go[i + 1][0][j - 1][k][l] = true; } if (l > 0) { dp[i + 1][2][j][k][l - 1] += dp[i][m][j][k][l] * l; dp[i + 1][2][j][k][l - 1] %= mod; go[i + 1][2][j][k][l - 1] = true; } } else { if (j > 0) { dp[i + 1][0][j - 1][k][l] += dp[i][m][j][k][l] * j; dp[i + 1][0][j - 1][k][l] %= mod; go[i + 1][0][j - 1][k][l] = true; } if (k > 0) { dp[i + 1][1][j][k - 1][l] += dp[i][m][j][k][l] * k; dp[i + 1][1][j][k - 1][l] %= mod; go[i + 1][1][j][k - 1][l] = true; } } } } } } } } long toadd = 0; for (int i = 0; i < 3; i++) { toadd += dp[nb][i][0][0][0]; } ans += toadd; ans %= (int) 1e9 + 7; } } out.println(ans); } static class Song { int l; int type; public Song(int x, int y) { l = x; type = y; } } } static class inputClass { BufferedReader br; StringTokenizer st; public inputClass(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Aman Kumar Singh */ 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); G1PlaylistForPolycarpEasyVersion solver = new G1PlaylistForPolycarpEasyVersion(); solver.solve(1, in, out); out.close(); } static class G1PlaylistForPolycarpEasyVersion { final long mod = 1000000007; PrintWriter out; InputReader in; int n; int time; int[][] arr; long[][][] dp; long go(int last, int t, int mask) { if (t > time) return 0; if (t == time) { return 1l; } if (mask == (1 << n) - 1) return 0; if (dp[last][t][mask] != -1) return dp[last][t][mask]; long cnt = 0; int i = 0, j = 0; for (i = 0; i < n; i++) { if ((mask & (1 << i)) == 0 && arr[i][1] != last) { cnt += go(arr[i][1], t + arr[i][0], mask | (1 << i)); cnt %= mod; } } dp[last][t][mask] = cnt; return cnt; } public void solve(int testNumber, InputReader in, PrintWriter out) { this.out = out; this.in = in; n = ni(); time = ni(); arr = new int[n][2]; int i = 0; for (i = 0; i < n; i++) { arr[i][0] = ni(); arr[i][1] = ni() - 1; } dp = new long[3][time + 1][1 << n]; for (i = 0; i < 3; i++) { for (int j = 0; j <= time; j++) Arrays.fill(dp[i][j], -1); } long ans = (((go(0, 0, 0) + go(1, 0, 0)) % mod + go(2, 0, 0)) % mod); ans *= modPow(2, mod - 2); ans %= mod; pn(ans); } int ni() { return in.nextInt(); } void pn(Object o) { out.println(o); } long modPow(long a, long p) { long o = 1; while (p > 0) { if ((p & 1) == 1) o = mul(o, a); a = mul(a, a); p >>= 1; } return o; } long mul(long a, long b) { if (a >= mod) a %= mod; if (b >= mod) b %= mod; a *= b; if (a >= mod) a %= mod; return a; } } 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; } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Sparsh Sanchorawala */ 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); G1PlaylistForPolycarpEasyVersion solver = new G1PlaylistForPolycarpEasyVersion(); solver.solve(1, in, out); out.close(); } static class G1PlaylistForPolycarpEasyVersion { long mod = (long) 1e9 + 7; public void solve(int testNumber, InputReader s, PrintWriter w) { int n = s.nextInt(), T = s.nextInt(); int[] t = new int[n + 1]; int[] g = new int[n + 1]; int[] f = new int[4]; for (int i = 1; i <= n; i++) { t[i] = s.nextInt(); g[i] = s.nextInt(); f[g[i]]++; } long[] fact = new long[n + 1]; fact[0] = 1; for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i % mod; long[][][][] perm = new long[f[1] + 1][f[2] + 1][f[3] + 1][3 + 1]; long[][][] sumPerm = new long[f[1] + 1][f[2] + 1][f[3] + 1]; perm[0][0][0][0] = 1; for (int a = 0; a <= f[1]; a++) { for (int b = 0; b <= f[2]; b++) { for (int c = 0; c <= f[3]; c++) { if (a - 1 >= 0) perm[a][b][c][1] = (sumPerm[a - 1][b][c] - perm[a - 1][b][c][1] + mod) % mod; if (b - 1 >= 0) perm[a][b][c][2] = (sumPerm[a][b - 1][c] - perm[a][b - 1][c][2] + mod) % mod; if (c - 1 >= 0) perm[a][b][c][3] = (sumPerm[a][b][c - 1] - perm[a][b][c - 1][3] + mod) % mod; for (int i = 0; i <= 3; i++) sumPerm[a][b][c] = (sumPerm[a][b][c] + perm[a][b][c][i]) % mod; } } } long[][][][][] dp = new long[n + 1][f[1] + 1][f[2] + 1][f[3] + 1][T + 1]; dp[0][0][0][0][0] = 1; for (int i = 1; i <= n; i++) { for (int a = 0; a <= f[1]; a++) { for (int b = 0; b <= f[2]; b++) { for (int c = 0; c <= f[3]; c++) { for (int j = 0; j <= T; j++) { dp[i][a][b][c][j] = dp[i - 1][a][b][c][j]; if (j - t[i] >= 0) { if (g[i] == 1 && a > 0) { dp[i][a][b][c][j] = (dp[i][a][b][c][j] + dp[i - 1][a - 1][b][c][j - t[i]]) % mod; } else if (g[i] == 2 && b > 0) { dp[i][a][b][c][j] = (dp[i][a][b][c][j] + dp[i - 1][a][b - 1][c][j - t[i]]) % mod; } else if (g[i] == 3 && c > 0) { dp[i][a][b][c][j] = (dp[i][a][b][c][j] + dp[i - 1][a][b][c - 1][j - t[i]]) % mod; } } } } } } } long res = 0; for (int a = 0; a <= f[1]; a++) for (int b = 0; b <= f[2]; b++) for (int c = 0; c <= f[3]; c++) res = (res + dp[n][a][b][c][T] * sumPerm[a][b][c] % mod * fact[a] % mod * fact[b] % mod * fact[c] % mod) % mod; w.println(res); } } 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); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class codeforces { public static long cnt = 0; public static void f(int g1, int g2, int g3, int last) { if (g1 == 0 && g2 == 0 && g3 == 0) cnt++; if (g1 > 0 && last != 1) f(g1 - 1, g2, g3, 1); if (g2 > 0 && last != 2) f(g1, g2 - 1, g3, 2); if (g3 > 0 && last != 3) f(g1, g2, g3 - 1, 3); } public static void main(String[] args) throws IOException { BufferedReader scan = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(scan.readLine()); int n = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st.nextToken()); int T[] = new int[n]; int G[] = new int[n]; for (int i = 0; i < n; i++) { st = new StringTokenizer(scan.readLine()); T[i] = Integer.parseInt(st.nextToken()); G[i] = Integer.parseInt(st.nextToken()); } long ans = 0; for (int mask = 1; mask < (1 << n); mask++) { int sum = 0; int g1 = 0; int g2 = 0; int g3 = 0; for (int i = 0; i < n; i++) { if (((1 << i) & mask) > 0) { sum += T[i]; if (G[i] == 1) g1++; if (G[i] == 2) g2++; if (G[i] == 3) g3++; } } cnt = 0; if (sum == t) f(g1, g2, g3, -1); for (long i = 1; i <= g1; i++) cnt *= i; for (long i = 1; i <= g2; i++) cnt *= i; for (long i = 1; i <= g3; i++) cnt *= i; ans += cnt; } System.out.println(ans % 1000000007); } }
np
1185_G1. Playlist for Polycarp (easy 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); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class G_PlaylistForPolycarp { static final int mod = 1000000007; static int dp[][]; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); String[] dat = br.readLine().split(" "); int n = Integer.parseInt(dat[0]); int T = Integer.parseInt(dat[1]); int[] st = new int[n]; byte[] sg = new byte[n]; dp = new int[1 << (n + 1)][4]; for (int j = 0; j < 1 << (n + 1); j++) { for (int k = 0; k < 4; k++) { dp[j][k] = -1; } } for (int i = 0; i < n; i++) { dat = br.readLine().split(" "); st[i] = Integer.parseInt(dat[0]); sg[i] = Byte.parseByte(dat[1]); } short visited = 0; int count = recur(0, visited, st, sg, T, 0); bw.write(count + "\n"); bw.close(); } private static int recur(int time, short visited, int[] st, byte[] sg, int T, int last) { int count = 0; if (dp[visited][last] != -1) { return dp[visited][last]; } for (int i = 0; i < st.length; i++) { if ((visited & (1 << i)) == 0 && sg[i] != last) { if (time + st[i] == T) { count += 1; } else if (time + st[i] < T) { short visitedc = (short) (visited | (1 << i)); count += recur(time + st[i], visitedc, st, sg, T, sg[i]); if (count > mod) { count = count % mod; } } } } return dp[visited][last] = count % mod; } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ /*********************************************Constants******************************************/ static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static long mod=(long)1e9+7; static long mod1=998244353; static boolean sieve[]; static ArrayList<Integer> primes; static long factorial[],invFactorial[]; static HashSet<Pair> graph[]; static boolean oj = System.getProperty("ONLINE_JUDGE") != null; /****************************************Solutions Begins***************************************/ static int n,T,input[],type[]; static long dp[][]; static long dfs(int mask,int t){ if(dp[mask][t]!=-1){ return dp[mask][t]; } int s=0; for(int i=0;i<n;i++){ if((mask&(1<<i))!=0){ s+=input[i]; } } if(s>T){ return 0; } if(s==T){ dp[mask][t]=1; return dp[mask][t]; } long ans=0; for(int i=0;i<n;i++){ if((mask&(1<<i))==0&&type[i]!=t){ ans=(ans+dfs(mask|(1<<i),type[i]))%mod; } } dp[mask][t]=ans; return dp[mask][t]; } public static void main (String[] args) throws Exception { String st[]=nl(); n=pi(st[0]); T=pi(st[1]); input=new int[n]; type=new int[n]; for(int i=0;i<n;i++){ st=nl(); input[i]=pi(st[0]); type[i]=pi(st[1]); } dp=new long[1<<n][4]; for(long arr[]:dp) Arrays.fill(arr,-1); long ans=dfs(0,0); // debug(dp); out.println(ans); /****************************************Solutions Ends**************************************************/ out.flush(); out.close(); } /****************************************Template Begins************************************************/ static String[] nl() throws Exception{ return br.readLine().split(" "); } static String[] nls() throws Exception{ return br.readLine().split(""); } static int pi(String str) { return Integer.parseInt(str); } static long pl(String str){ return Long.parseLong(str); } static double pd(String str){ return Double.parseDouble(str); } /***************************************Precision Printing**********************************************/ static void printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.00000000000000000"); out.println(ft.format(d)); } /**************************************Bit Manipulation**************************************************/ static void printMask(long mask){ System.out.println(Long.toBinaryString(mask)); } static int countBit(int mask){ int ans=0; while(mask!=0){ if(mask%2==1){ ans++; } mask/=2; } return ans; } /******************************************Graph*********************************************************/ static void Makegraph(int n){ graph=new HashSet[n]; for(int i=0;i<n;i++){ graph[i]=new HashSet<>(); } } static void addEdge(int a,int b){ graph[a].add(new Pair(b,1)); } static void addEdge(int a,int b,int c){ graph[a].add(new Pair(b,c)); } /*********************************************PAIR********************************************************/ static class PairComp implements Comparator<Pair>{ public int compare(Pair p1,Pair p2){ return ((p1.u+p1.v)-(p2.u+p2.v)); } } static class Pair implements Comparable<Pair> { int u; int v; int index=-1; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /******************************************Long Pair*************************************************/ static class PairCompL implements Comparator<Pairl>{ public int compare(Pairl p1,Pairl p2){ if((p1.u+2*p1.v)-(p2.u+2*p2.v)<0){ return -1; } else if((p1.u+2*p1.v)-(p2.u+2*p2.v)>0){ return 1; } else{ return 0; } } } static class Pairl implements Comparable<Pairl> { long u; long v; int index=-1; public Pairl(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pairl other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*****************************************DEBUG***********************************************************/ public static void debug(Object... o) { if(!oj) System.out.println(Arrays.deepToString(o)); } /************************************MODULAR EXPONENTIATION***********************************************/ static long modulo(long a,long b,long c) { long x=1; long y=a; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } /********************************************GCD**********************************************************/ static long gcd(long x, long y) { if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0) { r = a % b; a = b; b = r; } return r; } /******************************************SIEVE**********************************************************/ static void sieveMake(int n){ sieve=new boolean[n]; Arrays.fill(sieve,true); sieve[0]=false; sieve[1]=false; for(int i=2;i*i<n;i++){ if(sieve[i]){ for(int j=i*i;j<n;j+=i){ sieve[j]=false; } } } primes=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(sieve[i]){ primes.add(i); } } } /********************************************End***********************************************************/ }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); G1PlaylistForPolycarpEasyVersion solver = new G1PlaylistForPolycarpEasyVersion(); solver.solve(1, in, out); out.close(); } static class G1PlaylistForPolycarpEasyVersion { static ArrayList<Integer> list; static int n; static int req; static int mod = (int) 1e9 + 7; static int[] dur; static int[] genre; static Integer[][][] memo; public void solve(int testNumber, Scanner sc, PrintWriter pw) { n = sc.nextInt(); req = sc.nextInt(); dur = new int[n]; genre = new int[n]; list = new ArrayList<>(); for (int i = 0; i < n; i++) { dur[i] = sc.nextInt(); genre[i] = sc.nextInt(); } int ans = 0; memo = new Integer[1 << n][n + 1][4]; for (int i = 0; i <= n; i++) ans += bf(0, 0, 0, i) % mod; pw.print(ans % mod); } private int bf(int idx, int msk, int before, int max) { if (idx == max) { int sum = 0; for (int x : list) sum += x; if (sum == req) return 1; return 0; } if (memo[msk][max][before] != null) return memo[msk][max][before] % mod; int toRet = 0; for (int i = 0; i < n; i++) { if (genre[i] != before && (msk & 1 << i) == 0) { list.add(dur[i]); toRet += bf(idx + 1, msk | 1 << i, genre[i], max); toRet %= mod; list.remove(list.size() - 1); } } return memo[msk][max][before] = (toRet % mod); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
np
1185_G1. Playlist for Polycarp (easy 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); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Solution { BufferedReader in; PrintWriter out; StringTokenizer st; int[] x; int[] y; int n; int X, Y; int[] d; int[][] dist; int sqr(int a) { return a * a; } int dist(int X, int Y, int i) { return sqr(X - x[i]) + sqr(Y - y[i]); } int[] dp; byte[][] pred; int rec(int mask) { if (dp[mask] == -1) { int res = 1 << 29; boolean ok = false; for (int i = 0; i < n; ++i) if ((mask & (1 << i)) > 0) { ok = true; int mm = mask & ~(1 << i); for (int j = i; j < n; j++) if ((mask & (1 << j)) > 0) { int nmask = mm & ~(1 << j); int a = rec(nmask) + d[i] + d[j] + dist[i][j]; if (a < res) { res = a; pred[0][mask] = (byte) (i); pred[1][mask] = (byte) (j); } } break; } if (!ok) res = 0; dp[mask] = res; } return dp[mask]; } void solve() throws IOException { X = ni(); Y = ni(); n = ni(); x = new int[n]; y = new int[n]; for (int i = 0; i < n; i++) { x[i] = ni(); y[i] = ni(); } d = new int[n]; dist = new int[n][n]; for (int i = 0; i < n; ++i) d[i] = dist(X, Y, i); for (int i = 0; i < n; ++i) for (int j = 0; j < n; j++) { dist[i][j] = dist(x[i], y[i], j); } pred = new byte[2][1 << n]; dp = new int[1 << n]; Arrays.fill(dp, -1); out.println(rec((1 << n) - 1)); int a = (1 << n) - 1; while (a > 0) { if (pred[0][a] != pred[1][a]) out.print(0 + " " + (pred[0][a] + 1) + " " + (pred[1][a] + 1) + " "); else out.print(0 + " " + (pred[0][a] + 1) + " "); int na = a & ~(1 << pred[0][a]); na &= ~(1 << pred[1][a]); a = na; } out.println(0); } public Solution() throws IOException { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } String ns() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int ni() throws IOException { return Integer.valueOf(ns()); } long nl() throws IOException { return Long.valueOf(ns()); } double nd() throws IOException { return Double.valueOf(ns()); } public static void main(String[] args) throws IOException { new Solution(); } }
np
8_C. Looking for Order
CODEFORCES
import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; /** * Created by 11815 on 2017/7/1. */ public class Main { private static int[] x = new int[26], y = new int[26], dp = new int[1<<24], pre = new int[1<<24]; private static int dis(int i, int j) { return (x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int x0 = in.nextInt(), y0 = in.nextInt(), n = in.nextInt(); for (int i = 0; i < n; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); } x[n] = x0; y[n] = y0; int[][] gra = new int[26][26]; for (int i = 0; i < n + 1; i++) { for (int j = i+1; j < n+1; j++) { gra[i][j] = gra[j][i] = dis(i,j); } } Arrays.fill(dp, -1); dp[0] = 0; for (int i = 0; i < 1 << n; i++) { if (dp[i] != -1) { for (int j = 0; j < n; j++) { if (((1<<j)&i) == 0) { int t = i | (1<<j), tmp = dp[i] + 2*gra[j][n]; if (dp[t] == -1 || dp[t] > tmp) { dp[t] = tmp; pre[t] = i; } for (int k = 0; k < n; k++) { if ((t&(1<<k)) == 0) { int t2 = t | (1<<k), tmp2 = dp[i] + gra[n][j] + gra[j][k] + gra[k][n]; if (dp[t2] == -1 || dp[t2] > tmp2) { dp[t2] = tmp2; pre[t2] = i; } } } break; } } } } int end = (1<<n)-1, cnt = 0; int[] ans = new int[60]; System.out.println(dp[end]); while (end != 0) { int pr = pre[end]; int tem = pr^end; int a = 0, b = 0; for (int i = 0; i < n; i++) { if (((1<<i)&tem)!=0) { b=a; a=i+1; } } ans[cnt++] = 0; ans[cnt++] = a; if (b>0) { ans[cnt++] = b; } end = pr; } ans[cnt++] = 0; for (int i = cnt-1; i >= 0; i--) { System.out.print(ans[i] + " "); } System.out.print("\n"); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** Created by huhansan on 2017/10/9. */ public class CF_8C implements Runnable { int[] step = new int[1 << 24]; //每个状态所需要的步数 int[] steplast = new int[1 << 24]; //当前状态上一个 int n; int vs[] = new int[24]; int vd[][] = new int[24][24]; int x_bag, y_bag; int x[] = new int[24], y[] = new int[24]; /** */ private void solve() throws IOException { x_bag = nextInt(); y_bag = nextInt(); n = nextInt(); for (int i = 0; i < n; i++) { x[i] = nextInt(); y[i] = nextInt(); } //计算所有物品单取的全值和 任意两件物品一起取的权值 for (int i = 0; i < n; i++) { vs[i] = 2 * ((x[i] - x_bag) * (x[i] - x_bag) + (y[i] - y_bag) * (y[i] - y_bag)); } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { vd[i][j] = (x[i] - x_bag) * (x[i] - x_bag) + (y[i] - y_bag) * (y[i] - y_bag) + (x[j] - x_bag) * (x[j] - x_bag) + (y[j] - y_bag) * (y[j] - y_bag) + (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]); } } //记录达到每一个状态所需的最小步数和最后一次取得物品 for (int i = 1; i < 1 << n; i++) { int j, k = 0, l, m, lastState; for (j = 1; (i & j) == 0 && j < 1 << n; j <<= 1) { k++; } lastState = i & (~j); step[i] = step[lastState] + vs[k]; steplast[i] = lastState; m = k; for (l = j << 1; l < 1 << n; l <<= 1) { m++; if ((lastState & l) != 0) { if (step[i] > step[lastState & (~l)] + vd[k][m]) { step[i] = step[lastState & (~l)] + vd[k][m]; steplast[i] = lastState & (~l); } } } // System.out.println(steplast[i]+"---"+i+"---"+step[i]); } writer.println(step[(1 << n) - 1]); int i = (1 << n) - 1; writer.print("0 "); while (i != 0) { for (int j = 1, m = 1; j <= i; j <<= 1, m++) { if ((j & (i ^ steplast[i])) != 0) { writer.print(m + " "); } } writer.print("0 "); i = steplast[i]; } } public static void main(String[] args) { new CF_8C().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main implements Runnable { //public static final String FileName = "test"; StreamTokenizer ST; PrintWriter out; BufferedReader br; Scanner in; static final int inf = 1000000000+10; int nextInt() throws IOException{ ST.nextToken(); return (int)ST.nval; } long nextLong() throws IOException{ ST.nextToken(); return (long)ST.nval; } String next() throws IOException{ ST.nextToken(); return ST.sval; } double nextD() throws IOException{ ST.nextToken(); return ST.nval; } public static void main(String[] args) throws IOException { new Thread(new Main()).start(); // new Main().run(); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //br = new BufferedReader(new FileReader(new File(FileName+".in"))); //out = new PrintWriter(new BufferedWriter(new FileWriter(FileName+".out"))); //in = new Scanner(br); ST = new StreamTokenizer(br); solve(); out.close(); //in.close(); br.close(); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException(e); } } public void solve() throws IOException { int[] x = new int[32]; int[] y = new int[32]; x[0] = nextInt(); y[0] = nextInt(); int n = nextInt(); for (int i=1; i<=n; i++) { x[i] = nextInt(); y[i] = nextInt(); } n++; int[][] a = new int[n][n]; int[][] b = new int[n-1][n-1]; for (int i=0; i<n; i++) for (int j=0; j<n; j++) a[i][j] = (x[i]-x[j])*(x[i]-x[j])+ (y[i]-y[j])*(y[i]-y[j]); for (int i=1; i<n; i++) for (int j=1; j<n; j++) if (i!=j) b[i-1][j-1] = a[0][i]+a[i][j]+a[j][0]; else b[i-1][j-1] = 2*a[0][i]; n--; int sz = 1<<n; int[] d = new int[sz]; int[] p = new int[sz]; d[1] = 0; for (int msk=1; msk<sz; msk++) { int j = 0; while ((msk&(1<<j))==0) j++; int t = inf; for (int i=0; i<n; i++) if ((msk&(1<<i))>0) if (t>d[msk^((1<<i)|(1<<j))]+b[i][j]) { t = d[msk^((1<<i)|(1<<j))]+b[i][j]; p[msk] = i*n+j; } d[msk] = t; } out.println(d[sz-1]); out.print("0 "); int t = sz-1; while (t>0) { int hz = p[t]; int i = hz/n; int j = hz%n; if (i!=j) out.print((i+1)+" "+(j+1)+" 0 ");else out.print((i+1)+" 0 "); t ^= (1<<i)|(1<<j); } } }
np
8_C. Looking for Order
CODEFORCES
import java.util.*; import java.io.*; public class Main{ BufferedReader in; StringTokenizer str = null; PrintWriter out; private String next() throws Exception{ if (str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return str.nextToken(); } private int nextInt() throws Exception{ return Integer.parseInt(next()); } int []x,y; int n; int []dp, prev; public void run() throws Exception{ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int xs = nextInt(); int ys = nextInt(); n = nextInt(); x = new int[n]; y = new int[n]; for(int i=0;i<n;i++){ x[i] = nextInt(); y[i] = nextInt(); } int one[] = new int[n]; for(int i=0;i<n;i++){ one[i] = dist(xs, ys, x[i], y[i]); } int two[][] = new int[n][n]; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ two[i][j] = two[j][i] = dist(xs, ys, x[i], y[i]) + dist(x[i], y[i], x[j], y[j]) + dist(xs, ys, x[j], y[j]); } } dp = new int[1<<n]; Arrays.fill(dp, Integer.MAX_VALUE/2); dp[0] = 0; prev = new int[1<<n]; Arrays.fill(prev, -1); for(int mask=1;mask<(1<<n);mask++){ int i = 0; while((mask & (1<<i)) == 0) i++; dp[mask] = dp[mask ^ (1<<i)] + 2*one[i]; prev[mask] = i+1; for(int j=i+1;j<n;j++){ if ((mask & (1<<j)) > 0) { if (dp[mask] > dp[mask ^ (1<<i) ^ (1<<j)] + two[i][j]) { dp[mask] = dp[mask ^ (1<<i) ^ (1<<j)] + two[i][j]; prev[mask] = 100 * (i+1) + (j+1); } } } } out.println(dp[(1<<n)-1]); out.print(0 + " "); int cur = (1<<n)-1; int i = 0, j = 0; while(cur > 0) { i = prev[cur]/100; j = prev[cur]%100; if (i > 0) { cur^=1<<(i-1); out.print(i + " "); } if (j > 0) { cur^=1<<(j-1); out.print(j + " "); } out.print(0 + " "); } // if (i == 0 || j == 0) { // out.println(0); // } out.close(); } private String bit2str(int mask, int n) { String s = ""; for(int i=0;i<n;i++){ if ((mask & (1<<i)) > 0){ s+="1"; }else{ s+="0"; } } while(s.length() < n) s+="0"; return new StringBuilder(s).reverse().toString(); } private int dist(int x1, int y1, int x2, int y2) { return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); } public static void main(String args[]) throws Exception{ new Main().run(); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; // Jonathan // cpt_fwiffo public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] line = in.readLine().split(" "); int Xs = Integer.parseInt(line[0]); int Ys = Integer.parseInt(line[1]); int n = Integer.parseInt(in.readLine()); int[][] points = new int[n+1][2]; points[n][0] = Xs;//set starting point as last point for finding distances points[n][1] = Ys; for(int i=0; i< n ; i++) { line = in.readLine().split(" "); points[i][0] = Integer.parseInt(line[0]); points[i][1] = Integer.parseInt(line[1]); } int[][] distances = new int[n+1][n+1]; ComputeDistances(points, distances, n); int[] dp = new int[1<<n]; int[] path = new int[1<<n]; ComputeLowestPath(dp, path, distances, n); OutputLowestAndPath(dp, path, n); } private static void ComputeLowestPath(int[] dp, int[] path, int[][] distances, int n) { for(int i = 1; i < 1<<n; i++) { int j = 0; while(true) //find first 1 (LSB) { if((i&(1<<j))!=0) //check for a bit equal to 1 in location j { break; } j++; } int pastEntry = i & ~(1<<j); //remove first 1 from i path[i] = pastEntry; //set the path we came from to trace later int distance = distances[j][n] * 2; //distance from origin to the point being removed, and back dp[i] = dp[pastEntry] + distance; //set minimum distance if just this point is added to the collection for(int m = j +1; m < n; m++) { if((i & (1<<m))!=0) { int entry = i & ~((1<<j)|(1<<m)); //remove both 1 at position j and 1 at position m from i distance = distances[j][n] + distances[j][m] + distances[m][n]; //calculate round-trip distance to grab 2 points if(dp[i] > dp[entry] + distance) // check if this new option is a better choice. If it is, update our value and our path. { dp[i] = dp[entry] + distance; path[i] = entry; } } } } } private static void OutputLowestAndPath(int[] dp, int[] path, int n) { StringBuilder out = new StringBuilder(); out.append(dp[(1<<n)-1]);//output min value of traversal out.append("\n"); out.append("0 "); int index = (1<<n)-1; //start at our min value while(index != 0) { int j = path[index]; int k = index ^ j; //find the one or two values that were added at this step for(int m = 0; m < n; m++) { if((k & (1 << m)) != 0) { out.append(m+1); out.append(" "); } } out.append("0 "); index = j; } System.out.println(out.toString()); } private static void ComputeDistances(int[][] points, int[][] distances, int n) { for(int i = 0; i <= n; i++) //calculate distances between all points so that we don't have to compute later { for(int j=i+1; j<=n; j++) { int x= points[i][0] - points[j][0]; int y= points[i][1] - points[j][1]; distances[i][j] = x*x + y*y; } } } }
np
8_C. Looking for Order
CODEFORCES
import java.io.*; import java.util.*; public class CF8C { FastScanner in; PrintWriter out; int[] x, y; int[] av; int[][] d = new int[25][25]; int dist(int v, int u) { if (u == v) return 0; return (d[v][u] == 0 ? d[v][u] = d[u][v] = (x[v] - x[u]) * (x[v] - x[u]) + (y[v] - y[u]) * (y[v] - y[u]) : d[v][u]); } void add(int x) { av[++av[0]] = x; } int size() { return av[0]; } int get(int i) { return av[i + 1]; } int N = 24; int[] dp = new int[(1 << N)]; int[] dpFrom = new int[1 << N]; void solve() { int x1 = in.nextInt(); int y1 = in.nextInt(); int n = in.nextInt(); x = new int[n + 1]; y = new int[n + 1]; for (int i = 1; i <= n; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); } x[0] = x1; y[0] = y1; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; av = new int[n + 1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) dist(i, j); for (int st = 0; st < (1 << n); st++) { if (dp[st] == Integer.MAX_VALUE) continue; av[0] = 0; for (int i = 0; i < n; i++) if ((st & (1 << i)) == 0) add(i); if (av[0] == 0) continue; for (int i = 0; i < 1; i++) for (int j = i + 1; j < av[0]; j++) { int val = dp[st] + d[get(i) + 1][0] + d[get(j) + 1][0] + d[get(i) + 1][get(j) + 1]; if (dp[st | (1 << get(i)) | (1 << get(j))] > val) { dp[st | (1 << get(i)) | (1 << get(j))] = val; dpFrom[st | (1 << get(i)) | (1 << get(j))] = st; } } for (int i = 0; i < 1; i++) { int val = dp[st] + d[get(i) + 1][0] * 2; if (dp[st | (1 << get(i))] > val) { dp[st | (1 << get(i))] = val; dpFrom[st | (1 << get(i))] = st; } } } out.println(dp[(1 << n) - 1]); int nowSt = (1 << n) - 1; ArrayList<Integer> ans = new ArrayList<Integer>(); ans.add(0); while (nowSt != 0) { int newSt = dpFrom[nowSt]; for (int i = 0; i < n; i++) if (((1 << i) & nowSt) == (1 << i)) if (((1 << i) & newSt) == 0) ans.add(i + 1); ans.add(0); nowSt = newSt; } for (int i = ans.size() - 1; i >= 0; i--) out.print(ans.get(i) + " "); } void run() { try { in = new FastScanner(new File("object.in")); out = new PrintWriter(new File("object.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { new CF8C().runIO(); } }
np
8_C. Looking for Order
CODEFORCES
import java.awt.Point; import java.util.Arrays; import java.util.Scanner; public class C { static int[] DP; static Point[] Next; static int[][] pair; static int[] single; static int n; public static int get(int mask) { if (mask + 1 == (1 << n)) return 0; if (DP[mask] != -1) return DP[mask]; int x = 0; for (;; x++) if ((mask & (1 << x)) == 0) break; int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0 || i == x) continue; int temp = pair[x][i] + get(mask | (1 << i) | (1 << x)); if (temp < min) { min = temp; Next[mask] = new Point(x, i); } } int temp = single[x] + get(mask | (1 << x)); if (temp < min) { min = temp; Next[mask] = new Point(x, -1); } return DP[mask] = min; } public static void main(String[] args) { Scanner in = new Scanner(System.in); Point start = new Point(in.nextInt(), in.nextInt()); n = in.nextInt(); Point[] A = new Point[n]; for (int i = 0; i < n; i++) A[i] = new Point(in.nextInt(), in.nextInt()); DP = new int[1 << n]; Next = new Point[1 << n]; Arrays.fill(DP, -1); pair = new int[n][n]; single = new int[n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { int dx1 = A[i].x - start.x; int dy1 = A[i].y - start.y; int dx2 = A[j].x - A[i].x; int dy2 = A[j].y - A[i].y; int dx3 = A[j].x - start.x; int dy3 = A[j].y - start.y; pair[i][j] = dx1 * dx1 + dy1 * dy1 + dx2 * dx2 + dy2 * dy2 + dx3 * dx3 + dy3 * dy3; single[i] = 2 * (dx1 * dx1 + dy1 * dy1); } int ans = get(0); System.out.println(ans); int mask = 0; while (mask + 1 != (1 << n)) { Point temp = Next[mask]; if (temp.y == -1) System.out.print("0 " + (temp.x + 1) + " "); else { System.out .print("0 " + (temp.x + 1) + " " + (temp.y + 1) + " "); mask |= (1 << temp.y); } mask |= (1 << temp.x); } System.out.println("0"); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class ProblemC { public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // generateRandom(); int[] pt = readPoint(s); int n = Integer.valueOf(s.readLine()); int[][] xp = new int[n+1][]; for (int i = 1 ; i <= n ; i++) { xp[i] = readPoint(s); } xp[0] = pt; int[][] dist = new int[n+1][n+1]; for (int i = 0 ; i <= n ; i++) { for (int j = 0 ; j <= n ; j++) { int dx = Math.abs(xp[i][0] - xp[j][0]); int dy = Math.abs(xp[i][1] - xp[j][1]); dist[i][j] = dx*dx + dy*dy; } } int[][] dist2 = new int[n+1][n+1]; for (int i = 0 ; i <= n ; i++) { for (int j = 0 ; j <= n ; j++) { dist2[i][j] = dist[0][i] + dist[i][j] + dist[j][0]; } } int[] dp = new int[1<<n]; int[][] dp_prev = new int[2][1<<n]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for (int i = 0 ; i < (1<<n) ; i++) { if (dp[i] == Integer.MAX_VALUE) { continue; } int base = dp[i]; // two for (int y = 0 ; y < n ; y++) { if ((i & (1<<y)) >= 1) { break; } for (int z = y+1 ; z < n ; z++) { if ((i & (1<<z)) >= 1) { continue; } int ti = i | (1<<y) | (1<<z); int d = dist2[y+1][z+1]; if (dp[ti] > base + d) { dp[ti] = base + d; dp_prev[0][ti] = z+1; dp_prev[1][ti] = y+1; } } } } int bestOnes = 0; for (int i = 0 ; i < (1<<n) ; i++) { if (dp[i] == Integer.MAX_VALUE) { continue; } int sub = (1<<n) - 1 - i; int add = 0; for (int j = 0 ; j < n ; j++) { if ((sub & (1<<j)) >= 1) { add += dist[0][j+1] * 2; } } if (dp[i] + add < dp[(1<<n)-1]) { dp[(1<<n)-1] = dp[i] + add; bestOnes = sub; } } StringBuffer b = new StringBuffer(); b.append(" 0"); for (int i = 0 ; i < n ; i++) { if ((bestOnes & (1<<i)) >= 1) { b.append(" ").append(i+1).append(" ").append(0); } } out.println(dp[(1<<n)-1]); int nptn = (1<<n)-1-bestOnes; while (nptn >= 1) { int i1 = dp_prev[0][nptn]; int i2 = dp_prev[1][nptn]; if (i1 >= 1) { nptn -= 1<<(i1-1); b.append(" ").append(i1); } if (i2 >= 1) { nptn -= 1<<(i2-1); b.append(" ").append(i2); } b.append(" ").append(0); } out.println(b.substring(1)); out.flush(); } private static void generateRandom() { System.out.println("0 0"); System.out.println("24"); for (int i = 0 ; i < 24 ; i++) { int a = (int)(Math.random() * 200 - 100); int b = (int)(Math.random() * 200 - 100); System.out.println(a + " " + b); } } private static int[] readPoint(BufferedReader s) throws IOException { int[] ret = new int[2]; String[] data = s.readLine().split(" "); ret[0] = Integer.valueOf(data[0]); ret[1] = Integer.valueOf(data[1]); return ret; } public static void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; /** * @author Egor Kulikov ([email protected]) */ public class Order implements Runnable { private Scanner in = new Scanner(System.in); private PrintWriter out = new PrintWriter(System.out); private int xs, ys, n; private int[] x, y; public static void main(String[] args) { new Thread(new Order()).start(); } private void read() { xs = in.nextInt(); ys = in.nextInt(); n = in.nextInt(); x = new int[n]; y = new int[n]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); } } private void solve() { int[] res = new int[1 << n]; int[] last = new int[1 << n]; Arrays.fill(res, Integer.MAX_VALUE); int[] ds = new int[n]; for (int i = 0; i < n; i++) { ds[i] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys); } int[][] d = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) d[i][j] = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]); } res[0] = 0; for (int i = 1; i < (1 << n); i++) { for (int j = 0; j < n; j++) { if (((i >> j) & 1) != 0) { if (res[i - (1 << j)] + 2 * ds[j] < res[i]) { res[i] = res[i - (1 << j)] + 2 * ds[j]; last[i] = i - (1 << j); } for (int k = j + 1; k < n; k++) { if (((i >> k) & 1) != 0) { if (res[i - (1 << j) - (1 << k)] + ds[j] + ds[k] + d[j][k] < res[i]) { res[i] = res[i - (1 << j) - (1 << k)] + ds[j] + ds[k] + d[j][k]; last[i] = i - (1 << j) - (1 << k); } } } break; } } } int cur = (1 << n) - 1; out.println(res[cur]); while (cur != 0) { out.print("0 "); int dif = cur - last[cur]; for (int i = 0; i < n && dif != 0; i++) { if (((dif >> i) & 1) != 0) { out.print((i + 1) + " "); dif -= (1 << i); } } cur = last[cur]; } out.println("0"); } private void write() { } public void run() { read(); solve(); write(); out.close(); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * 111118315581 * * @author pttrung */ public class C { static Point hand; static int n; static Point[] data; static int[] next; static int[] dp; static int[][] pre; public static void main(String[] args) { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); // System.out.println(1 << 24); hand = new Point(in.nextInt(), in.nextInt()); n = in.nextInt(); data = new Point[n]; for (int i = 0; i < n; i++) { data[i] = new Point(in.nextInt(), in.nextInt()); } pre = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { pre[i][j] = distance(data[i], data[j]); } } next = new int[1 << n]; dp = new int[1 << n]; Arrays.fill(dp, -1); out.println(cal(0)); int start = 0; do { int m = next[start]; int val = m - start; out.print(0 + " "); for (int i = 0; i < n; i++) { if (((1 << i) & val) != 0) { out.print((i + 1) + " "); } } // out.print(0 + " ") ; start = m; } while (start != (1 << n) - 1); out.println(0); out.close(); } public static int cal(int mask) { if ((1 << n) - 1 == mask) { // System.out.println(mask); return 0; } if (dp[mask] != -1) { return dp[mask]; } int result = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { if (((1 << i) & mask) == 0) { int dist = distance(hand, data[i]); for (int j = i + 1; j < n; j++) { if (((1 << j) & mask) == 0) { //System.out.println(i + " " + j); int temp = dist + distance(hand, data[j]) + pre[i][j] + cal(mask | (1 << i) | (1 << j)); //System.out.println(temp); if (temp < result) { result = temp; next[mask] = (mask | (1 << i) | (1 << j)); } } } int temp = 2 * dist + cal(mask | (1 << i)); if (temp < result) { result = temp; next[mask] = (mask | (1 << i)); } break; } } dp[mask] = result; return result; } static int distance(Point a, Point b) { int total = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); return total; } static class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; import static java.lang.Integer.MAX_VALUE; import static java.lang.Integer.parseInt; /** * 8C * * @author artyom */ public class LookingForOrder { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] parsedString = parsedString = in.readLine().split(" "); int xStart = parseInt(parsedString[0]); int yStart = parseInt(parsedString[1]); int objectNum = parseInt(in.readLine()); int[] xLocs = new int[objectNum + 1]; int[] yLocs = new int[objectNum + 1]; int[] bitMasks = new int[1 << objectNum]; Arrays.fill(bitMasks, MAX_VALUE); int[] previous = new int[1 << objectNum]; xLocs[objectNum] = xStart; yLocs[objectNum] = yStart; for (int i = 0; i < objectNum; i++) { parsedString = in.readLine().split(" "); xLocs[i] = parseInt(parsedString[0]); yLocs[i] = parseInt(parsedString[1]); } //go through all pairs and find time requirement for each pair of objects //the entry at point [i][j] is equal to the time it takes to get from point i to point j int[][] times = new int[objectNum + 1][objectNum + 1]; for (int i = 0; i <= objectNum; i++) { for (int j = 0; j <= objectNum; j++) { times[i][j] = times[j][i] = (xLocs[i] - xLocs[j]) * (xLocs[i] - xLocs[j]) + (yLocs[i] - yLocs[j]) * (yLocs[i] - yLocs[j]); } } //each value in bitmasks represents the minimum time necessary to get //the unmasked bits //so bitmasks[5] (5=101) is the fastest time in which you can get //items 1 and 3 bitMasks[0] = 0; //collecting zero objects takes 0 time for (int i = 0; i < (1 << objectNum); i++) { if (bitMasks[i] != MAX_VALUE) { for (int j = 0; j < objectNum; j++) { if (((1 << j) & i) == 0) { //if our current j object hasn't been picked up yet int curState = (1 << j) | i; //ith state after picking up j object int curTime = bitMasks[i] + 2 * times[objectNum][j]; //time required to get object j from bag at state i if (curTime < bitMasks[curState]) { bitMasks[curState] = curTime; //put fastest time in for gettingto our current state previous[curState] = i; } //find another thing while you're out for (int k = 0; k < objectNum; k++) { if (((1 << k) & curState) == 0) { //if the kth position in our current state hasn't been picked up int kState = ((1 << k) | curState); //curstate after picking up the kth object //kTime is time it takes to go from bag, to j, to k and back int kTime = bitMasks[i] + times[objectNum][j] + times[j][k] + times[k][objectNum]; if (kTime < bitMasks[kState]) { bitMasks[kState] = kTime; //put shortest time for getting to kState in previous[kState] = i; } } } break; } } } } int finalState = (1 << objectNum) - 1; StringBuilder sb = new StringBuilder(); sb.append(bitMasks[finalState]).append('\n'); Deque<Integer> outputQ = new ArrayDeque<>(); outputQ.add(0); int curState = finalState; while (curState > 0) { //difference is the objects picked up in this state but not in previous state int difference = curState ^ previous[curState]; int firstItem = -1; int secondItem = -1; for (int i = 0; i < objectNum; i++) { if (((1 << i) & difference) > 0) { //if the ith object was picked up in this state secondItem = firstItem; //keep track of how many items are picked up firstItem = i; } } if (secondItem != -1) { //put in two items followed by a return to 0 outputQ.add(firstItem + 1); outputQ.add(secondItem + 1); outputQ.add(0); } else { outputQ.add(firstItem + 1); outputQ.add(0); } curState = previous[curState]; } sb.append(outputQ.removeLast()); while (!outputQ.isEmpty()) { sb.append(' ').append(outputQ.removeLast()); } System.out.print(sb); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class LookingForOrder { static final int INF = (int)1e9; static Point a[]; static Point o; static int n; static int dp[]; static PrintWriter out; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); o = new Point(sc.nextInt(), sc.nextInt()); n = sc.nextInt(); a = new Point[n]; for (int i = 0; i < n; i++) a[i] = new Point(sc.nextInt(), sc.nextInt()); dp = new int[(1 << n) + 5]; Arrays.fill(dp, -1); out.println(rec(0)); out.print(0 + " "); path(0); out.println(); out.flush(); out.close(); } static void path(int msk) { if (msk == (1 << n) - 1) return; int optimal = rec(msk); for (int i = 0; i < n; i++) { if ((msk & (1 << i)) == 0) { if (rec(msk | (1 << i)) + 2 * o.dist(a[i]) == optimal) { out.print((i + 1) + " " + 0 + " "); path(msk | (1 << i)); return; } for (int j = 0; j < n; j++) if (rec(msk | (1 << i) | (1 << j)) + o.dist(a[i]) + a[i].dist(a[j]) + a[j].dist(o) == optimal) { out.print((i + 1) + " " + (j + 1) + " " + 0 + " "); path(msk | (1 << i) | (1 << j)); return; } break; } } } static int rec(int msk) { if (msk == (1 << n) - 1) return 0; if (dp[msk] != -1) return dp[msk]; int ans = INF; for (int i = 0; i < n; i++) { if ((msk & (1 << i)) == 0) { ans = Math.min(ans, rec(msk | (1 << i)) + 2 * o.dist(a[i])); for (int j = 0; j < n; j++) { if (i == j) continue; if ((msk & (1 << j)) == 0) ans = Math.min(ans, rec(msk | (1 << i) | (1 << j)) + o.dist(a[i]) + a[i].dist(a[j]) + a[j].dist(o)); } break; } } return dp[msk] = ans; } static class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int dist(Point p) { return (x - p.x) * (x - p.x) + (y - p.y) * (y - p.y); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(FileReader f) { br = new BufferedReader(f); } public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean Ready() throws IOException { return br.ready(); } public void waitForInput(long time) { long ct = System.currentTimeMillis(); while(System.currentTimeMillis() - ct < time) {}; } } }
np
8_C. Looking for Order
CODEFORCES
import java.io.*; import java.util.*; public class Main { BufferedReader in = null; PrintWriter out = null; int dist(int x1, int y1, int x2, int y2) { int dx = Math.abs(x1 - x2); int dy = Math.abs(y1 - y2); return dx * dx + dy * dy; } boolean testBit(int use, int p) { return ((use >> p) & 1) == 1; } int rec(int use, int a[][], int dp[], int next[]) { if (dp[use] != -1) { return dp[use]; } if (use == 0) { return dp[use] = 0; } int n = a.length; int ix = -1; for (int i = 0; i < n; ++i) { if (testBit(use, i)) { if (ix == -1) { ix = i; break; } /* int t = rec(use ^ (1 << i), a, dp); t += a[i][i]; r = Math.min(r, t);*/ } } int r = rec(use ^ (1 << ix), a, dp, next) + a[ix][ix]; next[use] = use ^ (1 << ix); for (int i = ix + 1; i < n; ++i) { if (!testBit(use, i)) { continue; } int t = rec(use ^ (1 << ix) ^ (1 << i), a, dp, next); t += a[ix][i]; if (t < r) { r = t; next[use] = use ^ (1 << ix) ^ (1 << i); } } return dp[use] = r; } void print(int use1, int use2, int n) { for (int i = 0; i < n; ++i) { if (testBit(use1, i) ^ testBit(use2, i)) { int x = i + 1; out.print(x + " "); } } } void solve() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); //in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(System.out); StringTokenizer st; st = new StringTokenizer(in.readLine()); int sx = Integer.valueOf(st.nextToken()); int sy = Integer.valueOf(st.nextToken()); st = new StringTokenizer(in.readLine()); int n = Integer.valueOf(st.nextToken()); int x[] = new int[n]; int y[] = new int[n]; for (int i = 0; i < n; ++i) { st = new StringTokenizer(in.readLine()); x[i] = Integer.valueOf(st.nextToken()); y[i] = Integer.valueOf(st.nextToken()); } int a[][] = new int[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { a[i][j] = dist(x[i], y[i], sx, sy) + dist(x[j], y[j], sx, sy) + dist(x[i], y[i], x[j], y[j]); } } int dp[] = new int[1 << n]; Arrays.fill(dp, -1); int next[] = new int[1 << n]; int ans = rec((1 << n) - 1, a, dp, next); out.println(ans); int use = (1 << n) - 1; while (true) { int nuse = next[use]; out.print("0 "); print(use, nuse, n); if (nuse == 0) break; use = nuse; } out.println("0"); in.close(); out.close(); } public static void main(String[] args) throws IOException { new Main().solve(); } }
np
8_C. Looking for Order
CODEFORCES
import java.util.*; import static java.lang.System.*; import static java.lang.Math.*; public class C { static int[] dp; static int[] f; static void solve(){ dp = new int[1<<n]; f = new int[1<<n]; Arrays.fill(dp, 1<<29); dp[0] = 0; for(int i=0;i<(1<<n);i++){ // out.println("i="+i); for(int j=0;j<n;j++){ int ni = i | (1<<j); if( i != ni ){ // out.println("i="+i+",j="+j); int v = d[j]*2 + dp[i]; if(v < dp[ni]){ // out.println("up:"+ni+" to "+v + " fw="+i); dp[ni] = v; f[ni] = i; } for(int k=j+1;k<n;k++){ int nni = ni | (1<<k); if( ni != nni){ int vv = d[j] + t[j][k] + d[k] + dp[i]; if(vv < dp[nni]){ // out.println("up:"+nni+" to "+vv + " fw="+i); dp[nni] = vv; f[nni] = i; } } } break; } } } out.println(dp[dp.length-1]); // out.println("dp="+Arrays.toString(dp)); // out.println("f="+Arrays.toString(f)); int idx = dp.length - 1; out.print("0 "); while(idx != 0){ int road = idx ^ f[idx]; // out.println("idx = "+idx + " f[idx] = "+f[idx]); for(int i=0;i<n;i++) if( ((road>>i) & 1) == 1) out.print((i+1)+" "); idx = f[idx]; out.print("0 "); } out.println(); } static int[] d; static int[][] t; static int n; public static void main(String[] args) { Scanner sc = new Scanner(in); int x = sc.nextInt(); int y = sc.nextInt(); n = sc.nextInt(); int[] dx = new int[n]; int[] dy = new int[n]; for(int i=0;i<n;i++){ dx[i] = sc.nextInt(); dy[i] = sc.nextInt(); } d = new int[n]; for(int i=0;i<n;i++){ d[i] = (x-dx[i])*(x-dx[i]) + (y-dy[i])*(y-dy[i]); } t = new int[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ t[i][j] = (dx[i]-dx[j])*(dx[i]-dx[j]) + (dy[i]-dy[j])*(dy[i]-dy[j]); } } // out.println(Arrays.toString(d)); // out.println(Arrays.deepToString(t)); solve(); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.Locale; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { long prevTime = System.currentTimeMillis(); new Main().run(); System.err.println("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); System.err.println("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); Object o = solve(); if (o != null) out.println(o); out.close(); in.close(); } int n; Point[] ps; int[] dp; private Object solve() throws IOException { int o_x = ni(); int o_y = ni(); n = ni(); ps = new Point[n]; for (int i = 0; i < n; i++) ps[i] = new Point(ni() - o_x, ni() - o_y); dp = new int[1 << n]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; int[] path_x = new int[1 << n]; int[] path_y = new int[1 << n]; for (int mask = 1; mask < (1 << n); mask++) { int i = min(mask); int min_val = dp[mask - (1 << i)] + 2 * ps[i].norm; if (min_val < dp[mask]) { dp[mask] = min_val; path_x[mask] = i; path_y[mask] = i; } for (int j = i + 1; j < n; j++) if ((mask & (1 << j)) != 0) { int newMask = mask - (1 << i) - (1 << j); int val = dp[newMask] + ps[i].norm + ps[j].norm + ps[i].dist(ps[j]); if (val < dp[mask]) { dp[mask] = val; path_x[mask] = i; path_x[mask] = j; } } } pln(dp[(1 << n) - 1]); int maskPath = (1 << n) - 1; LinkedList<Long> list = new LinkedList<Long>(); while (maskPath != 0) { long x = path_x[maskPath]; long y = path_y[maskPath]; list.addFirst(0L); list.addFirst(y + 1); maskPath -= (1 << y); if (x != y) { list.addFirst(x + 1); maskPath -= 1 << x; } } list.addFirst(0L); show(list); return null; } private int min(int mask) { int ret = 0; while (mask % 2 == 0) { mask /= 2; ret++; } return ret; } private void show(LinkedList<Long> list) { int index = 0; for (long a : list) { if (index == 0) { p(a); } else { p(" " + a); } index++; } pln(); } class Point { int x; int y; int norm; public Point(int x, int y) { this.x = x; this.y = y; this.norm = x * x + y * y; } public int dist(Point other) { int dx = (x - other.x); int dy = (y - other.y); return dx * dx + dy * dy; } @Override public String toString() { return "Point [x=" + x + ", y=" + y + ", norm=" + norm + "]"; } } BufferedReader in; PrintWriter out; StringTokenizer strTok = new StringTokenizer(""); String nextToken() throws IOException { while (!strTok.hasMoreTokens()) strTok = new StringTokenizer(in.readLine()); return strTok.nextToken(); } int ni() throws IOException { return Integer.parseInt(nextToken()); } long nl() throws IOException { return Long.parseLong(nextToken()); } double nd() throws IOException { return Double.parseDouble(nextToken()); } int[] nia(int size) throws IOException { int[] ret = new int[size]; for (int i = 0; i < size; i++) ret[i] = ni(); return ret; } long[] nla(int size) throws IOException { long[] ret = new long[size]; for (int i = 0; i < size; i++) ret[i] = nl(); return ret; } double[] nda(int size) throws IOException { double[] ret = new double[size]; for (int i = 0; i < size; i++) ret[i] = nd(); return ret; } String nextLine() throws IOException { strTok = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!strTok.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; strTok = new StringTokenizer(s); } return false; } void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings("rawtypes") void printCollection(Collection collection) { boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } public void pln() { out.println(); } public void pln(int arg) { out.println(arg); } public void pln(long arg) { out.println(arg); } public void pln(double arg) { out.println(arg); } public void pln(String arg) { out.println(arg); } public void pln(boolean arg) { out.println(arg); } public void pln(char arg) { out.println(arg); } public void pln(float arg) { out.println(arg); } public void pln(Object arg) { out.println(arg); } public void p(int arg) { out.print(arg); } public void p(long arg) { out.print(arg); } public void p(double arg) { out.print(arg); } public void p(String arg) { out.print(arg); } public void p(boolean arg) { out.print(arg); } public void p(char arg) { out.print(arg); } public void p(float arg) { out.print(arg); } public void p(Object arg) { out.print(arg); } }
np
8_C. Looking for Order
CODEFORCES
import java.util.Scanner; import java.io.PrintWriter; import java.util.*; public class Order8C implements Runnable { private Scanner in = new Scanner(System.in); private PrintWriter out = new PrintWriter(System.out); int mintime; String path; int xs; int ys; int n; int[] obx; int[] oby; public static void main(String[] args) { new Thread(new Order8C()).start(); } private void read() { xs = in.nextInt(); ys = in.nextInt(); n = in.nextInt(); obx = new int[n]; oby = new int[n]; for(int i = 0; i<n; i++){ obx[i] = in.nextInt(); oby[i] = in.nextInt(); } } private void solve() { /* we will do dynamic programming over the subsets best[m] will be the shortest for binary digits of m being in. last[m] will be the last subset before m */ int[] ds = new int[n]; int[][] d = new int[n][n]; int[] best = new int[1 << n]; int[] last = new int[1 << n]; for(int i = 0; i<n; i++){ ds[i] = (obx[i]-xs)*(obx[i]-xs) + (oby[i]-ys)*(oby[i]-ys); for(int j = i+1; j<n; j++){ d[i][j] = (obx[i]-obx[j])*(obx[i]-obx[j]) + (oby[i]-oby[j])*(oby[i]-oby[j]); d[j][i] = (obx[i]-obx[j])*(obx[i]-obx[j]) + (oby[i]-oby[j])*(oby[i]-oby[j]); } } for(int i=0; i< (1<<n); i++){ //goes through subsets before supersets best[i] = 100000000; } best[0] = 0; for(int i=0; i< (1<<n); i++){ //goes through subsets before supersets /*if (i % 1000000 == 0 ){ System.out.println(i); }*/ for(int j = 0; j<n; j++){ if( ((1 << j) & i) != 0){ // if 2^j and i have bitwise sum nonzero if(best[i - (1<<j)] + 2*ds[j] < best[i]){ best[i] = best[i - (1<<j)] + 2*ds[j]; last[i] = i - (1<< j); } for(int k = j+1; k<n; k++){ if( ((1 << k) & i) != 0){ // if 2^k and i have bitwise sum nonzero if( (best[i-(1<<j) -(1<<k)] +ds[j]+ds[k]+d[j][k]) < best[i]){ best[i] = (best[i-(1<<j) -(1<<k)] +ds[j]+ds[k]+d[j][k]); last[i] = i -(1<<j) - (1<< k); } } } break; // break here because order doesn't really matter, just knowing which pairs to roup } } } int i = (1<<n) -1; mintime = best[i]; path = ""; while(i >0){ //System.out.println("Got to i = " + i + " and path is: " + path); path = path + "0 "; int dif = i-last[i]; // this has one or two 1s in binary for(int j=0; j<n; j++){ if( ((1<<j) & dif) != 0){ // if dif has a 1 in the j'th digit path = path + (j+1) + " "; } } i = last[i]; } path = path + "0"; } private void write() { out.println(mintime); out.println(path); } public void run() { read(); solve(); write(); out.close(); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Bag implements Runnable { private void solve() throws IOException { int xs = nextInt(); int ys = nextInt(); int n = nextInt(); int[] x = new int[n]; int[] y = new int[n]; for (int i = 0; i < n; ++i) { x[i] = nextInt(); y[i] = nextInt(); } int[][] pair = new int[n][n]; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]); int[] single = new int[n]; for (int i = 0; i < n; ++i) { single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys)); } int[] best = new int[1 << n]; int[] prev = new int[1 << n]; for (int set = 1; set < (1 << n); ++set) { int i; for (i = 0; i < n; ++i) if ((set & (1 << i)) != 0) break; best[set] = best[set ^ (1 << i)] + single[i]; prev[set] = i + 1; for (int j = i + 1; j < n; ++j) if ((set & (1 << j)) != 0) { int cur = best[set ^ (1 << i) ^ (1 << j)] + pair[i][j]; if (cur < best[set]) { best[set] = cur; prev[set] = (i + 1) * 100 + (j + 1); } } } writer.println(best[(1 << n) - 1]); int now = (1 << n) - 1; writer.print("0"); while (now > 0) { int what = prev[now]; int wa = what % 100 - 1; int wb = what / 100 - 1; if (wa >= 0) { writer.print(" "); writer.print(wa + 1); now ^= 1 << wa; } if (wb >= 0) { writer.print(" "); writer.print(wb + 1); now ^= 1 << wb; } writer.print(" "); writer.print("0"); } writer.println(); } public static void main(String[] args) { new Bag().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
np
8_C. Looking for Order
CODEFORCES
import java.util.Arrays; import java.util.Scanner; /** * @author vstepanov on 3/29/2017. */ public class Main { public static void main(String[] args) { try(Scanner in = new Scanner(System.in)) { int bx = in.nextInt(); int by = in.nextInt(); int n = in.nextInt(); int[][] xy = new int[n][2]; int[] res = new int[1 << n]; int[] last = new int[1 << n]; for (int i = 0; i < n; i++) { xy[i] = new int[]{in.nextInt(), in.nextInt()}; } int[] ds = new int[n]; for (int i = 0; i < ds.length; i++) { ds[i] = time(xy[i][0], xy[i][1], bx, by); } int[][] d = new int[n][n]; for (int i = 0; i < d.length; i++) { for (int j = 0; j < d.length; j++) { d[i][j] = time(xy[i][0], xy[i][1], xy[j][0], xy[j][1]); } } Arrays.fill(res, Integer.MAX_VALUE); res[0] = 0; for (int i = 0; i < (1 << n); i++) { for (int j = 0; j < n; j++) { if ((i & mask(j)) != 0) { if (res[i - mask(j)] + 2*ds[j] < res[i]) { res[i] = res[i - mask(j)] + 2*ds[j]; last[i] = i - mask(j); } for (int k = j + 1; k < n; k++) { if ((i & mask(k)) != 0) { if (res[i - mask(k) - mask(j)] + ds[j] + ds[k] + d[j][k] < res[i]) { res[i] = res[i - mask(k) - mask(j)] + ds[j] + ds[k] + d[j][k]; last[i] = i - mask(j) - mask(k); } } } break; } } } int cur = (1 << n) - 1; System.out.println(res[cur]); int k = cur; while (k != 0) { System.out.print("0 "); int diff = k - last[k]; for (int i = 0; i < n && diff != 0; i++) { if (((diff >> i) & 1) != 0) { System.out.print((i + 1) + " "); diff -= (1 << i); } } k = last[k]; } System.out.println("0"); } } static int mask(int i) { return 1 << i; } static int time(int x, int y, int x1, int y1) { return (x - x1)*(x - x1) + (y - y1)*(y - y1); } }
np
8_C. Looking for Order
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class C { public static void main(String[] args) { new C(); } final int oo = (int)1e9; int Hx,Hy; int N; int[][] P; int[] memo; int[][] soln; int[] dist1; int[][] dist2; C() { Scanner in = new Scanner(System.in); Hx=in.nextInt(); Hy=in.nextInt(); N=in.nextInt(); P=new int[N][2]; for (int i=0; i<N; ++i) { P[i][0]=in.nextInt(); P[i][1]=in.nextInt(); } memo=new int[1<<N]; Arrays.fill(memo, -1); soln=new int[2][1<<N]; dist1=new int[N]; Arrays.fill(dist1, -1); dist2=new int[N][N]; for (int[] d : dist2) Arrays.fill(d, -1); int res=go((1<<N)-1); System.out.println(res); int set=(1<<N)-1; while (set>0) { System.out.print("0 "); System.out.print((soln[0][set]+1)+" "); if (soln[1][set]>-1) System.out.print((soln[1][set]+1)+" "); if (soln[1][set]>-1) { set-=((1<<soln[0][set])+(1<<soln[1][set])); } else { set-=(1<<soln[0][set]); } } System.out.println("0"); } int go(int set) { if (set==0) return 0; if (memo[set]>-1) return memo[set]; int res=oo; int i=0; while (!on(set,i)) ++i; res=dist(i)+go(set-(1<<i)); soln[0][set]=i; soln[1][set]=-1; for (int j=i+1; j<N; ++j) { if (on(set,j)) { int tmp=dist(i,j)+go(set-(1<<i)-(1<<j)); if (tmp<res) { res=tmp; soln[0][set]=i; soln[1][set]=j; } } } return memo[set]=res; } // H->i->H int dist(int i) { if (dist1[i]>-1) return dist1[i]; int dx=P[i][0]-Hx; int dy=P[i][1]-Hy; return dist1[i]=2*(dx*dx+dy*dy); } // H->i->j->H int dist(int i, int j) { if (dist2[i][j]>-1) return dist2[i][j]; int res=0,dx,dy; dx=P[i][0]-Hx; dy=P[i][1]-Hy; res+=dx*dx+dy*dy; dx=P[i][0]-P[j][0]; dy=P[i][1]-P[j][1]; res+=dx*dx+dy*dy; dx=P[j][0]-Hx; dy=P[j][1]-Hy; res+=dx*dx+dy*dy; return dist2[i][j]=res; } boolean on(int set, int loc) { return (set&(1<<loc))>0; } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main implements Runnable { // //////////////////////////////////////////////////////////////////// // Solution private int n; private int nn; private int[][] D; private int[] dp; private int[] prev; private void solve() throws Throwable { int xs = nextInt(), ys = nextInt(); n = nextInt(); int[][] pts = new int[n][2]; for (int i = 0; i < n; i++) { pts[i][0] = nextInt(); pts[i][1] = nextInt(); } D = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { D[i][i] = 2 * (sqr(pts[i][0] - xs) + sqr(pts[i][1] - ys)); } else { D[i][j] = sqr(pts[i][0] - xs) + sqr(pts[i][1] - ys) + sqr(pts[i][0] - pts[j][0]) + sqr(pts[i][1] - pts[j][1]) + sqr(pts[j][0] - xs) + sqr(pts[j][1] - ys); } } } nn = 1 << n; dp = new int[nn]; prev = new int[nn]; Arrays.fill(dp, -1); Arrays.fill(prev, -1); dp[0] = 0; Dp(nn - 1); pw.println(dp[nn - 1]); pw.print(0); for (int p = nn - 1; p != -1 && prev[p] != -1; p = prev[p]) { int vv = p ^ prev[p]; for (int j = 0; j < n; j++) { int jj = 1 << j; if ((vv & jj) == 0) continue; pw.print(' '); pw.print(j + 1); } pw.print(" 0"); } pw.println(); } private int Dp(int i) { if (dp[i] != -1) return dp[i]; int ans = 107374182, p = -1; int j1 = 1, pos1 = 0; for (; pos1 < n && j1 < nn; j1 *= 2, pos1++) { if ((i & j1) == 0) continue; int a = D[pos1][pos1] + Dp(i ^ j1); if (a < ans) { ans = a; p = i ^ j1; } int j2 = j1 * 2, pos2 = pos1 + 1; for (; pos2 < n && j2 < nn; j2 *= 2, pos2++) { if ((i & j2) == 0) continue; a = D[pos1][pos2] + Dp(i ^ (j1 | j2)); if (a < ans) { ans = a; p = i ^ (j1 | j2); } } break; } dp[i] = ans; prev[i] = p; return ans; } private int sqr(int i) { return i * i; } // //////////////////////////////////////////////////////////////////// // Utility functions PrintWriter pw; BufferedReader in; StringTokenizer st; void initStreams() throws FileNotFoundException { //System.setIn(new FileInputStream("1")); in = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); } String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextString()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextString()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextString()); } static Throwable sError; public static void main(String[] args) throws Throwable { // Thread t = new Thread(null, new Main(), "1", 1 << 27); // t.start(); // t.join(); new Main().run(); if (sError instanceof OutOfMemoryError) { throw sError; } // if (sError != null) { // throw sError; // } } public void run() { try { initStreams(); solve(); } catch (Throwable e) { sError = e; } finally { if (pw != null) pw.close(); } } }
np
8_C. Looking for Order
CODEFORCES
import java.util.*; public class c8 { static int n; static int[] ds; static int[][] g; public static void main(String[] args) { Scanner input = new Scanner(System.in); int x = input.nextInt(), y = input.nextInt(); int n = input.nextInt(); int[] xs = new int[n], ys = new int[n]; for(int i = 0; i<n; i++) { xs[i] = input.nextInt(); ys[i] = input.nextInt(); } ds = new int[n]; g = new int[n][n]; for(int i = 0; i<n; i++) { ds[i] = (x - xs[i]) * (x - xs[i]) + (y - ys[i]) * (y - ys[i]); for(int j = 0; j<n; j++) { g[i][j] = (xs[i] - xs[j]) * (xs[i] - xs[j]) + (ys[i] - ys[j]) * (ys[i] - ys[j]); } } int[] dp = new int[1<<n]; Arrays.fill(dp, 987654321); dp[0] = 0; for(int i = 0; i<(1<<n); i++) { if(dp[i] == 987654321) continue; for(int a = 0; a<n; a++) { if((i & (1<<a)) > 0) continue; dp[i | (1<<a)] = Math.min(dp[i | (1<<a)], dp[i] + 2*ds[a]); for(int b = a+1; b<n; b++) { if((i & (1<<b)) > 0) continue; dp[i | (1<<a) | (1<<b)] = Math.min(dp[i | (1<<a) | (1<<b)], dp[i] + ds[a] + ds[b] + g[a][b]); } break; } } Stack<Integer> stk = new Stack<Integer>(); stk.add(0); int i = (1<<n) - 1; //System.out.println(Arrays.toString(dp)); trace: while(i > 0) { //System.out.println(i); for(int a = 0; a<n; a++) { if((i & (1<<a)) == 0) continue; if( dp[i] == dp[i - (1<<a)] + 2*ds[a]) { stk.add(a+1); stk.add(0); i -= (1<<a); continue trace; } for(int b = a+1; b<n; b++) { if((i & (1<<b)) == 0) continue; if(dp[i] == dp[i - (1<<a) - (1<<b)] + ds[a] + ds[b] + g[a][b]) { stk.add(a+1); stk.add(b+1); stk.add(0); i -= (1<<a) + (1<<b); continue trace; } } //break; } } System.out.println(dp[(1<<n) - 1]); while(!stk.isEmpty()) System.out.print(stk.pop()+" "); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.*; import java.util.*; public class A558 { static BufferedReader in = null; static PrintWriter out = null; static StringTokenizer st = new StringTokenizer(""); public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); } } public static String readString() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine(), " \n\r\t:"); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public static int readInt() { return Integer.parseInt(readString()); } public static long readLong() { return Long.parseLong(readString()); } private static int MAX_VALUE = Integer.MAX_VALUE - 10000000; private static int[] dp; private static int[] parents; private static int[] powers; private static int[] x; private static int[] y; private static int[][] dist; private static int[] distFrom0; private static void solve() throws IOException { int x0 = readInt(); int y0 = readInt(); int n = readInt(); long time = System.currentTimeMillis(); x = new int[n]; y = new int[n]; for (int i = 0; i < n; i++) { x[i] = readInt() - x0; y[i] = readInt() - y0; } dist = new int[n][n]; distFrom0 = new int[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dist[i][j] = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]); } } for (int i = 0; i < n; i++) { distFrom0[i] = x[i] * x[i] + y[i] * y[i]; } powers = new int[n + 1]; powers[0] = 1; for (int i = 1; i < n + 1; i++) { powers[i] = powers[i - 1] * 2; } int maxMask = 1 << n; dp = new int[maxMask]; parents = new int[maxMask]; Arrays.fill(dp, MAX_VALUE); dp[0] = 0; for (int i = 0; i < maxMask; i++) { if (dp[i] != MAX_VALUE) { int curMask = i; int notUsed = 0; for (int j = 0; j < n; j++) { if ((curMask & powers[j]) == 0) { notUsed = j; break; } } int mask = curMask | powers[notUsed]; for (int j = notUsed; j < n; j++) { if ((powers[j] & curMask) == 0 || j == notUsed) { int nextMask = mask | powers[j]; int minDist = dp[curMask] + distFrom0[notUsed] + dist[notUsed][j] + distFrom0[j]; if (dp[nextMask] > minDist) { dp[nextMask] = minDist; parents[nextMask] = curMask; } } } } } // System.err.println(((System.currentTimeMillis() - time))); // brute(n, 0) maxMask--; out.println(dp[maxMask]); while (maxMask != 0) { out.print("0 "); int[] diffBits = getBits(n, maxMask, parents[maxMask]); for (int i = 1; i <= diffBits[0]; i++) { out.print(diffBits[i] + 1 + " "); } maxMask = parents[maxMask]; } out.print(0); //System.err.println((System.currentTimeMillis() - time)); } private static boolean hasBit(int x, int index) { return (powers[index] & x) != 0; } private static int setBit(int x, int index) { return (x | powers[index]); } private static int getDist(int xFrom, int yFrom, int xTo, int yTo) { return (xTo - xFrom) * (xTo - xFrom) + (yTo - yFrom) * (yTo - yFrom); } private static int[] getBits(int n, int nextMask, int curMask) { int[] res = new int[3]; for (int i = 0; i < n; i++) { if (hasBit(nextMask, i) ^ hasBit(curMask, i)) { res[++res[0]] = i; } } return res; } private static void brute(int n, int mask) { List<Integer> listNotTaken = new ArrayList<>(); for (int i = 0; i < n; i++) { if (!hasBit(mask, i)) { listNotTaken.add(i); } } for (int first : listNotTaken) { int temp = setBit(mask, first); for (int second : listNotTaken) { int nextMask = setBit(temp, second); int minDist = dp[mask] + getDist(0, 0, x[first], y[first]) + getDist(x[first], y[first], x[second], y[second]) + getDist(x[second], y[second], 0, 0); if (dp[nextMask] > minDist) { dp[nextMask] = minDist; parents[nextMask] = mask; brute(n, nextMask); } } } } }
np
8_C. Looking for Order
CODEFORCES
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static int n, memo[], dS[], dd[][]; static int dp(int idx, int msk) { if(msk == (1 << n) - 1) return 0; if(memo[msk] != -1) return memo[msk]; while((msk & 1 << idx) != 0) ++idx; int ret = dS[idx] * 2 + dp(idx + 1, msk | 1 << idx); for(int i = 0; i < n; ++i) if((msk & 1 << i) == 0) ret = Math.min(ret, dS[i] + dS[idx] + dd[i][idx] + dp(idx + 1, msk | 1 << i | 1 << idx)); return memo[msk] = ret; } static StringBuilder sb = new StringBuilder("0 "); static void print(int idx, int msk) { if(msk == (1 << n) - 1) return; int opt = dp(idx, msk); while((msk & 1 << idx) != 0) ++idx; if(dS[idx] * 2 + dp(idx + 1, msk | 1 << idx) == opt) { sb.append((idx + 1) + " 0 "); print(idx + 1, msk | 1 << idx); return; } for(int i = 0; i < n; ++i) if((msk & 1 << i) == 0) if(opt == dS[i] + dS[idx] + dd[i][idx] + dp(idx + 1, msk | 1 << i | 1 << idx)) { sb.append((idx + 1) + " " + (i + 1) + " 0 "); print(idx + 1, msk | 1 << i | 1 << idx); return; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); Point s = new Point(sc.nextInt(), sc.nextInt()); n = sc.nextInt(); Point[] a = new Point[n]; for(int i = 0; i < n; ++i) a[i] = new Point(sc.nextInt(), sc.nextInt()); dS = new int[n]; dd = new int[n][n]; for(int i = 0; i < n; ++i) { dS[i] = dist2(s, a[i]); for(int j = 0; j < n; ++j) dd[i][j] = dist2(a[i], a[j]); } memo = new int[1 << n]; Arrays.fill(memo, -1); out.println(dp(0, 0)); print(0, 0); out.println(sb); out.flush(); out.close(); } static int dist2(Point a, Point b) { return sq(a.x - b.x) + sq(a.y - b.y); } static int sq(int x) { return x * x; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main implements Runnable { // //////////////////////////////////////////////////// // Solution private int n; private int nn; private int[][] D; private int[] dp; private int[] prev; private void solve() throws Throwable { int xs = nextInt(), ys = nextInt(); n = nextInt(); int[][] pts = new int[n][2]; for (int i = 0; i < n; i++) { pts[i][0] = nextInt(); pts[i][1] = nextInt(); } D = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { D[i][i] = 2 * (sqr(pts[i][0] - xs) + sqr(pts[i][1] - ys)); } else { D[i][j] = sqr(pts[i][0] - xs) + sqr(pts[i][1] - ys) + sqr(pts[i][0] - pts[j][0]) + sqr(pts[i][1] - pts[j][1]) + sqr(pts[j][0] - xs) + sqr(pts[j][1] - ys); } } } nn = 1 << n; dp = new int[nn]; prev = new int[nn]; Arrays.fill(dp, -1); Arrays.fill(prev, -1); dp[0] = 0; Dp(nn - 1); pw.println(dp[nn - 1]); pw.print(0); for (int p = nn - 1; p != -1 && prev[p] != -1; p = prev[p]) { int vv = p ^ prev[p]; for (int j = 0; j < n; j++) { int jj = 1 << j; if ((vv & jj) == 0) continue; pw.print(' '); pw.print(j + 1); } pw.print(" 0"); } pw.println(); } private int Dp(int i) { if (dp[i] != -1) return dp[i]; int ans = 107374182, p = -1; int j1 = 1, pos1 = 0; for (; pos1 < n && j1 < nn; j1 *= 2, pos1++) { if ((i & j1) == 0) continue; int a = D[pos1][pos1] + Dp(i ^ j1); if (a < ans) { ans = a; p = i ^ j1; } int j2 = j1 * 2, pos2 = pos1 + 1; for (; pos2 < n && j2 < nn; j2 *= 2, pos2++) { if ((i & j2) == 0) continue; a = D[pos1][pos2] + Dp(i ^ (j1 | j2)); if (a < ans) { ans = a; p = i ^ (j1 | j2); } } break; } dp[i] = ans; prev[i] = p; return ans; } private int sqr(int i) { return i * i; } // //////////////////////////////////////////////////// // Utility functions private void initstreams() throws Throwable { //System.setIn(new FileInputStream("1")); in = new BufferedReader(new InputStreamReader(System.in, "ISO-8859-1")); pw = new PrintWriter(System.out); } BufferedReader in; PrintWriter pw; StringTokenizer st; String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextString()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextString()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextString()); } @Override public void run() { try { initstreams(); solve(); } catch (Throwable e) { sError = e; } finally { if (pw != null) pw.close(); } } private static Throwable sError; public static void main(String[] args) throws Throwable { Thread t = new Thread(new Main()); t.start(); t.join(); if (sError != null) throw sError; } }
np
8_C. Looking for Order
CODEFORCES
import java.util.*; public class C { public static void main(String[] args) { new C(new Scanner(System.in)); } vect[] vs; int N; int oo = 987654321; ArrayList<choice> cs; choice[][] cg; int MF; int[] memo; int[] next; int go(int m) { if (m == MF) return 0; if (memo[m] != -1) return memo[m]; // Try a new place int res = oo; int nxt = -1; int i=0; for (i=0; i<N; i++) { if (((1<<i)&m) == 0) break; } for (int j=0; j<N; j++) { choice cc = cg[i][j]; if ((m&cc.m) > 0) continue; int r2 = cc.cost+go(m|cc.m); if (r2 < res) { res = r2; nxt = cc.index; } } memo[m] = res; next[m] = nxt; return res; } public C(Scanner in) { vect vt = new vect(in.nextInt(), in.nextInt()); N = in.nextInt(); vs = new vect[N+1]; vs[N] = vt; for (int i=0; i<N; i++) vs[i] = new vect(in.nextInt(), in.nextInt()); // Precompute all choices and masks cs = new ArrayList<choice>(); cg = new choice[N][N]; for (int i=0; i<N; i++) { choice cc = new choice(cs.size(), 2*vs[i].dist(vt), 1<<i); cc.add(i); cs.add(cc); cg[i][i] = cc; } for (int i=0; i<N; i++) { for (int j=i+1; j<N; j++) { int dist = vs[i].dist(vt); dist += vs[i].dist(vs[j]); dist += vs[j].dist(vt); choice cc = new choice(cs.size(), dist, (1<<i)|(1<<j)); cc.add(i); cc.add(j); cs.add(cc); cg[i][j] = cc; cg[j][i] = cc; } } MF = (1<<N)-1; next = new int[MF+1]; memo = new int[MF+1]; Arrays.fill(next, -1); Arrays.fill(memo, -1); int res = go(0); System.out.println(res); int m = 0; StringBuilder sb = new StringBuilder(); while (m != -1) { //System.out.println(Integer.toBinaryString(m)); sb.append(0); sb.append(' '); int i = next[m]; if (i == -1) break; choice cc = cs.get(i); for (int j : cc.iv) { sb.append(f(j)); sb.append(' '); } m = m|cc.m; } System.out.println(sb.toString().trim()); } int f(int i) { if (i == N) return 0; return i+1; } } class choice { int cost; int m; int index; ArrayList<Integer> iv; public choice(int ii, int c, int mm) { index = ii; cost = c; m = mm; iv = new ArrayList<Integer>(2); } void add(int i) { iv.add(i); } } class vect { int x, y; public vect(int i, int j) { x=i; y=j; } int dist(vect rhs) { int xx = x-rhs.x; int yy = y-rhs.y; return xx*xx+yy*yy; } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; /** * Created by Brandt Henslee on 2/24/2015. */ public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] parsedString; int objectNum = 0; int xStart=0; int yStart=0; parsedString = in.readLine().split(" "); xStart = Integer.parseInt(parsedString[0]); yStart = Integer.parseInt(parsedString[1]); objectNum = Integer.parseInt(in.readLine()); int[] xLocs = new int[objectNum+1]; int[] yLocs = new int[objectNum+1]; int[] bitMasks = new int[1<<objectNum]; Arrays.fill(bitMasks, -1); int[] previous = new int[1<<objectNum]; xLocs[objectNum]=xStart; yLocs[objectNum]=yStart; for(int i=0; i<objectNum; i++){ parsedString = in.readLine().split(" "); xLocs[i] = Integer.parseInt(parsedString[0]); yLocs[i] = Integer.parseInt(parsedString[1]); } //go through all pairs and find time requirement for each pair of objects //the entry at point [i][j] is equal to the time it takes to get from point i to point j int[][] times = new int[objectNum+1][objectNum+1]; for(int i=0;i<=objectNum;i++){ for(int j=0; j<=objectNum;j++){ times[i][j] = times[j][i] = (xLocs[i]-xLocs[j])*(xLocs[i]-xLocs[j])+(yLocs[i]-yLocs[j])*(yLocs[i]-yLocs[j]); } } //each value in bitmasks represents the minimum time necessary to get //the unmasked bits //so bitmasks[5] (5=101) is the fastest time in which you can get //items 1 and 3 bitMasks[0] = 0; //collecting zero objects takes 0 time //1<<n makes the n+1 position in the bit string = 1 //1<<2 = 100 for (int i=0; i<(1<<objectNum); i++){ if(bitMasks[i]==-1) { }else{ for(int j=0; j<objectNum; j++){ if(((1<<j)&i) == 0){ //if our current j object hasn't been picked up yet int curState = (1<<j) | i; //ith state after picking up j object int curTime = bitMasks[i] + 2*times[objectNum][j]; //time required to get object j from bag at state i if(bitMasks[curState] == -1 || curTime < bitMasks[curState]){ bitMasks[curState] = curTime; //put fastest time in for gettingto our current state previous[curState] = i; } for(int k=0; k<objectNum; k++){ if(((1<<k) & curState) == 0){ //if the kth position in our current state hasn't been picked up int kState = ((1<<k) | curState); //curstate after picking pu kth object //kTime is time it takes to go from bag, to j, to k and back int kTime = bitMasks[i] + times[objectNum][j] + times[j][k] + times[k][objectNum]; if(bitMasks[kState] == -1 || kTime < bitMasks[kState]){ bitMasks[kState] = kTime; //put shortest tiem in for getting to kState previous[kState] = i; } } } break; } } } } int finalState = (1<<objectNum)-1; System.out.println(bitMasks[finalState]); Deque<Integer> outputQ = new ArrayDeque<Integer>(); outputQ.add(0); int curState = finalState; while(curState>0){ //1100 ^ 1101 = 0001 //difference is the objects picked up in this state but not in previous state int difference = curState ^ previous[curState]; int firstItem = -1; int secondItem = -1; for(int i=0; i<objectNum; i++){ if(((1<<i)&difference)>0){ //if the ith object was picked up in this state secondItem=firstItem; //keep track of how many items are picked up firstItem=i; } } if(secondItem!=-1){ //put in two items followed by a return to 0 outputQ.add(firstItem+1); outputQ.add(secondItem+1); outputQ.add(0); } else{ outputQ.add(firstItem + 1); outputQ.add(0); } curState = previous[curState]; } System.out.print(outputQ.removeLast()); while(!outputQ.isEmpty()){ System.out.print(" "); System.out.print(outputQ.removeLast()); } } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class Handbag { // http://codeforces.com/problemset/problem/8/C // Source of most code : http://codeforces.com/contest/8/submission/3492661 // Keep track of each item location and also be able to // calculate distance between it and another object public static class Item{ int x; int y; Item(int x, int y){ this.x = x; this.y = y; } // Return distance between two points public int dist(Item i){ int dx = x - i.x; int dy = y - i.y; return dx*dx + dy*dy; } } // Each value in bits[] is the min time to get certain objects // Ex. bits[6] = 110 is the fastest time to get items that correspond with the '1s' public static int solve(int bitNum){ if(bitNum == (1 << N) - 1) // If bitNum is too big for the array return 0; if(bits[bitNum] != -1) // If bit value has already been calculated return bits[bitNum]; int ans = Integer.MAX_VALUE; int j = 0; for(int i = 1; i < N; i++){ if((bitNum & (1 << i)) == 0){ // Performs bitwise AND operation to see if bitNum and i have no bits in common if(j == 0){ // Only happens on the first time in IF statement // One item that can be picked up before returning to handbag ans = 2 * items[0].dist(items[i]) + solve(bitNum | (1 << i)); // Performs bitwise exclusive OR operation j = i; // Change value so this case isn't ever hit again && to store value to use in else statement dists } else{ // Find the distance between the handbag and the first item int dist1 = items[0].dist(items[i]); // Find the distance between the first item and the second item int dist2 = items[i].dist(items[j]); // Find the distance between the second item and the handbag int dist3 = items[j].dist(items[0]); // Two items that can be picked up before returning to handbag // distance covered between any two objects in the time equal // to the squared length of the segment between the points of the objects ans = Math.min(ans, dist1 + dist2 + dist3 + solve(bitNum | (1 << i) | (1 << j))); // Performs bitwise exclusive OR operation } } } return bits[bitNum] = ans; // Store all values in bits[] to speed up solve and for use in printOptPath } static void printOptPath(int bitNum) { if (bitNum == (1 << N) - 1) return; // Almost identical to solve equation except it doesn't calculate the answer, it checks the stored answer in bits int j = 0; for (int i = 1; i < N; i++) if ((bitNum & (1 << i)) == 0) { if (j == 0) { j = i; // Change value so this case isn't ever hit again && to find distance to this specific item in else if statement if (bits[bitNum] == 2 * items[0].dist(items[i]) + solve(bitNum | (1 << i))) { // solve() should quickly return an answer because the bits[] has already been calculated pw.print(" " + i + " 0"); // One item that can be picked up before returning to handbag printOptPath(bitNum | (1 << i)); // Recursively call print with new bitNum return; } } else if (bits[bitNum] == items[0].dist(items[i]) + items[i].dist(items[j]) + items[j].dist(items[0]) + solve(bitNum | (1 << i) | (1 << j))) { pw.print(" " + j + " " + i + " 0"); // Two items that can be picked up before returning to handbag printOptPath(bitNum | (1 << i) | (1 << j)); // Recursively call print with new bitNum return; } } } private static int N = 0; private static Item[] items; private static int[] bits; // PrintWriter needs to be class member because of recursive print strategy private static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] input = br.readLine().split(" "); Item handbag = new Item(Integer.parseInt(input[0]), Integer.parseInt(input[1])); N = Integer.parseInt(br.readLine()) + 1; items = new Item[N]; for(int n = 1; n < N; n++){ input = br.readLine().split(" "); items[n] = new Item(Integer.parseInt(input[0]), Integer.parseInt(input[1])); } items[0] = handbag; // x << n is a right shift operator // which will remove the last n bits from x // Ex 1 << 2 => 4 bits = new int[1 << N]; // Ex: 1 << 3 = 8; 1 << 5 = 64 Arrays.fill(bits, -1); // Init bits array to hold -1 values int ans = solve(1 << 0); // Start solving with bit #1 pw.println(ans); // Min time needed to put items in handbag pw.print("0"); // Init output with handbag location printOptPath(1 << 0); // Print possible optimum path to pick up items pw.close(); } }
np
8_C. Looking for Order
CODEFORCES
//package round8; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; public class C { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int x = ni(), y = ni(); int n = ni(); int[][] co = new int[n][]; for(int i = 0;i < n;i++){ co[i] = new int[]{ni()-x, ni()-y}; } int[] c1 = new int[n]; int[][] c2 = new int[n][n]; for(int i = 0;i < n;i++){ c1[i] = (co[i][0]*co[i][0]+co[i][1]*co[i][1])*2; } for(int i = 0;i < n;i++){ for(int j = i+1;j < n;j++){ c2[i][j] = c2[j][i] = (co[i][0]*co[i][0]+co[i][1]*co[i][1])+(co[j][0]*co[j][0]+co[j][1]*co[j][1])+(co[j][0]-co[i][0])*(co[j][0]-co[i][0])+(co[j][1]-co[i][1])*(co[j][1]-co[i][1]); } } int[] dp = new int[1<<n]; int[] prev = new int[1<<n]; prev[0] = -1; for(int i = 1;i < 1<<n;i++){ int a = Integer.numberOfTrailingZeros(i); dp[i] = c1[a] + dp[i^1<<a]; prev[i] = 1<<a; for(int j = a+1;j < n;j++){ if(i<<31-j<0){ int v = dp[i^1<<a^1<<j] + c2[a][j]; if(v < dp[i]){ dp[i] = v; prev[i] = 1<<a^1<<j; } } } } out.println(dp[(1<<n)-1]); int cur = (1<<n)-1; out.print("0"); while(true){ int targ; if(prev[cur] == -1){ targ = cur; }else{ targ = prev[cur]; cur ^= prev[cur]; } int a = Integer.numberOfTrailingZeros(targ); int b = Integer.numberOfTrailingZeros(targ&targ-1); if(targ == 1<<a){ out.print(" " + (a+1)); }else{ out.print(" " + (a+1)); out.print(" " + (b+1)); } out.print(" 0"); if(cur == 0)break; } out.println(); } void run() throws Exception { // int n = 24, m = 99999; // Random gen = new Random(); // StringBuilder sb = new StringBuilder(); // sb.append(0 + " " + 0 + " " + n + " "); // for(int i = 0;i < n;i++){ // sb.append(gen.nextInt(100) + " "); // sb.append(gen.nextInt(100) + " "); // } // 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 C().run(); } public int ni() { try { int num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public long nl() { try { long num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public String ns() { try{ int b = 0; StringBuilder sb = new StringBuilder(); while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' ')); if(b == -1)return ""; sb.append((char)b); while(true){ b = is.read(); if(b == -1)return sb.toString(); if(b == '\r' || b == '\n' || b == ' ')return sb.toString(); sb.append((char)b); } } catch (IOException e) { } return ""; } public char[] ns(int n) { char[] buf = new char[n]; try{ int b = 0, p = 0; while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n')); if(b == -1)return null; buf[p++] = (char)b; while(p < n){ b = is.read(); if(b == -1 || b == ' ' || b == '\r' || b == '\n')break; buf[p++] = (char)b; } return Arrays.copyOf(buf, p); } catch (IOException e) { } return null; } double nd() { return Double.parseDouble(ns()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class C { public static void main(String[] args) { new C().run(); } class FastScanner { BufferedReader br; StringTokenizer st; boolean eof; String buf; public FastScanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); nextToken(); } public FastScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); nextToken(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; break; } } String ret = buf; buf = eof ? "-1" : st.nextToken(); return ret; } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } void close() { try { br.close(); } catch (Exception e) { } } boolean isEOF() { return eof; } } FastScanner sc; PrintWriter out; public void run() { Locale.setDefault(Locale.US); try { sc = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); sc.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } long nextLong() { return sc.nextLong(); } double nextDouble() { return sc.nextDouble(); } int nextInt() { return sc.nextInt(); } String nextToken() { return sc.nextToken(); } static class Point { int x, y; public Point(int x, int y) { super(); this.x = x; this.y = y; } int dist(Point p) { return (x - p.x) * (x - p.x) + (y - p.y) * (y - p.y); } } void solve() { Point p0 = new Point(nextInt(), nextInt()); int n = nextInt(); Point[] p = new Point[n]; for (int i = 0; i < n; i++) { p[i] = new Point(nextInt(), nextInt()); } int[][] d = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { d[i][j] = p[i].dist(p[j]); } } int[] d0 = new int[n]; for (int i = 0; i < n; i++) { d0[i] = p0.dist(p[i]); } int[] dp = new int[1 << n]; Arrays.fill(dp, 1 << 30); dp[0] = 0; int[] from = new int[1 << n]; for (int i = 0; i + 1 < 1 << n; i++) { int j = Integer.numberOfTrailingZeros(Integer.lowestOneBit(~i)); int cnt = dp[i] + 2 * d0[j]; if (dp[i ^ (1 << j)] > cnt) { dp[i ^ (1 << j)] = cnt; from[i ^ (1 << j)] = i; } for (int k = j + 1; k < n; k++) { if (((i >> k) & 1) == 0) { cnt = dp[i] + d0[j] + d0[k] + d[j][k]; if (dp[i ^ (1 << j) ^ (1 << k)] > cnt) { dp[i ^ (1 << j) ^ (1 << k)] = cnt; from[i ^ (1 << j) ^ (1 << k)] = i; } } } } ArrayList<Integer> ans = new ArrayList<Integer>(); ans.add(0); int mask = (1 << n) - 1; while (mask > 0) { int xor = mask ^ from[mask]; while (xor > 0) { ans.add(Integer .numberOfTrailingZeros(Integer.lowestOneBit(xor)) + 1); xor = xor & (xor - 1); } ans.add(0); mask = from[mask]; } out.println(dp[(1 << n) - 1]); for (int i : ans) { out.print(i + " "); } } }
np
8_C. Looking for Order
CODEFORCES
import java.io.*; import static java.lang.Math.*; import java.util.*; import java.util.function.*; import java.lang.*; public class Main { final static boolean debug = false; final static String fileName = ""; final static boolean useFiles = false; public static void main(String[] args) throws FileNotFoundException { long start; if (debug) start = System.nanoTime(); InputStream inputStream; OutputStream outputStream; if (useFiles) { inputStream = new FileInputStream(fileName + ".in"); outputStream = new FileOutputStream(fileName + ".out"); } else { inputStream = System.in; outputStream = System.out; } InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(in, out); solver.solve(); if(debug) out.println((System.nanoTime() - start) / 1e+9); out.close(); } } class Task { int[][] dist, pre; int[] x, y, d, prev; String[] leafDescription; String[] linerDescription; String[][] allDescriptions; int xs, ys, n; int dist(int i, int j) { return (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]); } void go(int[] prev, String[] leafDescription, int[] d, int len, int add, String description){ for (int mask = 0; mask < d.length; mask++) { if ((mask & add) != add) continue; int newValue = d[mask & (~add)] + len; if (d[mask] > newValue){ d[mask] = newValue; leafDescription[mask] = description; prev[mask] = mask & (~add); } } } int rec(int mask) { if (d[mask] != -1) return d[mask]; int lowest = 0; for (; ((1 << lowest) & mask) == 0; lowest++) ; int newMask = mask & (~(1 << lowest)); d[mask] = rec(newMask) + dist[lowest][n]; prev[mask] = newMask; leafDescription[mask] = linerDescription[lowest]; for (int bit = lowest + 1; bit < n; bit++) { if (((1 << bit) & mask) > 0) { newMask = mask & (~(1 << bit)) & (~(1 << lowest)); int newValue = rec(newMask) + pre[bit][lowest]; if (newValue < d[mask]) { d[mask] = newValue; prev[mask] = newMask; leafDescription[mask] = allDescriptions[lowest][bit]; } } } return d[mask]; } public void solve() { final int inf = (int) 1e+9; xs = in.nextInt(); ys = in.nextInt(); n = in.nextInt(); x = new int[n + 1]; y = new int[n + 1]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); } x[n] = xs; y[n] = ys; allDescriptions = new String[n][n]; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ allDescriptions[i][j] = (i + 1) + " " + (j + 1) + " "; } } linerDescription = new String[n]; for (int i = 0; i < n; i++){ linerDescription[i] = (i + 1) + " "; } dist = new int[n + 1][n + 1]; pre = new int[n + 1][n + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) { dist[i][j] = 2 * dist(i, j); pre[i][j] = dist(i, n) + dist(i, j) + dist(j, n); } } d = new int[1 << n]; Arrays.fill(d, -1); d[0] = 0; prev = new int[1 << n]; leafDescription = new String[1 << n]; // Arrays.fill(d, inf); // prev[0] = 0; // d[0] = 0; // for (int i = 0; i < n; i++) { // int add = 1 << i; // int len = 2 * dist[n][i]; // String description = (i + 1) + " "; // // go(prev, leafDescription, d, len, add, description); // } // for (int i = 0; i < n; i++) { // for (int j = i + 1; j < n; j++) { // int add = (1 << i) | (1 << j); // int len = dist[n][i] + dist[i][j] + dist[n][j]; // String description = (i + 1) + " " + (j + 1) + " "; // // go(prev, leafDescription, d, len, add, description); // } // } // Debug.printObjects(out, d); // Debug.printObjects(out, prev); // Debug.printObjects(out, leafDescription); int result = rec((1 << n) - 1); String answer = ""; for (int curr = d.length - 1; prev[curr] != curr; curr = prev[curr] ){ answer += "0 " + leafDescription[curr]; } answer += "0"; out.println(result); out.println(answer); } private InputReader in; private PrintWriter out; Task(InputReader in, PrintWriter out) { this.in = in; this.out = out; } } 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 double nextDouble(){ return Double.parseDouble(next()); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public byte nextByte(){ return Byte.parseByte(next()); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.*; public class CF8C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int si = s.indexOf(' ', 0); int x = Integer.parseInt(s.substring(0, si)); int y = Integer.parseInt(s.substring(si + 1)); int n = Integer.parseInt(br.readLine()); int[] xx = new int[n + 1]; int[] yy = new int[n + 1]; for (int i = 0; i < n; i++) { s = br.readLine(); si = s.indexOf(' ', 0); xx[i] = Integer.parseInt(s.substring(0, si)); yy[i] = Integer.parseInt(s.substring(si + 1)); } xx[n] = x; yy[n] = y; int[][] dd = new int[n + 1][n + 1]; for (int i = 0; i <= n; i++) for (int j = i + 1; j <= n; j++) { int dx = xx[i] - xx[j]; int dy = yy[i] - yy[j]; dd[i][j] = dx * dx + dy * dy; } int[] aa = new int[1 << n]; int[] bb = new int[1 << n]; for (int k = 1; k < 1 << n; k++) { int a = -1; for (int b = 0; b < n; b++) if ((k & 1 << b) > 0) { a = b; break; } int l = k ^ 1 << a; int d = dd[a][n] + dd[a][n]; aa[k] = aa[l] + d; bb[k] = l; for (int b = a + 1; b < n; b++) if ((k & 1 << b) > 0) { l = k ^ 1 << a ^ 1 << b; d = dd[a][n] + dd[b][n] + dd[a][b]; if (aa[l] + d < aa[k]) { aa[k] = aa[l] + d; bb[k] = l; } } } int k = (1 << n) - 1; System.out.println(aa[k]); StringBuilder sb = new StringBuilder(); sb.append(0); while (k != 0) { int l = bb[k]; int m = k ^ l; for (int b = 0; b < n; b++) if ((m & 1 << b) > 0) sb.append(' ').append(b + 1); sb.append(' ').append(0); k = l; } System.out.println(sb); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Bag implements Runnable { private void solve() throws IOException { int xs = nextInt(); int ys = nextInt(); int n = nextInt(); int[] x = new int[n]; int[] y = new int[n]; for (int i = 0; i < n; ++i) { x[i] = nextInt(); y[i] = nextInt(); } final int[][] pair = new int[n][n]; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]); final int[] single = new int[n]; for (int i = 0; i < n; ++i) { single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys)); } final int[] best = new int[1 << n]; final int[] prev = new int[1 << n]; for (int set = 1; set < (1 << n); ++set) { int i; for (i = 0; i < n; ++i) if ((set & (1 << i)) != 0) break; int bestC = best[set ^ (1 << i)] + single[i]; int prevC = 1 << i; int nextSet = set ^ (1 << i); int unoI = 1 << i; for (int j = i + 1, unoJ = 1 << (i + 1); j < n; ++j, unoJ <<= 1) if ((set & unoJ) != 0) { int cur = best[nextSet ^ unoJ] + pair[i][j]; if (cur < bestC) { bestC = cur; prevC = unoI | unoJ; } } best[set] = bestC; prev[set] = prevC; } writer.println(best[(1 << n) - 1]); int now = (1 << n) - 1; writer.print("0"); while (now > 0) { int differents = prev[now]; for(int i = 0; i < n; i++) if((differents & (1 << i)) != 0) { writer.print(" "); writer.print(i + 1); now ^= 1 << i; } writer.print(" "); writer.print("0"); } writer.println(); } public static void main(String[] args) { new Bag().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
np
8_C. Looking for Order
CODEFORCES
import java.util.Scanner; public class Problem_8C { private static int dis(int x1, int y1, int x2, int y2) { return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int ox = sc.nextInt(); int oy = sc.nextInt(); int n = sc.nextInt(); int[] ix = new int[n]; int[] iy = new int[n]; int[] single = new int[n]; int[][] pair = new int[n][n]; for (int i = 0; i < n; i++) { ix[i] = sc.nextInt(); iy[i] = sc.nextInt(); single[i] = dis(ox, oy, ix[i], iy[i]) * 2; for (int j = 0; j < i; j++) { pair[i][j] = pair[j][i] = dis(ix[i], iy[i], ix[j], iy[j]) + (single[i] + single[j]) / 2; } } int[] min = new int[1 << n]; int[] pre = new int[1 << n]; for (int set = 1; set < 1 << n; set++) { int i; for (i = 0; i < n; i++) { if ((set & (1 << i)) != 0) { break; } } min[set] = min[set ^ (1 << i)] + single[i]; pre[set] = set ^ (1 << i); for (int j = 0; j < n; j++) { if ((set & (1 << j)) == 0) { continue; } if (min[set] > min[set ^ (1 << i) ^ (1 << j)] + pair[i][j]) { min[set] = min[set ^ (1 << i) ^ (1 << j)] + pair[i][j]; pre[set] = set ^ (1 << i) ^ (1 << j); } } } System.out.println(min[(1 << n) - 1]); for (int set = (1 << n) - 1; set != 0; set = pre[set]) { System.out.print("0 "); for (int i = 0; i < n; i++) { if (((set ^ pre[set]) & (1 << i)) != 0) { System.out.print((i + 1) + " "); } } } System.out.println("0"); sc.close(); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Bag implements Runnable { private void solve() throws IOException { int xs = nextInt(); int ys = nextInt(); int n = nextInt(); int[] x = new int[n]; int[] y = new int[n]; for (int i = 0; i < n; ++i) { x[i] = nextInt(); y[i] = nextInt(); } int[][] pair = new int[n][n]; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]); int[] single = new int[n]; for (int i = 0; i < n; ++i) { single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys)); } int[] best = new int[1 << n]; int[] prev = new int[1 << n]; for (int set = 1; set < (1 << n); ++set) { int i; for (i = 0; i < n; ++i) if ((set & (1 << i)) != 0) break; best[set] = best[set ^ (1 << i)] + single[i]; prev[set] = 1 << i; for (int j = i + 1; j < n; ++j) if ((set & (1 << j)) != 0) { int cur = best[set ^ (1 << i) ^ (1 << j)] + pair[i][j]; if (cur < best[set]) { best[set] = cur; prev[set] = (1 << i) | (1 << j); } } } writer.println(best[(1 << n) - 1]); int now = (1 << n) - 1; writer.print("0"); while (now > 0) { int differents = prev[now]; for(int i = 0; i < n; i++) if((differents & (1 << i)) != 0) { writer.print(" "); writer.print(i + 1); now ^= 1 << i; } writer.print(" "); writer.print("0"); } writer.println(); } public static void main(String[] args) { new Bag().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class LookingForOrder { static int[] dp = new int[(int) (1 << 24)]; static int[][] points; static int[] sol = new int[1<<24]; static int sx = 0, sy = 0; public static void main(String[] args) { sx = in.nextInt(); sy = in.nextInt(); Arrays.fill(dp, -2); int n = in.nextInt(); points = new int[n][3]; for (int i = 0; i < n; i++) { points[i][0] = in.nextInt(); points[i][1] = in.nextInt(); points[i][2] = (sx - points[i][0]) * (sx - points[i][0]) + (sy - points[i][1]) * (sy - points[i][1]); } //System.out.println("ANS"); System.out.println(solve(0)); int mask=0; while(true){ System.out.print(0+" "); if (mask==(1<<n)-1) break; int x = sol[mask]; int count=0; for(int i=0; i<n; i++){ if ((x&(1<<i))!=0) { count++; System.out.print((i+1)+" "); mask|=(1<<i); } if (count==2) break; } } System.out.println(); } public static int solve(int mask) { if (dp[mask]!=-2) return dp[mask]; int n = points.length; if (mask == ((1 << n)-1)) { return dp[mask]=0; } int here = -1; for (int i = 0; i < n; i++) { if ((mask & (1<<i)) == 0) { here = i; break; } } int ans = 2*points[here][2]+solve(mask | (1 << here)); sol[mask] = 1<<here; int x1 = points[here][0]; int y1 = points[here][1]; for (int i = here + 1; i < n; i++) { if ((mask & (1 << i)) == 0) { int x2 = points[i][0]; int y2 = points[i][1]; int p = mask|(1<<here); p = p|(1<<i); if (ans>points[here][2] + points[i][2] + (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + solve(p)){ ans=points[here][2] + points[i][2] + (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + solve(p); sol[mask]=(1<<here)|(1<<i); } } } return dp[mask]=ans; } 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; } } static MyScanner in = new MyScanner(); }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CodeD { static class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } public String next() { while(!st.hasMoreTokens()) { String l = nextLine(); if(l == null) return null; st = new StringTokenizer(l); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public void sortIntArray(int[] array) { Integer[] vals = new Integer[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortLongArray(long[] array) { Long[] vals = new Long[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortDoubleArray(double[] array) { Double[] vals = new Double[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } } static final Scanner sc; static final int n; static final int[][] distancias; static final int[] distancia; static final int[] dp; static final int[] dpNext; static final int X; static final int Y; static { sc = new Scanner(); X = sc.nextInt(); Y = sc.nextInt(); n = sc.nextInt(); distancias = new int[n][n]; distancia = new int[n]; dp = new int[1 << n]; Arrays.fill(dp, -1); dpNext = new int[1 << n]; } static int dp(int mascara) { if(dp[mascara] != -1) return dp[mascara]; int highest = -1; for(int i = 0, tmp = mascara; tmp != 0; i++, tmp >>= 1) { if((tmp & 1) == 1) { highest = i; break; } } if(highest == -1) return 0; int nextMsc = mascara ^ (1 << highest); int costHighest = distancia[highest]; int best = (costHighest << 1) + dp(nextMsc); int bestNext = nextMsc; for(int i = 0, tmp = nextMsc, iC = 1; tmp != 0; i++, tmp >>= 1, iC <<= 1) { if((tmp & 1) == 1) { int msc = nextMsc ^ iC; int possibleA = costHighest + distancias[highest][i] + distancia[i] + dp(msc); if(possibleA < best) { best = possibleA; bestNext = msc; } } } dpNext[mascara] = bestNext; return dp[mascara] = best; } public static void main(String[] args) { int[][] objetos = new int[n][2]; for(int i = 0; i < n; i++) { objetos[i][0] = sc.nextInt(); objetos[i][1] = sc.nextInt(); distancia[i] = (X - objetos[i][0]) * (X - objetos[i][0]) + (Y - objetos[i][1]) * (Y - objetos[i][1]); } for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) distancias[i][j] = (objetos[i][0] - objetos[j][0]) * (objetos[i][0] - objetos[j][0]) + (objetos[i][1] - objetos[j][1]) * (objetos[i][1] - objetos[j][1]); int ans = dp((1 << n) - 1); System.out.println(ans); int current = (1 << n) - 1; while(current != 0) { int next = dpNext[current]; int differents = next ^ current; System.out.print("0 "); for(int i = 0; i < n; i++) if((differents & (1 << i)) != 0) System.out.print((i + 1) + " "); current = next; } System.out.println("0"); } }
np
8_C. Looking for Order
CODEFORCES
import java.util.Scanner; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int xs = sc.nextInt(); int ys = sc.nextInt(); int n = sc.nextInt(); int[]x = new int[n], y = new int[n]; for (int i = 0; i < n; i++) { x[i] = sc.nextInt(); y[i] = sc.nextInt(); } int[]single = new int[n]; int[][]pair = new int[n][n]; for (int i = 0; i < n; i++) { single[i] = 2*((x[i]-xs)*(x[i]-xs)+(y[i]-ys)*(y[i]-ys)); } for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { pair[i][j] = (x[i]-xs)*(x[i]-xs)+(y[i]-ys)*(y[i]-ys)+(x[j]-xs)*(x[j]-xs)+(y[j]-ys)*(y[j]-ys)+(x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]); } } int[]best = new int[1 << n], prev = new int[1 << n]; for (int mask = 1; mask < (1 << n); mask++) { int i = 0; while ((mask & (1 << i))==0) i++; best[mask] = best[mask ^ (1 << i)]+single[i]; prev[mask] = i+1; for (int j = i+1; j < n; j++) { if ((mask & (1 << j)) != 0) { int temp = best[mask ^ (1 << i) ^ (1 << j)]+pair[i][j]; if (temp < best[mask]) { best[mask] = temp; prev[mask] = (i+1)*100+(j+1); } } } } System.out.println(best[(1 << n) - 1]); System.out.print("0 "); int cur = (1 << n) - 1; while (cur > 0) { int a = prev[cur] % 100; int b = prev[cur] / 100; if (a > 0) { System.out.print(a+" "); cur ^= 1 << (a-1); } if (b > 0) { System.out.print(b+" "); cur ^= 1 << (b-1); } System.out.print(0+" "); } } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Bag implements Runnable { private void solve() throws IOException { int xs = nextInt(); int ys = nextInt(); int n = nextInt(); int[] x = new int[n]; int[] y = new int[n]; for (int i = 0; i < n; ++i) { x[i] = nextInt(); y[i] = nextInt(); } final int[][] pair = new int[n][n]; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]); final int[] single = new int[n]; for (int i = 0; i < n; ++i) { single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys)); } final int[] best = new int[1 << n]; final int[] prev = new int[1 << n]; for (int set = 1; set < (1 << n); ++set) { int i; for (i = 0; i < n; ++i) if ((set & (1 << i)) != 0) break; int bestC = best[set ^ (1 << i)] + single[i]; int prevC = 1 << i; int nextSet = set ^ (1 << i); int unoI = 1 << i; int msc = set >> (i + 1); for (int j = i + 1, unoJ = 1 << (i + 1); msc != 0 && j < n; ++j, unoJ <<= 1, msc >>= 1) if ((msc & 1) != 0) { int cur = best[nextSet ^ unoJ] + pair[i][j]; if (cur < bestC) { bestC = cur; prevC = unoI | unoJ; } } best[set] = bestC; prev[set] = prevC; } writer.println(best[(1 << n) - 1]); int now = (1 << n) - 1; writer.print("0"); while (now > 0) { int differents = prev[now]; for(int i = 0; i < n; i++) if((differents & (1 << i)) != 0) { writer.print(" "); writer.print(i + 1); now ^= 1 << i; } writer.print(" "); writer.print("0"); } writer.println(); } public static void main(String[] args) { new Bag().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
np
8_C. Looking for Order
CODEFORCES
import java.util.*; import static java.lang.Math.*; public class Main { static int hx, hy; static int[] X, Y; static int N; static int[] DP; static int pw(int a) { return a * a; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); hx = sc.nextInt(); hy = sc.nextInt(); N = sc.nextInt(); X = new int[N]; Y = new int[N]; for (int i = 0; i < N; ++i) { X[i] = sc.nextInt(); Y[i] = sc.nextInt(); } DP = new int[1 << N]; Arrays.fill(DP, -1); int ans = recur(0); ArrayList<Integer> aa = new ArrayList<Integer>(); int U = 0; aa.add(0); int test = 0; while (U != (1 << N) - 1) { int a = 0; for (int i = 0; i < N; ++i) { if (((1 << i) & U) == 0) { a = i; break; } } int ans2 = recur(U | (1 << a)) + 2 * (pw(X[a] - hx) + pw(Y[a] - hy)); int temp = 2 * (pw(X[a] - hx) + pw(Y[a] - hy)); int best = -1; for (int i = a + 1; i < N; ++i) { if (((1 << i) & U) == 0) { int ans3 = recur(U|(1<<a)|(1<<i)) + pw(X[a]-X[i])+pw(Y[a]-Y[i]) + pw(X[a]-hx)+pw(Y[a]-hy) + pw(X[i]-hx)+pw(Y[i]-hy); if (ans3 < ans2) { ans2 = ans3; ans2 = ans3; best = i; temp = pw(X[a]-X[i])+pw(Y[a]-Y[i]) + pw(X[a]-hx)+pw(Y[a]-hy) + pw(X[i]-hx)+pw(Y[i]-hy); } } } if (best == -1) { aa.add(a + 1); aa.add(0); U |= (1 << a); } else { aa.add(a + 1); aa.add(best + 1); aa.add(0); U |= (1 << a) | (1 << best); } } System.out.println(ans); for (int i = 0; i < aa.size(); ++i) { System.out.print(aa.get(i) + " "); } } private static int recur(int U) { if (DP[U] != -1) { return DP[U]; } if (U == (1 << N) - 1) { return 0; } int a = 0; for (int i = 0; i < N; ++i) { if (((1 << i) & U) == 0) { a = i; break; } } int ans = recur(U | (1 << a)) + 2 * (pw(X[a] - hx) + pw(Y[a] - hy)); for (int i = a + 1; i < N; ++i) { if (((1 << i) & U) == 0) { ans = min(ans, recur(U|(1<<a)|(1<<i)) + pw(X[a]-X[i])+pw(Y[a]-Y[i]) + pw(X[a]-hx)+pw(Y[a]-hy) + pw(X[i]-hx)+pw(Y[i]-hy)); } } DP[U] = ans; return ans; } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class cf8c { static int n; static int[] bb; static int[] memo; static int[][] cost; static FastIO in = new FastIO(), out = in; public static void main(String[] args) { vec2 cen = new vec2(in.nextInt(),in.nextInt()); n = in.nextInt(); cost = new int[n][n]; vec2[] v = new vec2[n]; for(int i=0; i<n; i++) v[i] = new vec2(in.nextInt(),in.nextInt()); for(int i=0; i<n; i++) for(int j=0; j<n; j++) cost[i][j] = v[i].dist(cen) + v[i].dist(v[j]) + v[j].dist(cen); memo = new int[1<<n]; bb = new int[1<<n]; Arrays.fill(memo,-1); out.println(go(0)); build(0); out.close(); } static void build(int mask) { if(mask == (1<<n)-1) { out.println(0); return; } int first = 0; while((mask & (1<<first)) != 0) first++; int second = bb[mask]; out.print("0 " + (first+1) + " "); if(second != first) out.print((second+1)+" "); build(mask|(1<<first)|(1<<second)); } static int go(int mask) { if(mask == (1<<n)-1) return 0; if(memo[mask] != -1) return memo[mask]; int first = 0; int ans = Integer.MAX_VALUE; while((mask & (1<<first)) != 0) first++; for(int second = first; second < n; second++) { if((mask & (1<<second)) != 0) continue; int tans = cost[first][second] + go(mask|(1<<first)|(1<<second)); if(tans < ans) { ans = tans; bb[mask] = second; } } return memo[mask] = ans; } static class vec2 { int x, y; vec2(int a, int b) { x = a; y = b; } vec2 sub(vec2 v) { return new vec2(x-v.x,y-v.y); } int dist(vec2 v) { return sub(v).mag2(); } int mag2() { return x*x+y*y; } } static class FastIO extends PrintWriter { BufferedReader br; StringTokenizer st; public FastIO() { this(System.in,System.out); } public FastIO(InputStream in, OutputStream out) { super(new BufferedWriter(new OutputStreamWriter(out))); br = new BufferedReader(new InputStreamReader(in)); scanLine(); } public void scanLine() { try { st = new StringTokenizer(br.readLine().trim()); } catch(Exception e) { throw new RuntimeException(e.getMessage()); } } public int numTokens() { if(!st.hasMoreTokens()) { scanLine(); return numTokens(); } return st.countTokens(); } public String next() { if(!st.hasMoreTokens()) { scanLine(); return next(); } return st.nextToken(); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
np
8_C. Looking for Order
CODEFORCES