src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
import java.io.*; import java.text.DecimalFormat; public class ProblemD { private double survive(int round, int set) { if (sur[round][set] >= 0) return sur[round][set]; double res = 0.0; int count = 0; for(int i=0;i<n;i++) { if ((set & (1 << i)) > 0) { double res2 = 0.0; for(int j=0;j<n;j++) if ((set & (1 << j)) == 0) { res2 += survive(round - 1, set + (1 << j)) * a[i][j]; count++; } res += res2; } } count = (n-round+1) * (n - round) / 2; sur[round][set] = res / count; return sur[round][set]; } int n; double[][] a, sur; public void solve() { boolean oj = true; try { Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("inputD.txt"); Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("outputD.txt"); BufferedReader br = new BufferedReader(reader); PrintWriter out = new PrintWriter(writer); MyTokenizer tok = new MyTokenizer(br.readLine()); n = (int)tok.getNum(); a = new double[n][n]; int all = (1 << n) - 1; sur = new double[n][all + 1]; for(int i=0;i<n;i++) { tok = new MyTokenizer(br.readLine()); for(int j=0;j<n;j++) { a[i][j] = tok.getNum(); } for(int j=0;j<=all;j++) sur[i][j] = -1; } DecimalFormat format = new DecimalFormat("0.000000"); sur[0][all] = 1; double[] res = new double[n]; for(int i=0;i<n;i++) { res[i] = survive(n - 1, 1 << i); String sres = format.format(res[i]).replace(',','.'); out.printf("%s ", sres); } br.close(); out.close(); reader.close(); writer.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { } } public static void main(String[] args) { ProblemD f = new ProblemD(); f.solve(); } private class MyTokenizer { private String s; private int cur; public MyTokenizer(String s) { this.s = s; cur = 0; } public void skip() { while (cur < s.length() && (s.charAt(cur) == ' ' || s.charAt(cur) == '\n')) { cur++; } } public double getNum() { skip(); String snum = ""; while (cur < s.length() && (s.charAt(cur) >= '0' && s.charAt(cur) <= '9' || s.charAt(cur) == '.')) { snum += s.charAt(cur); cur++; } return Double.valueOf(snum); } public String getString() { skip(); String s2 = ""; while (cur < s.length() && (s.charAt(cur) >= 'a' && s.charAt(cur) <= 'z')) { s2 += s.charAt(cur); cur++; } return s2; } public char getCurrentChar() throws Exception { if (cur < s.length()) return s.charAt(cur); else throw new Exception("Current character out of string length"); } public void moveNextChar() { if (cur < s.length()) cur++; } public boolean isFinished() { return cur >= s.length(); } } }
np
16_E. Fish
CODEFORCES
import java.util.*; import java.io.*; public class Main{ public void run(){ Locale.setDefault(Locale.US); Scanner in = new Scanner(System.in); int n = in.nextInt(); double a[][] = new double[n][n]; for(int i=0;i<n;i++) for(int j=0;j<n;j++) a[i][j] = in.nextDouble(); double f[] = new double[1<<n]; f[(1<<n)-1] = 1; for(int mask = (1<<n)-1;mask > 0;mask--){ int k = Integer.bitCount(mask); if (k == 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){ f[mask&(~(1<<j))]+=f[mask]*a[i][j]/(k*(k-1)/2); } } } } } for(int i=0;i<n;i++) System.out.print(f[1<<i]+" "); } public static void main(String args[]){ new Main().run(); } }
np
16_E. Fish
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.PriorityQueue; import java.util.Queue; import java.util.StringTokenizer; public class Main implements Runnable { int n; double[] prob; double[][] a; void solve() throws IOException { n = nextInt(); a = new double[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { a[i][j] = nextDouble(); } } prob = new double[1<<n]; Arrays.fill(prob, 0.0); prob[(1<<n)-1] = 1.0; for (int i = (1<<n)-1; i > 1; --i) { int c = 0; for (int bit = 0; bit < n; ++bit) { if (((1<<bit) & i) > 0) { ++c; } } double k = c * (c - 1) / 2.0; for (int f = 0; f < n; ++f) { if (((1<<f) & i) > 0) { for (int s = f+1; s < n; ++s) { if (((1<<s) & i) > 0) { prob[i^(1<<f)] += prob[i] * a[s][f] / k; prob[i^(1<<s)] += prob[i] * a[f][s] / k; } } } } } for (int i = 0; i < n; ++i) { writer.printf(Locale.US, "%.6f ", prob[1<<i]); } } public static void main(String[] args) throws InterruptedException { new Thread(null, new Runnable() { public void run() { new Main().run(); } }, "1", 1 << 25).start(); } @Override public void run() { try { boolean fromStandart = true; reader = new BufferedReader(fromStandart ? new InputStreamReader(System.in) : new FileReader(INFILE)); writer = new PrintWriter(new BufferedWriter(fromStandart ? new OutputStreamWriter(System.out) : new FileWriter(OUTFILE))); tokenizer = null; solve(); writer.flush(); } catch (Exception error) { error.printStackTrace(); System.exit(1); } } static final String INFILE = "input.txt"; static final String OUTFILE = "output.txt"; BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; 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 nextString() throws IOException { return reader.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
np
16_E. Fish
CODEFORCES
import java.util.Locale; import java.util.Scanner; public class E { public static void main(String[] args) { new E().run(); } private void run() { Locale.setDefault(Locale.US); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); double[][] p = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) p[i][j] = sc.nextDouble(); } sc.close(); double[] w = new double[1 << n]; int max = (1 << n) - 1; w[max] = 1; for (int mask = max; mask > 0; mask--) { int count = 0; for (int i = 0; i < n; i++) if (((mask >> i) & 1) > 0) for (int j = i + 1; j < n; j++) if (((mask >> j) & 1) > 0) { count++; } if (count > 0) for (int i = 0; i < n; i++) if (((mask >> i) & 1) > 0) for (int j = i + 1; j < n; j++) if (((mask >> j) & 1) > 0) { w[mask ^ (1 << j)] += w[mask] * p[i][j] / count; w[mask ^ (1 << i)] += w[mask] * (1 - p[i][j]) / count; } } for (int i = 0; i < n; i++) { if (i != 0) System.out.print(' '); System.out.printf("%.6f", w[1 << i]); } System.out.println(); } }
np
16_E. Fish
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws java.lang.Exception { BufferedReader kek = new BufferedReader(new InputStreamReader(System.in)); //Scanner skek = new Scanner(System.in); PrintWriter outkek = new PrintWriter(System.out); int N = Integer.parseInt(kek.readLine()); double[][] lake = new double[N][N]; for(int i = 0; i < N; i++){ String[] input = kek.readLine().split(" "); for(int j = 0; j < N; j++){ lake[i][j] = Double.parseDouble(input[j]); } } int pow = (int)Math.pow(2, N); double[] res = new double[pow]; res[pow - 1] = 1.0; for(int i = pow - 1; i >= 0; i--){ int ones = Integer.bitCount(i); // So this is apparently a thing int possibleCombos = ones * (ones - 1) /2; for(int j = 0; j < N; j++){ if((i >> j) % 2 == 0){ // (X >> Y) literally does the same thing as divis func. Bit operators are weird. continue; } for(int k = j + 1; k < N; k++){ if((i >> k) % 2 == 0){ continue; } res[i ^ (1 << k)] += res[i] * lake[j][k]/possibleCombos; res[i ^ (1 << j)] += res[i] * lake[k][j]/possibleCombos; } } } for(int i = 0; i < N; i++){ outkek.print(res[1 << i] + " "); } kek.close(); outkek.close(); } /*static int divis(int n, int a){ for(int i = 0; i < a; i++){ n /= 2; } return n; }*/ }
np
16_E. Fish
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.Locale; import java.util.StringTokenizer; public class Main implements Runnable { // //////////////////////////////////////////////////////////////////// // Solution private int n; private int nn; private double[][] a; private double[] dp; private void solve() throws Throwable { n = nextInt(); nn = 1 << n; a = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = nextDouble(); } } dp = new double[nn]; Arrays.fill(dp, -1.0); dp[nn - 1] = 1.0; for (int j = 0; j < n; j++) { pw.format(Locale.US, "%.7f ", Dp(1 << j)); } } private double Dp(int i) { if (dp[i] >= 0.0) return dp[i]; double ans = 0; int count = Integer.bitCount(i); for (int j = 0; j < n; j++) { int jj = 1 << j; if ((jj & i) == 0) { double p = Dp(jj | i); double pPair = 2.0 / (double)((count + 1) * count); double s = 0; for (int l = 0; l < n; l++) { int ll = 1 << l; if ((ll & i) != 0) { s += a[l][j]; } } ans += p * pPair * s; } } dp[i] = ans; return dp[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(new Main()); t.start(); t.join(); if (sError != null) { throw sError; } } public void run() { try { initStreams(); solve(); } catch (Throwable e) { sError = e; } finally { if (pw != null) pw.close(); } } }
np
16_E. Fish
CODEFORCES
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Task2 { public static void main(String[] args) throws IOException { new Task2().solve(); } //ArrayList<Integer>[] g; int mod = 1000000007; PrintWriter out; int n; int m; //int[][] a = new int[1000][1000]; //int cnt = 0; long base = (1L << 63); long P = 31; int[][] a; void solve() throws IOException { //Reader in = new Reader("in.txt"); //out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); Reader in = new Reader(); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); //BufferedReader br = new BufferedReader( new FileReader("in.txt") ); //BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); int n = in.nextInt(); double[][] a = new double[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i][j] = in.nextDouble(); double[] dp = new double[1 << n]; dp[(1 << n) - 1] = 1; for (int mask = (1 << n) -1; mask >= 0; mask--) { int k = Integer.bitCount(mask); double p = 1.0 / (k*(k-1)/2.0); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if ((mask & (1 << i)) != 0 && (mask & (1 << j)) != 0) dp[(mask & ~(1 << j))] += p*dp[mask]*a[i][j]; } for (int i = 0; i < n; i++) out.print(dp[1 << i]+" "); out.flush(); out.close(); } long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a%b); } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Pair implements Comparable<Pair>{ int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (b < p.b) return 1; if (b > p.b) return -1; return 0; } // @Override // public boolean equals(Object o) { // Pair p = (Pair) o; // return a == p.a && b == p.b; // } // // @Override // public int hashCode() { // return Integer.valueOf(a).hashCode() + Integer.valueOf(b).hashCode(); // } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } } }
np
16_E. Fish
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 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()); } byte[][] nextBitMatrix(int n, int m) { byte[][] a = new byte[n][m]; for (int i = 0; i < n; i++) { String s = next(); for (int j = 0; j < m; j++) { a[i][j] = (byte) (s.charAt(j) - '0'); } } return a; } char[][] nextCharMatrix(int n, int m) { char[][] a = new char[n][m]; for (int i = 0; i < n; i++) { String s = next(); for (int j = 0; j < m; j++) { a[i][j] = s.charAt(j); } } return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } } class Task { boolean get(int mask, int i){ return (mask & (1 << i)) > 0; } int zero(int mask, int i){ return mask & (~(1 << i)); } public void solve() { int n = in.nextInt(); double[][] a = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) a[i][j] = in.nextDouble(); } double[] d = new double[1 << n]; d[(1 << n) - 1] = 1; for (int mask = (1 << n) - 1; mask >= 0; mask--) { int bits = Integer.bitCount(mask); double transfer = 1.0 / (bits * (bits - 1) / 2); for (int i = 0; i < n; i++) { if (get(mask, i)) { for (int j = i + 1; j < n; j++) { if (get(mask, j)) { d[zero(mask, j)] += a[i][j] * transfer * d[mask]; d[zero(mask, i)] += a[j][i] * transfer * d[mask]; } } } } } for(int i = 0; i < n; i++) out.print(d[1 << i] + " "); } private InputReader in; private PrintWriter out; Task(InputReader in, PrintWriter out) { this.in = in; this.out = out; } }
np
16_E. Fish
CODEFORCES
import java.util.Locale; import java.util.Scanner; public class E { public static void main(String[] args) { new E().solve(); } private int c(int n) { return n * (n - 1) / 2; } public void solve() { Locale.setDefault(Locale.US); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); double[][] pb = new double[n][n]; for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) pb[i][j] = sc.nextDouble(); int m = (1<<n); double[] dp = new double[m]; dp[0] = 1.0f; for (int i=1; i<m; ++i) for (int j=0; j<n; ++j) if ((i & (1<<j)) != 0) for (int k=0; k<n; ++k) if ((i & (1<<k)) == 0) dp[i] += pb[k][j] * dp[i & ~(1<<j)] / c(n - Integer.bitCount(i) + 1); int w = (1<<n) - 1; for (int i=0; i<n-1; ++i) System.out.printf("%.6f ", dp[w & ~(1<<i)]); System.out.printf("%.6f\n", dp[w & ~(1<<(n-1))]); } }
np
16_E. Fish
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.FileReader; import java.util.StringTokenizer; import java.io.IOException; import java.util.Arrays; public class Fish extends Thread { public Fish() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } private void solve() throws Throwable { int n = nextInt(); double[][] a = new double[n][n]; double[] dp = new double[(1 << n)]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { a[i][j] = nextDouble(); } } int limit = (1 << n) - 1; //dp[mask] = probability of current subset (mask) to remain in the end dp[limit] = 1.0; for (int mask = limit; mask > 0; --mask) { int cardinality = Integer.bitCount(mask); int probability = cardinality * (cardinality - 1) / 2; for (int first = 0; first < n; ++first) { if ((mask & powers[first]) != 0) { for (int second = first + 1; second < n; ++second) { if ((mask & powers[second]) != 0) { dp[mask - powers[first]] += dp[mask] * a[second][first] / probability; dp[mask - powers[second]] += dp[mask] * a[first][second] / probability; } } } } } for (int i = 0; i < n; ++i) { output.printf("%.10f ", dp[powers[i]]); } } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.flush(); output.close(); } } public static void main(String[] args) { new Fish().start(); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } static int powers[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144}; private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
16_E. Fish
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 8/14/11 * Time: 9:53 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.FileReader; import java.util.StringTokenizer; import java.io.IOException; import java.util.Arrays; public class Fish extends Thread { public Fish() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } static int getOnes(int mask) { int result = 0; while (mask != 0) { mask &= mask - 1; ++result; } return result; } private void solve() throws Throwable { int n = nextInt(); double[][] a = new double[n][n]; double[] dp = new double[(1 << n)]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { a[i][j] = nextDouble(); } } int limit = (1 << n) - 1; //dp[mask] = probability of current subset (mask) to remain in the end dp[limit] = 1.0; for (int mask = limit; mask > 0; --mask) { int cardinality = getOnes(mask); if (cardinality < 2) { continue; } int probability = cardinality * (cardinality - 1) / 2; for (int first = 0; first < n; ++first) { if ((mask & powers[first]) != 0) { for (int second = first + 1; second < n; ++second) { if ((mask & powers[second]) != 0) { dp[mask ^ powers[first]] += dp[mask] * a[second][first] / probability; dp[mask ^ powers[second]] += dp[mask] * a[first][second] / probability; } } } } } for (int i = 0; i < n; ++i) { output.printf("%.10f ", dp[powers[i]]); } } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.flush(); output.close(); } } public static void main(String[] args) { new Fish().start(); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } static final int powers[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144}; private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
16_E. Fish
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class Main { public static void main(String[] args) throws Exception { StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); PrintWriter pw = new PrintWriter(System.out); in.nextToken(); int n = (int) in.nval; double[][] a = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { in.nextToken(); a[i][j] = in.nval; } } double[] dp = new double[1 << n]; dp[(1 << n) - 1] = 1.0; for (int mask = (1 << n) - 2; mask > 0; mask--) { int count = Integer.bitCount(mask); double pPair = 2.0 / ((double) count * (count + 1)); double ans = 0.0; for (int j = 0; j < n; j++) { int jj = 1 << j; if ((jj & mask) != 0) continue; double p = dp[mask | jj]; double s = 0; for (int k = 0; k < n; k++) { int kk = 1 << k; if ((kk & mask) == 0) continue; s += a[k][j]; } ans += s * pPair * p; } dp[mask] = ans; } for (int i = 0; i < n; i++) { pw.print(dp[1 << i]); pw.print(' '); } pw.close(); } }
np
16_E. Fish
CODEFORCES
import java.text.DecimalFormat; import java.util.Arrays; import java.util.Scanner; public class E { static Scanner sc = new Scanner(System.in); static int N; static double[][] p; static DecimalFormat format = new DecimalFormat("0.000000"); public static void main(String[] args) throws Exception { N = sc.nextInt(); p = new double[N][N]; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { p[i][j] = sc.nextDouble(); } } double[] memo = new double[1 << N]; memo[memo.length - 1] = 1; for (int i = N; i >= 2; --i) { int[] live = new int[N]; for (int j = 0; j < i; ++j) { live[N - 1 - j] = 1; } do { int n = toInt(live); double norm = 2.0 / i / (i - 1); for (int f1 = 0; f1 < N; ++f1) { if (live[f1] == 0) continue; for (int f2 = f1 + 1; f2 < N; ++f2) { if (live[f2] == 0) continue; memo[n - (1 << f1)] += memo[n] * p[f2][f1] * norm; memo[n - (1 << f2)] += memo[n] * p[f1][f2] * norm; } } } while (nextPermutation(live)); // System.out.println(Arrays.toString(memo)); } for (int i = 0; i < N; ++i) { System.out.print(format.format(memo[1 << i])); if (i < N - 1) { System.out.print(" "); } } } static int toInt(int[] a) { int ret = 0; for (int i = 0; i < N; ++i) { ret += (1 << i) * a[i]; } return ret; } public static boolean nextPermutation(int[] a) { for (int i = a.length - 1; i > 0; --i) { if (a[i - 1] < a[i]) { int swapIndex = find(a[i - 1], a, i, a.length - 1); int temp = a[swapIndex]; a[swapIndex] = a[i - 1]; a[i - 1] = temp; Arrays.sort(a, i, a.length); return true; } } return false; } private static int find(int dest, int[] a, int s, int e) { if (s == e) { return s; } int m = (s + e + 1) / 2; return a[m] <= dest ? find(dest, a, s, m - 1) : find(dest, a, m, e); } }
np
16_E. Fish
CODEFORCES
import java.text.DecimalFormat; import java.util.Arrays; import java.util.Scanner; public class Main { public Main() { super(); } public static void main(String... args) { Main main = new Main(); main.start(); } public void start() { Scanner in = new Scanner(System.in); int n = in.nextInt(); double a[][] = new double[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i][j] = Double.parseDouble(in.next()); int nn = 1 << n; double p[] = new double[nn]; Arrays.fill(p, -1.0); p[nn - 1] = 1.0; DecimalFormat f = new DecimalFormat(); f.applyPattern("0.000000"); for (int i = 0; i < n; i++) { if (i != 0) System.out.print(" "); System.out.print(f.format(this.probability(a, p, 1 << i))); } } private double probability(double a[][], double p[], int i) { if (p[i] >= 0.0) return p[i]; double ans = 0; int count = Integer.bitCount(i); int n = a.length; for (int j = 0; j < n; j++) { int jj = 1 << j; if ((jj & i) == 0) { double d = this.probability(a, p, jj | i); double dPair = 2.0 / (double)((count + 1) * count); double s = 0; for (int l = 0; l < n; l++) { int ll = 1 << l; if ((ll & i) != 0) s += a[l][j]; } ans += d * dPair * s; } } p[i] = ans; return p[i]; } }
np
16_E. Fish
CODEFORCES
import java.util.Scanner; public class Fishes { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); double[][] p = new double[n][n]; double[] dp = new double[1 << 18]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { p[i][j] = Double.parseDouble(s.next()); } } int last = 1 << n; dp[last - 1] = 1.0; for (int i = last - 2; i > 0; i--) { int res = 0; for (int j = 0; j < n; j++) { if (((1 << j) & i) > 0) res++; } res++; res = res * (res - 1) / 2; for (int j = 0; j < n; j++) { if (((1 << j) & i) == 0) { for (int z = 0; z < n; z++) { if (((1 << z) & i) > 0) { dp[i] += dp[i | (1 << j)] * 1.0 / res * p[z][j]; } } } } } for (int i = 0; i < n; i++) { System.out.print(dp[1 << i] + " "); } } }
np
16_E. Fish
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Trung Pham */ public class E { public static double[] dp; public static double[][] data; public static int n; public static void main(String[] args) { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); n = in.nextInt(); data = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { data[i][j] = in.nextDouble(); } } dp = new double[1 << n]; Arrays.fill(dp, -1); for (int i = 0; i < n; i++) { int a = 1 << i; out.print(cal(a) + " "); } out.close(); //System.out.print(builder.toString()); } public static double cal(int mask) { if (mask == (1 << n) - 1) { // System.out.println(mask); return 1; } if (dp[mask] != -1) { return dp[mask]; } double result = 0; int c = 0; for (int i = 0; i < n; i++) { int a = 1 << i; if ((a & mask) != 0) { c++; for (int j = 0; j < n; j++) { int b = 1 << j; if ((b & mask) == 0) { result += (data[i][j] * cal(mask | b)); } } } } int nC2 = (c + 1) * c / 2; dp[mask] = result / nC2; return dp[mask]; } 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
16_E. Fish
CODEFORCES
import java.math.BigDecimal; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import java.util.Set; public class Task16e { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); double[][] prob = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { prob[i][j] = sc.nextDouble(); } } double[] var = new double[1 << n]; boolean[] was = new boolean[1 << n]; Arrays.fill(var, 0.0); Arrays.fill(was, false); was[0] = true; var[(1 << n) - 1] = 1.0; Set<Integer> cr = new HashSet<Integer>(); Set<Integer> nx = new HashSet<Integer>(); nx.add((1 << n) - 1); boolean[] fish = new boolean[n]; for (int cnt = 0; cnt < n -1; cnt++) { cr.clear(); cr.addAll(nx); nx.clear(); for (Iterator<Integer> iterator = cr.iterator(); iterator.hasNext();) { int curr = iterator.next(); for (int i = 0; i < n; i++) { fish[i] = ((1 << i) & curr) != 0; } int fishn = 0; for (int i = 0; i < n; i++) { if (fish[i]) fishn++; } if (fishn == 1) continue; for (int i = 0; i < n; i++) { if (!fish[i]) continue; for (int j = i + 1; j < n; j++) { if (!fish[j]) continue; int woi = curr & ~(1 << i); int woj = curr & ~(1 << j); var[woi] += var[curr] * prob[j][i]; var[woj] += var[curr] * prob[i][j]; nx.add(woi); nx.add(woj); } } } } double sum = 0.0; for (int i = 0; i < n; i++) { sum += var[1 << i]; } for (int i = 0; i < n; i++) { System.out.printf("%.6f ", var[1 << i] / sum); } } }
np
16_E. Fish
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Iterator; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Egor Kulikov (egor@egork.net) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE2 solver = new TaskE2(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) { solver.solve(i, in, out); } out.close(); } static class TaskE2 { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int m = in.readInt(); int[][] a = in.readIntTable(n, m); int[][] id = new int[n + 1][1 << n]; int[][] val = new int[n + 1][1 << n]; ArrayUtils.fill(id, m); int[] sum = new int[1 << n]; int[] low = new int[1 << n]; boolean[] base = new boolean[1 << n]; int[] vv = new int[1 << n]; for (int i = 1; i < (1 << n); i++) { low[i] = Integer.bitCount(Integer.lowestOneBit(i) - 1); int current = i; base[i] = true; vv[i] = i; for (int j = 0; j < n; j++) { current = current << 1; current += current >> n; current -= (current >> n) << n; if (current < i) { base[i] = false; vv[i] = vv[current]; break; } } } for (int i = 0; i < m; i++) { for (int j = 1; j < (1 << n); j++) { sum[j] = sum[j - (1 << low[j])] + a[low[j]][i]; } for (int j = 1; j < (1 << n); j++) { sum[vv[j]] = Math.max(sum[vv[j]], sum[j]); } for (int j = 1; j < (1 << n); j++) { if (!base[j]) { continue; } for (int k = n - 1; k >= 0; k--) { if (sum[j] > val[k][j]) { val[k + 1][j] = val[k][j]; id[k + 1][j] = id[k][j]; val[k][j] = sum[j]; id[k][j] = i; } else { break; } } } } int[] tempVal = new int[n]; int[] tempId = new int[n]; for (int i = 1; i < (1 << n); i++) { if (!base[i]) { for (int j = 0; j < n; j++) { val[j][i] = val[j][vv[i]]; id[j][i] = id[j][vv[i]]; } } else { for (int j = 0; j < n; j++) { tempVal[j] = val[j][i]; tempId[j] = id[j][i]; } ArrayUtils.orderBy(tempId, tempVal); for (int j = 0; j < n; j++) { val[j][i] = tempVal[j]; id[j][i] = tempId[j]; } } } int[] at = new int[1 << n]; int[] current = new int[1 << n]; int[] next = new int[1 << n]; int all = (1 << n) - 1; for (int i = 0; i < m; i++) { System.arraycopy(current, 0, next, 0, (1 << n)); for (int j = 1; j < (1 << n); j++) { if (at[j] == n || id[at[j]][j] != i) { continue; } int other = all - j; for (int k = other; k > 0; k = (k - 1) & other) { next[k + j] = Math.max(next[k + j], current[k] + val[at[j]][j]); } next[j] = Math.max(next[j], val[at[j]][j]); at[j]++; } int[] temp = current; current = next; next = temp; } out.printLine(current[all]); } } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void set(int index, int value); public abstract void addAt(int index, int value); public abstract void removeAt(int index); default public void swap(int first, int second) { if (first == second) { return; } int temp = get(first); set(first, get(second)); set(second, temp); } default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } default public void add(int value) { addAt(size(), value); } default public IntList sort(IntComparator comparator) { Sorter.sort(this, comparator); return this; } default public IntList subList(final int from, final int to) { return new IntList() { private final int shift; private final int size; { if (from < 0 || from > to || to > IntList.this.size()) { throw new IndexOutOfBoundsException("from = " + from + ", to = " + to + ", size = " + size()); } shift = from; size = to - from; } public int size() { return size; } public int get(int at) { if (at < 0 || at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size()); } return IntList.this.get(at + shift); } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } public void set(int at, int value) { if (at < 0 || at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size()); } IntList.this.set(at + shift, value); } public IntList compute() { return new IntArrayList(this); } }; } } static interface IntCollection extends IntStream { public int size(); default public void add(int value) { throw new UnsupportedOperationException(); } default public int[] toArray() { int size = size(); int[] array = new int[size]; int i = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { array[i++] = it.value(); } return array; } default public IntCollection addAll(IntStream values) { for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) { add(it.value()); } return this; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } 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[][] readIntTable(int rowCount, int columnCount) { int[][] table = new int[rowCount][]; for (int i = 0; i < rowCount; i++) { table[i] = readIntArray(columnCount); } return table; } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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 String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class Range { public static IntList range(int from, int to) { int[] result = new int[Math.abs(from - to)]; int current = from; if (from <= to) { for (int i = 0; i < result.length; i++) { result[i] = current++; } } else { for (int i = 0; i < result.length; i++) { result[i] = current--; } } return new IntArray(result); } } static class ArrayUtils { public static void fill(int[][] array, int value) { for (int[] row : array) { Arrays.fill(row, value); } } public static int[] range(int from, int to) { return Range.range(from, to).toArray(); } public static int[] createOrder(int size) { return range(0, size); } public static int[] sort(int[] array, IntComparator comparator) { return sort(array, 0, array.length, comparator); } public static int[] sort(int[] array, int from, int to, IntComparator comparator) { if (from == 0 && to == array.length) { new IntArray(array).sort(comparator); } else { new IntArray(array).subList(from, to).sort(comparator); } return array; } public static int[] order(final int[] array) { return sort(createOrder(array.length), new IntComparator() { public int compare(int first, int second) { if (array[first] < array[second]) { return -1; } if (array[first] > array[second]) { return 1; } return 0; } }); } public static void orderBy(int[] base, int[]... arrays) { int[] order = ArrayUtils.order(base); order(order, base); for (int[] array : arrays) { order(order, array); } } public static void order(int[] order, int[] array) { int[] tempInt = new int[order.length]; for (int i = 0; i < order.length; i++) { tempInt[i] = array[order[i]]; } System.arraycopy(tempInt, 0, array, 0, array.length); } } static class IntArrayList extends IntAbstractStream implements IntList { private int size; private int[] data; public IntArrayList() { this(3); } public IntArrayList(int capacity) { data = new int[capacity]; } public IntArrayList(IntCollection c) { this(c.size()); addAll(c); } public IntArrayList(IntStream c) { this(); if (c instanceof IntCollection) { ensureCapacity(((IntCollection) c).size()); } addAll(c); } public IntArrayList(IntArrayList c) { size = c.size(); data = c.data.clone(); } public IntArrayList(int[] arr) { size = arr.length; data = arr.clone(); } public int size() { return size; } public int get(int at) { if (at >= size) { throw new IndexOutOfBoundsException("at = " + at + ", size = " + size); } return data[at]; } private void ensureCapacity(int capacity) { if (data.length >= capacity) { return; } capacity = Math.max(2 * data.length, capacity); data = Arrays.copyOf(data, capacity); } public void addAt(int index, int value) { ensureCapacity(size + 1); if (index > size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size) { System.arraycopy(data, index, data, index + 1, size - index); } data[index] = value; size++; } public void removeAt(int index) { if (index >= size || index < 0) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } if (index != size - 1) { System.arraycopy(data, index + 1, data, index, size - index - 1); } size--; } public void set(int index, int value) { if (index >= size) { throw new IndexOutOfBoundsException("at = " + index + ", size = " + size); } data[index] = value; } public int[] toArray() { return Arrays.copyOf(data, size); } } static interface IntReversableCollection extends IntCollection { } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void addAt(int index, int value) { throw new UnsupportedOperationException(); } public void removeAt(int index) { throw new UnsupportedOperationException(); } public void set(int index, int value) { data[index] = value; } } static interface IntComparator { public int compare(int first, int second); } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } } static class Sorter { private static final int INSERTION_THRESHOLD = 16; private Sorter() { } public static void sort(IntList list, IntComparator comparator) { quickSort(list, 0, list.size() - 1, (Integer.bitCount(Integer.highestOneBit(list.size()) - 1) * 5) >> 1, comparator); } private static void quickSort(IntList list, int from, int to, int remaining, IntComparator comparator) { if (to - from < INSERTION_THRESHOLD) { insertionSort(list, from, to, comparator); return; } if (remaining == 0) { heapSort(list, from, to, comparator); return; } remaining--; int pivotIndex = (from + to) >> 1; int pivot = list.get(pivotIndex); list.swap(pivotIndex, to); int storeIndex = from; int equalIndex = to; for (int i = from; i < equalIndex; i++) { int value = comparator.compare(list.get(i), pivot); if (value < 0) { list.swap(storeIndex++, i); } else if (value == 0) { list.swap(--equalIndex, i--); } } quickSort(list, from, storeIndex - 1, remaining, comparator); for (int i = equalIndex; i <= to; i++) { list.swap(storeIndex++, i); } quickSort(list, storeIndex, to, remaining, comparator); } private static void heapSort(IntList list, int from, int to, IntComparator comparator) { for (int i = (to + from - 1) >> 1; i >= from; i--) { siftDown(list, i, to, comparator, from); } for (int i = to; i > from; i--) { list.swap(from, i); siftDown(list, from, i - 1, comparator, from); } } private static void siftDown(IntList list, int start, int end, IntComparator comparator, int delta) { int value = list.get(start); while (true) { int child = ((start - delta) << 1) + 1 + delta; if (child > end) { return; } int childValue = list.get(child); if (child + 1 <= end) { int otherValue = list.get(child + 1); if (comparator.compare(otherValue, childValue) > 0) { child++; childValue = otherValue; } } if (comparator.compare(value, childValue) >= 0) { return; } list.swap(start, child); start = child; } } private static void insertionSort(IntList list, int from, int to, IntComparator comparator) { for (int i = from + 1; i <= to; i++) { int value = list.get(i); for (int j = i - 1; j >= from; j--) { if (comparator.compare(list.get(j), value) <= 0) { break; } list.swap(j, j + 1); } } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class E { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int T = Integer.parseInt(bf.readLine()); for(int t=0; t<T; t++) { StringTokenizer st = new StringTokenizer(bf.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[][] a = new int[n][m]; for(int i=0; i<n; i++) { st = new StringTokenizer(bf.readLine()); for(int j=0; j<m; j++) a[i][j] = Integer.parseInt(st.nextToken()); } // small case int[] max = new int[m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { if(a[i][j] > max[j]) max[j] = a[i][j]; } } int[][] pos = new int[m][2]; for(int i=0; i<m; i++) { pos[i][0] = max[i]; pos[i][1] = i; } Arrays.sort(pos, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(o2[0], o1[0]); } }); int[][] new_a = new int[n][Math.min(n,m)]; for(int i=0; i<n; i++) { for(int j=0; j<Math.min(n,m); j++) { new_a[i][j] = a[i][pos[j][1]]; } } int exp = 1; for(int i=0; i<Math.min(n,m); i++) exp *= n; int maxval = -1; for(int i=0; i<exp; i++) { // int val = i; int sum = 0; for(int j=0; j<n; j++) { int toAdd = 0; int val = i; for(int k=0; k<Math.min(n,m); k++) { int tooAdd = new_a[(j+val)%n][k]; val /= n; if(tooAdd > toAdd) toAdd = tooAdd; } sum += toAdd; } if(sum > maxval) maxval = sum; } out.println(maxval); } // StringTokenizer st = new StringTokenizer(bf.readLine()); // int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); // int n = Integer.parseInt(st.nextToken()); out.close(); System.exit(0); } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class mainE { public static PrintWriter out = new PrintWriter(System.out); public static FastScanner enter = new FastScanner(System.in); public static void main(String[] args) throws IOException { int t=enter.nextInt(); for (int i = 0; i < t; i++) { solve(); } out.close(); } public static int[][] arr=new int[13][2010]; public static pair[] par= new pair[2010]; private static void solve() throws IOException{ int n=enter.nextInt(); int m=enter.nextInt(); for (int i = 0; i <n ; i++) { for (int j = 0; j <m ; j++) { arr[i][j]=enter.nextInt(); } } for (int i = 0; i <n ; i++) { for (int j = m; j <m+3 ; j++) { arr[i][j]=0; } } m=m+3; for (int i = 0; i <m ; i++) { int max=-1; for (int j = 0; j <n ; j++) { max=Math.max(arr[j][i], max); } par[i]=new pair(max,i); } Arrays.sort(par,0,m, pair::compareTo); int i0=par[0].st; int i1=par[1].st; int i2=par[2].st; int i3=par[3].st; int ans=-1; for (int i = 0; i <n ; i++) { for (int j = 0; j <n ; j++) { for (int k = 0; k <n ; k++) { for (int l = 0; l <n ; l++) { int first=Math.max(Math.max(arr[i][i0],arr[j][i1]), Math.max(arr[k][i2],arr[l][i3])); int second=Math.max(Math.max(arr[(i+1)%n][i0],arr[(j+1)%n][i1]), Math.max(arr[(k+1)%n][i2],arr[(l+1)%n][i3])); int third=Math.max(Math.max(arr[(i+2)%n][i0],arr[(j+2)%n][i1]), Math.max(arr[(k+2)%n][i2],arr[(l+2)%n][i3])); int fourth=Math.max(Math.max(arr[(i+3)%n][i0],arr[(j+3)%n][i1]), Math.max(arr[(k+3)%n][i2],arr[(l+3)%n][i3])); if(n==1) { second=0; third=0; fourth=0; } else if(n==2){ third=0; fourth=0; } else if(n==3){ fourth=0; } ans=Math.max(ans, first+second+fourth+third); } } } } System.out.println(ans); } static class pair implements Comparable<pair>{ int max,st; public pair(int max, int st) { this.max = max; this.st = st; } @Override public int compareTo(pair o) { return -Integer.compare(max, o.max); } } static class FastScanner { BufferedReader br; StringTokenizer stok; FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.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()); } char nextChar() throws IOException { return (char) (br.read()); } String nextLine() throws IOException { return br.readLine(); } } }
np
1209_E1. Rotate Columns (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.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE2 solver = new TaskE2(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskE2 { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); TaskE2.Column[] columns = new TaskE2.Column[m]; for (int i = 0; i < m; ++i) columns[i] = new TaskE2.Column(new int[n]); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { columns[j].vals[i] = in.nextInt(); } } for (int i = 0; i < m; ++i) columns[i].initMax(); Arrays.sort(columns, new Comparator<TaskE2.Column>() { public int compare(TaskE2.Column o1, TaskE2.Column o2) { return o2.max - o1.max; } }); if (columns.length > n) { columns = Arrays.copyOf(columns, n); } out.println(solveOne(columns)); } private int solveOne(TaskE2.Column[] columns) { int n = columns[0].vals.length; int[] best = new int[1 << n]; int[] next = new int[1 << n]; int[] tmp = new int[1 << n]; for (TaskE2.Column c : columns) { System.arraycopy(best, 0, next, 0, best.length); for (int rot = 0; rot < n; ++rot) { System.arraycopy(best, 0, tmp, 0, best.length); for (int i = 0, pos = rot; i < n; ++i, ++pos) { if (pos >= n) pos = 0; int val = c.vals[pos]; for (int j = 0; j < tmp.length; ++j) if ((j & (1 << i)) == 0) { tmp[j ^ (1 << i)] = Math.max(tmp[j ^ (1 << i)], tmp[j] + val); } } for (int j = 0; j < tmp.length; ++j) { next[j] = Math.max(next[j], tmp[j]); } } int[] aa = best; best = next; next = aa; } return best[best.length - 1]; } static class Column { int[] vals; int max; public Column(int[] vals) { this.vals = vals; } void initMax() { max = 0; for (int x : vals) max = Math.max(max, x); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
np
1209_E1. Rotate Columns (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.io.FileNotFoundException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE2 solver = new TaskE2(); solver.solve(1, in, out); out.close(); } static class TaskE2 { public void solve(int testNumber, FastScanner in, PrintWriter out) { int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(), m = in.nextInt(); int[][] a = new int[m][n]; int[] bestMask = new int[1 << n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[j][i] = in.nextInt(); } } int[] dp = new int[1 << n]; for (int i = 0; i < m; i++) { int[] array = a[i]; for (int j = 0; j < n; j++) { int val = array[j]; for (int mask = 0; mask < 1 << n; mask++) { if ((mask & (1 << j)) == 0) { dp[mask | (1 << j)] = Math.max(dp[mask | (1 << j)], dp[mask] + val); } } } for (int mask = 0; mask < 1 << n; mask++) { int best = 0; int cur = mask; for (int j = 0; j < n; j++) { best = Math.max(best, dp[cur]); cur = (cur >> 1) | ((cur & 1) << (n - 1)); } for (int j = 0; j < n; j++) { dp[cur] = best; cur = (cur >> 1) | ((cur & 1) << (n - 1)); } } } out.println(dp[(1 << n) - 1]); } } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public FastScanner(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (st == null || !st.hasMoreElements()) { String line = null; try { line = br.readLine(); } catch (IOException e) { } st = new StringTokenizer(line); } return st.nextToken(); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class E implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int t = scn.nextInt(); while(t-- > 0) { int n = scn.nextInt(), m = scn.nextInt(); int[][] arr = scn.next2DInt(n, m); int[][] col = new int[m][2]; for(int j = 0; j < m; j++) { int max = 0; for(int i = 0; i < n; i++) { max = Math.max(max, arr[i][j]); } col[j][0] = max; col[j][1] = j; } Arrays.parallelSort(col, (o1, o2) -> o2[0] - o1[0]); int take = Math.min(n, m); int[][] lol = new int[n][take]; for(int j = 0; j < take; j++) { for(int i = 0; i < n; i++) { lol[i][j] = arr[i][col[j][1]]; } } ans = 0; func(lol, 0); out.println(ans); } } int ans = 0; void func(int[][] arr, int col) { int n = arr.length, m = arr[0].length; if(col == m) { int rv = 0; for(int i = 0; i < n; i++) { int mx = 0; for(int j = 0; j < m; j++) { mx = Math.max(mx, arr[i][j]); } rv += mx; } ans = Math.max(ans, rv); return; } for(int rot = 0; rot < n; rot++) { int f = arr[0][col]; for(int j = 1; j < n; j++) { arr[j - 1][col] = arr[j][col]; } arr[n - 1][col] = f; func(arr, col + 1); } } public void run() { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) { new Thread(null, new E(), "Main", 1 << 26).start(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); int c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } long[] shuffle(long[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); long c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } int[] uniq(int[] arr) { arr = scn.shuffle(arr); Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } long[] uniq(long[] arr) { arr = scn.shuffle(arr); Arrays.sort(arr); long[] rv = new long[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } int[] reverse(int[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } long[] reverse(long[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } int[] compress(int[] arr) { int n = arr.length; int[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } long[] compress(long[] arr) { int n = arr.length; long[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; import java.io.*; public class E { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out, false); int t = scanner.nextInt(); while(t-->0) { int n = scanner.nextInt(); int m = scanner.nextInt(); int[][] cols = new int[m][n]; for(int i = 0; i < n; i++) { for(int j =0; j < m; j++) { cols[j][i] = scanner.nextInt(); } } int maxMask = 1 << n; int[] dp = new int[maxMask]; Arrays.fill(dp, -1); dp[0] = 0; for(int i = 0; i < m; i++) { for(int mask = maxMask-1; mask>=0; mask--) { int[] arr = cols[i].clone(); for(int j = 0; j < n; j++) { for(int smask = mask; smask >= 0; smask = (smask-1)&mask) { if (dp[smask] == -1) continue; int add = 0; for(int k = 0; k < n; k++) { if (((mask^smask)&(1 << k)) > 0) add += arr[k]; } dp[mask] = Math.max(dp[mask], dp[smask] + add); if (smask == 0) break; } arr = shift(arr); } } } out.println(dp[maxMask-1]); } out.flush(); } static int[] shift (int[] a) { int[] b = new int[a.length]; b[0] = a[a.length-1]; for(int i = 0; i < a.length-1; i++) { b[i+1] = a[i]; } return b; } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1209e1_2 { public static void main(String[] args) throws IOException { int t = ri(); while (t --> 0) { int n = rni(), m = ni(), a[][] = new int[m][n], dp[] = new int[1 << n]; for (int i = 0; i < n; ++i) { int[] row = ria(m); for (int j = 0; j < m; ++j) { a[j][i] = row[j]; } } for (int i = 0; i < m; ++i) { for (int r = 0; r < 1 << n; ++r) { for (int j = 0; j < n; ++j) { if ((r & (1 << j)) == 0) { continue; } dp[r] = max(dp[r], dp[r ^ (1 << j)] + a[i][j]); } } for (int r = 0; r < 1 << n; ++r) { int s = r; for (int j = 0; j < n; ++j) { if ((s & 1) != 0) { s = (s >> 1) | (1 << (n - 1)); } else { s >>= 1; } dp[s] = max(dp[s], dp[r]); } } } prln(dp[(1 << n) - 1]); } close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static 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() {__out.flush();} static void close() {__out.close();} }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
/** * Date: 14 Sep, 2019 * Link: * * @author Prasad-Chaudhari * @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/ * @git: https://github.com/Prasad-Chaudhari */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Hashtable; import java.util.LinkedList; import java.util.Map; public class newProgram9 { public static void main(String[] args) throws IOException { // TODO code application logic here FastIO in = new FastIO(); int t = in.ni(); // int t = 1; while (t-- > 0) { int n = in.ni(); int m = in.ni(); int a[][] = new int[n][m]; int b[][] = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.ni(); b[j][i] = a[i][j]; } } for (int i = 0; i < m; i++) { Arrays.sort(b[i]); } Data d[] = new Data[m]; for (int i = 0; i < m; i++) { d[i] = new Data(-b[i][n - 1], i); } Arrays.sort(d); int col = Math.min(n, m); int c[][] = new int[n][col]; for (int i = 0; i < col; i++) { for (int j = 0; j < n; j++) { c[j][i] = a[j][d[i].b]; } } // for (int i = 0; i < n; i++) { // for (int j = 0; j < col; j++) { // System.out.print(c[i][j] + " "); // } // System.out.println(); // } System.out.println(ans(c, n, col, 0)); } in.bw.flush(); } private static int ans(int c[][], int n, int m, int col) { if (col == m) { int sum = 0; for (int i = 0; i < n; i++) { int max = 0; for (int j = 0; j < m; j++) { // System.out.print(c[i][j] + " "); max = Math.max(c[i][j], max); } sum += max; // System.out.println(); } // System.out.println(sum); return sum; } else { int max = ans(c, n, m, col + 1); int curr[] = new int[n]; for (int i = 0; i < n; i++) { curr[i] = c[i][col]; } for (int i = 1; i < n; i++) { for (int j = 0; j < n; j++) { c[j][col] = curr[(i + j) % n]; } max = Math.max(max, ans(c, n, m, col + 1)); } return max; } } static class FastIO { private final BufferedReader br; private final BufferedWriter bw; private String s[]; private int index; private final StringBuilder sb; public FastIO() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8")); s = br.readLine().split(" "); sb = new StringBuilder(); index = 0; } public int ni() throws IOException { return Integer.parseInt(nextToken()); } public double nd() throws IOException { return Double.parseDouble(nextToken()); } public long nl() throws IOException { return Long.parseLong(nextToken()); } public String next() throws IOException { return nextToken(); } public String nli() throws IOException { try { return br.readLine(); } catch (IOException ex) { } return null; } public int[] gia(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public int[] gia(int n, int start, int end) throws IOException { validate(n, start, end); int a[] = new int[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } public double[] gda(int n) throws IOException { double a[] = new double[n]; for (int i = 0; i < n; i++) { a[i] = nd(); } return a; } public double[] gda(int n, int start, int end) throws IOException { validate(n, start, end); double a[] = new double[n]; for (int i = start; i < end; i++) { a[i] = nd(); } return a; } public long[] gla(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nl(); } return a; } public long[] gla(int n, int start, int end) throws IOException { validate(n, start, end); long a[] = new long[n]; for (int i = start; i < end; i++) { a[i] = nl(); } return a; } public int[][][] gwtree(int n) throws IOException { int m = n - 1; int adja[][] = new int[n + 1][]; int weight[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; int cost[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = i + 1; to[i] = ni(); cost[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; weight[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][count[from[i]] - 1] = to[i]; adja[to[i]][count[to[i]] - 1] = from[i]; weight[from[i]][count[from[i]] - 1] = cost[i]; weight[to[i]][count[to[i]] - 1] = cost[i]; count[from[i]]--; count[to[i]]--; } return new int[][][] { adja, weight }; } public int[][][] gwg(int n, int m) throws IOException { int adja[][] = new int[n + 1][]; int weight[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; int cost[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = ni(); to[i] = ni(); cost[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; weight[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][count[from[i]] - 1] = to[i]; adja[to[i]][count[to[i]] - 1] = from[i]; weight[from[i]][count[from[i]] - 1] = cost[i]; weight[to[i]][count[to[i]] - 1] = cost[i]; count[from[i]]--; count[to[i]]--; } return new int[][][] { adja, weight }; } public int[][] gtree(int n) throws IOException { int adja[][] = new int[n + 1][]; int from[] = new int[n - 1]; int to[] = new int[n - 1]; int count[] = new int[n + 1]; for (int i = 0; i < n - 1; i++) { from[i] = i + 1; to[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; } for (int i = 0; i < n - 1; i++) { adja[from[i]][--count[from[i]]] = to[i]; adja[to[i]][--count[to[i]]] = from[i]; } return adja; } public int[][] gg(int n, int m) throws IOException { int adja[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = ni(); to[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][--count[from[i]]] = to[i]; adja[to[i]][--count[to[i]]] = from[i]; } return adja; } public void print(String s) throws IOException { bw.write(s); } public void println(String s) throws IOException { bw.write(s); bw.newLine(); } public void print(int s) throws IOException { bw.write(s + ""); } public void println(int s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(long s) throws IOException { bw.write(s + ""); } public void println(long s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(double s) throws IOException { bw.write(s + ""); } public void println(double s) throws IOException { bw.write(s + ""); bw.newLine(); } private String nextToken() throws IndexOutOfBoundsException, IOException { if (index == s.length) { s = br.readLine().split(" "); index = 0; } return s[index++]; } private void validate(int n, int start, int end) { if (start < 0 || end >= n) { throw new IllegalArgumentException(); } } } static class Data implements Comparable<Data> { int a, b; public Data(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Data o) { if (a == o.a) { return Integer.compare(b, o.b); } return Integer.compare(a, o.a); } public static void sort(int a[]) { Data d[] = new Data[a.length]; for (int i = 0; i < a.length; i++) { d[i] = new Data(a[i], 0); } Arrays.sort(d); for (int i = 0; i < a.length; i++) { a[i] = d[i].a; } } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class A { FastScanner in; PrintWriter out; void solve() { int tc = in.nextInt(); for (int t = 0; t < tc; t++) { int n = in.nextInt(); int m = in.nextInt(); O[] a = new O[n * m]; int[][] cols = new int[m][n + n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cols[j][i] = cols[j][i + n] = in.nextInt(); a[i * m + j] = new O(i, j, cols[j][i]); } } Arrays.sort(a); boolean[] used = new boolean[m]; int cntUsed = 0; for (O o : a) { if (!used[o.y]) { used[o.y] = true; cntUsed++; if (cntUsed == n) { break; } } } int[] dp = new int[1 << n]; int[] ndp = new int[1 << n]; int[] maxndp = new int[1 << n]; for (int col = 0; col < m; col++) { if (!used[col]) { continue; } int[] curColumn = cols[col]; for (int shift = 0; shift < n; shift++) { System.arraycopy(dp, 0, ndp, 0, ndp.length); for (int mask = 0; mask < 1 << n; mask++) { for (int bit = 0; bit < n; bit++) { if (((1 << bit) & mask) == 0) { int nmask = mask | (1 << bit); ndp[nmask] = Math.max(ndp[nmask], ndp[mask] + curColumn[bit + shift]); } } } for (int i = 0; i < ndp.length; i++) { maxndp[i] = Math.max(maxndp[i], ndp[i]); } } int[] tmp = dp; dp = maxndp; maxndp = tmp; } out.println(dp[dp.length - 1]); } } class O implements Comparable<O> { int x, y, value; public O(int x, int y, int value) { this.x = x; this.y = y; this.value = value; } @Override public int compareTo(O o) { return -Integer.compare(value, o.value); } } void run() { try { in = new FastScanner(new File("A.in")); out = new PrintWriter(new File("A.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new A().runIO(); } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
/** * BaZ :D */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static MyScanner scan; static PrintWriter pw; static long MOD = 1_000_000_007; static long INF = 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 << 27) { public void run() { try { solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static int n,m,need,a[][],dp[][][],real[][]; static void solve() throws IOException { //initIo(true); initIo(false); StringBuilder sb = new StringBuilder(); int t = ni(); while(t-->0) { n = ni(); m = ni(); a = new int[n][m]; for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { a[i][j] = ni(); } } need = min(n,m); Pair max_in_cols[] = new Pair[m]; for(int COL=0;COL<m;++COL) { int max = 0; for(int i=0;i<n;++i) { max = max(max, a[i][COL]); } max_in_cols[COL] = new Pair(max, COL); } real = new int[n][need]; Arrays.sort(max_in_cols); for(int i=0;i<need;++i) { int COL = max_in_cols[m-1-i].y; for(int j=0;j<n;++j) { real[j][i] = a[j][COL]; } } // pl("need : "+need); // pa("Real", real); dp = new int[need][n+1][(1<<n)]; for(int i=0;i<need;++i) { for(int j=0;j<=n;++j) { for(int k=0;k<(1<<n);++k) { dp[i][j][k] = -1; } } } pl(f(0, n, 0)); } pw.flush(); pw.close(); } static int f(int idx, int bias, int mask) { //pl("idx: "+idx+" bias : "+bias + " mask : "+mask); if(idx==need) { return 0; } if(dp[idx][bias][mask]!=-1) { return dp[idx][bias][mask]; } //didn't fix bias yet if(bias==n) { int max = 0; for(int b=0;b<n;++b) { max = max(max, f(idx, b, mask)); } //pl("maxxxxxxx : "+max); dp[idx][bias][mask] = max; return max; } else { int max = f(idx+1, n, mask); for(int i=0;i<n;++i) { if((mask&(1<<i))==0) { max = max(max, real[(i-bias+n)%n][idx] + f(idx, bias, mask | (1<<i))); } } //pl("max : "+max); dp[idx][bias][mask] = max; return max; } } static class Pair implements Comparable<Pair> { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(Pair other) { if(this.x!=other.x) return this.x-other.x; return this.y-other.y; } public String toString() { return "("+x+","+y+")"; } } static void initIo(boolean isFileIO) throws IOException { scan = new MyScanner(isFileIO); if(isFileIO) { pw = new PrintWriter("/Users/amandeep/Desktop/output.txt"); } else { pw = new PrintWriter(System.out, true); } } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static String ne() throws IOException { return scan.next(); } static String nel() throws IOException { return scan.nextLine(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String 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 MyScanner { BufferedReader br; StringTokenizer st; MyScanner(boolean readingFromFile) throws IOException { if(readingFromFile) { br = new BufferedReader(new FileReader("/Users/amandeep/Desktop/input.txt")); } else { br = new BufferedReader(new InputStreamReader(System.in)); } } String nextLine()throws IOException { return br.readLine(); } String next() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; import java.math.*; // **** E1. Rotate Columns (easy version) **** public class E1 { static char [] in = new char [1000000]; public static void main (String [] arg) throws Throwable { int t = nextInt(); C : for (int ii = 0; ii<t; ++ii) { int n = nextInt(); int m = nextInt(); Pair [] P = new Pair [n*m]; int [][] g = new int [n][m]; for (int i = 0; i<n; ++i) { for (int j = 0; j<m; ++j) { g[i][j] = nextInt(); P[j + m*i] = new Pair (i, j, g[i][j]); } } for (int i = 0; i<P.length; ++i) if (P[i] == null) continue C; Arrays.sort(P); HashSet<Integer> rotcols =new HashSet<Integer>(); for (int i = 0; i<n; ++i) { //System.err.println("Adding " + P[i].j + " , " + P[i].L); rotcols.add(P[i].j); } if (n <= 3 || rotcols.size() >= 3) { //System.err.println("EASY"); int sum = 0; for (int i = 0; i<n && i < P.length; ++i) sum += P[i].L; System.out.println(sum); } else { // n == 4 if (P.length > 4) rotcols.add(P[4].j); //Integer [] rr = rotcols.toArray(new Integer[0]); int [] rot = new int [rotcols.size()]; int maxmax = 0; A : while (true) { for (int i = 0; i<rot.length; ++i) { rot[i]++; if (rot[i] == n) { rot[i] = 0; if (i == rot.length-1) break A; } else { break; } } int [] max = new int [n]; for (int i = 0; i<n; ++i) { int j = 0; for (int col : rotcols) { max[i] = Math.max(max[i], g[(i+rot[j])%n][col]); j++; } } int sum = 0; for (int m2 : max) sum+= m2; maxmax = Math.max(maxmax, sum); } System.out.println(maxmax); } } } /************** HELPER CLASSES ***************/ //static class HS extends HashSet<Integer>{public HS(){super();}public HS(int a){super(a);}}; //static class AL extends ArrayList<Integer>{public AL(){super();}public AL(int a){super (a);}}; static class Pair implements Comparable<Pair> { int i,j;long L; public Pair(int xx, int yy, long LL){i=xx;j=yy;L=LL;} public int compareTo(Pair p) { return (this.L > p.L) ? -1 : (this.L == p.L) ? this.i - p.i : 1;} } /************** FAST IO CODE FOLLOWS *****************/ public static long nextLong() throws Throwable { long i = System.in.read();boolean neg = false;while (i < 33) i = System.in.read();if (i == 45) {neg=true;i=48;}i = i - 48; int j = System.in.read();while (j > 32) {i*=10;i+=j-48;j = System.in.read();}return (neg) ? -i : i; } public static int nextInt() throws Throwable {return (int)nextLong();} public static String next() throws Throwable { int i = 0; while (i < 33 && i != -1) i = System.in.read(); int cptr = 0; while (i >= 33) { in[cptr++] = (char)i; i = System.in.read();} return new String(in, 0,cptr); } /**** LIBRARIES ****/ public static long gcdL(long a, long b) {while (b != 0) {long tmp = b;b = (a % b);a = tmp;}return a;} public static int gcd(int a, int b) {while (b != 0) {int tmp = b;b = (a % b);a = tmp;}return a;} public static int[] sieve(int LIM) { int i,count = 0; boolean [] b = new boolean [LIM]; for (i = 2;i<LIM; ++i) if (!b[i]) {count++; for (int j = i<<1; j<LIM; j+=i) b[j] = true;} int [] primes = new int[count]; for (i = 2,count=0;i<LIM;++i) if (!b[i]) primes[count++] = i; return primes; } public static int[] numPrimeFactors(int LIM) { int i,count = 0; int [] b = new int [LIM]; for (i = 2;i<LIM; ++i) if (b[i] == 0) {count++; for (int j = i; j<LIM; j+=i) b[j]++;} return b; } public static StringBuilder stringFromArray(int [] a) { StringBuilder b = new StringBuilder(9*a.length); for (int i = 0; i<a.length; ++i) { if (i != 0) b = b.append(' '); b = b.append(a[i]); } return b; } public static long modPow (long a, long n, long MOD) { long S = 1; for (;n > 0; n>>=1, a=(a*a)%MOD) if ((n & 1) != 0) S = (a*S) % MOD; return S;} } /* Full Problem Text: This is an easier version of the next problem. The difference is only in constraints. You are given a rectangular n \times m matrix a. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times. After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for i-th row it is equal r_i. What is the maximal possible value of r_1+r_2+...+r_n? */
np
1209_E1. Rotate Columns (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.FilterInputStream; import java.io.BufferedInputStream; import java.util.Random; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); E2RotateColumnsHardVersion solver = new E2RotateColumnsHardVersion(); int testCount = in.scanInt(); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class E2RotateColumnsHardVersion { int[][] dp; int[] cur; public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int m = in.scanInt(); int[][] ar = new int[n][m]; int[][] max = new int[m][2]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) ar[i][j] = in.scanInt(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) max[i][0] = Math.max(max[i][0], ar[j][i]); max[i][1] = i; } CodeHash.shuffle(max); Arrays.sort(max, (o1, o2) -> -o1[0] + o2[0]); dp = new int[2][1 << n]; cur = new int[1 << n]; for (int i = 0; i < Math.min(m, n); i++) { Arrays.fill(dp[i & 1], 0); for (int k = 0; k < n; k++) { System.arraycopy(dp[(i - 1) & 1], 0, cur, 0, 1 << n); for (int l = 0; l < n; l++) { for (int j = 0; j < 1 << n; j++) { if ((j & (1 << l)) == 0) { cur[j ^ (1 << l)] = Math.max(cur[j ^ (1 << l)], cur[j] + ar[(k + l) % n][max[i][1]]); } } } for (int j = 0; j < 1 << n; j++) dp[i & 1][j] = Math.max(dp[i & 1][j], cur[j]); } } out.println(dp[Math.min(n, m) & 1 ^ 1][(1 << n) - 1]); } } static class CodeHash { public static void shuffle(int[][] ar) { Random rd = new Random(new Random().nextInt()); for (int i = 0; i < ar.length; i++) { int index = rd.nextInt(ar.length); int[] temp = ar[i]; ar[i] = ar[index]; ar[index] = temp; } } } 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
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.IntStream; public class Test { static PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static int readInt() { int ans = 0; boolean neg = false; try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (c == '-') { start = true; neg = true; continue; } else if (c >= '0' && c <= '9') { start = true; ans = ans * 10 + c - '0'; } else if (start) break; } } catch (IOException e) { } return neg ? -ans : ans; } static long readLong() { long ans = 0; boolean neg = false; try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (c == '-') { start = true; neg = true; continue; } else if (c >= '0' && c <= '9') { start = true; ans = ans * 10 + c - '0'; } else if (start) break; } } catch (IOException e) { } return neg ? -ans : ans; } static String readLine() { StringBuilder b = new StringBuilder(); try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (Character.isLetterOrDigit(c)) { start = true; b.append((char) c); } else if (start) break; } } catch (IOException e) { } return b.toString(); } public static void main(String[] args) { Test te = new Test(); te.start(); writer.flush(); } int[] buf = new int[10]; int best(int[][] a, int c) { int ans = 0; if (c == a[0].length) { for (int i = 0; i < a.length; i++) ans += Arrays.stream(a[i]).max().getAsInt(); return ans; } for (int r = 0; r <= a.length; r++) { for (int i = 0; i < a.length; i++) buf[(i+1) % a.length] = a[i][c]; for (int i = 0; i < a.length; i++) a[i][c] = buf[i]; ans = Math.max(ans, best(a, c+1)); } return ans; } void start() { int t = readInt(); while (t-- > 0) { int n = readInt(), m = readInt(); int[][] a = new int[n][m]; int[][] e = new int[n*m][]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { a[i][j] = readInt(); e[i*m+j] = new int[]{a[i][j], j}; } Arrays.sort(e, (x, y) -> x[0] == y[0] ? Integer.compare(x[1], y[1]) : Integer.compare(y[0], x[0])); Set<Integer> cols = new HashSet<>(); for (int[] x : e) { cols.add(x[1]); if (cols.size() >= n) break; } int[] cs = cols.stream().mapToInt(Integer::intValue).toArray(); int[][] na = new int[n][cs.length]; for (int i = 0; i < n; i++) for (int j = 0; j < cs.length; j++) na[i][j] = a[i][cs[j]]; writer.println(best(na, 0)); } } }
np
1209_E1. Rotate Columns (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.Scanner; /** * 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); E2VrashayaStolbciUslozhnennayaVersiya solver = new E2VrashayaStolbciUslozhnennayaVersiya(); solver.solve(1, in, out); out.close(); } static class E2VrashayaStolbciUslozhnennayaVersiya { public void solve(int testNumber, Scanner in, PrintWriter out) { int tn = in.nextInt(); for (int t = 0; t < tn; t++) { int n = in.nextInt(); int m = in.nextInt(); Col[] a = new Col[m]; for (int i = 0; i < m; i++) { a[i] = new Col(n); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[j].a[i] = in.nextInt(); if (a[j].a[i] > a[j].max) { a[j].max = a[j].a[i]; } } } Arrays.sort(a, (o1, o2) -> o2.max - o1.max); if (m > n) { m = n; } for (int i = 0; i < m; i++) { a[i].calcMask(); } int[][] dp = new int[m + 1][1 << n]; Arrays.fill(dp[0], -1); dp[0][0] = 0; for (int i = 0; i < m; i++) { for (int msk = 0; msk < (1 << n); msk++) { dp[i + 1][msk] = dp[i][msk]; for (int sub = msk; sub > 0; sub = (sub - 1) & msk) { int v = dp[i][msk ^ sub] + a[i].mask[sub]; if (v > dp[i + 1][msk]) { dp[i + 1][msk] = v; } } } } out.println(dp[m][(1 << n) - 1]); } } class Col { int n; int[] a; int[] mask; int max; public Col(int n) { this.n = n; a = new int[n]; } void calcMask() { mask = new int[1 << n]; for (int i = 0; i < (1 << n); i++) { for (int j = 0; j < n; j++) { int sum = 0; for (int k = 0; k < n; k++) { if (((1 << k) & i) != 0) { sum += a[(j + k) % n]; } } if (sum > mask[i]) { mask[i] = sum; } } } } } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; import java.io.*; public class E584 { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); while (t > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int [][] a = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[j][i] = sc.nextInt(); } } int [][] dp = new int[m + 1][(1 << n)]; for (int i = 1; i <= m; i++) { for (int j = 0; j < (1 << n); j++) { dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]); int [] b = a[i - 1]; for (int start = 0; start < n; start++) { int [] c = new int[n]; for (int p = 0; p < n; p++) c[p] = b[(start + p) % n]; for (int k = 0; k < (1 << n); k++) { if ((k | j) == j) { int sum = 0; for (int p = 0; p < n; p++) { if (((k >> p) & 1) == 0 && ((j >> p) & 1) == 1) sum += c[p]; } dp[i][j] = Math.max(dp[i][j], dp[i - 1][k] + sum); } } } } } out.println(dp[m][(1 << n) - 1]); t--; } out.close(); } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; public class Main { public static class Pair implements Comparable<Pair> { int k, x; public Pair(int k) { this.k = k; } public void update(int x) { this.x = Math.max(this.x, x); } public int compareTo(Pair other) { if (x != other.x) { return other.x - x; } return k - other.k; } } public static int sum(int[] arr) { int sum = 0; for (int x : arr) { sum += x; } return sum; } public static int[] join(int[] a, int[] b) { int n = a.length; int[] best = new int[n]; int sum = 0; for (int shift = 0; shift < n; shift++) { int[] curr = new int[n]; for (int i = 0; i < n; i++) { curr[i] = Math.max(a[i], b[(i + shift) % n]); } int now = sum(curr); if (now > sum) { sum = now; best = curr; } } return best; } public static int n; public static int[] pow; public static int[][] dp, real; public static void calc(int mask) { int[] best = new int[n]; int sum = 0; for (int i = 0; i < n; i++) { if ((mask & pow[i]) != 0) { int to = mask ^ pow[i]; int[] init = new int[n]; for (int j = 0; j < n; j++) { init[j] = real[j][i]; } int[] curr = join(dp[to], init); int s = sum(curr); if (s > sum) { sum = s; best = curr; } } } dp[mask] = best; } public static void main(String[] args) { pow = new int[15]; pow[0] = 1; for (int i = 1; i < pow.length; i++) { pow[i] = pow[i - 1] * 2; } Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { n = in.nextInt(); int m = in.nextInt(); int[][] arr = new int[n][m]; for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { arr[j][k] = in.nextInt(); } } Pair[] best = new Pair[m]; for (int j = 0; j < m; j++) { best[j] = new Pair(j); for (int k = 0; k < n; k++) { best[j].update(arr[k][j]); } } Arrays.sort(best); real = new int[n][n]; for (int j = 0; j < n; j++) { for (int k = 0; k < Math.min(n, m); k++) { real[j][k] = arr[j][best[k].k]; } } dp = new int[1 << n][]; Stack<Integer>[] min = new Stack[n + 1]; for (int j = 0; j <= n; j++) { min[j] = new Stack<>(); } for (int j = 0; j < dp.length; j++) { int cnt = 0; for (int k = 0; k < n; k++) { if ((j & pow[k]) != 0) { cnt++; } } min[cnt].add(j); } for (int j = 0; j < min.length; j++) { for (int x : min[j]) { if (j == 0) { dp[x] = new int[n]; } else { calc(x); } } } System.out.println(sum(dp[dp.length - 1])); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Array; 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 = true; 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) 1e8; long lInf = (long) 1e18; public Task(FastIO io, Debug debug) { this.io = io; this.debug = debug; } @Override public void run() { int t = io.readInt(); while (t-- > 0) solve1(); } public void solve1() { cache.clear(); int n = io.readInt(); int m = io.readInt(); Col[] mat = new Col[m]; for (int i = 0; i < m; i++) { mat[i] = new Col(); mat[i].data = new int[n]; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int v = io.readInt(); mat[j].data[i] = v; mat[j].max = Math.max(mat[j].max, v); } } Arrays.sort(mat, (a, b) -> -(a.max - b.max)); mat = Arrays.copyOf(mat, Math.min(n, m)); io.cache.append(bf(mat, getCol(n), n, 0)).append('\n'); } public void enhance(Col mask, Col c, Col ans, int n) { for (int i = 0; i < n; i++) { ans.data[i] = Math.max(mask.get(i), c.get(i)); } } Deque<Col> cache = new ArrayDeque<>(); public Col getCol(int n) { if (cache.isEmpty()) { Col col = new Col(); col.data = new int[n]; return col; } return cache.removeFirst(); } public void destroy(Col c) { c.offset = 0; c.max = 0; cache.addLast(c); } public int bf(Col[] cols, Col mask, int n, int k) { if (k >= cols.length) { int sum = 0; for (int i = 0; i < n; i++) { sum += mask.data[i]; } return sum; } int max = 0; cols[k].offset = 0; for (int i = 0; i < n; i++) { Col c = getCol(n); enhance(mask, cols[k], c, n); max = Math.max(max, bf(cols, c, n, k + 1)); destroy(c); cols[k].turn(); } return max; } } public static class Col { int[] data; int offset; public int get(int i) { return data[(i + offset) % data.length]; } public void turn() { offset++; } int max; } public static class FastIO { public final StringBuilder cache = new StringBuilder(20 << 20); 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 << 20]; 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
1209_E1. Rotate Columns (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.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author anand.oza */ 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); E1RotateColumnsEasyVersion solver = new E1RotateColumnsEasyVersion(); solver.solve(1, in, out); out.close(); } static class E1RotateColumnsEasyVersion { public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); for (int i = 0; i < t; i++) { solve(in, out); } } private void solve(InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); int[][] a = new int[n][]; for (int i = 0; i < n; i++) { a[i] = in.readIntArray(m); } out.println(solve(n, m, a)); } private int solve(int n, int m, int[][] a) { Cell[] cells = new Cell[n * m]; for (int i = 0, index = 0; i < n; i++) { for (int j = 0; j < m; j++) { cells[index++] = new Cell(i, j, a[i][j]); if (index == cells.length) break; } } Arrays.sort(cells, Comparator.comparingInt(cell -> -cell.x)); HashSet<Integer> colset = new HashSet<>(); for (int i = 0; colset.size() < n && colset.size() < m; i++) { colset.add(cells[i].j); } ArrayList<Integer> cols = new ArrayList<>(); cols.addAll(colset); int answer = 0; for (long perm = 0; perm < pow(n, cols.size() - 1); perm++) { long p = perm; int[] offset = new int[cols.size()]; for (int col = 0; col < cols.size(); col++) { offset[col] = (int) (p % n); p /= n; } int sum = 0; for (int row = 0; row < n; row++) { int max = 0; for (int col = 0; col < cols.size(); col++) { int cur = a[(row + offset[col]) % n][cols.get(col)]; max = Math.max(max, cur); } sum += max; } answer = Math.max(answer, sum); } return answer; } private long pow(int base, int exponent) { long p = 1; for (int i = 0; i < exponent; i++) { p *= base; } return p; } private class Cell { final int i; final int j; final int x; private Cell(int i, int j, int x) { this.i = i; this.j = j; this.x = x; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] readIntArray(int n) { int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = nextInt(); } return x; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; import java.util.stream.Collectors; import java.math.*; public class E1 { static byte[] buf = new byte[1<<26]; static int bp = -1; public static void main(String[] args) throws IOException { /**/ DataInputStream in = new DataInputStream(System.in); /*/ DataInputStream in = new DataInputStream(new FileInputStream("src/e.in")); /**/ in.read(buf, 0, 1<<26); int t = nni(); for (int z = 0; z < t; z++) { int n = nni(); int m = nni(); int[][] mat = new int[n][m]; int[] rmax = new int[n]; int tot = 0; HashSet<Integer> care = new HashSet<>(); for (int i = 0; i < n; i++) { PriorityQueue<Integer> cols = new PriorityQueue<>(); for (int j = 0; j < m; j++) { mat[i][j] = nni(); cols.add(-(mat[i][j]*2000+j)); rmax[i] = Math.max(rmax[i], mat[i][j]); } tot += rmax[i]; for (int j = 0; j < Math.min(m, n); j++) care.add((-cols.poll())%2000); } List<Integer> cal = care.stream().sorted().collect(Collectors.toList()); int ret = tot; if (Math.min(m, n)==1) { System.out.println(ret); } else if (Math.min(m, n)==2) { for (int a = 0; a < cal.size(); a++) { int la = cal.get(a); for (int d = 0; d < cal.size(); d++) { if (d==a) continue; int ld = cal.get(d); for (int i = 0; i < n; i++) { int tret = 0; for (int x = 0; x < n; x++) { tret += Math.max(mat[x][ld], mat[(i+x)%n][la]); } ret = Math.max(ret, tret); } } } System.out.println(ret); } else if (Math.min(m, n)==3) { for (int a = 0; a < cal.size(); a++) { int la = cal.get(a); for (int b = a+1; b < cal.size(); b++) { int lb = cal.get(b); for (int d = 0; d < cal.size(); d++) { if (d==a) continue; if (d==b) continue; int ld = cal.get(d); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int tret = 0; for (int x = 0; x < n; x++) { tret += Math.max(mat[x][ld], Math.max(mat[(i+x)%n][la], mat[(j+x)%n][lb])); } ret = Math.max(ret, tret); } } } } } System.out.println(ret); } else if (Math.min(m, n)==4) { for (int a = 0; a < cal.size(); a++) { int la = cal.get(a); for (int b = a+1; b < cal.size(); b++) { int lb = cal.get(b); for (int c = b+1; c < cal.size(); c++) { int lc = cal.get(c); for (int d = 0; d < cal.size(); d++) { if (d==a) continue; if (d==b) continue; if (d==c) continue; int ld = cal.get(d); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { int tret = 0; for (int x = 0; x < n; x++) { tret += Math.max(mat[x][ld], Math.max(mat[(i+x)%n][la], Math.max(mat[(j+x)%n][lb], mat[(k+x)%n][lc]))); } ret = Math.max(ret, tret); } } } } } } } System.out.println(ret); } } } public static int nni() { int ret = 0; byte b = buf[++bp]; while (true) { ret = ret*10+b-'0'; b = buf[++bp]; if (b<'0'||b>'9') { while (buf[bp+1]=='\r'||buf[bp+1]=='\n'||buf[bp+1]==' ') {++bp;} break; } } return ret; } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.util.PriorityQueue; public class Main { static PrintWriter out; static InputReader ir; static void solve() { int t = ir.nextInt(); while (t-- > 0) { int n = ir.nextInt(); int m = ir.nextInt(); int[][] a = new int[n][]; for (int i = 0; i < n; i++) { a[i] = ir.nextIntArray(m); } int[][][] comx = new int[n + 1][m][2]; for (int i = 0; i < m; i++) { int[] b = new int[n]; for (int j = 0; j < n; j++) { b[j] = a[j][i]; } Arrays.sort(b); for (int j = 0; j < n; j++) { comx[j + 1][i][0] = comx[j][i][0] + b[n - 1 - j]; comx[j + 1][i][1] = i; } } int[][][] org = new int[n + 1][m][2]; for (int i = 0; i <= n; i++) for (int j = 0; j < m; j++) { for (int k = 0; k < 2; k++) { org[i][j][k] = comx[i][j][k]; } } for (int i = 1; i <= n; i++) Arrays.sort(comx[i], new Comparator<int[]>() { public int compare(int[] A, int[] B) { return A[0] - B[0]; } }); // tr(org); // tr(comx); if (n == 1) { out.println(comx[1][m - 1][0]); } else if (n == 2) { out.println(Math.max(comx[2][m - 1][0], m >= 2 ? comx[1][m - 1][0] + comx[1][m - 2][0] : 0)); } else if (n == 3) { int res = Math.max(comx[3][m - 1][0], m >= 3 ? comx[1][m - 1][0] + comx[1][m - 2][0] + comx[1][m - 3][0] : 0); if (m >= 2) { for (int i = 0; i < m; i++) { int p = comx[2][i][0]; int ma = 0; for (int j = 0; j < m; j++) { if (comx[2][i][1] == j) continue; ma = Math.max(org[1][j][0], ma); } res = Math.max(res, p + ma); } } out.println(res); } else { int res = Math.max(comx[4][m - 1][0], m >= 4 ? comx[1][m - 1][0] + comx[1][m - 2][0] + comx[1][m - 3][0] + comx[1][m - 4][0] : 0); if (m >= 2) { for (int i = 0; i < m; i++) { int p = comx[3][i][0]; int ma = 0; for (int j = 0; j < m; j++) { if (comx[3][i][1] == j) continue; ma = Math.max(org[1][j][0], ma); } res = Math.max(res, p + ma); } } if (m >= 3) { for (int i = 0; i < m; i++) { int p = comx[2][i][0]; PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); for (int j = 0; j < m; j++) { if (comx[2][i][1] == j) continue; pq.add(org[1][j][0]); } res = Math.max(res, p + pq.poll() + pq.poll()); } } if (m >= 2) { for (int i = 0; i < m; i++) { int p = 0; for (int j = 0; j < 4; j++) { p = Math.max(p, a[j][i] + a[(j + 1) % 4][i]); } int ma = 0; for (int j = 0; j < m; j++) { if (i == j) continue; for (int k = 0; k < 4; k++) { ma = Math.max(ma, a[k][j] + a[(k + 1) % 4][j]); } } res = Math.max(res, p + ma); } for (int i = 0; i < m; i++) { int p = 0; for (int j = 0; j < 4; j++) { p = Math.max(p, a[j][i] + a[(j + 2) % 4][i]); } int ma = 0; for (int j = 0; j < m; j++) { if (i == j) continue; for (int k = 0; k < 4; k++) { ma = Math.max(ma, a[k][j] + a[(k + 2) % 4][j]); } } res = Math.max(res, p + ma); } } out.println(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
1209_E1. Rotate Columns (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.FilterInputStream; import java.io.BufferedInputStream; import java.util.Random; import java.util.Comparator; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); E2RotateColumnsHardVersion solver = new E2RotateColumnsHardVersion(); int testCount = in.scanInt(); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class E2RotateColumnsHardVersion { int[][] dp; int[] cur; public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int m = in.scanInt(); int[][] ar = new int[n][m]; int[][] max = new int[m][2]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) ar[i][j] = in.scanInt(); } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { max[i][0] = Math.max(max[i][0], ar[j][i]); } max[i][1] = i; } CodeHash.shuffle(max); Arrays.sort(max, new Comparator<int[]>() { public int compare(int[] o1, int[] o2) { return -o1[0] + o2[0]; } }); dp = new int[2][1 << n]; cur = new int[1 << n]; for (int i = 0; i < Math.min(m, n); i++) { Arrays.fill(cur, 0); Arrays.fill(dp[i & 1], 0); for (int j = 0; j < 1 << n; j++) { for (int k = 0; k < n; k++) { int sum = 0; for (int l = 0; l < n; l++) { if ((j & (1 << l)) != 0) { sum += (ar[(k + l) % n][max[i][1]]); } } cur[j] = Math.max(cur[j], sum); } } for (int j = 0; j < (1 << n); j++) { for (int k = j; ; k = (k - 1) & j) { dp[i & 1][j] = Math.max(dp[i & 1][j], dp[(i - 1) & 1][k] + cur[j ^ k]); if (k == 0) break; } } } out.println(dp[Math.min(n, m) & 1 ^ 1][(1 << n) - 1]); } } static class CodeHash { public static void shuffle(int[][] ar) { Random rd = new Random(new Random().nextInt()); for (int i = 0; i < ar.length; i++) { int index = rd.nextInt(ar.length); int[] temp = ar[i]; ar[i] = ar[index]; ar[index] = temp; } } } 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
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class Main { static final long MOD = 998244353; //static final long MOD = 1000000007; static boolean[] visited; public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); int Q = sc.nextInt(); for (int q = 0; q < Q; q++) { int N = sc.nextInt(); int M = sc.nextInt(); int[][] grid = new int[N][M]; int[][] maxes = new int[M][2]; for (int i = 0; i < M; i++) maxes[i][1] = i; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { grid[i][j] = sc.nextInt(); maxes[j][0] = Math.max(maxes[j][0],grid[i][j]); } } maxes = sort(maxes); int[] keyCols = new int[Math.min(M, N)]; for (int i = 0; i < keyCols.length; i++) keyCols[i] = maxes[i][1]; int ans = 0; for (int x = 0; x < (int)Math.pow(N,N); x++) { int[] base = baseN(keyCols.length,x); int ansx = 0; for (int i = 0; i < N; i++) { int r = 0; for (int j = 0; j < keyCols.length; j++) { r = Math.max(r,grid[(i+base[j])%N][keyCols[j]]); } ansx += r; } ans = Math.max(ans,ansx); } System.out.println(ans); } } public static int[] baseN(int N, int num) { int[] ans = new int[N]; for (int i = N-1; i >= 0; i--) { int pow = (int)Math.pow(N,i); ans[i] = num/pow; num -= ans[i]*pow; } return ans; } public static int[][] sort(int[][] array) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i< array.length; i++) { int randomPosition = rgen.nextInt(array.length); int[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } Arrays.sort(array, new Comparator<int[]>() { @Override public int compare(int[] arr1, int[] arr2) { //Descending order return arr2[0]-arr1[0]; } }); return array; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class E { 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(); } static int dp[][], a[][], rows, cols; public static void solveIt() throws Exception { FastReader in = new FastReader(System.in); PrintWriter pw = new PrintWriter(System.out); int test = in.nextInt(); for (int t = 1; t <= test; t++) { rows = in.nextInt(); cols = in.nextInt(); dp = new int[cols][1 << rows]; for (int x[] : dp) Arrays.fill(x, -1); a = new int[cols][rows]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { a[j][i] = in.nextInt(); } } debug(a); pw.println(solve(0, 0)); } pw.close(); } static int solve(int pos, int mask) { if (pos >= cols) return 0; if (dp[pos][mask] != -1) return dp[pos][mask]; int res = 0; for (int i = 0; i < rows; i++) { for (int k = 0; k < (1 << rows); k++) { if ((mask & k) != 0) continue; int sum = 0; for (int bit = 0; bit < rows; bit++) { if (check(k, bit)) sum += a[pos][bit]; } res = max(res, sum + solve(pos + 1, mask | k)); } cyclicShift(pos); } return dp[pos][mask] = res; } static boolean check(int N, int pos) { return (N & (1 << pos)) != 0; } static void cyclicShift(int col) { int m = a[col].length; int last = a[col][m - 1]; for (int i = m - 1; i >= 1; i--) { a[col][i] = a[col][i - 1]; } a[col][0] = last; } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } static class FastReader { InputStream is; private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; public FastReader(InputStream is) { this.is = is; } public int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } public boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } public String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public String nextLine() { int c = skip(); StringBuilder sb = new StringBuilder(); while (!isEndOfLine(c)) { sb.appendCodePoint(c); c = readByte(); } return sb.toString(); } public int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = (num << 3) + (num << 1) + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = (num << 3) + (num << 1) + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public double nextDouble() { return Double.parseDouble(next()); } public char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } public char readChar() { return (char) skip(); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ int q=in.nextInt(); for(int i=0;i<q;i++) { out.println(work()); } out.flush(); } long mod=1000000007; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } int id[]; long work() { int n=in.nextInt(); int m=in.nextInt(); long ret=0; PriorityQueue<int[]> pq=new PriorityQueue<>(new Comparator<int[]>() { public int compare(int[] arr1,int[] arr2) { return arr1[2]-arr2[2]; } }); long sum=0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { int v=in.nextInt(); pq.add(new int[] {i,j,v}); sum+=v; if(pq.size()>6)pq.poll(); } } if(m==1)return sum; if(n<=3) { while(pq.size()>0) { int[] p=pq.poll(); if(pq.size()<n) { ret+=p[2]; } } return ret; } int[][] A=new int[6][]; for(int i=0;pq.size()>0;i++) { A[i]=pq.poll(); } for(int i=0;i<6;i++) { for(int j=i+1;j<6;j++) { for(int k=j+1;k<6;k++) { out: for(int p=k+1;p<6;p++) { int s=A[i][2]+A[j][2]+A[k][2]+A[p][2]; HashMap<Integer,ArrayList<Integer>> map=new HashMap<>(); if(map.get(A[i][1])==null) { map.put(A[i][1],new ArrayList<>()); } if(map.get(A[j][1])==null) { map.put(A[j][1],new ArrayList<>()); } if(map.get(A[k][1])==null) { map.put(A[k][1],new ArrayList<>()); } if(map.get(A[p][1])==null) { map.put(A[p][1],new ArrayList<>()); } map.get(A[i][1]).add(A[i][0]); map.get(A[j][1]).add(A[j][0]); map.get(A[k][1]).add(A[k][0]); map.get(A[p][1]).add(A[p][0]); if(map.size()!=2) { ret=Math.max(ret, s); continue; } Integer l1=null,l2=null,r1=null,r2=null; for(int key:map.keySet()) { ArrayList<Integer> list=map.get(key); if(map.get(key).size()!=2) { ret=Math.max(ret, s); continue out; } if(l1==null) { l1=list.get(0); l2=list.get(1); }else { r1=list.get(0); r2=list.get(1); } } if((Math.abs(l1-l2)==2&&Math.abs(r1-r2)==2)||(Math.abs(l1-l2)!=2&&Math.abs(r1-r2)!=2)) { ret=Math.max(ret, s); } } } } } return ret; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class E implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int t = scn.nextInt(); while(t-- > 0) { int n = scn.nextInt(), m = scn.nextInt(); int[][] arr = scn.next2DInt(n, m); int[][] col = new int[m][2]; for(int j = 0; j < m; j++) { int max = 0; for(int i = 0; i < n; i++) { max = Math.max(max, arr[i][j]); } col[j][0] = max; col[j][1] = j; } Arrays.parallelSort(col, (o1, o2) -> o2[0] - o1[0]); m = Math.min(n, m); int[][] lol = new int[n][m]; for(int j = 0; j < m; j++) { for(int i = 0; i < n; i++) { lol[i][j] = arr[i][col[j][1]]; } } int[] row = new int[n]; for(int i = 0; i < n; i++) { row[i] = lol[i][0]; } ans = 0; func(lol, 1, row); out.println(ans); } } int ans; void func(int[][] arr, int col, int[] rowM) { int n = arr.length, m = arr[0].length; if(col >= m) { int rv = 0; for(int a : rowM) { rv += a; } ans = Math.max(ans, rv); return; } int max = 0, ind = -1; for(int i = 0; i < n; i++) { if(arr[i][col] > max) { max = arr[i][col]; ind = i; } } boolean in = false; for(int r = 0; r < n; r++) { if(max <= rowM[r]) { continue; } int rot = (ind - r + n) % n; int[] need = new int[n], copy = Arrays.copyOf(rowM, n); for(int i = 0; i < n; i++) { need[i] = arr[(i + rot) % n][col]; } for(int i = 0; i < n; i++) { arr[i][col] = need[i]; copy[i] = Math.max(rowM[i], arr[i][col]); } ind = r; in = true; func(arr, col + 1, copy); } if(!in) { func(arr, col + 2, rowM); } } public void run() { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) { new Thread(null, new E(), "Main", 1 << 26).start(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); int c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } long[] shuffle(long[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); long c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } int[] uniq(int[] arr) { arr = scn.shuffle(arr); Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } long[] uniq(long[] arr) { arr = scn.shuffle(arr); Arrays.sort(arr); long[] rv = new long[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } int[] reverse(int[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } long[] reverse(long[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } int[] compress(int[] arr) { int n = arr.length; int[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } long[] compress(long[] arr) { int n = arr.length; long[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class C { static int n, m, a[][]; static int[][] memo; static Integer[] indices; static int[] getCol(int col, int shift) { int[] ans = new int[n]; for (int i = 0, j = shift; i < n; i++, j = (j + 1) % n) { ans[i] = a[j][col]; } return ans; } static int dp(int col, int msk) { if (col == n||col==m) return 0; if (memo[msk][col] != -1) return memo[msk][col]; int ans = 0; for (int shift = 0; shift < n; shift++) { int[] currCol = getCol(indices[col], shift); for (int nxtMsk = 0; nxtMsk < 1 << n; nxtMsk++) { if ((nxtMsk & msk) != msk) continue; int curr = 0; int diff = msk ^ nxtMsk; for (int i = 0; i < n; i++) if ((diff & 1 << i) != 0) curr += currCol[i]; ans = Math.max(ans, dp(col + 1, nxtMsk) + curr); } } return memo[msk][col] = ans; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int tc = sc.nextInt(); while (tc-- > 0) { n = sc.nextInt(); m = sc.nextInt(); indices = new Integer[m]; memo = new int[1 << n][m]; for (int[] x : memo) Arrays.fill(x, -1); a = new int[n][m]; int[] max = new int[m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { a[i][j] = sc.nextInt(); max[j] = Math.max(max[j], a[i][j]); } for (int j = 0; j < m; j++) { indices[j] = j; } Arrays.sort(indices, Comparator.comparingInt(i -> -max[i])); out.println(dp(0, 0)); } 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(); } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class TaskE { static int[][] transpose(int[][] a, int n, int m) { int[][] t = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { t[j][i] = a[i][j]; } } return t; } public static void main(String[] args) { FastReader in = new FastReader(System.in); // FastReader in = new FastReader(new FileInputStream("input.txt")); PrintWriter out = new PrintWriter(System.out); // PrintWriter out = new PrintWriter(new FileOutputStream("output.txt")); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[n + 1][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); a[n][j] = Math.max(a[n][j], a[i][j]); } } a = transpose(a, n, m); Arrays.sort(a, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { int max1 = 0; for (int i = 0; i < o1.length; i++) { max1 = Math.max(max1, o1[i]); } int max2 = 0; for (int i = 0; i < o2.length; i++) { max2 = Math.max(max2, o2[i]); } return max2 - max1; } }); a = transpose(a, m, n); int[] dp = new int[1 << n]; for (int i = 0; i < Math.min(n, m); i++) { int[] best = new int[1 << n]; for (int j = 1; j < (1 << n); j++) { for (int k = 0; k < n; k++) { int sum = 0; for (int l = 0; l < n; l++) { if ((j & (1 << l)) != 0) sum += a[(l + k) % n][i]; } best[j] = Math.max(best[j], sum); } } int[] dp1 = dp.clone(); for (int j = 0; j < (1 << n); j++) { for (int k = j; k > 0; k = (k - 1) & j) { dp[j] = Math.max(dp[j], dp1[k ^ j] + best[k]); } } } out.println(dp[(1 << n) - 1]); } out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } Integer nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } Double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; public class Main { public static int n, m; public static int[][] arr; public static class Item implements Comparable<Item> { int i, x; public Item(int i, int x) { this.i = i; this.x = x; } public int compareTo(Item other) { if (x == other.x) { return i - other.i; } return other.x - x; } } public static int calc(int[] cols, int k, String mask) { if (k == cols.length) { int res = 0; for (int i = 0; i < n; i++) { int max = 0; for (int j = 0; j < cols.length; j++) { int shift = mask.charAt(j) - '0'; max = Math.max(max, arr[(shift + i) % n][cols[j]]); } res += max; } return res; } else { int best = 0; for (int i = 0; i < n; i++) { best = Math.max(best, calc(cols, k + 1, mask + i)); } return best; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { n = in.nextInt(); m = in.nextInt(); arr = new int[n][m]; for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { arr[j][k] = in.nextInt(); } } Item[] max = new Item[m]; for (int j = 0; j < m; j++) { max[j] = new Item(j, 0); for (int k = 0; k < n; k++) { max[j].x = Math.max(max[j].x, arr[k][j]); } } Arrays.sort(max); int[] cols = new int[Math.min(n, m)]; for (int j = 0; j < cols.length; j++) { cols[j] = max[j].i; } System.out.println(calc(cols, 0, "")); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
//package round584; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Map; public class E1 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { for(int T = ni();T > 0;T--){ int n = ni(), m = ni(); int[][] a = new int[n][]; for(int i = 0;i < n;i++)a[i] = na(m); int[][] sss = new int[1<<n][m]; for(int i = 1;i < 1<<n;i+=2){ int[] ss = new int[m]; for(int j = 0;j < m;j++){ int cur = i; int lmax = 0; for(int sh = 0;sh < n;sh++){ int s = 0; for(int k = 0;k < n;k++){ if(cur<<~k<0){ s += a[k][j]; } } lmax = Math.max(lmax, s); cur = cur>>>1|(cur&1)<<n-1; } ss[j] = lmax; } sss[i] = ss; } ptns = new HashMap<>(); dfs(new int[n], 0, -1); int ans = 0; if(n == 4 && m >= 4){ int[] one = Arrays.copyOf(sss[1], m); Arrays.sort(one); ans = one[m-1] + one[m-2] + one[m-3] + one[m-4]; } for(int[] cs : ptns.values()){ if(cs.length == 4)continue; int[] u = new int[cs.length]; inner: do{ for(int i = 0;i < cs.length;i++){ for(int j = i+1;j < cs.length;j++){ if(u[i] == u[j])continue inner; } } int val = 0; for(int i = 0;i < cs.length;i++){ val += sss[cs[i]][u[i]]; } ans = Math.max(ans, val); }while(inc(u, m)); } out.println(ans); } } public static boolean inc(int[] a, int base) { int n = a.length; int i; for (i = n - 1; i >= 0 && a[i] == base - 1; i--) ; if (i == -1) return false; a[i]++; Arrays.fill(a, i + 1, n, 0); return true; } Map<Long, int[]> ptns = new HashMap<>(); // Set<Long> all = new HashSet<>(); void dfs(int[] a, int pos, int max) { if(pos == a.length){ int[] ptn = new int[max+1]; int n = a.length; for(int i = 0;i < n;i++){ ptn[a[i]] |= 1<<i; } for(int i = 0;i <= max;i++){ ptn[i] = ptn[i]>>>Integer.numberOfTrailingZeros(ptn[i]); } // for(int i = 0;i <= max;i++){ // int min = ptn[i]; // int k = ptn[i]; // for(int j = 0;j < 12;j++){ // int nk = k>>>1|(k&1)<<11; // k = nk; // min = Math.min(min, k); // } // ptn[i] = min; // } Arrays.sort(ptn); long h = 0; for(int v : ptn){ h= h * 1000000009 + v; } // all.add(h); ptns.put(h, ptn); return; } for(int i = 0;i <= max+1;i++){ a[pos] = i; dfs(a, pos+1, Math.max(i, max)); } } void run() throws Exception { // int n = 4, m = 100; // Random gen = new Random(); // StringBuilder sb = new StringBuilder(); // sb.append(40 + " "); // for(int rep = 0;rep < 40;rep++){ // sb.append(n + " "); // sb.append(m + " "); // for (int i = 0; i < n*m; i++) { // sb.append(gen.nextInt(100000) + " "); // } // } // 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 E1().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class r584p5 { private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter pw = new PrintWriter(System.out); private static int n, m, arr[][]; private static ArrayList<HashSet<Integer>> chls; private static void gench(){ chls.add(new HashSet<>()); chls.get(0).add(0); for(int i=1; i<(1<<n); i++){ int des = i^Integer.highestOneBit(i); HashSet<Integer> st = new HashSet<>(); for(int z : chls.get(des)){ st.add(z); st.add(z|Integer.highestOneBit(i)); } chls.add(st); } } private static void cal(){ int val[][] = new int[(1<<n)][m]; for(int j=0; j<m; j++){ val[0][j] = 0; for(int mask=1; mask<(1<<n); mask++){ int max = 0; for(int begin=0; begin<n; begin++){ int sum = 0; for(int ptr=begin, pos=0; pos<n; ptr=(ptr+1)%n, pos++){ if((mask&(1<<pos)) > 0) sum += arr[ptr][j]; } max = Math.max(max, sum); } val[mask][j] = max; } } int dp[][] = new int[(1<<n)][m]; for(int mask=0; mask<(1<<n); mask++) dp[mask][0] = val[mask][0]; for(int j=1; j<m; j++){ dp[0][j] = 0; for(int mask=1; mask<(1<<n); mask++){ dp[mask][j] = 0; for(int ch1 : chls.get(mask)){ int ch2 = mask^ch1; dp[mask][j] = Math.max(dp[mask][j], val[ch1][j]+dp[ch2][j-1]); } } } pw.println(dp[(1<<n)-1][m-1]); } private static void run()throws IOException{ StringTokenizer tk = new StringTokenizer(r.readLine()); n = Integer.parseInt(tk.nextToken()); m = Integer.parseInt(tk.nextToken()); arr = new int[n][m]; chls = new ArrayList<>(); for(int i=0; i<n; i++){ tk = new StringTokenizer(r.readLine()); for(int j=0; j<m; j++) arr[i][j] = Integer.parseInt(tk.nextToken()); } gench(); cal(); } public static void main(String args[])throws IOException{ int t = Integer.parseInt(r.readLine()); while(t-->0) run(); pw.flush(); pw.close(); } }
np
1209_E1. Rotate Columns (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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); E2RotateColumnsHardVersion solver = new E2RotateColumnsHardVersion(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class E2RotateColumnsHardVersion { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); E2RotateColumnsHardVersion.Column[] columns = new E2RotateColumnsHardVersion.Column[m]; for (int i = 0; i < columns.length; ++i) columns[i] = new E2RotateColumnsHardVersion.Column(new int[n]); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { columns[j].v[i] = in.nextInt(); if (i == n - 1) columns[j].initMax(); } } Arrays.sort(columns, (o1, o2) -> o2.max - o1.max); if (columns.length > n) columns = Arrays.copyOf(columns, n); long[] dp = new long[1 << n]; for (E2RotateColumnsHardVersion.Column c : columns) { long[] ndp = new long[1 << n]; System.arraycopy(dp, 0, ndp, 0, dp.length); for (int rot = 0; rot < n; ++rot) { long[] temp = new long[1 << n]; System.arraycopy(dp, 0, temp, 0, dp.length); for (int i = 0, pos = rot; i < n; ++i, ++pos) { if (pos >= n) pos = 0; int val = c.v[pos]; for (int j = 0; j < temp.length; ++j) { if ((j & (1 << i)) == 0) temp[j | (1 << i)] = Math.max(temp[j | (1 << i)], temp[j] + val); } } for (int i = 0; i < ndp.length; ++i) ndp[i] = Math.max(ndp[i], temp[i]); } dp = ndp; } out.println(dp[dp.length - 1]); } static class Column { int[] v; int max; public Column(int[] v) { this.v = v; } void initMax() { max = 0; for (int vv : v) max = Math.max(max, vv); } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public String next() { return nextString(); } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = pread(); while (isSpaceChar(c)) c = pread(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = pread(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class E { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok; public void go() throws IOException { StringTokenizer tok = new StringTokenizer(in.readLine()); int zzz = Integer.parseInt(tok.nextToken()); for (int zz = 0; zz < zzz; zz++) { ntok(); int n = ipar(); int m = ipar(); int[][] mat = new int[n][m]; for (int i = 0; i < n; i++) { ntok(); mat[i] = iapar(m); } long[][] dp = new long[1 << n][m+1]; for (int i = 0; i < 1 << n; i++) { dp[i][m] = -1000000000; } dp[(1 << n) - 1][m] = 0; for (int i = m-1; i >= 0; i--) { for (int e = 0; e < 1 << n; e++) { dp[e][i] = dp[e][i+1]; for (int w = 0; w < 1 << n; w++) { if ((e & w) == 0) { dp[e][i] = Math.max(dp[e][i], best(w, mat, i) + dp[e|w][i+1]); } } } } // for (long[] arr : dp) // { // out.println(Arrays.toString(arr)); // } out.println(dp[0][0]); } out.flush(); in.close(); } public long best(int mask, int[][] mat, int col) { long max = 0; for (int t = 0; t < mat.length; t++) { long sum = 0; int mk = mask; for (int i = 0; i < mat.length; i++) { if (mk % 2 == 1) { sum += mat[i][col]; } mk /= 2; } max = Math.max(max, sum); cycle(mat, col); } return max; } public void cycle(int[][] mat, int col) { int temp = mat[0][col]; for (int i = 0; i < mat.length-1; i++) { mat[i][col] = mat[i+1][col]; } mat[mat.length-1][col] = temp; } public void ntok() throws IOException { tok = new StringTokenizer(in.readLine()); } public int ipar() { return Integer.parseInt(tok.nextToken()); } public int[] iapar(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ipar(); } return arr; } public long lpar() { return Long.parseLong(tok.nextToken()); } public long[] lapar(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = lpar(); } return arr; } public double dpar() { return Double.parseDouble(tok.nextToken()); } public String spar() { return tok.nextToken(); } public static void main(String[] args) throws IOException { new E().go(); } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.IntStream; public class Test { static PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static int readInt() { int ans = 0; boolean neg = false; try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (c == '-') { start = true; neg = true; continue; } else if (c >= '0' && c <= '9') { start = true; ans = ans * 10 + c - '0'; } else if (start) break; } } catch (IOException e) { } return neg ? -ans : ans; } static long readLong() { long ans = 0; boolean neg = false; try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (c == '-') { start = true; neg = true; continue; } else if (c >= '0' && c <= '9') { start = true; ans = ans * 10 + c - '0'; } else if (start) break; } } catch (IOException e) { } return neg ? -ans : ans; } static String readLine() { StringBuilder b = new StringBuilder(); try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (Character.isLetterOrDigit(c)) { start = true; b.append((char) c); } else if (start) break; } } catch (IOException e) { } return b.toString(); } public static void main(String[] args) { Test te = new Test(); te.start(); writer.flush(); } void start() { int t = readInt(); while (t-- > 0) { int n = readInt(), m = readInt(); int[][] a = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = readInt(); int[] dp = new int[1<<n]; Arrays.fill(dp, -1); dp[0] = 0; for (int c = 0; c < m; c++) { for (int i = (1 << n) - 1; i >= 0; i--) { int u = (1 << n) - 1 - i; int p = u; if (dp[i] >= 0) while (p > 0) { for (int r = 0; r < n; r++) { int sum = 0; for (int j = 0; j < n; j++) if (((p >> j) & 1) != 0) sum += a[(j + r) % n][c]; dp[i | p] = Math.max(dp[i | p], dp[i] + sum); } p = (p - 1) & u; } } } writer.println(dp[(1<<n) - 1]); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; public class E1 { public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(System.in); FastPrinter out = new FastPrinter(System.out); int T = sc.nextInt(); for (int i = 0; i < T; i++) { new E1().run(sc, out); } out.close(); } int N, M, arr[][], ans; public void run(FastScanner sc, FastPrinter out) throws Exception { N = sc.nextInt(); M = sc.nextInt(); arr = new int[N][M]; int[][] nums = new int[N * M][3]; int count = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { int v = sc.nextInt(); arr[i][j] = v; nums[count++] = new int[] { v, j, i }; } } Arrays.sort(nums, new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { return b[0] - a[0]; } }); // System.err.println(Arrays.deepToString(arr)); // System.err.println(Arrays.deepToString(nums)); if (N == 4 && M > 1) { int colCount = 0; HashMap<Integer, Integer> map = new HashMap<>(); // I believe you only need top 6 numbers? for (int i = 0; i < 8; i++) { int col = nums[i][1]; Integer newCol = map.get(col); if (newCol == null) { map.put(col, colCount++); } } int[][] arr = new int[N][colCount]; for (int i = 0; i < 8; i++) { int val = nums[i][0]; int col = map.get(nums[i][1]); int row = nums[i][2]; arr[row][col] = val; } // System.err.println(Arrays.deepToString(arr)); solve(0, arr); } else { ans = 0; for (int i = 0; i < N; i++) { ans += nums[i][0]; } } System.out.println(ans); } private void solve(int index, int[][] arr) { if (index == arr[0].length) { int temp = 0; for (int i = 0; i < arr.length; i++) { int m = 0; for (int j = 0; j < arr[i].length; j++) { m = Math.max(m, arr[i][j]); } temp += m; } ans = Math.max(temp, ans); } else { for (int t = 0; t < N; t++) { int v = arr[0][index]; for (int i = 0; i < N - 1; i++) { arr[i][index] = arr[i + 1][index]; } arr[N - 1][index] = v; solve(index + 1, arr); } } } static class FastScanner { final private int BUFFER_SIZE = 1 << 10; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public FastScanner() { this(System.in); } public FastScanner(InputStream stream) { din = new DataInputStream(stream); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastScanner(String fileName) throws IOException { Path p = Paths.get(fileName); buffer = Files.readAllBytes(p); bytesRead = buffer.length; } int[] nextIntArray(int N) throws IOException { int[] arr = new int[N]; for (int i = 0; i < N; i++) { arr[i] = nextInt(); } return arr; } String nextLine() throws IOException { int c = read(); while (c != -1 && isEndline(c)) c = read(); if (c == -1) { return null; } StringBuilder res = new StringBuilder(); do { if (c >= 0) { res.appendCodePoint(c); } c = read(); } while (!isEndline(c)); return res.toString(); } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } String next() throws Exception { int c = readOutSpaces(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { if (din == null) { bufferPointer = 0; bytesRead = -1; } else { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); } if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } private int readOutSpaces() throws IOException { while (true) { if (bufferPointer == bytesRead) fillBuffer(); int c = buffer[bufferPointer++]; if (!isSpaceChar(c)) { return c; } } } public void close() throws IOException { if (din == null) return; din.close(); } public int[][] readGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception { int[][] adj = new int[N][]; int[] numNodes = new int[N]; int[][] input = new int[M][2]; for (int i = 0; i < M; i++) { int a = nextInt(); int b = nextInt(); if (zeroIndexed) { a--; b--; } input[i][0] = a; input[i][1] = b; numNodes[a]++; if (bidirectional) numNodes[b]++; } for (int i = 0; i < N; i++) { adj[i] = new int[numNodes[i]]; numNodes[i] = 0; } for (int i = 0; i < M; i++) { int a = input[i][0]; int b = input[i][1]; adj[a][numNodes[a]++] = b; if (bidirectional) adj[b][numNodes[b]++] = a; } return adj; } public int[][][] readWeightedGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception { int[][][] adj = new int[N][][]; int[] numNodes = new int[N]; int[][] input = new int[M][3]; for (int i = 0; i < M; i++) { int a = nextInt(); int b = nextInt(); if (zeroIndexed) { a--; b--; } int d = nextInt(); input[i][0] = a; input[i][1] = b; input[i][2] = d; numNodes[a]++; if (bidirectional) numNodes[b]++; } for (int i = 0; i < N; i++) { adj[i] = new int[numNodes[i]][2]; numNodes[i] = 0; } for (int i = 0; i < M; i++) { int a = input[i][0]; int b = input[i][1]; int d = input[i][2]; adj[a][numNodes[a]][0] = b; adj[a][numNodes[a]][1] = d; numNodes[a]++; if (bidirectional) { adj[b][numNodes[b]][0] = a; adj[b][numNodes[b]][1] = d; numNodes[b]++; } } return adj; } } static class FastPrinter { static final char ENDL = '\n'; StringBuilder buf; PrintWriter pw; public FastPrinter(OutputStream stream) { buf = new StringBuilder(); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))); } public FastPrinter(String fileName) throws Exception { buf = new StringBuilder(); pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); } public FastPrinter(StringBuilder buf) { this.buf = buf; } public void print(int a) { buf.append(a); } public void print(long a) { buf.append(a); } public void print(char a) { buf.append(a); } public void print(char[] a) { buf.append(a); } public void print(double a) { buf.append(a); } public void print(String a) { buf.append(a); } public void print(Object a) { buf.append(a.toString()); } public void println() { buf.append(ENDL); } public void println(int a) { buf.append(a); buf.append(ENDL); } public void println(long a) { buf.append(a); buf.append(ENDL); } public void println(char a) { buf.append(a); buf.append(ENDL); } public void println(char[] a) { buf.append(a); buf.append(ENDL); } public void println(double a) { buf.append(a); buf.append(ENDL); } public void println(String a) { buf.append(a); buf.append(ENDL); } public void println(Object a) { buf.append(a.toString()); buf.append(ENDL); } public void printf(String format, Object... args) { buf.append(String.format(format, args)); } public void close() { pw.print(buf); pw.close(); } public void flush() { pw.print(buf); pw.flush(); buf.setLength(0); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.IntStream; public class Test { static PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static int readInt() { int ans = 0; boolean neg = false; try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (c == '-') { start = true; neg = true; continue; } else if (c >= '0' && c <= '9') { start = true; ans = ans * 10 + c - '0'; } else if (start) break; } } catch (IOException e) { } return neg ? -ans : ans; } static long readLong() { long ans = 0; boolean neg = false; try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (c == '-') { start = true; neg = true; continue; } else if (c >= '0' && c <= '9') { start = true; ans = ans * 10 + c - '0'; } else if (start) break; } } catch (IOException e) { } return neg ? -ans : ans; } static String readLine() { StringBuilder b = new StringBuilder(); try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (Character.isLetterOrDigit(c)) { start = true; b.append((char) c); } else if (start) break; } } catch (IOException e) { } return b.toString(); } public static void main(String[] args) { Test te = new Test(); te.start(); writer.flush(); } void start() { int t = readInt(); while (t-- > 0) { int n = readInt(), m = readInt(); int[][] a = new int[n][m]; int[][] e = new int[n*m][]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { a[i][j] = readInt(); e[i*m+j] = new int[]{a[i][j], j}; } Arrays.sort(e, (x, y) -> x[0] == y[0] ? Integer.compare(x[1], y[1]) : Integer.compare(y[0], x[0])); Set<Integer> cols = new HashSet<>(); for (int[] x : e) { cols.add(x[1]); if (cols.size() >= n) break; } int[] dp = new int[1<<n]; Arrays.fill(dp, -1); dp[0] = 0; for (int c : cols) { for (int i = (1 << n) - 1; i >= 0; i--) { int u = (1 << n) - 1 - i; int p = u; if (dp[i] >= 0) while (p > 0) { for (int r = 0; r < n; r++) { int sum = 0; for (int j = 0; j < n; j++) if (((p >> j) & 1) != 0) sum += a[(j + r) % n][c]; dp[i | p] = Math.max(dp[i | p], dp[i] + sum); } p = (p - 1) & u; } } } writer.println(dp[(1<<n) - 1]); } } }
np
1209_E1. Rotate Columns (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.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author null */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, Input in, PrintWriter out) { try { int kt = in.readInt(); for (int nt = 0; nt < kt; nt++) { int n = in.readInt(); int m = in.readInt(); int[][] a = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[j][i] = in.readInt(); } } Arrays.sort(a, (x, y) -> { int xMax = 0; for (int i = 0; i < x.length; i++) { xMax = Math.max(xMax, x[i]); } int yMax = 0; for (int i = 0; i < y.length; i++) { yMax = Math.max(yMax, y[i]); } return Integer.compare(-xMax, -yMax); }); int ans = 0; int[] s = new int[4]; for (s[0] = 0; s[0] < n; s[0]++) { for (s[1] = 0; s[1] < n; s[1]++) { for (s[2] = 0; s[2] < n; s[2]++) { for (s[3] = 0; s[3] < n; s[3]++) { int cur = 0; for (int i = 0; i < n; i++) { int max = 0; for (int j = 0; j < Math.min(m, n); j++) { max = Math.max(max, a[j][(i + s[j]) % n]); } cur += max; } ans = Math.max(cur, ans); } } } } out.println(ans); } } catch (Exception e) { throw new RuntimeException(e); } } } static class Input { public final BufferedReader reader; private String line = ""; private int pos = 0; public Input(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private boolean isSpace(char ch) { return ch <= 32; } public String readWord() throws IOException { skip(); int start = pos; while (pos < line.length() && !isSpace(line.charAt(pos))) { pos++; } return line.substring(start, pos); } public int readInt() throws IOException { return Integer.parseInt(readWord()); } private void skip() throws IOException { while (true) { if (pos >= line.length()) { line = reader.readLine(); pos = 0; } while (pos < line.length() && isSpace(line.charAt(pos))) { pos++; } if (pos < line.length()) { return; } } } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class C { static int n, m, a[][]; static int[][] memo; static int[] getCol(int col, int shift) { int[] ans = new int[n]; for (int i = 0, j = shift; i < n; i++, j = (j + 1) % n) { ans[i] = a[j][col]; } return ans; } static int dp(int col, int msk) { if (col == m) return 0; if (memo[msk][col] != -1) return memo[msk][col]; int ans = 0; for (int shift = 0; shift < n; shift++) { int[] currCol = getCol(col, shift); for (int nxtMsk = 0; nxtMsk < 1 << n; nxtMsk++) { if ((nxtMsk & msk) != msk) continue; int curr = 0; int diff = msk ^ nxtMsk; for (int i = 0; i < n; i++) if ((diff & 1 << i) != 0) curr += currCol[i]; ans = Math.max(ans, dp(col + 1, nxtMsk) + curr); } } return memo[msk][col] = ans; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int tc = sc.nextInt(); while (tc-- > 0) { n = sc.nextInt(); m = sc.nextInt(); memo = new int[1 << n][m]; for (int[] x : memo) Arrays.fill(x, -1); a = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = sc.nextInt(); out.println(dp(0, 0)); } 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(); } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class Main { static int inf = (int) 1e9 + 7; static int n, m, a[][]; static ArrayList<Integer> used; static int num[]; static int ans; static void rec(int id) { if (id == used.size()) { check(); return; } for(int i = 0;i < n;i++) { num[id] = i; rec(id + 1); } } static void check() { int new_ans = 0; for(int i = 0;i < n;i++) { int max = 0; for(int j = 0;j < used.size();j++) { max = Math.max(max, a[(i + num[j]) % n][used.get(j)]); } new_ans += max; } ans = Math.max(ans, new_ans); } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); int test = nextInt(); while(test-- > 0) { n = nextInt(); m = nextInt(); a = new int [n][m]; for(int i = 0;i < n;i++) { for(int j = 0;j < m;j++) a[i][j] = nextInt(); } used = new ArrayList<>(); num = new int [n * m]; ans = 0; pair b[] = new pair[n * m]; for(int i = 0;i < n;i++) { for(int j = 0;j < m;j++) { b[i * m + j] = new pair(a[i][j], j); } } Arrays.sort(b, new pair()); for(int i = b.length - 1;i >= Math.max(0, b.length - 5);i--) { int v = b[i].y; boolean bad = false; for(int j = 0;j < used.size();j++) if (used.get(j) == v) bad = true; if (!bad) used.add(v); } rec(0); pw.println(ans); } pw.close(); } static BufferedReader br; static StringTokenizer st = new StringTokenizer(""); static PrintWriter pw; static String next() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } class pair implements Comparator<pair>{ int x, y; pair(int x, int y) { this.x = x; this.y = y; } pair() {} @Override public int compare(pair o1, pair o2) { return Integer.compare(o1.x, o2.x); } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author ilyakor */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE1 solver = new TaskE1(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) { solver.solve(i, in, out); } out.close(); } static class TaskE1 { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[][] d = new int[2][1 << n]; int[] buf = new int[1 << n]; int[][] a = new int[m][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { a[j][i] = in.nextInt(); } } for (int i = 0; i < m; ++i) { int[] prev = d[i % 2], nx = d[(i + 1) % 2]; for (int shift = 0; shift < n; ++shift) { int[] b = new int[n]; for (int j = 0; j < n; ++j) { b[j] = a[i][(j + shift) % n]; } System.arraycopy(prev, 0, buf, 0, prev.length); for (int mask = 0; mask < (1 << n); ++mask) { int val0 = buf[mask]; for (int j = 0; j < n; ++j) { if ((mask >> j) % 2 == 0) { int val = val0 + b[j]; int nm = mask ^ (1 << j); if (val > buf[nm]) { buf[nm] = val; } } } } for (int mask = 0; mask < (1 << n); ++mask) { if (nx[mask] < buf[mask]) { nx[mask] = buf[mask]; } } } } out.printLine(d[m % 2][(1 << n) - 1]); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) { return -1; } } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public String nextToken() { int c = readSkipSpace(); StringBuilder sb = new StringBuilder(); while (!isSpace(c)) { sb.append((char) c); c = read(); } return sb.toString(); } public String next() { return nextToken(); } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
//package cf584d12; import java.io.*; import java.util.*; import static java.lang.Math.*; public class E { public static void main(String[] args) { MyScanner sc = new MyScanner(); int t = sc.nextInt(); for(int w = 0; w < t; w++) { int n = sc.nextInt(), m = sc.nextInt(); TreeSet<X> set = new TreeSet<X>(); int[][] grid = new int[n][m]; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) { grid[i][j] = sc.nextInt(); set.add(new X(i, j, grid[i][j])); } Y[] top4 = new Y[n]; int sum = 0; for(int i = 0; i < n; i++) { top4[i] = new Y(set.pollLast()); sum += top4[i].a; } Arrays.sort(top4); HashSet<String> strs = new HashSet<String>(); AAA[] sss = new AAA[n]; boolean[] used = new boolean[n]; if(n == 4) { for(int i = 0; i < 4; i++) { int max = -1, jj = -1; for(int j = 0; j < 4; j++) { if(!used[j] && top4[j].a > max) { max = top4[j].a; jj = j; } } used[jj] = true; sss[i] = new AAA(max, jj); } for(int i = 0; i < n; i++) strs.add(top4[i].i + " " + top4[i].j); } int ans = sum; if(n == 4 && top4[0].j == top4[1].j && top4[2].j == top4[3].j && top4[0].j != top4[2].j) { if(two(top4[0], top4[1]) != two(top4[2], top4[3])) { ans = 0; int oneCol = two(top4[0], top4[1]) ? top4[2].j : top4[0].j; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if(!strs.contains(i + " " + j)){ int no = -1; for(int k = 0; k < 4; k++) if(j == oneCol && top4[k].j == oneCol && two(top4[k], new Y(new X(i, j, 0)))) no = k; ans = max(ans, sum - sss[no == sss[3].i ? 2 : 3].a + grid[i][j]); } } } out.println(ans); } out.close(); } static class AAA { int a, i; public AAA(int A, int I) { a = A; i = I; } } static boolean two(Y y1, Y y2) { return (y1.i - y2.i + 4) % 4 == 2; } static class Y implements Comparable<Y> { int i, j, a; public Y(X x) { i = x.i; j = x.j; a = x.a; } public int compareTo(Y x) { if(j == x.j) return i - x.i; return j - x.j; } } static class X implements Comparable<X> { int i, j, a; public X(int I, int J, int A) { i = I; j = J; a = A; } public int compareTo(X x) { if(a == x.a && i == x.i) return j - x.j; else if(a == x.a) return i - x.i; return a - x.a; } } public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static class MyScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; 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
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main2 { static long mod = 998244353; static FastScanner scanner; static StringBuilder result = new StringBuilder(); public static void main(String[] args) { scanner = new FastScanner(); int t = scanner.nextInt(); for (int i = 0; i < t; i++) { solve(); result.append("\n"); } System.out.print(result.toString()); } static void solve() { int n = scanner.nextInt(); int m = scanner.nextInt(); PriorityQueue<WithIdx2> queue = new PriorityQueue<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { queue.add(new WithIdx2(scanner.nextInt(), i, j)); } } if (n <= 3) { int res = 0; for (int k = 0; k < n; k++) { res += queue.poll().val; } result.append(res); } else { List<WithIdx2> a = new ArrayList<>(); for (int i = 0; i < 9; i++) { if (!queue.isEmpty()) a.add(queue.poll()); } int[] offsets = new int[m]; best = -1; Arrays.fill(offsets, -100); put(0, a, offsets, new int[4]); result.append(best); } } static int best = -1; static void put(int current, List<WithIdx2> vals, int[] offsets, int[] rows) { if (current == vals.size()) { for (int i = 0; i < rows.length; i++) if (rows[i] == 0) return; int sum = IntStream.of(rows).sum(); best = Math.max(best, sum); return; } for (int row = 0; row < 4; row++) { if (rows[row] == 0) { WithIdx2 c = vals.get(current); if (offsets[c.y] == -100) { rows[row] = c.val; offsets[c.y] = row - c.x; put(current + 1, vals, offsets, rows); rows[row] = 0; offsets[c.y] = -100; } else { int bind = c.x + offsets[c.y]; if (bind < 0) bind += 4; if (bind >= 4) bind -= 4; if (row == bind) { rows[row] = c.val; put(current + 1, vals, offsets, rows); rows[row] = 0; } } } } put(current + 1, vals, offsets, rows); } static class WithIdx2 implements Comparable<WithIdx2>{ int x, y, val; public WithIdx2(int val, int x, int y) { this.val = val; this.x = x; this.y = y; } @Override public int compareTo(WithIdx2 o) { return -Integer.compare(val, o.val); } } static class WithIdx implements Comparable<WithIdx>{ int val, idx; public WithIdx(int val, int idx) { this.val = val; this.idx = idx; } @Override public int compareTo(WithIdx o) { 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; } } } /* 1 4 2 5 7 6 2 2 5 3 6 */
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.stream.IntStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.util.stream.Stream; import java.nio.charset.Charset; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); E1RotateColumnsEasyVersion solver = new E1RotateColumnsEasyVersion(); solver.solve(1, in, out); out.close(); } static class E1RotateColumnsEasyVersion { public void solve(int testNumber, LightScanner in, LightWriter out) { // out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP); int testCases = in.ints(); for (int testCase = 0; testCase < testCases; testCase++) { int n = in.ints(), m = in.ints(); int pow = 1; for (int i = 0; i < n; i++) pow *= n; int[][] a = in.ints(n, m); E1RotateColumnsEasyVersion.P[] columns = new E1RotateColumnsEasyVersion.P[m]; for (int i = 0; i < m; i++) { int max = 0; for (int j = 0; j < n; j++) max = Math.max(max, a[j][i]); columns[i] = new E1RotateColumnsEasyVersion.P(i, max); } IntroSort.sort(columns, Comparator.comparing(column -> -column.m)); int ans = 0; for (int i = 0; i < pow; i++) { int[] res = new int[n]; int t = i; for (int j = 0; j < Math.min(n, m); j++) { int shift = t % n; t /= n; for (int k = 0; k < n; k++) { res[(k + shift) % n] = Math.max(res[(k + shift) % n], a[k][columns[j].i]); } } int sum = 0; for (int j = 0; j < n; j++) { sum += res[j]; } ans = Math.max(ans, sum); } out.ans(ans).ln(); } } private static class P { int i; int m; P(int i, int m) { this.i = i; this.m = m; } } } static class InsertionSort { private InsertionSort() { } static <T> void sort(T[] a, int low, int high, Comparator<? super T> comparator) { for (int i = low; i < high; i++) { for (int j = i; j > low && comparator.compare(a[j - 1], a[j]) > 0; j--) { ArrayUtil.swap(a, j - 1, j); } } } } static class HeapSort { private HeapSort() { } private static <T> void heapfy(T[] a, int low, int high, int i, T val, Comparator<? super T> comparator) { int child = 2 * i - low + 1; while (child < high) { if (child + 1 < high && comparator.compare(a[child], a[child + 1]) < 0) { child++; } if (comparator.compare(val, a[child]) >= 0) { break; } a[i] = a[child]; i = child; child = 2 * i - low + 1; } a[i] = val; } static <T> void sort(T[] a, int low, int high, Comparator<T> comparator) { for (int p = (high + low) / 2 - 1; p >= low; p--) { heapfy(a, low, high, p, a[p], comparator); } while (high > low) { high--; T pval = a[high]; a[high] = a[low]; heapfy(a, low, high, low, pval, comparator); } } } static class QuickSort { private QuickSort() { } private static <T> void med(T[] a, int low, int x, int y, int z, Comparator<? super T> comparator) { if (comparator.compare(a[z], a[x]) < 0) { ArrayUtil.swap(a, low, x); } else if (comparator.compare(a[y], a[z]) < 0) { ArrayUtil.swap(a, low, y); } else { ArrayUtil.swap(a, low, z); } } static <T> int step(T[] a, int low, int high, Comparator<? super T> comparator) { int x = low + 1, y = low + (high - low) / 2, z = high - 1; if (comparator.compare(a[x], a[y]) < 0) { med(a, low, x, y, z, comparator); } else { med(a, low, y, x, z, comparator); } int lb = low + 1, ub = high; while (true) { while (comparator.compare(a[lb], a[low]) < 0) { lb++; } ub--; while (comparator.compare(a[low], a[ub]) < 0) { ub--; } if (lb >= ub) { return lb; } ArrayUtil.swap(a, lb, ub); lb++; } } } static final class BitMath { private BitMath() { } public static int count(int v) { v = (v & 0x55555555) + ((v >> 1) & 0x55555555); v = (v & 0x33333333) + ((v >> 2) & 0x33333333); v = (v & 0x0f0f0f0f) + ((v >> 4) & 0x0f0f0f0f); v = (v & 0x00ff00ff) + ((v >> 8) & 0x00ff00ff); v = (v & 0x0000ffff) + ((v >> 16) & 0x0000ffff); return v; } public static int msb(int v) { if (v == 0) { throw new IllegalArgumentException("Bit not found"); } v |= (v >> 1); v |= (v >> 2); v |= (v >> 4); v |= (v >> 8); v |= (v >> 16); return count(v) - 1; } } static interface Verified { } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset()))); } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ans(String s) { if (!breaked) { print(' '); } return print(s); } public LightWriter ans(int i) { return ans(Integer.toString(i)); } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } } static class IntroSort { private static int INSERTIONSORT_THRESHOLD = 16; private IntroSort() { } static <T> void sort(T[] a, int low, int high, int maxDepth, Comparator<T> comparator) { while (high - low > INSERTIONSORT_THRESHOLD) { if (maxDepth-- == 0) { HeapSort.sort(a, low, high, comparator); return; } int cut = QuickSort.step(a, low, high, comparator); sort(a, cut, high, maxDepth, comparator); high = cut; } InsertionSort.sort(a, low, high, comparator); } public static <T> void sort(T[] a, Comparator<T> comparator) { if (a.length <= INSERTIONSORT_THRESHOLD) { InsertionSort.sort(a, 0, a.length, comparator); } else { sort(a, 0, a.length, 2 * BitMath.msb(a.length), comparator); } } } static final class ArrayUtil { private ArrayUtil() { } public static <T> void swap(T[] a, int x, int y) { T t = a[x]; a[x] = a[y]; a[y] = t; } } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public int ints() { return Integer.parseInt(string()); } public int[] ints(int length) { return IntStream.range(0, length).map(x -> ints()).toArray(); } public int[][] ints(int height, int width) { return IntStream.range(0, height).mapToObj(x -> ints(width)).toArray(int[][]::new); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; import java.io.*; /* */ public class e1 { static int n; static int m; static int[][] mat; public static void main(String[] args){ JS scan = new JS(); PrintWriter out = new PrintWriter(System.out); int t = scan.nextInt(); for(int q = 1; q <= t; q++){ ans = 0; n = scan.nextInt(); m = scan.nextInt(); mat = new int[n][m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ mat[i][j] = scan.nextInt(); } } int[] max = new int[m]; PriorityQueue<Item> pq = new PriorityQueue<Item>(); for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ max[i] = Math.max(max[i], mat[j][i]); } pq.add(new Item(i, max[i])); } ArrayList<Item> guys = new ArrayList<Item>(); while(!pq.isEmpty() && guys.size() < 8){ Item tt = pq.poll(); guys.add(tt); } perm(guys, 0, new int[guys.size()]); out.println(ans); } out.flush(); } static int ans = 0; static void perm(ArrayList<Item> guys, int me, int[] shift){ if(me == guys.size()){ // System.out.println(Arrays.toString(shift)); int res = 0; int[] best = new int[n]; for(int j = 0; j < guys.size(); j++){ Item g = guys.get(j); int pp = g.a; for(int i = 0; i < n; i++){ best[(i+shift[j])%n] = Math.max(best[(i+shift[j])%n], mat[i][pp]); } } for(int i = 0; i < n; i++) res += best[i]; ans = Math.max(res, ans); return; } for(int i = 0; i < n; i++){ shift[me] = i; perm(guys, me+1, shift); } } static class Item implements Comparable<Item>{ int a; int b; public Item(int a, int b){ this.a = a; this.b = b; } public int compareTo(Item o){ return o.b-this.b; } } static class JS{ public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public JS() { in = new BufferedInputStream(System.in, BS); } public JS(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar(){ 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 long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } } }
np
1209_E1. Rotate Columns (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); TaskE1 solver = new TaskE1(); solver.solve(1, in, out); out.close(); } static class TaskE1 { int n; int m; int[][] map; int[][] dp; int two(int idx) { return 1 << idx; } boolean contain(int mask, int idx) { return (mask & two(idx)) > 0; } int best(int mask, int col) { int res = 0; for (int rot = 0; rot < n; rot++) { int sum = 0; for (int i = 0; i < n; i++) { int curRow = (rot + i) % n; if (contain(mask, curRow)) { sum += map[i][col]; } } res = Math.max(res, sum); } return res; } int rec(int col, int used) { if (col == m) return 0; int res = dp[col][used]; if (res != -1) return res; res = 0; for (int mask = 0; mask < two(n); mask++) if ((mask & used) == 0) { res = Math.max(res, rec(col + 1, used | mask) + best(mask, col)); } dp[col][used] = res; return res; } public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); for (int test = 0; test < t; test++) { n = in.nextInt(); m = in.nextInt(); map = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { map[i][j] = in.nextInt(); } } dp = new int[m][1 << n]; for (int[] aux : dp) Arrays.fill(aux, -1); int ans = rec(0, 0); 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
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class Main{ static int[][]memo; static int n,m,in[][]; static int dp(int col,int maxRowMask) { if(col>=m)return 0; if(memo[col][maxRowMask]!=-1)return memo[col][maxRowMask]; int ans=0; for(int colMask=0;colMask<(1<<n);colMask++) { int sum=0; for(int i=0;i<n;i++) { if(((colMask>>i)&1)!=0) { sum+=in[i][col]; } } int curMask=colMask; for(int cyclicShift=0;cyclicShift<n;cyclicShift++) { if((curMask&maxRowMask)!=0) {//some row has max value already determined int lastBit=curMask&1; curMask>>=1; curMask|=(lastBit<<(n-1)); continue; } ans=Math.max(ans, sum+dp(col+1, maxRowMask|curMask)); int lastBit=curMask&1; curMask>>=1; curMask|=(lastBit<<(n-1)); } } return memo[col][maxRowMask]=ans; } public static void main(String[] args) throws Exception{ pw=new PrintWriter(System.out); sc = new MScanner(System.in); int tc=sc.nextInt(); while(tc-->0) { n=sc.nextInt();m=sc.nextInt(); in=new int[n][m]; for(int i=0;i<n;i++)in[i]=sc.intArr(m); memo=new int[m][1<<n]; for(int i=0;i<m;i++)Arrays.fill(memo[i], -1); pw.println(dp(0, 0)); } pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.System.exit; import static java.util.Arrays.fill; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class E { static void solve() throws Exception { int tests = scanInt(); // int tests = 40; for (int test = 0; test < tests; test++) { int n = scanInt(), m = scanInt(), a[][] = new int[n][m]; // int n = 12, m = 2000, a[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = scanInt(); } } int bestCols[] = new int[min(m, n)]; for (int i = 0; i < bestCols.length; i++) { bestCols[i] = i; } if (m > n) { int bestColMax[] = new int[n]; for (int i = 0; i < n; i++) { int cmax = 0; for (int j = 0; j < n; j++) { cmax = max(cmax, a[j][i]); } bestColMax[i] = cmax; } for (int i = n; i < m; i++) { int cmax = 0; for (int j = 0; j < n; j++) { cmax = max(cmax, a[j][i]); } int minBC = 0, minBCM = Integer.MAX_VALUE; for (int j = 0; j < n; j++) { if (bestColMax[j] < minBCM) { minBC = j; minBCM = bestColMax[j]; } } if (cmax > minBCM) { bestCols[minBC] = i; bestColMax[minBC] = cmax; } } } int dyn[] = new int[1 << n], dynNext[] = new int[1 << n], sums[] = new int[1 << n], csums[] = new int[1 << n]; for (int i: bestCols) { fill(dynNext, 0); fill(sums, 0); for (int j = 0; j < n; j++) { for (int k = 1, bit = 0; k < 1 << n; k++) { if (k == 1 << (bit + 1)) { ++bit; } sums[k] = max(sums[k], csums[k] = csums[k ^ (1 << bit)] + a[(bit + j) % n][i]); } } for (int mask1 = 0; mask1 < 1 << n; mask1++) { int cdyn = dynNext[mask1]; for (int mask2 = mask1;; mask2 = (mask2 - 1) & mask1) { cdyn = max(cdyn, dyn[mask2] + sums[mask1 ^ mask2]); if (mask2 == 0) { break; } } dynNext[mask1] = cdyn; } int t[] = dyn; dyn = dynNext; dynNext = t; } out.println(dyn[(1 << n) - 1]); } } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
np
1209_E1. Rotate Columns (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; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE1 solver = new TaskE1(); solver.solve(1, in, out); out.close(); } static class TaskE1 { public void solve(int testNumber, FastScanner in, PrintWriter out) { int numTests = in.nextInt(); for (int test = 0; test < numTests; test++) { int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); } } int[] d = new int[1 << n]; int[] nd = new int[1 << n]; for (int j = 0; j < m; j++) { System.arraycopy(d, 0, nd, 0, d.length); for (int mask = 0; mask < 1 << n; mask++) { for (int submask = mask; submask > 0; submask = (submask - 1) & mask) { for (int shift = 0; shift < n; shift++) { int sum = 0; for (int i = 0; i < n; i++) { if ((submask & (1 << i)) > 0) { sum += a[(i + shift) % n][j]; } } nd[mask] = Math.max(nd[mask], d[mask ^ submask] + sum); } } } int[] t = d; d = nd; nd = t; } int ans = 0; for (int x : d) { ans = Math.max(ans, x); } out.println(ans); } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { static ArrayList<Integer> cols; static int ans, n, a[][]; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int tc = sc.nextInt(); while (tc-- > 0) { ans = 0; n = sc.nextInt(); int m = sc.nextInt(); boolean[] taken = new boolean[m]; PriorityQueue<Pair> pq = new PriorityQueue<>(); a = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int cur = sc.nextInt(); pq.add(new Pair(i, j, cur)); a[i][j] = cur; } cols = new ArrayList<>(); while (!pq.isEmpty() && cols.size() < 8) { Pair cur = pq.remove(); if (!taken[cur.j]) cols.add(cur.j); taken[cur.j] = true; } solve(0,new int [cols.size()]); out.println(ans); } out.flush(); out.close(); } static void solve(int i, int[] p) { if (i == cols.size()) { int[] max = new int[n]; for (int k = 0; k < cols.size(); k++) { int j = cols.get(k); for (int ii = 0; ii < n; ii++) { int idx = (ii + p[k]) % n; max[idx] = Math.max(max[idx], a[ii][j]); } } int poss = 0; for (int x : max) poss += x; ans = Math.max(ans, poss); return; } for (int j = 0; j < n; j++) { p[i] = j; solve(i + 1, p); } } static class Pair implements Comparable<Pair> { int i, j, val; public Pair(int i, int j, int val) { this.i = i; this.j = j; this.val = val; } @Override public int compareTo(Pair o) { return o.val - val; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
np
1209_E1. Rotate Columns (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{} void solve(int TC)throws Exception{ int n = ni(), m = ni(); long[][] a = new long[n][m]; long[] col = new long[m]; for(int i = 0; i< n; i++){ for(int j = 0; j< m; j++){ a[i][j] = nl(); col[j] = Math.max(a[i][j], col[j]); } } Integer[] p = new Integer[m]; for(int i = 0; i< m; i++)p[i] = i; Arrays.sort(p, (Integer i1, Integer i2) -> Long.compare(col[i2], col[i1])); long[][] mat = new long[n][Math.min(m, 6)]; for(int i = 0; i< Math.min(m, 6); i++){ for(int j = 0; j< n; j++)mat[j][i] = a[j][p[i]]; } long pow = 1; for(int i = 0; i< Math.min(m, 6); i++)pow *= n; int[] sh = new int[Math.min(m, 6)]; long ans = 0; for(int i = 0; i< pow; i++){ int x = i; for(int j = 0; j< Math.min(m, 6); j++){ sh[j] = x%n; x/=n; } long cur = 0; for(int ro = 0; ro < n; ro++){ long cR = 0; for(int j = 0; j < Math.min(m, 6); j++)cR = Math.max(cR, mat[(ro+sh[j])%n][j]); cur += cR; } ans = Math.max(ans, cur); } pn(ans); } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} void exit(boolean b){if(!b)System.exit(0);} long IINF = (long)1e18, mod = (long)1e9+7; final int INF = (int)1e9, MX = (int)2e6+5; DecimalFormat df = new DecimalFormat("0.00000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-6; static boolean multipleTC = true, memory = false, fileIO = false; FastReader in;PrintWriter out; void run() throws Exception{ if(fileIO){ in = new FastReader("input.txt"); out = new PrintWriter("output.txt"); }else { in = new FastReader(); out = new PrintWriter(System.out); } //Solution Credits: Taranpreet Singh int T = (multipleTC)?ni():1; pre(); for(int t = 1; t<= T; t++)solve(t); out.flush(); out.close(); } 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(); } int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;} long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){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
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintWriter; import java.util.Arrays; import java.io.OutputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { double special(int[] loyalties, int[] levels, int playerlevelsum) { int poss = 1 << loyalties.length; double res = 0; for(int pos = 0; pos < poss; pos++) { double occurs = 1; int happy = 0; int badlevelssum = 0; for(int i = 0; i < loyalties.length; i++) { if(((pos >> i) & 1) == 1) { //happy senator happy++; occurs *= (double) loyalties[i] / 100; } else { //unhappy senator badlevelssum += levels[i]; occurs *= (double) (100 - loyalties[i]) / 100; } } double winprob = (happy <= levels.length / 2) ? (double) playerlevelsum / (playerlevelsum + badlevelssum) : 1; res += occurs * winprob; } return res; } public void solve(int testNumber, InputReader in, OutputWriter out) { int senators = in.readInt(); // n, [1, 8] int sweets = in.readInt(); // k, [1, 8] int playerlevelsum = in.readInt(); // A, [1, 9999] int[] levels = new int[senators]; // [1, 9999] int[] loyalties = new int[senators]; // [0, 100] divisible by 10 IOUtils.readIntArrays(in, levels, loyalties); ArrayList<ArrayList<Integer>> possibilities = new ArrayList<>(Arrays.asList(new ArrayList<>())); for(int senator = 0; senator < senators; senator++) { ArrayList<ArrayList<Integer>> newpossibilities = new ArrayList<>(); for(ArrayList<Integer> al : possibilities) { int sumsofar = 0; for(int val : al) sumsofar += val; int minadd = senator == senators - 1 ? sweets - sumsofar : 0; for(int moar = minadd; moar <= sweets - sumsofar; moar++) { ArrayList<Integer> copy = new ArrayList<>(al); copy.add(moar); newpossibilities.add(copy); } } possibilities = newpossibilities; } double res = 0; for(ArrayList<Integer> al : possibilities) { int[] newloyalties = new int[senators]; for(int i = 0; i < senators; i++) newloyalties[i] = Math.min(100, loyalties[i] + 10 * al.get(i)); double special = special(newloyalties, levels, playerlevelsum); double tot = special; res = Math.max(res, tot); } out.printLine(res); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if(numChars == -1) throw new InputMismatchException(); if(curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch(IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if(c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while(!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if(filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for(int i = 0; i < objects.length; i++) { if(i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class IOUtils { public static void readIntArrays(InputReader in, int[]... arrays) { for(int i = 0; i < arrays[0].length; i++) { for(int j = 0; j < arrays.length; j++) arrays[j][i] = in.readInt(); } } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.*; import java.util.*; public class B { int n, k; double A; int[] b, l; double ans; double curAns; void check(boolean[] used) { int cnt = 0; for (boolean t : used) if (t) cnt++; double prob = 1; for (int i = 0; i < n; i++) { if (used[i]) prob *= ((double) l[i]) / ((double) 100); else prob *= 1 - ((double) l[i]) / ((double) 100); } if (2 * cnt > n) { curAns += prob; } else { int level = 0; for (int i = 0; i < n; i++) if (!used[i]) level += b[i]; curAns += prob * ( A / ((double) A + level)); } } void go(int i, boolean[] used) { if (n == i) { check(used); return; } used[i] = true; go(i + 1, used); used[i] = false; go(i + 1, used); } void candies(int k, int i) { if (i == n) { curAns = 0; go(0, new boolean[n]); if (curAns > ans) ans = curAns; return; } candies(k, i + 1); for (int j = 1; j <= k && l[i] + 10 * j <= 100; j++) { l[i] += 10 * j; candies(k - j, i + 1); l[i] -= 10 * j; } } void solve() throws Exception { n = nextInt(); k = nextInt(); A = nextInt(); b = new int[n]; l = new int[n]; for (int i = 0; i < n; i++) { b[i] = nextInt(); l[i] = nextInt(); } ans = 0; candies(k, 0); out.printf("%.12f", ans); } void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // in = new BufferedReader(new FileReader(filename + ".in")); // out = new PrintWriter(filename + ".out"); Locale.setDefault(Locale.US); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } BufferedReader in; StringTokenizer st; PrintWriter out; final String filename = new String("B").toLowerCase(); String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(nextToken()); } long nextLong() throws Exception { return Long.parseLong(nextToken()); } double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } public static void main(String[] args) { new B().run(); } }
np
105_B. Dark Assembly
CODEFORCES
import java.util.*; public class B { static int[] loyality; static int[] level; static int mid; static int a, n; static double sol; public static void getMax(int idx, int rem) { if (idx == loyality.length) { double pos = 0; for (int i = 0; i < (1 << n); i++) pos += solve(i); sol = Math.max(sol, pos); return; } int cur = loyality[idx]; int r = 0; while (r + cur <= 10 && r <= rem) { loyality[idx] = cur + r; getMax(idx + 1, rem - r); r++; } loyality[idx] = cur; } public static double solve(int mask) { int c = 0; int sum = 0; double b = 1; for (int i = 0; i < n; i++) { if (((1 << i) | mask) == mask) { c++; b *= (loyality[i] / 10.0); } else { sum += level[i]; b *= (1 - (loyality[i] / 10.0)); } } if (c >= mid) return b; return b * (a * 1.0) / (a + sum); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); int k = sc.nextInt(); a = sc.nextInt(); level = new int[n]; loyality = new int[n]; for (int i = 0; i < n; i++) { level[i] = sc.nextInt(); loyality[i] = sc.nextInt() / 10; } mid = (n/2) +1; sol = 0; getMax(0, k); System.out.println(sol); } }
np
105_B. Dark Assembly
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 8/13/11 * Time: 6:10 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.io.IOException; public class DarkAssembly extends Thread { public DarkAssembly() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } static class Senator { int loyalty; int level; public Senator(int level, int loyalty) { this.level = level; this.loyalty = loyalty; } } private static double doIt(Senator[] senators, int A) { double probability = .0; for (int mask = 0; mask < (1 << senators.length); ++mask) { int sum = A; double current = 1.0; for (int i = 0; i < senators.length; ++i) { if ((mask & (1 << i)) != 0) { current *= .01 * senators[i].loyalty; } else { current *= .01 * (100 - senators[i].loyalty); sum += senators[i].level; } } if (getOnes(mask) > senators.length / 2) { probability += current; } else { probability += current * (double)A / sum; } } return probability; } private static double go(Senator []senators, int candies, int A, int current) { if (current == senators.length) { return doIt(senators, A); } else { double result = go(senators, candies, A, current + 1); if (candies > 0 && senators[current].loyalty < 100) { senators[current].loyalty += 10; result = Math.max(result, go(senators, candies - 1, A, current)); senators[current].loyalty -= 10; } return result; } } static int getOnes(int mask) { int result = 0; while (mask != 0) { mask &= mask - 1; ++result; } return result; } public void run() { try { int n = nextInt(); int k = nextInt(); int A = nextInt(); Senator[] senators = new Senator[n]; for (int i = 0; i < n; ++i) { senators[i] = new Senator(nextInt(), nextInt()); } output.printf("%.10f", go(senators, k, A, 0)); output.flush(); output.close(); } catch (Throwable e) { System.err.println(e.getMessage()); System.err.println(Arrays.deepToString(e.getStackTrace())); } } public static void main(String[] args) { new DarkAssembly().start(); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
105_B. Dark Assembly
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(), k = iread(), A = iread(); int[] b = new int[n], l = new int[n]; for (int i = 0; i < n; i++) { l[i] = iread(); b[i] = iread(); } int[] c = new int[n]; double ans = 0.0; for (int mask = 0; mask < 1 << (k + n - 1); mask++) { int t = 0; for (int i = 0; i < n + k - 1; i++) { if ((mask & (1 << i)) != 0) t++; } if (t != k) continue; int x = mask; for (int i = 0; i < n; i++) { c[i] = b[i]; while (x % 2 == 1) { c[i] += 10; x /= 2; } if (c[i] > 100) c[i] = 100; x /= 2; } double res = 0.0; for (int mask2 = 0; mask2 < 1 << n; mask2++) { int m = 0; double p = 1.0; t = 0; for (int i = 0; i < n; i++) { if ((mask2 & (1 << i)) == 0) { t += l[i]; p *= (100.0 - c[i]) / 100.0; } else { p *= c[i] / 100.0; m++; } } if (m * 2 > n) res += p; else res += p * A * 1.0 / (A + t); } ans = Math.max(ans, res); } DecimalFormat df = new DecimalFormat("0.0000000"); out.write(df.format(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
105_B. Dark Assembly
CODEFORCES
import static java.lang.Math.*; import java.io.*; import java.util.*; public class flags1225 implements Runnable { static int n, k, a, b[], loy[]; static boolean decision[]; static double ans, max; static void check(int i) { if (i == n) { checkAgain(); return; } decision[i] = true; check(i + 1); if (loy[i] < 100) { decision[i] = false; check(i + 1); } } static void checkAgain() { double prob = 1; int enemyEnergy = 0; int count = 0; for (int i = 0; i < n; i++) { if (decision[i]) { count++; prob *= loy[i]; } else { prob = prob * (100 - loy[i]); enemyEnergy += b[i]; } } double killProb = (double) (a) / (a + enemyEnergy); if (count > n / 2) { ans += prob; return; } prob *= killProb; ans += prob; } static void rec(int sum, int i) { if (i == n || sum == 0) { ans = 0; check(0); max = max(ans, max); return; } for (int j = 0; j <= sum; j = j + 10) { if (loy[i] + j > 100) continue; loy[i] += j; rec(sum - j, i + 1); loy[i] -= j; } } public void run() { n = nextInt(); k = nextInt() * 10; a = nextInt(); max = 0; b = new int[n]; loy = new int[n]; decision = new boolean[n]; for (int i = 0; i < n; i++) { b[i] = nextInt(); loy[i] = nextInt(); } // System.out.println(Arrays.toString(loy)); rec(k, 0); long pow = (long) pow(100, n); out.print((double) max / pow); // -------------------------------------------------------------------------------------------- out.close(); System.exit(0); } private static boolean fileIOMode = false; private static String problemName = "harmful"; private static BufferedReader in; private static PrintWriter out; private static StringTokenizer tokenizer; public static void main(String[] args) throws Exception { Locale.setDefault(Locale.ENGLISH); if (fileIOMode) { in = new BufferedReader(new FileReader(problemName + ".in")); out = new PrintWriter(problemName + ".out"); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } tokenizer = new StringTokenizer(""); new Thread(new flags1225()).start(); } private static String nextLine() { try { return in.readLine(); } catch (IOException e) { return null; } } private static String nextToken() { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(nextLine()); } return tokenizer.nextToken(); } private static double nextDouble() { return Double.parseDouble(nextToken()); } private static int nextInt() { return Integer.parseInt(nextToken()); } }
np
105_B. Dark Assembly
CODEFORCES
//package round81; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class B { Scanner in; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int k = ni(); int a = ni(); int[] lv = new int[n]; int[] lo = new int[n]; for(int i = 0;i < n;i++){ lv[i] = ni(); lo[i] = ni(); } out.printf("%.9f", rec(lv, lo, n, 0, k, a)); } double rec(int[] lv, int[] lo, int n, int pos, int k, int a) { if(pos == n){ int h = n/2+1; double gp = 0; for(int i = 0;i < 1<<n;i++){ if(Integer.bitCount(i) >= h){ double p = 1.0; for(int j = 0;j < n;j++){ if(i<<31-j<0){ p *= (double)lo[j] / 100; }else{ p *= (double)(100-lo[j]) / 100; } } gp += p; }else{ double p = 1.0; int sl = 0; for(int j = 0;j < n;j++){ if(i<<31-j<0){ p *= (double)lo[j] / 100; }else{ p *= (double)(100-lo[j]) / 100; sl += lv[j]; } } gp += p * a/(a+sl); } } return gp; }else{ int o = lo[pos]; double max = 0; for(int i = 0;i <= k && lo[pos] <= 100;i++){ max = Math.max(max, rec(lv, lo, n, pos+1, k-i, a)); lo[pos]+=10; } lo[pos] = o; return max; } } void run() throws Exception { in = oj ? new Scanner(System.in) : new Scanner(INPUT); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new B().run(); } int ni() { return Integer.parseInt(in.next()); } long nl() { return Long.parseLong(in.next()); } double nd() { return Double.parseDouble(in.next()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.*; import java.util.*; import java.lang.reflect.Array; import java.math.*; public class Solution { private BufferedReader in; private PrintWriter out; private StringTokenizer st; private Random rnd; int[] levels; int[] loyal; int n, k; double A; int[] choices; int[] new_loyal; double[] koef; double ans = 0.0; int total; void rec(int step, int start) { if(step == k) { for(int i = 0; i < n; i++) { new_loyal[i] = loyal[i]; } for(int i = 0; i < k; i++) { new_loyal[choices[i]] = Math.min(100, new_loyal[choices[i]] + 10); } int full = 0; for(int i = 0; i < n; i++) { if(new_loyal[i] == 100) { ++full; } } if(full > (n / 2)) { ans = 1.0; return; } for(int i = 0; i < n; i++) { koef[i] = (double) new_loyal[i] / 100.0; } int bits_needed = (n / 2) + 1; double total_win = 0.0; double total_fights = 0.0; for(int mask = 0; mask < total; mask++) { int bits = 0; double win = 1.0; double loose = 1.0; double b = 0.0; for(int bit = 0; bit < n; bit++) { if((mask & (1 << bit)) != 0) { ++bits; win *= koef[bit]; } else { loose *= (1.0 - koef[bit]); b += levels[bit]; } } double prob = win * loose; if(bits >= bits_needed) { total_win += prob; } else { total_fights += prob * (A / (A + b)); } } ans = Math.max(ans, total_win + total_fights); } else { for(int i = start; i < n; i++) { choices[step] = i; rec(step + 1, i); } } } public void solve() throws IOException { n = nextInt(); k = nextInt(); A = nextInt(); levels = new int[n]; loyal = new int[n]; new_loyal = new int[n]; choices = new int[k]; koef = new double[n]; for(int i = 0; i < n; i++) { levels[i] = nextInt(); loyal[i] = nextInt(); } total = 1 << n; rec(0, 0); out.println(ans); } public static void main(String[] args) { new Solution().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); st = null; rnd = new Random(); solve(); out.close(); } catch(IOException e) { e.printStackTrace(); } } private String nextToken() throws IOException, NullPointerException { while(st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.PriorityQueue; import java.util.Scanner; import java.util.StringTokenizer; public class D { static int n, KA, A; static int[] b; static int[] l; static double ans = 0; public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); n = in.nextInt(); KA = in.nextInt(); A = in.nextInt(); b = new int[n]; l = new int[n]; for (int i = 0; i < l.length; i++) { b[i] = in.nextInt(); l[i] = in.nextInt(); } dp = new double[n + 2][n + 2][n * 9999 + 2]; go(0, KA); System.out.printf("%.6f\n", ans); } public static void go(int at, int k) { if (at == n) { ans = Math.max(ans, solve(0, 0, 0)); return; } for (int i = 0; i <= k; i++) { if (l[at] + i * 10 <= 100) { l[at] += i * 10; go(at + 1, k - i); l[at] -= i * 10; } } } static double dp[][][]; public static double solve(int at, int ok, int B) { if (at == n) { if (ok > n / 2) { return 1; } else { return (A * 1.0) / (A * 1.0 + B); } } double ret = ((l[at]) / 100.0) * solve(at + 1, ok + 1, B) + (1.0 - ((l[at]) / 100.0)) * solve(at + 1, ok, B + b[at]); return ret; } // 3 0 31 // 10 60 // 12 60 // 15 0 static class InputReader { BufferedReader in; StringTokenizer st; public InputReader() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(in.readLine()); } public String next() throws IOException { while (!st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
np
105_B. Dark Assembly
CODEFORCES
/** * Created by IntelliJ IDEA. * User: piyushd * Date: 3/26/11 * Time: 10:53 PM * To change this template use File | Settings | File Templates. */ public class TaskB { int[] levels; int[] loyalty; int n, k, A; double ans = Double.NEGATIVE_INFINITY; void rec(int ix, int sweets, int[] loyalty) { if (ix == n) { double nres = 0.0; for(int mask = 0; mask < (1<<n); mask++) { double res = 1.0, totalStrength = 0; for (int i = 0; i < n; i++) { if ((mask & (1 << i)) > 0) { res *= loyalty[i] / 100.0; } else { res *= 1.0 - (loyalty[i]/ 100.0); totalStrength += levels[i]; } } int bitCount = Integer.bitCount(mask); if(bitCount > n / 2) { nres += res; } else { nres += res * (A) / (A + totalStrength); } } ans = Math.max(ans, nres); return; } for (int j = 0; j <= sweets; j++) { if (loyalty[ix] + 10 * j > 100) break; int[] nloyalty = loyalty.clone(); nloyalty[ix] += 10 * j; rec(ix + 1, sweets - j, nloyalty); } } void run() { n = nextInt(); k = nextInt(); A = nextInt(); levels = new int[n]; loyalty = new int[n]; for (int i = 0; i < n; i++) { levels[i] = nextInt(); loyalty[i] = nextInt(); } rec(0, k, loyalty); System.out.println(ans); } int nextInt() { try { int c = System.in.read(); if (c == -1) return c; while (c != '-' && (c < '0' || '9' < c)) { c = System.in.read(); if (c == -1) return c; } if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } long nextLong() { try { int c = System.in.read(); if (c == -1) return -1; while (c != '-' && (c < '0' || '9' < c)) { c = System.in.read(); if (c == -1) return -1; } if (c == '-') return -nextLong(); long res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } String nextLine() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (c == '\r' || c == '\n') c = System.in.read(); do { res.append((char) c); c = System.in.read(); } while (c != '\r' && c != '\n'); return res.toString(); } catch (Exception e) { return null; } } public static void main(String[] args) { new TaskB().run(); } }
np
105_B. Dark Assembly
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 8/13/11 * Time: 6:10 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.io.IOException; public class DarkAssembly extends Thread { public DarkAssembly() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } class Senator { int loyalty; int level; public Senator(int level, int loyalty) { this.level = level; this.loyalty = loyalty; } } private static double doIt(Senator[] senators, int A) { double probability = .0; for (int mask = 0; mask < (1 << senators.length); ++mask) { int sum = A; double current = 1.0; for (int i = 0; i < senators.length; ++i) { if ((mask & (1 << i)) != 0) { current *= .01 * senators[i].loyalty; } else { current *= .01 * (100 - senators[i].loyalty); sum += senators[i].level; } } if (getOnes(mask) > senators.length / 2) { probability += current; } else { probability += current * (double)A / sum; } } return probability; } private static double go(Senator []senators, int candies, int A, int current) { if (current == senators.length) { return doIt(senators, A); } else { double result = go(senators, candies, A, current + 1); if (candies > 0 && senators[current].loyalty < 100) { senators[current].loyalty += 10; result = Math.max(result, go(senators, candies - 1, A, current)); senators[current].loyalty -= 10; } return result; } } static int getOnes(int mask) { int result = 0; while (mask != 0) { mask &= mask - 1; ++result; } return result; } public void run() { try { int n = nextInt(); int k = nextInt(); int A = nextInt(); Senator[] senators = new Senator[n]; for (int i = 0; i < n; ++i) { senators[i] = new Senator(nextInt(), nextInt()); } output.printf("%.10f", go(senators, k, A, 0)); output.flush(); output.close(); } catch (Throwable e) { System.err.println(e.getMessage()); System.err.println(Arrays.deepToString(e.getStackTrace())); } } public static void main(String[] args) { new DarkAssembly().start(); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
105_B. Dark Assembly
CODEFORCES
import java.util.*; public class B { public static void main(String[] args) { new B(new FastScanner()); } int hash(int i, int[] cc) { int res = i; for (int ii : cc) { res *= 8; res += ii; } return res; } int N, K, A; int[] lvl; int[] vs; // loyalty double calc(int i, int[] cc) { // Find the probability of winning double res = 0; int cnt = 0; for (int m=0; m<1<<N; m++) { double pt = 1.0; boolean passed = true; int nG = 0; int lvlcnt = 0; for (int j=0; j<N; j++) { int p = 10*cc[j]+vs[j]; int u = m&(1<<j); boolean votesGood = (u > 0); if (votesGood) nG++; else lvlcnt += lvl[j]; if ((p == 0)&&(votesGood)) passed = false; if ((p == 100)&&(!votesGood)) passed = false; if (!passed) break; if (votesGood) pt *= (p/100.0); else pt *= ((100-p)/100.0); } if (passed == false) continue; if (2*nG <= N) { // Calculate if we kill all senators double p1 = A/(1.0*(A+lvlcnt)); // Add in the probability of losing res += (1-p1)*pt; } } return 1.0-res; } HashMap<Integer, Double> memo; double go(int i, int[] cc) { if (i == -1) return calc(i, cc); int hv = hash(i, cc); Double rr = memo.get(hv); if (rr != null) return rr; double res = go(i-1, cc); for (int j=0; j<N; j++) { int cv = vs[j]+cc[j]*10; if (cv == 100) continue; cc[j]++; double rrr = go(i-1, cc); cc[j]--; if (rrr > res) res = rrr; } memo.put(hv, res); return res; } public B(FastScanner in) { N = in.nextInt(); K = in.nextInt(); A = in.nextInt(); memo = new HashMap<Integer, Double>(); lvl = new int[N]; vs = new int[N]; for (int i=0; i<N; i++) { lvl[i] = in.nextInt(); vs[i] = in.nextInt(); } int[] cs = new int[8]; double res = go(K-1, cs); System.out.printf("%.10f%n", res); } } class FastScanner{ int nextInt(){ try{ int c=System.in.read(); if(c==-1) return c; while(c!='-'&&(c<'0'||'9'<c)){ c=System.in.read(); if(c==-1) return c; } if(c=='-') return -nextInt(); int res=0; do{ res*=10; res+=c-'0'; c=System.in.read(); }while('0'<=c&&c<='9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c=System.in.read(); if(c==-1) return -1; while(c!='-'&&(c<'0'||'9'<c)){ c=System.in.read(); if(c==-1) return -1; } if(c=='-') return -nextLong(); long res=0; do{ res*=10; res+=c-'0'; c=System.in.read(); }while('0'<=c&&c<='9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res=new StringBuilder(""); int c=System.in.read(); while(Character.isWhitespace(c)) c=System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res=new StringBuilder(""); int c=System.in.read(); while(c=='\r'||c=='\n') c=System.in.read(); do{ res.append((char)c); c=System.in.read(); }while(c!='\r'&&c!='\n'); return res.toString(); }catch(Exception e){ return null; } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.*; import java.util.*; public class B { static double max; static int n, A, b[], l[]; static int sw[]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); int k = sc.nextInt(); A = sc.nextInt(); b = new int[n]; l = new int[n]; sw = new int[n]; for(int i=0; i<n; i++) { b[i] = sc.nextInt(); l[i] = sc.nextInt(); } max = 0; search(k, 0); System.out.println(max); } static void search(int k, int m) { if(max == 1) return; if(m == n) { if(k > 0) return; double pr[] = new double[n]; for(int i=0; i<n; i++) { pr[i] = Math.min(100, l[i] + 10*sw[i])*1./100; } double ex = 0; for(int i=0; i<1<<n; i++) { double p = 1; int cnt = 0; int lv = 0; for(int j=0; j<n; j++) { if((i&(1<<j))>0) { p *= pr[j]; cnt++; } else { p *= (1-pr[j]); lv += b[j]; } } if(cnt > n/2) { ex += p; } else { ex += p*A/(A+lv); } } max = Math.max(max, ex); return; } for(int i=k; i>=0; i--) { sw[m] = i; search(k-i, m+1); } } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); eat(""); } void eat(String s) { st = new StringTokenizer(s); } String nextLine() { try { return br.readLine(); } catch (IOException e) { throw new IOError(e); } } boolean hasNext() { while (!st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } String next() { hasNext(); return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
np
105_B. Dark Assembly
CODEFORCES
import java.awt.geom.*; import java.io.*; import java.math.*; import java.util.*; import java.util.regex.*; import static java.lang.Math.*; public class B { public static void swap(int[] array, int a, int b) { // {{{ int t = array[a]; array[a] = array[b]; array[b] = t; } // }}} int n, k, A; int[] b; int[] l; double ans; double cal() { double total = 0; for (int mask=0;mask<(1<<n);mask++) { int bit = Integer.bitCount(mask); double p = 1; for (int i=0;i<n;i++) { if ((mask&(1<<i))!=0) p *= l[i]/10.0; else p *= 1.0-l[i]/10.0; } if (bit*2>n) total += p; else { int B = 0; for (int i=0;i<n;i++) { if ((mask&(1<<i))==0) { B += b[i]; } } total += p*(A/(double)(A+B)); } } return total; } void rec(int d, int remain) { ans = max(ans, cal()); if (remain==0) return; for (int i=d;i<n;i++) { if (l[i]==10) continue; l[i]++; rec(i, remain-1); l[i]--; } } public B() throws Exception { n = in.nextInt(); k = in.nextInt(); A = in.nextInt(); b = new int[n]; l = new int[n]; for (int i=0;i<n;i++) { b[i] = in.nextInt(); l[i] = in.nextInt()/10; } ans = 0; rec(0, k); System.out.print(ans); } Scanner in = new Scanner(System.in); StringBuilder buf = new StringBuilder(); public static void main(String[] args) throws Exception { // {{{ new B(); } // }}} public static void debug(Object... arr) { // {{{ System.err.println(Arrays.deepToString(arr)); } // }}} }
np
105_B. Dark Assembly
CODEFORCES
import static java.lang.Math.max; import static java.lang.Math.min; import java.io.*; import java.util.*; public class B { private void solve() throws IOException { int senators = nextInt(); int candies = nextInt(); scoreA = nextInt(); lvl = new int[senators]; unloyal = new int[senators]; for (int i = 0; i < senators; i++) { lvl[i] = nextInt(); unloyal[i] = 10 - nextInt() / 10; } n = senators; give = new int[n]; res = 0; go(0, candies); out.println(res); } static double res; static int[] lvl; static int[] unloyal; static int[] give; static int n; static int scoreA; static double probability() { double res = 0; for (int mask = 0; mask < 1 << n; mask++) { double p = 1; int scoreB = 0; int cntGood = Integer.bitCount(mask); for (int i = 0; i < n; i++) { int cnt = unloyal[i] - give[i]; if ((mask & (1 << i)) == 0) { scoreB += lvl[i]; p *= cnt * .1; } else { p *= (10 - cnt) * .1; } } if (2 * cntGood > n) { res += p; } else { res += p * scoreA / (scoreA + scoreB); } } return res; } static void go(int man, int candies) { if (man == n) { res = max(res, probability()); return; } give[man] = 0; go(man + 1, candies); for (int i = 1; i <= min(unloyal[man], candies); i++) { give[man] = i; go(man + 1, candies - i); } } public static void main(String[] args) { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); new B().solve(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(239); } } static BufferedReader br; static StringTokenizer st; static PrintWriter out; static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
np
105_B. Dark Assembly
CODEFORCES
import java.util.*; public class b { static int n,k,A; static int[] l,p; static double [][][] memo; public static void main(String[] args) { Scanner in = new Scanner(System.in); n = in.nextInt(); k = in.nextInt(); A = in.nextInt(); memo = new double[n+1][n+1][1<<n]; l = new int[n]; p = new int[n]; for(int i=0; i<n; i++) { l[i] = in.nextInt(); p[i] = in.nextInt(); } System.out.printf("%.10f%n",go(0,k)); } static double go(int pos, int left) { if(pos==n) { for(int i=0; i<=n; i++) for(int j=0; j<=n; j++) Arrays.fill(memo[i][j],-1); return go2(0,n/2+1,0); } double best = go(pos+1,left); if(left == 0) return best; if(p[pos] < 100) { p[pos] += 10; best = Math.max(best, go(pos,left-1)); p[pos] -= 10; } return best; } static double go2(int pos, int needed, int mask) { if(needed == 0) return 1.0; if(pos == n) { int tot = 0; for(int i=0; i<n; i++) if((mask&(1<<i))!=0) tot += l[n-i-1]; return (A)/(A+tot+0.0); } if(memo[pos][needed][mask] != -1) return memo[pos][needed][mask]; double a = (p[pos]/100.)*go2(pos+1,needed-1,mask*2); double b = (1-(p[pos]/100.))*go2(pos+1,needed,mask*2+1); return memo[pos][needed][mask] = a+b; } }
np
105_B. Dark Assembly
CODEFORCES
import java.awt.*; import java.io.*; import java.math.*; import java.util.*; import static java.lang.Math.*; public class BetaRound81_B implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new BetaRound81_B(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } /** http://pastebin.com/j0xdUjDn */ static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static final int MAGIC_VALUE = 50; private static void mergeSort(int[] a, int leftIndex, int rightIndex) { if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } // solution int n, k, A; int[] b, l, c; void solve() throws IOException { n = readInt(); k = readInt(); A = readInt(); b = new int[n]; l = new int[n]; for (int i = 0; i < n; i++) { b[i] = readInt(); l[i] = readInt(); } c = new int[n]; rec(0, 0); out.printf("%.12f\n", ans); } double ans = 0; void rec(int sum, int i) { if (i > n) return; if (sum > k) return; if (i == n) { ans = max(ans, p()); return; } if (l[i] + c[i]*10 <= 100) { int can = min(k - sum, (100 - (l[i] + c[i]*10)) / 10); for (int set = can; set >= 0; set--) { c[i] += set; rec(sum + set, i + 1); c[i] -= set; } } } double p() { int n = c.length; int need = n / 2 + 1; int[] L = new int[n]; for (int i = 0; i < n; i++) { L[i] = l[i] + c[i]*10; if (L[i] > 100) { throw new RuntimeException(); } } double p = 0; for (int mask = 0; mask < (1 << n); mask++) { double q = 1; for (int i = 0; i < n; i++) { if (((1 << i) & mask) != 0) { q *= L[i] / 100.0; } else { q *= 1 - (L[i] / 100.0); } } if (q == 0) continue; if (Integer.bitCount(mask) >= need) { p += q; } else { int B = 0; for (int i = 0; i < n; i++) { if (((1 << i) & mask) == 0) { B += b[i]; } } double q2 = ((double) A) / (A + B); p += q * q2; } } return p; } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.util.InputMismatchException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Niyaz Nigmatullin */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { static int myLevel; static int[] level; static int[] loyalty; static double get(int n) { double ret = 0; for (int mask = 0; mask < 1 << n; mask++) { int k = Integer.bitCount(mask); double prob = 1.; int sum = 0; for (int i = 0; i < n; i++) { if (((mask >> i) & 1) == 1) { prob *= loyalty[i] * .1; } else { prob *= (10 - loyalty[i]) * .1; sum += level[i]; } } if (k * 2 > n) { ret += prob; } else { ret += prob * myLevel / (myLevel + sum); } } return ret; } static double go(int x, int k, int n) { if (x == n) { return get(n); } double ret = 0; for (int i = 0; i <= k && loyalty[x] + i <= 10; i++) { loyalty[x] += i; ret = Math.max(go(x + 1, k - i, n), ret); loyalty[x] -= i; } return ret; } public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int k = in.nextInt(); myLevel = in.nextInt(); level = new int[n]; loyalty = new int[n]; for (int i = 0; i < n; i++) { level[i] = in.nextInt(); loyalty[i] = in.nextInt() / 10; } out.println(go(0, k, n)); } } class FastScanner extends BufferedReader { boolean isEOF; public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); if (isEOF && ret < 0) { throw new InputMismatchException(); } isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } static boolean isWhiteSpace(int c) { return c >= -1 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (!isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } }
np
105_B. Dark Assembly
CODEFORCES
/** * * @author Saransh */ import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class Main { static int senator_attr[][]; static int senators; static double A; public static void main(String[] args) { try { Parserdoubt pd=new Parserdoubt(System.in); PrintWriter pw=new PrintWriter(System.out); senators=pd.nextInt(); int candies=pd.nextInt(); senator_attr=new int[senators][2]; A=pd.nextInt(); for(int i=0;i<senators;i++) { senator_attr[i][0]=pd.nextInt(); senator_attr[i][1]=pd.nextInt(); } max=-1; make(0,candies,new int[senators]); //print(maxer); System.out.printf("%.10f",max); } catch(Exception e) { e.printStackTrace(); } } static double max; static int maxer[]; public static void get(int a[]) { maxer=new int[senators]; for(int i=0;i<maxer.length;i++) maxer[i]=a[i]; } public static void make(int pos,int left,int arr[]) { if(pos==senators-1) { arr[pos]=left; //print(arr); double f=calc(arr); if(f>max) { max=f; get(arr); } return; } if(left==0) { //print(arr); double f=calc(arr); if(f>max) { max=f; get(arr); } return; } for(int i=0;i<=left;i++) { arr[pos]=i; make(pos+1,left-i,arr); arr[pos]=0; } } public static double calc(int arr[]) { // print(arr); int tmp[][]=new int[senators][2]; for(int i=0;i<senators;i++) { tmp[i][0]=senator_attr[i][0]; tmp[i][1]=Math.min(senator_attr[i][1]+arr[i]*10, 100); // System.out.println(tmp[i][0]+" "+tmp[i][1]); } //print(tmp[0]); return prob(tmp); } public static void print(int a[]) { for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } public static double prob(int arr[][]) { double probability=0.0; for(int i=0;i<(1<<senators);i++) { if(Integer.bitCount(i)>senators/2) { double add=1.0; int tmpi=i; for(int p=0;p<senators;p++) { if(tmpi%2==1) { add*=arr[p][1]/100.0; } else { add*=(100-arr[p][1])/100.0; } tmpi/=2; } probability+=add; //System.out.println(i+" "+add); } else { double add=1.0; double B=0; int tmpi=i; for(int p=0;p<senators;p++) { if(tmpi%2==1) { add*=arr[p][1]/100.0; } else { add*=(100-arr[p][1])/100.0; B+=arr[p][0]; } tmpi/=2; } add*=A/(A+B); probability+=add; //System.out.println(i+" "+add); } } return probability; } } class Skill implements Comparable<Skill> { String name; int v; public Skill(String n,int val) { name=n; v=val; } public int compareTo(Skill k) { return -k.name.compareTo(name); } } class Parserdoubt { final private int BUFFER_SIZE = 1 << 17; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parserdoubt(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString() throws Exception { StringBuffer sb=new StringBuffer(""); byte c = read(); while (c <= ' ') c = read(); do { sb.append((char)c); c=read(); }while(c>' '); return sb.toString(); } public char nextChar() throws Exception { byte c=read(); while(c<=' ') c= read(); return (char)c; } public int nextInt() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } public long nextLong() throws Exception { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } }
np
105_B. Dark Assembly
CODEFORCES
import static java.util.Arrays.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import java.util.*; import java.math.*; import java.io.*; public class B implements Runnable { String file = "input"; boolean TEST = false; double EPS = 1e-8; void solve() throws IOException { int n = nextInt(), k = nextInt(), A = nextInt(); int[] level = new int[n]; int[] loyal = new int[n]; for(int i = 0; i < n; i++) { level[i] = nextInt(); loyal[i] = nextInt(); } double res = 0; for(int mask = 0; mask < 1 << (n + k - 1); mask++) { if(Integer.bitCount(mask) != k) continue; int[] L = new int[n]; int x = mask; for(int i = 0; i < n; i++) { L[i] = loyal[i]; while(x % 2 == 1) { L[i] += 10; x /= 2; } L[i] = min(L[i], 100); x /= 2; } double tmp = 0; for(int w = 0; w < 1 << n; w++) { double p = 1.; double B = 0; for(int i = 0; i < n; i++) if((w >> i & 1) != 0) p *= L[i] / 100.; else { p *= (100 - L[i]) / 100.; B += level[i]; } if(Integer.bitCount(w) * 2 > n) tmp += p; else tmp += p * (A / (A + B)); } res = max(res, tmp); } out.printf("%.8f\n", res); } class Player { } String next() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(input.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } void print(Object... o) { System.out.println(deepToString(o)); } void gcj(Object o) { String s = String.valueOf(o); out.println("Case #" + test + ": " + s); System.out.println("Case #" + test + ": " + s); } BufferedReader input; PrintWriter out; StringTokenizer st; int test; void init() throws IOException { if(TEST) input = new BufferedReader(new FileReader(file + ".in")); else input = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedOutputStream(System.out)); } public static void main(String[] args) throws IOException { new Thread(null, new B(), "", 1 << 20).start(); } public void run() { try { init(); if(TEST) { int runs = nextInt(); for(int i = 0; i < runs; i++) solve(); } else solve(); out.close(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.*; import java.util.*; public class B2 { String s = null; String[] ss = null; int[][] sn = null; int n = 0; double ans = 1; int A = 0; public void run() throws Exception{ BufferedReader br = null; File file = new File("input.txt"); if(file.exists()){ br = new BufferedReader(new FileReader("input.txt")); } else{ br = new BufferedReader(new InputStreamReader(System.in)); } s = br.readLine(); ss = s.split(" "); n = Integer.parseInt(ss[0]); int k = Integer.parseInt(ss[1]); A = Integer.parseInt(ss[2]); sn = new int[n][2]; for(int i = 0; i < n; i++){ s = br.readLine(); ss = s.split(" "); sn[i][0] = Integer.parseInt(ss[0]); sn[i][1] = Integer.parseInt(ss[1]); } int num = 0; for(int i = 0; i < n; i++){ num += (100 - sn[i][1]) / 10; } if(k >= num){ System.out.println("1.0"); return; } check(0, k, sn); ans = 1 - ans; System.out.println(ans); } void check(int i, int k, int[][] sn){ if(i == n && k == 0){ check2(sn); return; } else if(i == n && k > 0){ return; } else if(k == 0){ check(i+1, k, sn); } else{ for(int j = 0; j <= k; j++){ if(sn[i][1] + j * 10 <= 100){ int[][] nsn = copy(sn); nsn[i][1] += j * 10; check(i+1, k - j, nsn); } } } } void check2(int[][] sn){ List<Integer> target = new ArrayList<Integer>(); int h = 0; for(int i = 0; i < sn.length; i++){ if(sn[i][1] != 100){ target.add(i); } else{ h++; } } if(h > n / 2){ System.out.println("1.0"); System.exit(0); } int makemax = n - h; int makemin = (n+1)/2; double ma = 0; for(int i = makemax; i >= makemin; i--){ Combination c = new Combination(makemax, i); Iterator<int[]> ite = c.iterator(); while(ite.hasNext()){ int[] ret = ite.next(); Set<Integer> make = new HashSet<Integer>(); for(int j = 0; j < ret.length; j++){ if(ret[j] > 0){ make.add(target.get(j)); } } double makeK = 1; int B = 0; for(int j = 0; j < n; j++){ int perc = 0; if(make.contains(j)){ perc = 100 - sn[j][1]; B += sn[j][0]; } else{ perc = sn[j][1]; } makeK *= ((double)perc / 100); } ma += makeK * (1 - (double)A/(A+B)); } } ans = Math.min(ans, ma); } int[][] copy(int[][] sn){ int[][] csn = new int[sn.length][2]; for(int i = 0; i < sn.length; i++){ csn[i][0] = sn[i][0]; csn[i][1] = sn[i][1]; } return csn; } /** * @param args */ public static void main(String[] args) throws Exception{ B2 t = new B2(); t.run(); } public class Combination implements Iterable<int[]> { private final int max; private final int select; public Combination(int max, int select) { if (max < 1 || 62 < max) { throw new IllegalArgumentException(); } this.max = max; this.select = select; } public Iterator<int[]> iterator() { return new CombinationIterator(max, select); } private class CombinationIterator implements Iterator<int[]> { private long value; private final long max; private final int size; private int[] ret = null; public CombinationIterator(int max, int select) { this.value = (1L << select) - 1L; this.size = max; this.max = 1L << max; this.ret = new int[size]; } public boolean hasNext() { return value < max; } public int[] next() { long stock = value; value = next(value); for(int i = 0; i < size; i++){ long tmp = stock >> i; tmp = tmp & 1; ret[i] = (int)tmp; } return ret; } public void remove() { throw new UnsupportedOperationException(); } private long next(long source) { long param1 = smallestBitOf(source); long param2 = param1 + source; long param3 = smallestBitOf(param2); long param5 = (param3 / param1) >>> 1; return param5 - 1 + param2; } private long smallestBitOf(long source) { long result = 1L; while (source % 2 == 0) { source >>>= 1; result <<= 1; } return result; } } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.util.StringTokenizer; public class Main { static int N; static int K; static int A; static double dl[]; static int base[]; static int needed; static int b[] = new int[N]; static int l[] = new int[N]; static double best; static void printLevels() { int i; for (i=0;i<N;i++) { System.out.println(i+" "+dl[i]); } } static void giveCandies(int i, int remaining) { if (remaining == 0) { check(); return; } if (i == N) { check(); return; } int j; double ns; double orig = dl[i]; for (j=0;j<=remaining;j++) { ns = orig+j*0.1; if (ns <= 1.0) { dl[i] = ns; giveCandies(i+1, remaining-j); dl[i] = orig; } else { break; } } } static void check() { int i,j,k; double res = 0.0; int total; double prob; int max = 1<<N; double sumg, sumb; double pk, da = (double)A; for (k=0;k<max;k++) { prob = 1.0; total = 0; sumg = 0; sumb = 0; for (i=0;i<N;i++) { if ((base[i]&k) > 0) { prob *= dl[i]; total++; sumg += b[i]; } else { prob *= (1.0-dl[i]); sumb += b[i]; } } if (total >= needed) { // needed number of senators voted positivelly res += prob; } else { pk = da/(da+sumb); res += prob*pk; } } best = Math.max(best, res); } public static void main(String[] args) throws Exception { int i,j,k; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); K = Integer.parseInt(st.nextToken()); A = Integer.parseInt(st.nextToken()); needed = N/2+1; b = new int[N]; l = new int[N]; dl = new double[N]; for (i=0;i<N;i++) { st = new StringTokenizer(br.readLine()); b[i] = Integer.parseInt(st.nextToken()); l[i] = Integer.parseInt(st.nextToken()); dl[i] = ((double)l[i])/100.0; } base = new int[8]; base[0] = 1; for (i=1;i<N;i++) { base[i] = base[i-1]*2; } best = 0.0; giveCandies(0, K); DecimalFormat df = new DecimalFormat("0.0000000000"); String rs = df.format(best); String mrs = ""; for (i=0;i<rs.length();i++) { if (rs.charAt(i) == ',') { mrs += '.'; } else { mrs += rs.charAt(i); } } System.out.println(mrs); } }
np
105_B. Dark Assembly
CODEFORCES
import java.awt.Point; import java.util.Scanner; public class p105b { static int[] b, l; static int n; static int A; static boolean[] masks; static double max; public static double work(int index, int k, int mask) { if (index == n) { if (Integer.bitCount(mask) * 2 <= n) { int sum = 0; for (int i = 0; i < n; i++) { if (((1 << i) & mask) == 0) { sum += b[i]; } } return (A * 1.0) / (A * 1.0 + sum); } return 1; } double max = 0; int to = Math.min(k, (100 - l[index]) / 10); for (int i = to; i >= 0; i--) { double loy = l[index] + i * 10; double b = ((100.0 - loy) / 100.0) * work(index + 1, k - i, mask); double a = (loy / 100.0) * work(index + 1, k - i, (mask | (1 << index))); max = Math.max(max, a + b); } return max; } public static void rec(int index, int k) { if (k == -1) return; if (index == n) { double tot = 0; for (int i = 0; i < 1 << n; i++) { double temp = 1.0; int bb = 0; for (int j = 0; j < n; j++) { if(l[j]>100) return; if (((1 << j) & i) != 0) { temp *= (l[j] * 1.0 / 100.0); } else { bb += b[j]; temp *= ((100.0 - l[j]) / 100.0); } } if (Integer.bitCount(i) * 2 <= n) { temp *= (A * 1.0) / (A * 1.0 + bb); } tot += temp; } max = Math.max(max, tot); return; } l[index] += 10; rec(index, k - 1); l[index] -= 10; rec(index + 1, k); } public static void main(String[] args) { Scanner in = new Scanner(System.in); n = in.nextInt(); int k = in.nextInt(); A = in.nextInt(); b = new int[n]; l = new int[n]; for (int i = 0; i < n; i++) { b[i] = in.nextInt(); l[i] = in.nextInt(); } masks = new boolean[1 << n]; max = 0; rec(0, k); System.out.println(max); } } /* * 5 3 100 23 70 80 30 153 70 11 80 14 90 */
np
105_B. Dark Assembly
CODEFORCES
import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author pttrung */ public class B { static Senator[] data; public static void main(String[] args) { Scanner in = new Scanner(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int k = in.nextInt(); int A = in.nextInt(); data = new Senator[n]; for (int i = 0; i < n; i++) { data[i] = new Senator(in.nextInt(), in.nextInt()); } out.println(cal(0, new int[n], A, k)); out.close(); } public static double cal(int index, int[] num, int A, int left) { if (index == data.length - 1) { int dif = (100 - data[index].loyal)/10; dif = left >= dif? dif:left; num[index] = dif; double result = 0; for (int k = 0; k < (1 << num.length); k++) { double val = 1; double total = 0; for (int i = 0; i < num.length; i++) { if (((1 << i) & k) != 0) { val *= ((double)(data[i].loyal + 10*num[i])/100); } else { val *= ((double)(100 - (data[i].loyal + 10*num[i]))/100); total += data[i].level; } } if (countBit(k) > num.length / 2) { result += val; } else { result += val * ((double) A / (A + total)); } } // // if(result >= 1){ // for(int i : num){ // System.out.print(i + " "); // } // System.out.println("\n" + result); // //} return result; } else { double result = 0; for (int i = 0; i <= left; i++) { if (i * 10 + data[index].loyal <= 100) { num[index] = i; // double val = cal(index + 1 , num , A, left - i); result = Math.max(result, cal(index + 1, num, A, left - i)); } else { break; } } return result; } } public static int countBit(int val) { int result = 0; while (val > 0) { result += val % 2; val >>= 1; } return result; } public static class Senator { int level, loyal; public Senator(int level, int loyal) { this.level = level; this.loyal = loyal; } } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static class Point { int x, y, z; public Point(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } public double pow(double a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } double val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * val * a; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long lcm(long a, long b) { return a * b / gcd(a, b); } }
np
105_B. Dark Assembly
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 8/13/11 * Time: 6:10 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.io.IOException; public class DarkAssembly extends Thread { public DarkAssembly() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } class Senator { int loyalty; int level; public Senator(int level, int loyalty) { this.level = level; this.loyalty = loyalty; } } private static double doIt(Senator[] senators, int A) { double probability = .0; for (int mask = 0; mask < (1 << senators.length); ++mask) { int sum = A; double current = 1.0; for (int i = 0; i < senators.length; ++i) { if ((mask & (1 << i)) != 0) { current *= .01 * Math.min(senators[i].loyalty, 100); } else { current *= .01 * (100 - Math.min(senators[i].loyalty, 100)); sum += senators[i].level; } } if (getOnes(mask) > senators.length / 2) { probability += current; } else { probability += current * (double)A / sum; } } return probability; } private static double go(Senator []senators, int candies, int A, int current) { if (current == senators.length) { return doIt(senators, A); } else { double result = Double.MIN_VALUE; if (candies > 0) { senators[current].loyalty += 10; result = Math.max(result, go(senators, candies - 1, A, current)); senators[current].loyalty -= 10; } result = Math.max(result, go(senators, candies, A, current + 1)); return result; } } static int getOnes(int mask) { int result = 0; while (mask != 0) { mask &= mask - 1; ++result; } return result; } public void run() { try { int n = nextInt(); int k = nextInt(); int A = nextInt(); Senator[] senators = new Senator[n]; for (int i = 0; i < n; ++i) { senators[i] = new Senator(nextInt(), nextInt()); } output.printf("%.10f", go(senators, k, A, 0)); output.flush(); output.close(); } catch (Throwable e) { System.err.println(e.getMessage()); System.err.println(Arrays.deepToString(e.getStackTrace())); } } public static void main(String[] args) { new DarkAssembly().start(); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
105_B. Dark Assembly
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 int nextPerm(int[] a, int k) { if (a[0] == k) return -1; int last = 0; for (int i = a.length - 1; i >= 0; i--) if (a[i] != 0) { last = i; break; } int mem=a[last]; a[last-1]++; a[last]=0; a[a.length-1]=mem-1; return 0; } public double poss(int A,int[][] sen,int[] rasp){ int n=sen.length; double[] possluck=new double[n]; for(int i=0;i<n;i++) possluck[i]=Math.min(100, sen[i][1]+rasp[i]*10)/100.0; double poss=0; for(int i=0;i<(1<<n);i++){ int kol=0; for(int j=0;j<n;j++) if((i%(1<<(j+1)))/(1<<(j))==1) kol++; double thisposs=1; for(int j=0;j<n;j++) if((i%(1<<(j+1)))/(1<<(j))==1) thisposs*=possluck[j]; else thisposs*=(1-possluck[j]); if(kol>n/2) poss+=thisposs; else{ double lvl=0; for(int j=0;j<n;j++) if((i%(1<<(j+1)))/(1<<(j))==0) lvl+=sen[j][0]; poss+=thisposs*(A/(A+lvl)); } } return poss; } public void solve() throws Exception { int n = iread(), k = iread(), A = iread(); int[][] sen = new int[n][2]; for (int i = 0; i < n; i++) { sen[i][0] = iread(); sen[i][1] = iread(); } double maxposs=0; int[] rasp=new int[n]; rasp[n-1]=k; maxposs=Math.max(maxposs, poss(A,sen,rasp)); while(nextPerm(rasp,k)==0) maxposs=Math.max(maxposs, poss(A,sen,rasp)); out.write(maxposs+"\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
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Collection; import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.ArrayList; import java.util.StringTokenizer; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author AlexFetisov */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { private double[][][] dp; private int n; private int k; private int[] loyalty; private int[] level; double[] P; private int a; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); k = in.nextInt(); a = in.nextInt(); level = new int[n]; loyalty = new int[n]; for (int i = 0; i < n; ++i) { level[i] = in.nextInt(); loyalty[i] = in.nextInt(); } P = new double[1 << n]; for (int mask = 0; mask < (1 << n); ++mask) { if (Integer.bitCount(mask) * 2 > n) { P[mask] = 1.; } else { double sumB = 0; for (int i = 0; i < n; ++i) { if (!BitUtils.checkBit(mask, i)) { sumB += level[i]; } } P[mask] = (double)a / (sumB + a); } } dp = new double[1 << n][n + 1][k + 1]; ArrayUtils.fill(dp, -1); newLoyalty = new int[n]; //double res = rec(0, 0, k, 0); brute(0, k); out.println(best); } int[] newLoyalty; double best = 0; void brute(int id, int leftCandies) { if (id == n) { double cur = calcCur(); if (best < cur) { best = cur; } return; } for (int candies = 0; candies <= leftCandies; ++candies) { newLoyalty[id] = loyalty[id] + candies * 10; if (newLoyalty[id] > 100) { break; } brute(id + 1, leftCandies - candies); } } private double calcCur() { double sum = 0; for (int mask = 0; mask < (1 << n); ++mask) { double p = getP(mask) * P[mask]; sum += p; } return sum; } private double getP(int mask) { double p = 1; for (int i = 0; i < n; ++i) { if (BitUtils.checkBit(mask, i)) { p *= (newLoyalty[i] * 1.) / 100.; } else { p *= (100. - newLoyalty[i]) / 100.; } } return p; } } class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine().trim(); } catch (IOException e) { return null; } } public String nextString() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(nextString()); } } class BitUtils { public static boolean checkBit(int mask, int bit) { return (mask & (1 << bit)) > 0; } } class ArrayUtils { public static void fill(double[][][] f, double value) { for (int i = 0; i < f.length; ++i) { for (int j = 0; j < f[i].length; ++j) { Arrays.fill(f[i][j], value); } } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintWriter; import java.util.Arrays; import java.io.OutputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { double special(int[] loyalties, int[] levels, int playerlevelsum) { int poss = 1 << loyalties.length; double res = 0; for(int pos = 0; pos < poss; pos++) { double occurs = 1; int happy = 0; int badlevelssum = 0; for(int i = 0; i < loyalties.length; i++) { if(((pos >> i) & 1) == 1) { //happy senator happy++; occurs *= (double) loyalties[i] / 100; } else { //unhappy senator badlevelssum += levels[i]; occurs *= (double) (100 - loyalties[i]) / 100; } } double winprob = (happy <= levels.length / 2) ? (double) playerlevelsum / (playerlevelsum + badlevelssum) : 1; // System.err.println(pos + " " + (happy <= levels.length / 2) + " " + playerlevelsum + " " + (playerlevelsum + badlevelssum) + " " + occurs + " " + winprob + " " + occurs * winprob); res += occurs * winprob; } return res; } public void solve(int testNumber, InputReader in, OutputWriter out) { int senators = in.readInt(); // n, [1, 8] int sweets = in.readInt(); // k, [1, 8] int playerlevelsum = in.readInt(); // A, [1, 9999] int[] levels = new int[senators]; // [1, 9999] int[] loyalties = new int[senators]; // [0, 100] divisible by 10 IOUtils.readIntArrays(in, levels, loyalties); ArrayList<ArrayList<Integer>> possibilities = new ArrayList<>(Arrays.asList(new ArrayList<>())); for(int senator = 0; senator < senators; senator++) { ArrayList<ArrayList<Integer>> newpossibilities = new ArrayList<>(); for(ArrayList<Integer> al : possibilities) { int sumsofar = 0; for(int val : al) sumsofar += val; int minadd = senator == senators - 1 ? sweets - sumsofar : 0; for(int moar = minadd; moar <= sweets - sumsofar; moar++) { ArrayList<Integer> copy = new ArrayList<>(al); copy.add(moar); newpossibilities.add(copy); } } possibilities = newpossibilities; } double res = 0; // out.printLine(possibilities.size()); for(ArrayList<Integer> al : possibilities) { int[] newloyalties = new int[senators]; for(int i = 0; i < senators; i++) newloyalties[i] = Math.min(100, loyalties[i] + 10 * al.get(i)); // out.printLine(al); // out.printLine(newloyalties); // double works = dp(0, 0, newloyalties); double special = special(newloyalties, levels, playerlevelsum); double tot = special; res = Math.max(res, tot); } out.printLine(res); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if(numChars == -1) throw new InputMismatchException(); if(curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch(IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if(c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while(!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if(filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for(int i = 0; i < objects.length; i++) { if(i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class IOUtils { public static void readIntArrays(InputReader in, int[]... arrays) { for(int i = 0; i < arrays[0].length; i++) { for(int j = 0; j < arrays.length; j++) arrays[j][i] = in.readInt(); } } } }
np
105_B. Dark Assembly
CODEFORCES
import java.util.*; import java.math.*; import static java.lang.Character.isDigit; import static java.lang.Character.isLowerCase; import static java.lang.Character.isUpperCase; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.lang.Character.isDigit; public class Main{ static void debug(Object...os){ System.err.println(deepToString(os)); } int n,A; int[] bs,ls; void run(){ n=nextInt();int k=nextInt();A=nextInt(); bs=new int[n];ls=new int[n]; for(int i=0;i<n;i++) { bs[i]=nextInt();ls[i]=nextInt(); } dfs(k,0); System.out.println(res); } double res=0; private void dfs(int k,int i){ if(i==n) { double val=0; for(int j=0;j<1<<n;j++) {// 1 approve double p=1; int B=0; for(int l=0;l<n;l++)p*= (j>>l&1)==1 ? ls[l]/100.0 : (100-ls[l])/100.0; for(int l=0;l<n;l++)if((j>>l&1)==0)B += bs[l]; if(Integer.bitCount(j) > n/2) { val += p; }else { val += p * A / (A+B); } } res=max(res,val); return; } for(int j=0;j<k+1;j++) { ls[i]+=j*10; if(ls[i]<=100) { dfs(k-j,i+1); } ls[i]-=j*10; } } int nextInt(){ try{ int c=System.in.read(); if(c==-1) return c; while(c!='-'&&(c<'0'||'9'<c)){ c=System.in.read(); if(c==-1) return c; } if(c=='-') return -nextInt(); int res=0; do{ res*=10; res+=c-'0'; c=System.in.read(); }while('0'<=c&&c<='9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c=System.in.read(); if(c==-1) return -1; while(c!='-'&&(c<'0'||'9'<c)){ c=System.in.read(); if(c==-1) return -1; } if(c=='-') return -nextLong(); long res=0; do{ res*=10; res+=c-'0'; c=System.in.read(); }while('0'<=c&&c<='9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res=new StringBuilder(""); int c=System.in.read(); while(Character.isWhitespace(c)) c=System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res=new StringBuilder(""); int c=System.in.read(); while(c=='\r'||c=='\n') c=System.in.read(); do{ res.append((char)c); c=System.in.read(); }while(c!='\r'&&c!='\n'); return res.toString(); }catch(Exception e){ return null; } } public static void main(String[] args){ new Main().run(); } }
np
105_B. Dark Assembly
CODEFORCES
import java.awt.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; public class B { static int ourLevel; 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 k = Integer.parseInt(st.nextToken()); ourLevel = Integer.parseInt(st.nextToken()); State[] list = new State[n]; for(int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); list[i] = new State(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())/10); } System.out.println(solve(list, 0, k)); } public static double solve(State[] s, int index, int left) { if(index == s.length) return prob(s); double ret = 0; for(int c = 0; c <= left && s[index].prob + c <= 10; c++) { s[index].prob += c; ret = Math.max(ret, solve(s, index+1, left-c)); s[index].prob -= c; } return ret; } public static double prob(State[] s) { double win = 1; for(int i = 0; i < (1<<s.length); i++) { int numLose = s.length - Integer.bitCount(i); if(2*numLose >= s.length) { int level = 0; double p = 1; for(int j = 0; j < s.length; j++) { if((i&(1<<j)) == 0) { p *= (10-s[j].prob)/10.; level += s[j].level; } else { p *= s[j].prob/10.; } } double lose = level * 1.0 / (ourLevel + level); win -= p * lose; } } return win; } static class State { public int level,prob; public State(int a, int b) { level = a; prob = b; } } }
np
105_B. Dark Assembly
CODEFORCES
import java.util.Arrays; import java.util.PriorityQueue; import java.util.Scanner; public class Main { static double max = 0.0; public static void main(String[] args) { Scanner r = new Scanner(System.in); int n = r.nextInt(); int k = r.nextInt(); int A = r.nextInt(); Person[] p = new Person[n]; for(int i = 0; i < n; i++){ int l = r.nextInt(); int prob = r.nextInt(); p[i] = new Person(l, prob); } int[] add = new int[n]; double res = dfs(0, k, p, add, n, A); System.out.println(res); } private static double dfs(int ptr, int k, Person[] p, int[] add, int n, int A) { if(k < 0)return 0; double res1 = 0; for(int m = 0; m < 1<<n; m++){ double win = 1; int cnt = 0; for(int i = 0; i < n; i++){ if((m & (1 << i)) == 0){ win *= (100-(p[i].p+add[i]))*1.0/100; }else{ win *= (add[i]+p[i].p)*1.0/100; cnt++; } } if(cnt > n/2){ res1 += win; }else{ int B = 0; for(int i = 0; i < n; i++){ if((m & (1 << i)) == 0){ B += p[i].l; } } win *= A*1.0/(A+B); res1 += win; } } double res2 = 0, res3 = 0; if(add[ptr]+p[ptr].p < 100){ add[ptr] += 10; res2 = dfs(ptr, k-1, p, add, n, A); add[ptr] -= 10; } if(ptr+1 < n){ res3 = dfs(ptr+1, k, p, add, n, A); } return Math.max(res1, Math.max(res2, res3)); } } class Person{ int l, p; public Person(int li, int pi){ l = li; p = pi; } public String toString(){ return String.format("[%d, %d]", l, p); } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class BNew { double gAns = 0; public static void main(String[] args) throws IOException { new BNew().solve(); } private void solve() throws IOException { MyScanner in = new MyScanner(new BufferedReader(new InputStreamReader(System.in))); int n = in.nextInt(); int k = in.nextInt(); int A = in.nextInt(); List<Senator> allSenators = new ArrayList<Senator>(); for (int i = 0; i < n; i++) { int level = in.nextInt(); int loyalty = in.nextInt(); allSenators.add(new Senator(level, loyalty)); } allSenators = Collections.unmodifiableList(allSenators); int npow2 = 1 << n; rec(allSenators, 0, k, A); for (int okSenatorMask = 0; okSenatorMask < npow2; okSenatorMask++) { List<Senator> okSenators = copy(getSenatorsByMask(okSenatorMask, allSenators)); liftLeastSenators(okSenators, k); List<Senator> updatedSenators = new ArrayList<Senator>(okSenators); List<Senator> otherSenators = getSenatorsByMask(npow2 - 1 - okSenatorMask, allSenators); updatedSenators.addAll(otherSenators); check(updatedSenators, A); } in.close(); PrintWriter pw = new PrintWriter(System.out); System.out.printf("%.6f\n", gAns); pw.close(); } private void rec(List<Senator> senators, int senatorId, int k, int A) { if (senatorId == senators.size()) { check(senators, A); return; } Senator senator = senators.get(senatorId); int up = Math.min(k, (100 - senator.loyalty) / 10); final int old = senator.loyalty; for (int i = 0; i <= up; i++) { senator.loyalty = old + i * 10; rec(senators, senatorId + 1, k - i, A); } senator.loyalty = old; } private void check(List<Senator> senators, double A) { double winProp = 0.0; for (int mask = 0; mask < 1 << senators.size(); mask++) { double caseP = 1.0; int okCnt = 0; int notOkLevelSum = 0; for (int i = 0; i < senators.size(); i++) { Senator senator = senators.get(i); double senatorLoyalty = senator.loyalty / 100.0; boolean ok = (mask & (1 << i)) != 0; if (ok) { caseP *= senatorLoyalty; okCnt++; } else { caseP *= (1 - senatorLoyalty); notOkLevelSum += senator.level; } } if (okCnt * 2 > senators.size()) { winProp += caseP; } else { double killProp = A / (A + notOkLevelSum); winProp += caseP * killProp; } } gAns = Math.max(gAns, winProp); } List<Senator> copy(List<Senator> senators) { List<Senator> copied = new ArrayList<Senator>(); for (Senator senator : senators) { copied.add(new Senator(senator.level, senator.loyalty)); } return copied; } void liftLeastSenators(List<Senator> senators, int k) { if (senators.isEmpty()) { return; } for (int i = 0; i < k; i++) { Senator least = senators.get(0); for (Senator senator : senators) { if (senator.loyalty < least.loyalty) { least = senator; } } if (least.loyalty < 100) { least.loyalty += 10; } } } List<Senator> getSenatorsByMask(int mask, List<Senator> allSenators) { List<Senator> list = new ArrayList<Senator>(); for (int i = 0; i < allSenators.size(); i++) { if ((mask & (1 << i)) != 0) { list.add(allSenators.get(i)); } } return list; } static class Senator { final int level; int loyalty; Senator(int level, int loyalty) { this.level = level; this.loyalty = loyalty; } @Override public String toString() { return "{" + "level=" + level + ", loyalty=" + loyalty + '}'; } } static class MyScanner { final BufferedReader myBr; StringTokenizer st = new StringTokenizer(""); MyScanner(BufferedReader br) { myBr = br; } String nextToken() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(myBr.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } void close() throws IOException { myBr.close(); } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.*; import java.util.*; public class B { int n, k, a; int[] b, l; double best; double calc(int i, int r, int c, double p) { if (i == n) { if (c <= n / 2) { p *= 1.0 * a / (a + r); } return p; } else { return calc(i + 1, r, c + 1, p * l[i] / 10.0) + calc(i + 1, r + b[i], c, p * (10 - l[i]) / 10.0); } } void go(int i, int k) { if (i == n) { double p = calc(0, 0, 0, 1.0); if (p > best) best = p; } else { for (int c = 0; c <= k && l[i] + c <= 10; ++c) { l[i] += c; go(i + 1, k - c); l[i] -= c; } } } void solve() throws IOException { in("__std"); out("__std"); n = readInt(); k = readInt(); a = readInt(); b = new int[n]; l = new int[n]; for (int i = 0; i < n; ++i) { b[i] = readInt(); l[i] = readInt() / 10; } go(0, k); println("%.10f", best); exit(); } void in(String name) throws IOException { if (name.equals("__std")) { in = new BufferedReader(new InputStreamReader(System.in)); } else { in = new BufferedReader(new FileReader(name)); } } void out(String name) throws IOException { if (name.equals("__std")) { out = new PrintWriter(System.out); } else { out = new PrintWriter(name); } } void exit() { out.close(); System.exit(0); } int readInt() throws IOException { return Integer.parseInt(readToken()); } long readLong() throws IOException { return Long.parseLong(readToken()); } double readDouble() throws IOException { return Double.parseDouble(readToken()); } String readLine() throws IOException { st = null; return in.readLine(); } String readToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } boolean eof() throws IOException { return !in.ready(); } void print(String format, Object ... args) { out.println(new Formatter().format(format, args)); } void println(String format, Object ... args) { out.println(new Formatter().format(format, args)); } void print(Object value) { out.print(value); } void println(Object value) { out.println(value); } void println() { out.println(); } StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) throws IOException { new B().solve(); } }
np
105_B. Dark Assembly
CODEFORCES