src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringlengths 6
50
| from
stringclasses 1
value |
---|---|---|---|
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class ElongatedMatrix {
static int[][][] memo;
static int mn1[][];
static int mn2[][];
static int r, c;
static int dp(int mask, int first, int lastvisited) {
if (memo[first][lastvisited][mask] != -1)
return memo[first][lastvisited][mask];
int ans = 0;
for (int i = 0; i < r; i++) {
if ((mask & (1 << i)) == 0) {
if (Integer.bitCount(mask) != r - 1) {
ans = Math.max(ans, Math.min(mn1[lastvisited][i], dp(((mask) | (1 << i)), first, i)));
} else
ans = Math.max(ans, Math.min(mn2[first][i], mn1[lastvisited][i]));
}
}
//System.out.println(ans);
return memo[first][lastvisited][mask] = ans;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
PrintWriter out = new PrintWriter(System.out);
r = Integer.parseInt(st.nextToken());
c = Integer.parseInt(st.nextToken());
int[][] arr = new int[r][c];
memo = new int[r][r][1 << r];
mn1 = new int[r][r];
mn2 = new int[r][r];
for(int i=0;i<r;i++) {
st=new StringTokenizer(br.readLine());
for(int j=0;j<c;j++) {
arr[i][j]=Integer.parseInt(st.nextToken());
}
}
for (int i = 0; i < r; i++) {
Arrays.fill(mn1[i], (int)1e9);
Arrays.fill(mn2[i], (int)1e9);
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < r; j++) {
Arrays.fill(memo[i][j], -1);
}
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < r; j++) {
for (int k = 0; k < c; k++) {
mn1[i][j] = Math.min(mn1[i][j], Math.abs(arr[i][k] - arr[j][k]));
}
}
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < r; j++) {
for (int k = 0; k < c-1; k++) {
mn2[i][j] = Math.min(mn2[i][j], Math.abs(arr[j][k] - arr[i][k + 1]));
}
}
}
int ans = 0;
for (int i = 0; i < r; i++) {
ans=Math.max(ans, dp(1<<i,i,i));
}
if(r==1)
ans=mn2[0][0];
out.println(ans);
out.flush();
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
//package ;
import java.io.*;
import java.util.*;
public class D {
static int dp(int i,int start,int msk)
{
if(Integer.bitCount(msk)==n)
return s_e[i][start];
if(dp[i][start][msk]!=-1)
return dp[i][start][msk];
int max=0;
for(int k=0;k<n;k++)
{
int min=Integer.MAX_VALUE;
if((msk & (1<<k)) == 0 )
{
min=diff[i][k];
min=Math.min(min, dp(k,start,msk | (1<<k)));
max=Math.max(max, min);
}
}
return dp[i][start][msk]=max;
}
static int n,m,a[][],dp[][][],diff[][],s_e[][];
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter pw = new PrintWriter(System.out);
n=sc.nextInt();
m=sc.nextInt();
a=new int[n][m];
diff=new int[n][n];
s_e=new int[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
a[i][j]=sc.nextInt();
dp=new int[n][n][70000];
int ans=0;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
Arrays.fill(dp[i][j], -1);
diff[i][j]=Integer.MAX_VALUE;
s_e[i][j]=Integer.MAX_VALUE;
for(int k=0;k<m-1;k++)
{
diff[i][j]=Math.min(Math.abs(a[i][k]-a[j][k]), diff[i][j]);
s_e[i][j]=Math.min(Math.abs(a[i][k]-a[j][k+1]), s_e[i][j]);
}
diff[i][j]=Math.min(Math.abs(a[i][m-1]-a[j][m-1]), diff[i][j]);
}
for(int i=0;i<n;i++)
ans=Math.max(ans, dp(i,i,1<<i));
pw.print(ans);
pw.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while (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());
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasnext() throws IOException {
return br.ready();
}
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main implements Runnable {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new Main(),"Main",1<<26).start();
}
static long gcd(long a,long b){ if(b==0)return a;return gcd(b,a%b); }
static long modPow(long a,long p,long m){ if(a==1)return 1;long ans=1;while (p>0){ if(p%2==1)ans=(ans*a)%m;a=(a*a)%m;p>>=1; }return ans; }
static long modInv(long a,long m){return modPow(a,m-2,m);}
static long sol_x,sol_y,gcd_a_b;
static void extendedEuclid(long a,long b){ if(b==0){gcd_a_b=a;sol_x=1;sol_y=0; } else{ extendedEuclid(b,a%b);long temp = sol_x;sol_x=sol_y;sol_y = temp - (a/b)*sol_y; } }
static class Bhavansort{ Random random;Bhavansort(int a[]){ randomArray(a); sort(a);}Bhavansort(long a[]){ randomArray(a); sort(a);}static int[] sort(int a[]){ Arrays.sort(a);return a;}static long[] sort(long a[]){ Arrays.sort(a);return a; }void randomArray(long a[]){ int n=a.length;for(int i=0;i<n;i++){ int p=random.nextInt(n)%n;long tm=a[i];a[i]=a[p];a[p]=tm; } }void randomArray(int a[]){ int n=a.length;for(int i=0;i<n;i++){ int p=random.nextInt(n)%n;int tm=a[i];a[i]=a[p];a[p]=tm; } }}
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt();
int m=sc.nextInt();
int a[][]=new int[n][m];
for (int i = 0; i <n ; i++) {
for (int j = 0; j <m ; j++) {
a[i][j]=sc.nextInt();
}
}
int cost[][]=new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <n ; j++) {
cost[i][j]=Integer.MAX_VALUE;
for (int k = 0; k <m ; k++) {
cost[i][j]=Math.min(cost[i][j],Math.abs(a[i][k]-a[j][k]));
}
}
}
int costRight[][]=new int[n][n];
for (int i = 0; i <n ; i++) {
for (int j = 0; j <n ; j++) {
costRight[i][j]=Integer.MAX_VALUE;
for (int k = 0; k <m-1 ; k++) {
costRight[i][j]=Math.min(Math.abs(a[i][k+1]-a[j][k]),costRight[i][j]);
}
}
}
/*for (int i = 0; i <n ; i++) {
for (int j = 0; j <n ; j++) {
out.print(cost[i][j]+" ");
}
out.println();
}
out.println();
for (int i = 0; i <n ; i++) {
for (int j = 0; j <n ; j++) {
out.print(costRight[i][j]+" ");
}
out.println();
}*/
if(n==1){
int ans=Integer.MAX_VALUE;
for (int i = 0; i <m-1 ; i++) {
ans=Math.min(ans,Math.abs(a[0][i]-a[0][i+1]));
}
out.println(ans);
out.close();
return;
}
Long dp[][][]=new Long[n+1][n+1][1<<n];
long max=0;
for (int i = 0; i <n ; i++) {
// out.println(f(i,i,1<<i,dp,n,cost,costRight));
max=Math.max(max,f(i,i,1<<i,dp,n,cost,costRight));
}
out.println(max);
out.close();
}
long f(int start,int end,int mask,Long dp[][][],int n,int cost[][],int costRight[][]){
if(dp[start][end][mask]!=null)return dp[start][end][mask];
long ans=Integer.MIN_VALUE;
for (int i = 0; i <n ; i++) {
if((mask&(1<<i))==0){
int newMask=mask|(1<<i);
if((1<<n)-1!=(mask|(1<<i))){
ans = Math.max(ans, Math.min(cost[end][i], f(start, i, newMask, dp, n, cost, costRight)));
}
else{
ans=Math.max(ans,Math.min(cost[end][i],costRight[start][i]));
}
}
}
return dp[start][end][mask]=ans;
}
} | np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class ElongatedMatrix {
public static void main(String[] args) {
InputStream input;
OutputStream output;
try {
input = new FileInputStream("input.txt");
output = new FileOutputStream("output.txt");
} catch (FileNotFoundException e) {
input = System.in;
output = System.out;
}
Kattio io = new Kattio(input, output);
(new Solve(io)).main();
io.close();
if (input instanceof FileInputStream)
try {
input.close();
} catch (IOException e) {
}
if (output instanceof FileOutputStream)
try {
output.close();
} catch (IOException e) {
}
}
}
class Solve {
static final int oo = (int) 1e9;
Kattio io;
int n, m;
int[][] a;
int[][][] dp;
int[][] diff;
int[][] slant;
Solve(Kattio io) {
this.io = io;
}
int getbit(int x, int n) {
n--;
return (x >> n) & 1;
}
int setbit(int x, int n) {
n--;
return x | (1 << n);
}
int caldp(int currentRow, int firstRow, int mask) {
if (dp[currentRow][firstRow][mask] != -1)
return dp[currentRow][firstRow][mask];
dp[currentRow][firstRow][mask] = 0;
if (mask == (1 << n) - 1)
dp[currentRow][firstRow][mask] = slant[currentRow][firstRow];
else {
for (int i = 1; i <= n; i++)
if (getbit(mask, i) == 0) {
dp[currentRow][firstRow][mask] = Math.max(
Math.min(caldp(i, firstRow, setbit(mask, i)), diff[currentRow][i]),
dp[currentRow][firstRow][mask]);
}
}
return dp[currentRow][firstRow][mask];
}
void main() {
n = io.getInt();
m = io.getInt();
a = new int[n+1][m+1];
dp = new int[n+1][n+1][1<<n];
for (int i=1; i<=n; i++)
for (int j=1; j<=m; j++)
a[i][j] = io.getInt();
diff = new int[n+1][n+1];
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++)
{
diff[i][j]=oo;
for (int x=1; x<=m; x++)
diff[i][j]=Math.min(diff[i][j], Math.abs(a[i][x]-a[j][x]));
}
slant = new int[n+1][n+1];
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++)
{
slant[i][j] = oo;
for (int x=1; x+1<=m; x++)
slant[i][j] = Math.min(slant[i][j], Math.abs(a[i][x]-a[j][x+1]));
}
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++)
Arrays.fill(dp[i][j], -1);
int res = 0;
for (int i=1; i<=n; i++)
res = Math.max(res, caldp(i,i,setbit(0,i)));
io.print(res);
}
}
class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int getInt() {
return Integer.parseInt(nextToken());
}
public double getDouble() {
return Double.parseDouble(nextToken());
}
public long getLong() {
return Long.parseLong(nextToken());
}
public String getWord() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
} | np | 1102_F. Elongated Matrix | 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);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[][] graph = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
graph[i][j] = in.nextInt();
}
int[][] mn1 = new int[n][n];
int[][] mn2 = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
int min_val = Integer.MAX_VALUE;
for (int k = 0; k < m; k++)
min_val = Math.min(min_val, Math.abs(graph[i][k] - graph[j][k]));
mn1[i][j] = min_val;
min_val = Integer.MAX_VALUE;
for (int k = 0; k < m - 1; k++) {
min_val = Math.min(min_val, Math.abs(graph[i][k] - graph[j][k + 1]));
}
mn2[i][j] = min_val;
}
int[][] dp = new int[(1 << (n + 2))][n];
int ans = 0;
for (int i = 0; i < n; i++) {
for (int[] temp : dp)
Arrays.fill(temp, -1);
for (int j = 0; j < n; j++) {
dp[1 << j][j] = (j == i ? Integer.MAX_VALUE : 0);
// dp[1 << j][j] = (j == i ? 0: Integer.MAX_VALUE );
}
for (int j = 0; j < n; j++) {
ans = Math.max(ans, Math.min(mn2[j][i], calc((1 << n) - 1, j, dp, mn1, n)));
}
}
out.println(ans);
}
public int calc(int mask, int v, int[][] dp, int[][] mn1, int n) {
// System.out.println(mask+","+v);
if (dp[mask][v] != -1)
return dp[mask][v];
dp[mask][v] = 0;
for (int u = 0; u < n; u++) {
if (u != v && (((mask >> u) & 1) == 1))
dp[mask][v] = Math.max(dp[mask][v], Math.min(mn1[u][v], calc(mask ^ (1 << v), u, dp, mn1, n)));
}
return dp[mask][v];
}
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
FElongatedMatrix solver = new FElongatedMatrix();
solver.solve(1, in, out);
out.close();
}
}
static class FElongatedMatrix {
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
int m = in.readInt();
int[][] mat = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mat[i][j] = in.readInt();
}
}
int[][] minDist = new int[n][n];
SequenceUtils.deepFill(minDist, (int) 1e9);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < m; k++) {
minDist[i][j] = Math.min(minDist[i][j], Math.abs(mat[i][k] - mat[j][k]));
}
}
}
int[][] minDistBetweenHeadAndTail = new int[n][n];
SequenceUtils.deepFill(minDistBetweenHeadAndTail, (int) 1e9);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 1; k < m; k++) {
minDistBetweenHeadAndTail[i][j] = Math.min(minDistBetweenHeadAndTail[i][j], Math.abs(mat[i][k] - mat[j][k - 1]));
}
}
}
Log2 log2 = new Log2();
BitOperator bo = new BitOperator();
int[][][] dp = new int[1 << n][n][n];
for (int i = 1; i < (1 << n); i++) {
if (i == Integer.lowestOneBit(i)) {
dp[i][log2.floorLog(i)][log2.floorLog(i)] = (int) 1e9;
continue;
}
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
if (bo.bitAt(i, j) == 0) {
continue;
}
for (int t = 0; t < n; t++) {
dp[i][j][k] = Math.max(dp[i][j][k],
Math.min(dp[bo.setBit(i, j, false)][t][k],
minDist[j][t]));
}
}
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
ans = Math.max(ans, Math.min(dp[(1 << n) - 1][i][j], minDistBetweenHeadAndTail[j][i]));
}
}
out.println(ans);
}
}
static class SequenceUtils {
public static void deepFill(Object array, int val) {
if (!array.getClass().isArray()) {
throw new IllegalArgumentException();
}
if (array instanceof int[]) {
int[] intArray = (int[]) array;
Arrays.fill(intArray, val);
} else {
Object[] objArray = (Object[]) array;
for (Object obj : objArray) {
deepFill(obj, val);
}
}
}
}
static class Log2 {
public int floorLog(int x) {
return 31 - Integer.numberOfLeadingZeros(x);
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
static class BitOperator {
public int bitAt(int x, int i) {
return (x >> i) & 1;
}
public int setBit(int x, int i, boolean v) {
if (v) {
x |= 1 << i;
} else {
x &= ~(1 << i);
}
return x;
}
}
static class FastOutput implements AutoCloseable, Closeable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput println(int c) {
cache.append(c).append('\n');
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.*;
import java.util.*;
public class F
{
static Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int n,m,res=0;
static int[][] a=new int[20][10005],Min=new int[20][20],Min1=new int[20][20];
static int[][][] f=new int[1<<16][20][20];
static int GetBit(int x,int k)
{
return (x>>k)&1;
}
static int TurnBit(int x,int k)
{
return x^(1<<k);
}
public static void main(String[] args)
{
n=in.nextInt();
m=in.nextInt();
for(int i=0;i<n;i++)
for(int j=1;j<=m;j++)
a[i][j]=in.nextInt();
if(n==1)
{
res=(int)1e9;
for(int i=1;i<m;i++)
res=Math.min(res,Math.abs(a[0][i]-a[0][i+1]));
out.print(res);
out.close();
return;
}
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
Min[i][j]=Min1[i][j]=(int)1e9;
for(int t=1;t<=m;t++)
Min[i][j]=Math.min(Min[i][j],Math.abs(a[i][t]-a[j][t]));
for(int t=1;t<m;t++)
Min1[i][j]=Math.min(Min1[i][j],Math.abs(a[i][t]-a[j][t+1]));
}
for(int i=0;i<n;i++)
f[1<<i][i][i]=(int)1e9;
for(int mask=0;mask<(1<<n);mask++)
if(Integer.bitCount(mask)>1)
for(int i=0;i<n;i++)
if(GetBit(mask,i)==1)
for(int j=0;j<n;j++)
if(i!=j&&GetBit(mask,j)==1)
{
for(int t=0;t<n;t++)
if(j!=t&&GetBit(mask,t)==1)
f[mask][i][j]=Math.max(f[mask][i][j],Math.min(f[TurnBit(mask,j)][i][t],Min[j][t]));
if(mask==(1<<n)-1)
res=Math.max(res,Math.min(f[mask][i][j],Min1[j][i]));
}
out.print(res);
out.close();
}
} | np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
static class Task {
int NN = 1000006;
int MOD = 998244353;
int INF = 2000000000;
long INFINITY = 1000000000000000000L;
long [][] a;
long [][] w, w1;
long [][] dp;
int countBit(int num) {
int ret = 0;
while(num > 0) {
if((num&1)!=0)
++ret;
num >>= 1;
}
return ret;
}
long rec(int at, int mask, int n, int start) {
long ans = -INFINITY;
if(dp[at][mask] != -1)
return dp[at][mask];
if(countBit(mask) == n) {
return dp[at][mask] = w1[start][at];
}
for(int i=0;i < n;++i) {
if(((mask>>i)&1)==0) {
ans = Math.max(ans,
Math.min(w[at][i], rec(i, mask | (1<<i), n, start)));
}
}
return dp[at][mask] = ans;
}
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt(), m = in.nextInt();
dp = new long[n][1<<n];
a = new long[n][m];
w = new long[n][n];
w1 = new long[n][n];
for(int i=0;i<n;++i) {
for(int j=0;j<m;++j) {
a[i][j] = in.nextLong();
}
}
for(int i=0;i<n;++i) {
for(int j=0;j<n;++j) {
w[i][j] = INFINITY;
if(i == j)
continue;
for(int k=0;k<m;++k) {
w[i][j] = Math.min(w[i][j], Math.abs(a[j][k] - a[i][k]));
}
}
}
for(int i=0;i<n;++i) {
for(int j=0;j<n;++j) {
w1[i][j] = INFINITY;
for(int k=1;k<m;++k) {
w1[i][j] = Math.min(w1[i][j], Math.abs(a[i][k] - a[j][k - 1]));
}
}
}
long ans = 0;
for(int start = 0;start < n;++start) {
for(int i=0;i<n;++i) {
for(int j=0;j<(1<<n);++j)
dp[i][j] = -1;
}
ans = Math.max(ans, rec(start, 1<<start, n, start));
}
out.println(ans);
}
class Pair {
Integer first, second;
public Pair() {
}
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
private Task getOuterType() {
return Task.this;
}
}
}
static void prepareIO(boolean isFileIO) {
Task solver = new Task();
// Standard IO
if(!isFileIO) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solver.solve(in, out);
out.close();
}
// File IO
else {
String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in";
String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out";
InputReader fin = new InputReader(IPfilePath);
PrintWriter fout = null;
try {
fout = new PrintWriter(new File(OPfilePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
solver.solve(fin, fout);
fout.close();
}
}
public static void main(String[] args) {
prepareIO(false);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public InputReader(String filePath) {
File file = new File(filePath);
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tokenizer = null;
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.*;
import java.util.*;
public class CF1102F {
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 m = Integer.parseInt(st.nextToken());
int[][] aa = new int[n][m];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < m; j++)
aa[i][j] = Integer.parseInt(st.nextToken());
}
int[][] dd = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
int d = Integer.MAX_VALUE;
for (int h = 0; h < m; h++)
d = Math.min(d, Math.abs(aa[i][h] - aa[j][h]));
dd[i][j] = dd[j][i] = d;
}
int[][] dd_ = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
int d = Integer.MAX_VALUE;
for (int h = 0; h < m - 1; h++)
d = Math.min(d, Math.abs(aa[i][h] - aa[j][h + 1]));
dd_[i][j] = d;
}
if (n == 1) {
System.out.println(dd_[0][0]);
return;
}
int[] ii = new int[1 << n];
for (int i = 0; i < n; i++)
ii[1 << i] = i;
int[][][] dp = new int[1 << n][n][n];
for (int b = 0; b < 1 << n; b++)
for (int u = b; u > 0; u &= u - 1) {
int i = ii[u & -u];
for (int v = b ^ 1 << i; v > 0; v &= v - 1) {
int j = ii[v & -v];
if (b == (1 << i ^ 1 << j))
dp[b][i][j] = dd[i][j];
else {
int x = 0;
for (int w = b ^ 1 << i ^ 1 << j; w > 0; w &= w - 1) {
int k = ii[w & -w];
x = Math.max(x, Math.min(dp[b ^ 1 << j][i][k], dd[k][j]));
}
dp[b][i][j] = x;
}
}
}
int b = (1 << n) - 1;
int x = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (i != j)
x = Math.max(x, Math.min(dp[b][i][j], dd_[i][j]));
System.out.println(x);
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class f {
static int n, m;
static int start;
static int[][] memo;
static int[][] arr;
static int[][] costs;
static int[][] wrapCosts;
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
n = in.nextInt();
m = in.nextInt();
arr = new int[n][m];
costs = new int[n][n];
wrapCosts = new int[n][n];
for (int r = 0; r < n; r++) {
for (int c = 0; c < m; c++) {
arr[r][c] = in.nextInt();
}
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
costs[i][j] = Integer.MAX_VALUE;
for (int c = 0; c < m; c++) {
costs[i][j] = Math.min(costs[i][j], Math.abs(arr[i][c] - arr[j][c]));
}
costs[j][i] = costs[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
wrapCosts[i][j] = Integer.MAX_VALUE;
for (int c = 0; c < m - 1; c++) {
wrapCosts[i][j] = Math.min(wrapCosts[i][j], Math.abs(arr[i][c + 1] - arr[j][c]));
}
}
}
memo = new int[n][1 << n];
long best = 0;
for (start = 0; start < n; start++) {
for (int[] a : memo) Arrays.fill(a, -1);
best = Math.max(best, go(start, (1 << n) - 1 - (1 << start)));
}
out.println(best);
out.close();
}
static int go(int cur, int mask) {
if (mask == 0) {
return wrapCosts[start][cur];
}
if (memo[cur][mask] != -1) return memo[cur][mask];
int ans = 0;
for (int next = 0; next < n; next++) {
int bit = 1 << next;
if ((mask & bit) == 0) continue;
ans = Math.max(ans, Math.min(costs[cur][next], go(next, mask ^ bit)));
}
return memo[cur][mask] = ans;
}
//@
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = new StringTokenizer("");
}
public String next() throws IOException {
if(st.hasMoreTokens())
return st.nextToken();
else
st = new StringTokenizer(br.readLine());
return next();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
//#
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
//$
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class ElongatedMatrix2 {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
int N = scanner.nextInt();
int M = scanner.nextInt();
int[][] arr = new int[N][M];
for(int i = 0; i < N; i++) {
for(int j = 0; j < M; j++) {
arr[i][j] = scanner.nextInt();
}
}
int[][] distRow = new int[N][N];
int[][] distTop = new int[N][N];
// for(int i = 0; i < N; i++) {
// Arrays.fill(distTop, Integer.MAX_VALUE);
// Arrays.fill(distRow, Integer.MAX_VALUE);
// }
//compute row distances
for(int i = 0; i < N; i++) {
for(int j = i+1; j < N; j++) {
int curMin = Integer.MAX_VALUE;
for(int k = 0; k < M; k++) {
curMin = Math.min(curMin, Math.abs(arr[i][k] - arr[j][k]));
}
distRow[i][j] = distRow[j][i] = curMin;
}
}
//compute bottom/top distances
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
int curMin = Integer.MAX_VALUE;
for(int k = 0; k+1 < M; k++) {
curMin = Math.min(curMin, Math.abs(arr[i][k] - arr[j][k+1]));
}
distTop[i][j] = curMin;
}
}
int maxMask = 1 << N;
int[][][] dp = new int[maxMask][N][N];
for(int i = 0; i < maxMask; i++) {
for(int j = 0; j < N; j++) {
Arrays.fill(dp[i][j], Integer.MAX_VALUE);
}
}
for(int mask = 1; mask < maxMask; mask++) {
for (int j = 0; j < N; j++) {
if ((mask & ( 1 << j)) == 0) continue;
for(int k = 0; k < N; k++) {
if ((mask &(1 << k)) == 0) continue;
if (j == k && mask - (1 << k) != 0) continue;
for (int i = 0; i < N; i++) {
if ((mask & (1 << i)) > 0) continue;
int curMask = mask | (1 << i);
if (dp[curMask][i][k] != Integer.MAX_VALUE)
dp[curMask][i][k] = Math.max(dp[curMask][i][k], Math.min(dp[mask][j][k], distRow[i][j]));
else
dp[curMask][i][k] = Math.min(dp[mask][j][k], distRow[i][j]);
}
}
}
}
maxMask--;
int max = 0;
for(int i= 0; i < N; i++) {
for(int j = 0; j < N; j++) {
if (i==j && N != 1) continue;
max = Math.max(max, Math.min(dp[maxMask][i][j], distTop[i][j]));
}
}
System.out.println(max);
}
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;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
}
}
| np | 1102_F. Elongated Matrix | 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;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
F solver = new F();
solver.solve(1, in, out);
out.close();
}
static class F {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.ni(), m = in.ni();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
a[i] = in.na(m);
}
if (n == 1) {
int ans = Integer.MAX_VALUE;
for (int i = 1; i < m; i++) {
ans = Math.min(ans, Math.abs(a[0][i] - a[0][i - 1]));
}
out.println(ans);
return;
}
int[][] mk = new int[n][n];
int[][] mk1 = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int minK = Integer.MAX_VALUE;
int minK1 = Integer.MAX_VALUE;
int minK2 = Integer.MAX_VALUE;
for (int l = 0; l < m; l++) {
minK = Math.min(minK, Math.abs(a[i][l] - a[j][l]));
if (l > 0) {
minK1 = Math.min(minK1, Math.abs(a[i][l] - a[j][l - 1]));
minK2 = Math.min(minK2, Math.abs(a[i][l - 1] - a[j][l]));
}
}
mk[i][j] = mk[j][i] = minK;
mk1[i][j] = minK1;
mk1[j][i] = minK2;
}
}
int ans = 0;
for (int first = 0; first < n; first++) {
int[][] dp = new int[1 << n][n];
for (int mask = 1; mask < (1 << n) - 1; mask++) {
int bc = Integer.bitCount(mask);
if ((mask & (1 << first)) != 0) {
if (bc == 1) {
dp[mask][first] = Integer.MAX_VALUE;
}
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0) {
for (int j = 0; j < n; j++) {
if ((mask & (1 << j)) == 0) {
dp[mask | (1 << j)][j] = Math.max(dp[mask | (1 << j)][j], Math.min(dp[mask][i], mk[i][j]));
}
}
}
}
}
}
for (int i = 0; i < n; i++) {
if (i != first) {
ans = Math.max(ans, Math.min(dp[(1 << n) - 1][i], mk1[first][i]));
}
}
}
out.println(ans);
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String ns() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(ns());
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
}
} | np | 1102_F. Elongated Matrix | CODEFORCES |
import java.util.*;
import java.io.*;
public class F531 {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt(); int m = sc.nextInt();
long [][] mn1 = new long[n][n];
long [][] mn2 = new long[n][n];
long [][] grid = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) grid[i][j] = sc.nextInt();
}
if (n == 1) {
long ans = Integer.MAX_VALUE;
for (int i = 0; i < m - 1; i++) ans = Math.min(ans, Math.abs(grid[0][i] - grid[0][i + 1]));
out.println(ans);
out.close();
return;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) continue;
long min = Long.MAX_VALUE;
for (int k = 0; k < m; k++) min = Math.min(min, Math.abs(grid[i][k] - grid[j][k]));
mn1[i][j] = min;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) continue;
long min = Long.MAX_VALUE;
for (int k = 0; k < m - 1; k++) min = Math.min(min, Math.abs(grid[i][k] - grid[j][k + 1]));
mn2[i][j] = min;
}
}
long [][] dp = new long[1 << n][n];
// start vertex
long ans = 0;
for (int i = 0; i < n; i++) {
for (long [] a: dp) Arrays.fill(a, -1);
for (int j = 0; j < n; j++) {
if (j == i) dp[1 << j][j] = Long.MAX_VALUE;
else dp[1 << j][j] = 0;
}
for (int mask = 1; mask < (1 << n); mask++) {
for (int last = 0; last < n; last++) {
if (dp[mask][last] != -1) continue;
for (int prev = 0; prev < n; prev++) {
if (prev == last) continue;
if (((mask >> prev) & 1) == 1) {
dp[mask][last] = Math.max(dp[mask][last], Math.min(mn1[prev][last], dp[mask ^ (1 << last)][prev]));
}
}
}
}
// end vertex
for (int j = 0; j < n; j++) {
// step from the last vertex to the first
long end = mn2[j][i];
ans = Math.max(ans, Math.min(dp[(1 << n) - 1][j], end));
}
}
out.println(ans);
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 | 1102_F. Elongated Matrix | CODEFORCES |
import java.util.*;
import java.io.*;
public class main{
static int max = 5000+1;
static FastReader in = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static int N = 18;
static int[][] mn1 = new int[N][N];
static int[][] mn2 = new int[N][N];
static int[][] dp = new int[1<<N][N];
static int n,m;
static void solve(){
n = in.nextInt(); 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();
for(int i=0;i<n;i++){
Arrays.fill(mn1[i],Integer.MAX_VALUE);
Arrays.fill(mn2[i],Integer.MAX_VALUE);
}
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int k=0;k<m;k++){
mn1[i][j] = Math.min(mn1[i][j],Math.abs(a[i][k]-a[j][k]));
if(k<=m-2)
mn2[i][j] = Math.min(mn2[i][j],Math.abs(a[i][k]-a[j][k+1]));
}
int ans = 0;
for(int i=0;i<n;i++){
for(int x=0;x<1<<n;x++)Arrays.fill(dp[x],-1);
for(int j=0;j<n;j++)dp[1<<j][j] = 0;
dp[1<<i][i] = Integer.MAX_VALUE;
for(int j=0;j<n;j++)
ans = Math.max(ans,Math.min(mn2[j][i],calc((1 << n) - 1, j)));
}
out.println(ans);
}
static int calc(int mask, int v){
if (dp[mask][v] != -1)
return dp[mask][v];
dp[mask][v] = 0;
for(int u=0;u<n;u++) if (v != u && (((mask >> u) & 1)>0))
dp[mask][v] = Math.max(dp[mask][v], Math.min(mn1[u][v], calc(mask ^ (1 << v), u)));
return dp[mask][v];
}
public static void main(String[] args){
solve();
out.close();
}
static 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(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
int nextInt(){return Integer.parseInt(in.next());}
long nextLong(){return Long.parseLong(in.next());}
double nextDouble(){return Double.parseDouble(in.next());}
}
}
// |xvcxv|vcv[cvcvc|cxv||]vcvx:v|c|vxc|[|cvx:cxvx||||] | np | 1102_F. Elongated Matrix | CODEFORCES |
import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int n=ni(),m=ni();
int a[][]=new int[n+1][m+1];
for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) a[i][j]=ni();
if(n==1){
int mn=Integer.MAX_VALUE;
for(int i=1;i<m;i++) mn=Math.min(mn,Math.abs(a[1][i]-a[1][i+1]));
pw.println(mn) ;
return ;
}
mn1=new int[n+1][n+1];
mn2=new int[n+1][n+1];
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i==j) continue;
mn1[i][j]=mn2[i][j]=Integer.MAX_VALUE;
for(int k=1;k<=m;k++){
mn1[i][j]=Math.min(mn1[i][j],Math.abs(a[i][k]-a[j][k]));
// if(i==3 && j==4) pw.println(a[i][k]+" "+a[j][k]);
}
for(int k=1;k<m;k++){
mn2[i][j]=Math.min(mn2[i][j],Math.abs(a[i][k+1]-a[j][k]));
}
//if(m==1) mn2[i][j]=0;
}
}
// pw.println(mn1[3][4]);
dp=new int[17][1<<16][17];
for(int i=1;i<17;i++) for(int j=0;j<(1<<16);j++) Arrays.fill(dp[i][j],-1);
int ans=0;
for(int i=1;i<=n;i++){
ans=Math.max(ans,go(2,1<<(i-1),i,i,n));
}
pw.println(ans);
}
int mn1[][],mn2[][];
int dp[][][];
int go(int i,int mask,int prev,int first,int n){
if(i>n){
// if(mn2[first][prev]==0) pw.println(prev+" "+first+" "+mn2[first][prev]);
return mn2[first][prev];
}
if(dp[first][mask][prev]!=-1) return dp[first][mask][prev];
int cc=0;
for(int k=1;k<=n;k++){
if((mask&(1<<(k-1)))==0){
cc=Math.max(cc,Math.min(mn1[prev][k],go(i+1,mask|(1<<(k-1)),k,first,n)));
//if(mn1[prev][k]==0) pw.println(mn1[prev][k]+" "+prev+" "+k);
}
}
dp[first][mask][prev]=cc;
return cc;
}
long M= (long)1e9+7;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Main().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(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
} | np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class A {
static MyScanner sc;
static PrintWriter pw;
public static void main(String[] args) throws Throwable {
sc = new MyScanner();
pw = new PrintWriter(System.out);
n = sc.nextInt();
int m = sc.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = sc.nextInt();
val = new int[n][n];
for (int i = 0; i < n; i++)
Arrays.fill(val[i], Integer.MAX_VALUE);
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++) {
for (int k = 0; k < m; k++)
val[i][j] = val[j][i] = Math.min(val[i][j], Math.abs(a[i][k] - a[j][k]));
}
val2 = new int[n][n];
for (int i = 0; i < n; i++)
Arrays.fill(val2[i], Integer.MAX_VALUE);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
for (int k = 0; k < m - 1; k++)
val2[i][j] = Math.min(val2[i][j], Math.abs(a[i][k] - a[j][k + 1]));
}
mem = new Long[n][n][1 << n];
long ans = 0;
for (int i = 0; i < n; i++) {
ans = Math.max(ans, dp(i, i, 1 << i));
}
if (n == 1)
pw.println(val2[0][0]);
else
pw.println(ans);
pw.flush();
pw.close();
}
static int n;
static int[][] val, val2;
static Long[][][] mem;
static long dp(int st, int lst, int msk) {
int bits = Integer.bitCount(msk);
if (mem[st][lst][msk] != null)
return mem[st][lst][msk];
long ans = 0;
for (int i = 0; i < n; i++)
if ((msk & (1 << i)) == 0) {
int newMsk = (msk | (1 << i));
if (bits < n - 1)
ans = Math.max(ans, Math.min(val[lst][i], dp(st, i, newMsk)));
else
ans = Math.max(ans, Math.min(val[lst][i], val2[i][st]));
}
return mem[st][lst][msk] = ans;
}
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 | 1102_F. Elongated Matrix | 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);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
final int INF = (int) 1e9 + 5;
int n;
int m;
int[][][] dp;
int[][] diff;
int[][] diffStartLast;
int two(int x) {
return 1 << x;
}
boolean contain(int mask, int x) {
return (mask & two(x)) > 0;
}
int rec(int start, int pre, int mask) {
if (mask == two(n) - 1)
return INF;
int res = dp[start][pre][mask];
if (res != -1)
return res;
res = 0;
for (int i = 0; i < n; i++)
if (contain(mask, i) == false) {
int diffPre = mask == 0 ? INF : diff[pre][i]; // mask == 0 should never happen
int diffLast = (mask | two(i)) == two(n) - 1 ? diffStartLast[start][i] : INF;
res = Math.max(res, Math.min(rec(start, i, mask | two(i)), Math.min(diffLast, diffPre)));
}
dp[start][pre][mask] = res;
return res;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
grid[i][j] = in.nextInt();
if (n == 1) {
int res = INF;
for (int i = 0; i + 1 < m; i++) {
res = Math.min(res, Math.abs(grid[0][i] - grid[0][i + 1]));
}
out.println(res);
return;
}
diff = new int[n][n];
diffStartLast = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
diff[i][j] = INF;
diffStartLast[i][j] = INF;
for (int k = 0; k < m; k++) {
diff[i][j] = Math.min(diff[i][j], Math.abs(grid[i][k] - grid[j][k]));
if (k + 1 < m) {
diffStartLast[i][j] = Math.min(diffStartLast[i][j], Math.abs(grid[i][k + 1] - grid[j][k]));
}
}
}
}
dp = new int[n][n][two(n)];
for (int[][] aux : dp)
for (int[] aux2 : aux)
Arrays.fill(aux2, -1);
int ans = 0;
for (int start = 0; start < n; start++) {
ans = Math.max(ans, rec(start, start, two(start)));
}
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 | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FElongatedMatrix solver = new FElongatedMatrix();
solver.solve(1, in, out);
out.close();
}
static class FElongatedMatrix {
int n;
int m;
int[][] arr;
int[][] memo;
int[][][] memo2;
int first;
public void readInput(Scanner sc) {
n = sc.nextInt();
m = sc.nextInt();
arr = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = sc.nextInt();
}
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int tc = 1;
while (tc-- > 0) {
readInput(sc);
int max = 0;
memo2 = new int[2][n][n];
for (int[][] x : memo2)
for (int[] y : x)
Arrays.fill(y, -1);
for (int i = 0; i < n; i++) {
memo = new int[n][1 << n];
for (int[] y : memo)
Arrays.fill(y, -1);
first = i;
max = Math.max(max, dp(1 << i, i));
}
pw.println(max);
}
}
private int dp(int msk, int prev) {
if (msk == (1 << n) - 1)
return getLast(first, prev);
if (memo[prev][msk] != -1)
return memo[prev][msk];
int max = 0;
for (int i = 0; i < n; i++) {
if ((msk & 1 << i) == 0)
max = Math.max(max, Math.min(getDiff(prev, i), dp(msk | 1 << i, i)));
}
return memo[prev][msk] = max;
}
private int getLast(int i, int j) {
if (memo2[0][i][j] != -1)
return memo2[0][i][j];
int min = Integer.MAX_VALUE;
for (int k = 0; k < m - 1; k++)
min = Math.min(min, Math.abs(arr[i][k] - arr[j][k + 1]));
return memo2[0][i][j] = min;
}
private int getDiff(int i, int j) {
if (memo2[1][i][j] != -1)
return memo2[1][i][j];
int min = Integer.MAX_VALUE;
for (int k = 0; k < m; k++)
min = Math.min(min, Math.abs(arr[i][k] - arr[j][k]));
return memo2[1][i][j] = min;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
FElongatedMatrix solver = new FElongatedMatrix();
solver.solve(1, in, out);
out.close();
}
}
static class FElongatedMatrix {
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
int m = in.readInt();
int[][] mat = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mat[i][j] = in.readInt();
}
}
int[][] minDist = new int[n][n];
SequenceUtils.deepFill(minDist, (int) 1e9);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < m; k++) {
minDist[i][j] = Math.min(minDist[i][j], Math.abs(mat[i][k] - mat[j][k]));
}
}
}
int[][] minDistBetweenHeadAndTail = new int[n][n];
SequenceUtils.deepFill(minDistBetweenHeadAndTail, (int) 1e9);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 1; k < m; k++) {
minDistBetweenHeadAndTail[i][j] = Math.min(minDistBetweenHeadAndTail[i][j], Math.abs(mat[i][k] - mat[j][k - 1]));
}
}
}
Log2 log2 = new Log2();
BitOperator bo = new BitOperator();
int[][][] dp = new int[1 << n][n][n];
for (int i = 1; i < (1 << n); i++) {
if (i == Integer.lowestOneBit(i)) {
dp[i][log2.floorLog(i)][log2.floorLog(i)] = (int) 1e9;
continue;
}
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
if (bo.bitAt(i, j) == 0) {
continue;
}
for (int t = 0; t < n; t++) {
dp[i][j][k] = Math.max(dp[i][j][k],
Math.min(dp[bo.setBit(i, j, false)][t][k],
minDist[j][t]));
}
}
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
ans = Math.max(ans, Math.min(dp[(1 << n) - 1][i][j], minDistBetweenHeadAndTail[j][i]));
}
}
out.println(ans);
}
}
static class SequenceUtils {
public static void deepFill(Object array, int val) {
if (!array.getClass().isArray()) {
throw new IllegalArgumentException();
}
if (array instanceof int[]) {
int[] intArray = (int[]) array;
Arrays.fill(intArray, val);
} else {
Object[] objArray = (Object[]) array;
for (Object obj : objArray) {
deepFill(obj, val);
}
}
}
}
static class Log2 {
public int floorLog(int x) {
return 31 - Integer.numberOfLeadingZeros(x);
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
static class BitOperator {
public int bitAt(int x, int i) {
return (x >> i) & 1;
}
public int setBit(int x, int i, boolean v) {
if (v) {
x |= 1 << i;
} else {
x &= ~(1 << i);
}
return x;
}
}
static class FastOutput implements AutoCloseable, Closeable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput println(int c) {
cache.append(c).append('\n');
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
}
| np | 1102_F. Elongated Matrix | 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);
F solver = new F();
solver.solve(1, in, out);
out.close();
}
static class F {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.ni(), m = in.ni();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
a[i] = in.na(m);
}
if (n == 1) {
int ans = Integer.MAX_VALUE;
for (int i = 1; i < m; i++) {
ans = Math.min(ans, Math.abs(a[0][i] - a[0][i - 1]));
}
out.println(ans);
return;
}
int[][] mk = new int[n][n];
int[][] mk1 = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int minK = Integer.MAX_VALUE;
int minK1 = Integer.MAX_VALUE;
int minK2 = Integer.MAX_VALUE;
for (int l = 0; l < m; l++) {
minK = Math.min(minK, Math.abs(a[i][l] - a[j][l]));
if (l > 0) {
minK1 = Math.min(minK1, Math.abs(a[i][l] - a[j][l - 1]));
minK2 = Math.min(minK2, Math.abs(a[i][l - 1] - a[j][l]));
}
}
mk[i][j] = mk[j][i] = minK;
mk1[i][j] = minK1;
mk1[j][i] = minK2;
}
}
int ans = 0;
for (int first = 0; first < n; first++) {
int[][] dp = new int[1 << n][n];
for (int mask = 1; mask < (1 << n) - 1; mask++) {
int bc = Integer.bitCount(mask);
if ((mask & (1 << first)) != 0) {
if (bc == 1) {
dp[mask][first] = Integer.MAX_VALUE;
}
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0) {
for (int j = 0; j < n; j++) {
if ((mask & (1 << j)) == 0) {
dp[mask | (1 << j)][j] = Math.max(dp[mask | (1 << j)][j], Math.min(dp[mask][i], mk[i][j]));
}
}
}
}
}
}
for (int i = 0; i < n; i++) {
if (i != first) {
ans = Math.max(ans, Math.min(dp[(1 << n) - 1][i], mk1[first][i]));
}
}
}
out.println(ans);
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String ns() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(ns());
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
import java.util.*;
import java.io.*;
public class main{
static int max = 5000+1;
static FastReader in = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static int N = 18;
static int[][] mn1 = new int[N][N];
static int[][] mn2 = new int[N][N];
static int[][] dp = new int[1<<N][N];
static int n,m;
static void solve(){
n = in.nextInt(); 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();
for(int i=0;i<n;i++){
Arrays.fill(mn1[i],Integer.MAX_VALUE);
Arrays.fill(mn2[i],Integer.MAX_VALUE);
}
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int k=0;k<m;k++){
mn1[i][j] = Math.min(mn1[i][j],Math.abs(a[i][k]-a[j][k]));
if(k<=m-2)
mn2[i][j] = Math.min(mn2[i][j],Math.abs(a[i][k]-a[j][k+1]));
}
int ans = 0;
for(int i=0;i<n;i++){
for(int x=0;x<1<<n;x++)Arrays.fill(dp[x],-1);
for(int j=0;j<n;j++)dp[1<<j][j] = 0;
dp[1<<i][i] = Integer.MAX_VALUE;
for(int j=0;j<n;j++)
ans = Math.max(ans,Math.min(mn2[j][i],calc((1 << n) - 1, j)));
}
out.println(ans);
}
static int calc(int mask, int v){
if (dp[mask][v] != -1)
return dp[mask][v];
dp[mask][v] = 0;
for(int u=0;u<n;u++) if (v != u && (((mask >> u) & 1)>0))
dp[mask][v] = Math.max(dp[mask][v], Math.min(mn1[u][v], calc(mask ^ (1 << v), u)));
return dp[mask][v];
}
public static void main(String[] args){
solve();
out.flush();
out.close();
}
static 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(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
int nextInt(){return Integer.parseInt(in.next());}
long nextLong(){return Long.parseLong(in.next());}
double nextDouble(){return Double.parseDouble(in.next());}
}
}
// |xvcxv|vcv[cvcvc|cxv||]vcvx:v|c|vxc|[|cvx:cxvx||||] | np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.*;
import java.util.*;
public class D{
static int bot;
static int n,m;
static int [][]a;
static int [][]Min;
static int [][]memo;
static int K;
static int dp(int msk,int ones,int last) {
if(ones==n) {
return Min[last][bot]>=K?1:0;
}
if(memo[last][msk]!=-1)
return memo[last][msk];
int ans=0;
for(int nxt=0;nxt<n;nxt++)
if((msk & (1<<nxt)) ==0 && Min[last][nxt]>=K)
{
ans|=dp(msk|1<<nxt,ones+1,nxt);
}
return memo[last][msk]= ans;
}
static boolean check(int top,int bottom) {
for(int j=0;j+1<m;j++)
{
int diff=Math.abs(a[bottom][j]-a[top][j+1]);
if(diff<K)
return false;
}
return true;
}
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner();
PrintWriter out=new PrintWriter(System.out);
n=sc.nextInt();
m=sc.nextInt();
a=new int [n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
a[i][j]=sc.nextInt();
Min=new int [n][n];
if(n==1) {
int lo=0,hi=(int)1e9;
int ans=0;
while(lo<=hi) {
K=lo+hi>>1;
if(check(0, 0))
{
ans=K;
lo=K+1;
}
else
hi=K-1;
}
System.out.println(ans);
return;
}
for(int i1=0;i1<n;i1++)
for(int i2=0;i2<n;i2++)
{
if(i1==i2)
continue;
int min=(int) 1e9;
for(int j=0;j<m;j++)
min=Math.min(Math.abs(a[i1][j]-a[i2][j]), min);
Min[i1][i2]=min;
}
memo=new int [n][1<<n];
int ans=0;
int lo=0,hi=(int)1e9;
while(lo<=hi) {
K=lo+hi>>1;
for(int []x:memo)
Arrays.fill(x, -1);
int ok=0;
for(int top=0;top<n && ok==0;top++)
for(int bottom=0;bottom<n && ok==0 ;bottom++) {
bot=bottom;
if(top==bottom || !check(top, bottom))
continue;
int dp=dp(1<<top | 1<<bottom, 2, top);
ok|=dp;
}
if(ok==1)
{
ans=K;
lo=K+1;
}
else
hi=K-1;
}
out.println(ans);
out.close();
}
static class Scanner
{
BufferedReader br;
StringTokenizer st;
Scanner(){
br=new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException{
br=new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while(st==null || !st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException{
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Scanner;
import java.util.Vector;
public class Main {
private static final int SIM = 1;
private static final int NAO = 2;
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int n = in.nextInt();
int m = in.nextInt();
int[][] a = new int[n][m];
int[][] graphVerticial = null;
int[][] graphDiagonal = null;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
}
}
graphVerticial = createGraphVertical(n, m, a);
graphDiagonal = createGraphDiagonal(n, m, a);
// print(graphVerticial);
// System.out.println("##########################");
// print(graphDiagonal);
int result = 0;
int k = 1;
int piso = 0;
int teto = 1000000000;
while(true) {
k = (int) Math.ceil((teto - piso) / 2.0) + piso;
if(isOk(n, k, graphVerticial, graphDiagonal)) {
result = Math.max(result, k);
piso = k;
}
else{
teto = k - 1;
}
//System.out.println(piso + ", " + teto);
if(teto <= piso) break;
}
System.out.println(result);
}
public static int[][] createGraphVertical(int n, int m, int[][] a){
int[][] graph = new int[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(i == j) continue;
if(i > j) {graph[i][j] = graph[j][i]; continue;}
graph[i][j] = Integer.MAX_VALUE;
for(int k = 0; k < m; k++) {
graph[i][j] = Math.min(graph[i][j], Math.abs(a[i][k] - a[j][k]));
}
}
}
return graph;
}
public static int[][] createGraphDiagonal(int n, int m, int[][] a){
int[][] graph = new int[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
graph[i][j] = Integer.MAX_VALUE;
for(int k = 0; k < m - 1; k++) {
graph[i][j] = Math.min(graph[i][j], Math.abs(a[j][k] - a[i][k + 1]));
}
}
}
return graph;
}
public static int hasPath(int n, int k, int origem, int destino, int conjunto, int[][] graph, int[][][] pd) {
//System.out.println(origem + ", " + destino);
//print(conjunto);
if(pd[origem][destino][conjunto] != 0) return pd[origem][destino][conjunto];
if(conjunto == 0) {
return origem == destino ? SIM : NAO;
}
else if(origem == destino){
return NAO;
}
for(int i = 0; i < n; i++) {
if(i == origem) continue;
int novoConjunto = conjunto - (1 << i);
boolean pertenceConjunto = ((conjunto >> i) % 2) == 1;
if(pertenceConjunto && graph[origem][i] >= k && hasPath(n, k, i, destino, novoConjunto, graph, pd) == SIM) {
pd[origem][destino][conjunto] = SIM;
return pd[origem][destino][conjunto];
}
}
pd[origem][destino][conjunto] = NAO;
return pd[origem][destino][conjunto];
}
public static boolean isOk(int n, int k, int[][] graphVertical, int[][] graphDiagonal) {
int conjunto = (int) Math.pow(2, n) - 1;
int[][][] pd = new int[n][n][(int)Math.pow(2, n)];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(i == j && n > 1) continue;
int novoConjunto = conjunto - (1 << i);
if(graphDiagonal[i][j] >= k && hasPath(n, k, i, j, novoConjunto, graphVertical, pd) == SIM) {
return true;
}
}
}
return false;
}
public static void print(int[][] graph) {
for(int i = 0; i < graph.length; i++) {
for(int j = 0; j < graph.length; j++) {
// if(graph[i][j] >= 3 ) System.out.print("1 ");
// else System.out.print("0 ");
System.out.print(graph[i][j] + " ");
}
System.out.println();
}
}
public static void print(int n) {
List<Integer> bits = new Vector<>();
while(n > 0) {
bits.add(n % 2);
n /= 2;
}
for(int i = bits.size() - 1; i >= 0; i--) {
System.out.print(bits.get(i));
}
System.out.println();
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1102f {
public static void main(String[] args) throws IOException {
int n = rni(), m = ni(), a[][] = new int[n][];
for (int i = 0; i < n; ++i) {
a[i] = ria(m);
}
int delta[][] = new int[n][n], end_delta[][] = new int[n][n], dp[][][] = new int[n][1 << n][n];
for (int i = 0; i < n; ++i) {
fill(delta[i], IBIG);
fill(end_delta[i], IBIG);
delta[i][i] = 0;
}
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++j) {
for (int k = 0; k < m; ++k) {
delta[i][j] = delta[j][i] = min(delta[i][j], abs(a[i][k] - a[j][k]));
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
for (int k = 1; k < m; ++k) {
end_delta[i][j] = min(end_delta[i][j], abs(a[j][k] - a[i][k - 1]));
}
}
}
for (int[][] layer : dp) {
for (int[] row : layer) {
fill(row, IBIG);
}
}
for (int i = 1; i < 1 << n; ++i) {
boolean one_bit = Integer.bitCount(i) == 1;
for (int j = 0; j < n; ++j) {
if ((i & (1 << j)) > 0) {
for (int l = 0; l < n; ++l) {
if ((i & (1 << l)) == 0) {
int max = 0;
for (int k = 0; k < n; ++k) {
if ((one_bit || j != k) && (i & (1 << k)) > 0) {
max = max(max, min(dp[j][i][k], delta[k][l]));
}
}
// pr(j + " ");
// pr(Integer.toBinaryString(i) + " ");
// prln(l, max);
dp[j][i | (1 << l)][l] = max;
}
}
}
}
}
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i != j) {
// prln(i, j, dp[i][(1 << n) - 1][j]);
ans = max(ans, min(dp[i][(1 << n) - 1][j], end_delta[j][i]));
}
}
}
if (n == 1) {
ans = maxof(end_delta[0]);
}
prln(ans);
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 | 1102_F. Elongated Matrix | CODEFORCES |
import java.util.Scanner;
public class Main {
private static boolean check(int n , int m , int k) {
for (int i = 0;i < n;i ++) {
for (int j = 0;j < n;j ++) {
for (int l = 0;l < (1 << n);l ++) {
dp[i][j][l] = - 1;
}
}
}
for (int i = 0;i < n;i ++) {
if (dfs(i , i , n , m , k , 0)) {
return true;
}
}
return false;
}
private static boolean dfs(int first , int current , int n , int m , int k , int bitmap) {
bitmap |= (1 << current);
if (bitmap == (1 << n) - 1) {
// check first and current
if (n == 1) {
if (m > 1) {
if (rowMinDist[current] >= k) {
return true;
} else {
return false;
}
} else {
return true;
}
} else {
if (m > 1) {
if (minDistBetweenHeadAndTail[first][current] >= k) {
return true;
} else {
return false;
}
} else {
return true;
}
}
} else {
if (dp[first][current][bitmap] >= 0) {
if (dp[first][current][bitmap] > 0) {
return true;
} else {
return false;
}
}
short ans = 0;
for (int i = 0;i < n;i ++) {
if ((bitmap & (1 << i)) == 0 && minDistBetweenRow[current][i] >= k) {
if (dfs(first , i , n , m , k , bitmap)) {
ans = 1;
break;
}
}
}
dp[first][current][bitmap] = ans;
if (ans > 0) {
return true;
} else {
return false;
}
}
}
private static short[][][] dp = new short[20][20][(1 << 17)];
private static int[][] input = new int[20][10010];
private static int[][] minDistBetweenRow = new int[20][20];
private static int[][] minDistBetweenHeadAndTail = new int[20][20];
private static int[] rowMinDist = new int[20];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i , j , k , n , m;
n = scan.nextInt();
m = scan.nextInt();
for (i = 0;i < n;i ++) {
for (j = 0;j < m;j ++) {
input[i][j] = scan.nextInt();
}
}
for (i = 0;i < n;i ++) {
for (j = i + 1;j < n;j ++) {
int minDist = - 1;
for (k = 0;k < m;k ++) {
int dist = Math.abs(input[i][k] - input[j][k]);
if (dist < minDist || minDist < 0) {
minDist = dist;
}
}
minDistBetweenRow[i][j] = minDistBetweenRow[j][i] = minDist;
}
}
for (i = 0;i < n;i ++) {
for (j = 0;j < n;j ++) {
if (i != j) {
// i head , j tail
int minDist = - 1;
for (k = 0;k < m - 1;k ++) {
int dist = Math.abs(input[j][k] - input[i][k + 1]);
if (dist < minDist || minDist < 0) {
minDist = dist;
}
}
minDistBetweenHeadAndTail[i][j] = minDist;
}
}
}
for (i = 0;i < n;i ++) {
int minDist = - 1;
for (j = 0;j < m - 1;j ++) {
int dist = Math.abs(input[i][j] - input[i][j + 1]);
if (dist < minDist || minDist < 0) {
minDist = dist;
}
}
rowMinDist[i] = minDist;
}
int low = 0 , high = 1000000010;
while (low < high) {
int mid = (low + high) / 2;
if (check(n , m , mid)) {
low = mid + 1;
} else {
high = mid;
}
}
System.out.println(high - 1);
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
// Don't place your source in a package
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
// Please name your class Main
public class Main {
static FastScanner fs=new FastScanner();
static class FastScanner {//scanner from SecondThread
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int Int() {
return Integer.parseInt(next());
}
long Long() {
return Long.parseLong(next());
}
String Str(){
return next();
}
}
public static void main (String[] args) throws java.lang.Exception {
PrintWriter out = new PrintWriter(System.out);
int T=1;
for(int t=0;t<T;t++){
int n=Int();int m=Int();
int A[][]=new int[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
A[i][j]=Int();
}
}
Sol sol=new Sol();
sol.solution(out,A);
}
out.flush();
}
public static int Int(){
return fs.Int();
}
public static long Long(){
return fs.Long();
}
public static String Str(){
return fs.Str();
}
}
class Sol{
int dif[][];
int dp[][][];
public void solution(PrintWriter out,int A[][]){
int n=A.length;int m=A[0].length;
int res=0;
dif=new int[n][n];
for(int i=0;i<n;i++){
for(int j=i+1;j<A.length;j++){
int mn=Integer.MAX_VALUE;
for(int k=0;k<m;k++){//different ordering pair
mn=Math.min(mn,Math.abs(A[i][k]-A[j][k]));
}
dif[i][j]=mn;
dif[j][i]=mn;
//System.out.println(i+" "+j+" "+mn);
}
}
int state=(1<<n)-1;
dp=new int[state+5][n+1][n+1];
for(int i=0;i<dp.length;i++){
for(int j=0;j<dp[0].length;j++){
Arrays.fill(dp[i][j],-1);
}
}
for(int i=0;i<n;i++){
res=Math.max(res,dfs(A,state^(1<<i),i,i));
}
out.println(res);
}
public int dfs(int A[][],int state,int pre,int start){
if(state==0){
int mn=Integer.MAX_VALUE;
for(int i=1;i<A[0].length;i++){
mn=Math.min(mn,Math.abs(A[start][i]-A[pre][i-1]));
}
return mn;
}
if(dp[state][pre][start]!=-1){
return dp[state][pre][start];
}
int res=0;
for(int i=0;i<A.length;i++){
if((state&(1<<i))!=0){
int di=dif[pre][i];
res=Math.max(res,Math.min(di,dfs(A,state^(1<<i),i,start)));
}
}
//System.out.println(Integer.toBinaryString(state)+" "+res);
dp[state][pre][start]=res;
return res;
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.*;
import java.util.*;
public class f{
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt();
int m = sc.nextInt();
int[][] arr = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
arr[i][j] = sc.nextInt();
}
}
if(n==1) {
int min = Integer.MAX_VALUE;
for(int i=0; i<m-1; i++) {
min = Math.min(min, Math.abs(arr[0][i]-arr[0][i+1]));
}
out.println(min);
out.close();
}
int[][] adj = new int[n][n];
int[][] edgeadj = new int[n][n];
for(int i=0; i<n; i++) {
for(int j=i+1; j<n; j++) {
int min = Integer.MAX_VALUE;
for(int k=0; k<m; k++) {
min = Math.min(min, Math.abs(arr[i][k]-arr[j][k]));
}
adj[i][j]=min;
adj[j][i]=min;
int min1 = Integer.MAX_VALUE;
int min2 = Integer.MAX_VALUE;
for(int k=0; k<m-1; k++) {
min1 = Math.min(min1, Math.abs(arr[i][k]-arr[j][k+1]));
min2 = Math.min(min2, Math.abs(arr[i][k+1]-arr[j][k]));
}
edgeadj[i][j]=min1;
edgeadj[j][i]=min2;
}
}
int power = (int)Math.pow(2,n);
int[][][] dp = new int[power][n][n];
for(int i=0; i<n; i++) {
dp[(int)Math.pow(2,i)][i][i] = Integer.MAX_VALUE;
}
for(int bit=0; bit<power; bit++) {
for(int j=0; j<n; j++) {
for(int k=0; k<n; k++) {
if((bit & (1<<j))>0 && (bit & (1<<k))>0 && j!=k) {
int temp = bit;
temp &= ~(1<<k);
int ans = 0;
for(int l=0; l<n; l++) {
if((temp & (1<<l))>0) {
int min = Math.min(dp[temp][j][l], adj[l][k]);
ans = Math.max(ans, min);
}
}
if(j!=k) {
dp[bit][j][k] = ans;
}
// out.println(bit + " " + j + " " + k + " " + dp[bit][j][k]);
}
}
}
}
int answer = 0;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if(i!=j) {
int ans = Math.min(dp[power-1][i][j], edgeadj[i][j]);
answer = Math.max(answer, ans);
}
}
}
// for(int i=0; i<n; i++) {
// for(int j=0; j<n; j++) {
// out.println(dp[power-1][i][j]+" "+edgeadj[i][j]);
// }
// }
out.println(answer);
// Start writing your solution here. -------------------------------------
/*
int n = sc.nextInt(); // read input as integer
long k = sc.nextLong(); // read input as long
double d = sc.nextDouble(); // read input as double
String str = sc.next(); // read input as String
String s = sc.nextLine(); // read whole line as String
int result = 3*n;
out.println(result); // print via PrintWriter
*/
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
} | np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class A {
static MyScanner sc;
static PrintWriter pw;
public static void main(String[] args) throws Throwable {
sc = new MyScanner();
pw = new PrintWriter(System.out);
n = sc.nextInt();
int m = sc.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = sc.nextInt();
val = new int[n][n];
for (int i = 0; i < n; i++)
Arrays.fill(val[i], Integer.MAX_VALUE);
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++) {
for (int k = 0; k < m; k++)
val[i][j] = val[j][i] = Math.min(val[i][j], Math.abs(a[i][k] - a[j][k]));
}
val2 = new int[n][n];
for (int i = 0; i < n; i++)
Arrays.fill(val2[i], Integer.MAX_VALUE);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
for (int k = 0; k < m - 1; k++)
val2[i][j] = Math.min(val2[i][j], Math.abs(a[i][k] - a[j][k + 1]));
}
mem = new Integer[n][n][1 << n];
int ans = 0;
for (int i = 0; i < n; i++) {
ans = Math.max(ans, dp(i, i, 1 << i));
}
if (n == 1)
pw.println(val2[0][0]);
else
pw.println(ans);
pw.flush();
pw.close();
}
static int n;
static int[][] val, val2;
static Integer[][][] mem;
static int dp(int st, int lst, int msk) {
int bits = Integer.bitCount(msk);
if (mem[st][lst][msk] != null)
return mem[st][lst][msk];
int ans = 0;
for (int i = 0; i < n; i++)
if ((msk & (1 << i)) == 0) {
int newMsk = (msk | (1 << i));
if (bits < n - 1)
ans = Math.max(ans, Math.min(val[lst][i], dp(st, i, newMsk)));
else
ans = Math.max(ans, Math.min(val[lst][i], val2[i][st]));
}
return mem[st][lst][msk] = ans;
}
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 | 1102_F. Elongated Matrix | CODEFORCES |
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main {
static final long MOD = 1_000_000_007, INF = 1_000_000_000_000_000_000L;
static final int INf = 1_000_000_000;
static FastReader reader;
static PrintWriter writer;
public static void main(String[] args) {
Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000);
t.start();
}
static class O implements Runnable {
public void run() {
try {
magic();
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
static class FastReader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[1000000];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
static int n,m,pre[][], pre_stop_and_start[][],mat[][], dp[][][];
static void magic() throws IOException {
reader = new FastReader();
writer = new PrintWriter(System.out, true);
n = reader.nextInt();
m = reader.nextInt();
mat = new int[n][m];
for(int i=0;i<n;++i) {
for(int j=0;j<m;++j) {
mat[i][j] = reader.nextInt();
}
}
if(n==1) {
int ans = Integer.MAX_VALUE;
for(int i=0;i+1<m;++i) {
ans = min(ans, abs(mat[0][i] - mat[0][i+1]));
}
writer.println(ans);
System.exit(0);
}
pre = new int[n][n];
pre_stop_and_start = new int[n][n];
for(int i=0;i<n;++i) {
for(int j=i+1;j<n;++j) {
int min = Integer.MAX_VALUE;
for(int k=0;k<m;++k) {
min = min(min, abs(mat[i][k] - mat[j][k]));
}
pre[i][j] = pre[j][i] = min;
}
}
for(int i=0;i<n;++i) {
for(int j=0;j<n;++j) {
if(j==i) {
continue;
}
int min = Integer.MAX_VALUE;
for(int k=0;k+1<m;++k) {
min = min(min, abs(mat[j][k+1] - mat[i][k]));
}
pre_stop_and_start[i][j] = min;
}
}
// writer.println("Pre array: ");
// for(int i=0;i<n;++i) {
// for(int j=0;j<n;++j) {
// writer.print(pre[i][j]+" ");
// }
// writer.println();
// }
// writer.println("Pre stop and start array: ");
// for(int i=0;i<n;++i) {
// for(int j=0;j<n;++j) {
// if(j==i) {
// writer.print("SKIP ");
// }
// else writer.print(pre_stop_and_start[i][j]+" ");
// }
// writer.println();
// }
dp = new int[1<<n][n][n];
for(int i=0;i<(1<<n);++i) {
for(int j=0;j<n;++j) {
for(int k=0;k<n;++k) {
dp[i][j][k] = -1;
}
}
}
int ans = 0;
for(int i=0;i<n;++i) {
ans = max(ans, f((1<<i), i, i));
}
writer.println(ans);
}
static int f(int mask_already, int prev, int first) {
if(mask_already==(1<<n) - 1) {
return pre_stop_and_start[prev][first];
}
if(dp[mask_already][prev][first] != -1) {
return dp[mask_already][prev][first];
}
int max = 0;
for(int i=0;i<n;++i) {
if((mask_already&(1<<i)) == 0) {
max = max(max, min(pre[prev][i], f(mask_already|(1<<i), i, first)));
}
}
return dp[mask_already][prev][first] = max;
}
} | np | 1102_F. Elongated Matrix | CODEFORCES |
/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
What do you think? What do you think?
1st on Billboard, what do you think of it
Next is a Grammy, what do you think of it
However you think, I’m sorry, but shit, I have no fcking interest
*******************************
I'm standing on top of my Monopoly board
That means I'm on top of my game and it don't stop
til my hip don't hop anymore
https://www.a2oj.com/Ladder16.html
*******************************
300IQ as writer = Sad!
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class F
{
public static void main(String hi[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[][] grid = new int[N][M];
for(int i=0; i < N; i++)
grid[i] = readArr(M, infile, st);
int[][] mindiff = new int[N][N];
for(int a=0; a < N; a++)
for(int b=a+1; b < N; b++)
{
int val = Integer.MAX_VALUE;
for(int i=0; i < M; i++)
val = Math.min(val, Math.abs(grid[a][i]-grid[b][i]));
mindiff[a][b] = mindiff[b][a] = val;
}
int res = 0;
for(int start=0; start < N; start++)
{
int[][] dp = new int[1<<N][N];
Arrays.fill(dp[0], Integer.MAX_VALUE);
for(int mask=0; mask < (1<<N); mask++)
{
if(Integer.bitCount(mask) == 1 && mask != (1<<start))
continue;
for(int prev=0; prev < N; prev++)
if((mask&(1<<prev)) > 0 || mask == 0)
{
for(int b=0; b < N; b++)
if((mask&(1<<b)) == 0)
{
int submask = mask|(1<<b);
if(mask == 0)
dp[submask][b] = Integer.MAX_VALUE;
else
dp[submask][b] = Math.max(dp[submask][b], Math.min(dp[mask][prev], mindiff[prev][b]));
}
}
}
for(int b=0; b < N; b++)
{
int temp = dp[(1<<N)-1][b];
for(int i=0; i < M-1; i++)
temp = Math.min(temp, Math.abs(grid[b][i]-grid[start][i+1]));
res = Math.max(res, temp);
}
}
System.out.println(res);
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
} | np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.*;
import java.util.*;
public class EMatrix{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.flush();out.close();
}
static class TaskE {
final int max = (int)(1E9);
int n , m;
int a[][];
int gm[];
boolean visit[][]; int dp[][];
boolean check(int d){
if(n == 1){
for(int i = 0; i < m - 1; i++){
if(Math.abs(a[0][i] - a[0][i + 1]) < d)return false;
}
return true;
}
int nm[] = new int[n], pm[] = new int[n];
for(int i = 0; i < n; i++){
boolean r;
for(int j = 0; j < n; j++){
if(j == i)continue;
r = true;
for(int k = 0; k < m; k++){
if(Math.abs(a[i][k] - a[j][k]) < d){
r = false; break;
}
}
if(r){
nm[i] |= (1 << j);
}
r = true;
for(int k = 0; k < m - 1; k++){
if(Math.abs(a[i][k + 1] - a[j][k]) < d){
r = false; break;
}
}
if(r){
pm[i] |= (1 << j);
}
}
}
// for(int i = 0; i < n; i++){
// System.out.println(nm[i] + " " + pm[i]);
// }
for(int i = 0; i < n; i++){
gm = new int[n];
gm[i] = nm[i];
for(int j = 0; j < n; j++){
if(j == i)continue;
if((nm[j] & (1 << i)) != 0){
gm[j] = nm[j] ^ (1 << i);
}else{
gm[j] = nm[j];
}
}
for(int j = 0; j < n; j++){
if(j == i)continue;
if((pm[i] >> j) % 2 == 1){
gm[j] |= (1 << i);
}
}
visit = new boolean[n][1 << n]; dp = new int[n][1 << n];
// for(int x = 0; x < n; x++)System.out.println(gm[x]);
if(dfs(i, i, (1 << i)) == n){
return true;
}
}
return false;
}
int dfs(int u, int r, int mask){
// System.out.println(u + " " + r + " " + mask);
if(u == r && mask == (1 << n) - 1)return 0;
if(visit[u][mask])return dp[u][mask];
visit[u][mask] = true;
int val = 0;
for(int i = 0; i < n; i++){
if((gm[u] >> i) % 2 == 1 && ((i == r && mask == (1 << n) - 1) || (mask >> i) % 2 != 1)){
val = Math.max(val, 1 + dfs(i, r, mask | (1 << i)));
}
}
// System.out.println(u + " " + mask + " " + val);
return dp[u][mask] = val;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt(); m = in.nextInt();
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 l = 0, r = max, ans = 0;
while(l <= r){
int m = (l + r) >> 1;
if(check(m)){
ans = m;
l = m + 1;
}else{
r = m - 1;
}
}
out.println(ans);
}
// pair ja[][];long w[];int from[],to[],c[];
// void make(int n,int m,InputReader in){
// ja=new pair[n+1][];w=new long[m];from=new int[m];to=new int[m];c=new int[n+1];
// for(int i=0;i<m;i++){
// int u=in.nextInt(),v=in.nextInt();long wt=in.nextLong();
// c[u]++;c[v]++;from[i]=u;to[i]=v;w[i]=wt;
// }
// for(int i=1;i<=n;i++){
// ja[i]=new pair[c[i]];c[i]=0;
// }
// for(int i=0;i<m;i++){
// ja[from[i]][c[from[i]]++]=new pair(to[i],w[i]);
// ja[to[i]][c[to[i]]++]=new pair(from[i],w[i]);
// }
// }
// int[] radixSort(int[] f){ return radixSort(f, f.length); }
// int[] radixSort(int[] f, int n)
// {
// int[] to = new int[n];
// {
// int[] b = new int[65537];
// for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++;
// for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
// for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i];
// int[] d = f; f = to;to = d;
// }
// {
// int[] b = new int[65537];
// for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++;
// for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
// for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i];
// int[] d = f; f = to;to = d;
// }
// return f;
// }
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
st = null;
}
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;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* @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);
FElongatedMatrix solver = new FElongatedMatrix();
solver.solve(1, in, out);
out.close();
}
static class FElongatedMatrix {
int[][] G;
int[][] G1;
public int findIt(int[] map, int n, int start) {
int[][] mask = new int[1 << n][n];
for (int i = 0; i < n; i++) mask[(1 << i)][i] = G[start][map[i]];
for (int i = 1; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
if (k != j && (i & (1 << k)) == 0 && (i & (1 << j)) != 0) {
mask[(i | (1 << k))][k] = Math.max(mask[(i | (1 << k))][k], Math.min(mask[i][j], G[map[j]][map[k]]));
}
}
}
}
int ans = 0;
for (int i = 0; i < n; i++) ans = Math.max(ans, Math.min(mask[(1 << n) - 1][i], G1[start][map[i]]));
return ans;
}
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int m = in.scanInt();
G = new int[n][n];
G1 = new int[n][n];
int[][] ar = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ar[i][j] = in.scanInt();
}
}
if (n == 1) {
int ans = Integer.MAX_VALUE;
for (int i = 0; i < m - 1; i++) ans = Math.min(ans, Math.abs(ar[0][i] - ar[0][i + 1]));
out.println(ans);
return;
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int min = Integer.MAX_VALUE;
for (int k = 0; k < m; k++) min = Math.min(min, Math.abs(ar[i][k] - ar[j][k]));
G[i][j] = G[j][i] = min;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) continue;
int min = Integer.MAX_VALUE;
for (int k = 1; k < m; k++) min = Math.min(min, Math.abs(ar[i][k] - ar[j][k - 1]));
G1[i][j] = min;
}
}
int[] map;
int ans = 0;
for (int i = 0; i < n; i++) {
map = new int[n - 1];
int tl = 0;
for (int temp = 0; temp < n; temp++) {
if (temp == i) continue;
map[tl++] = temp;
}
ans = Math.max(ans, findIt(map, n - 1, i));
}
out.println(ans);
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (total <= 0) return -1;
}
return buf[index++];
}
public int scanInt() {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;
public class F {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
int N = scanner.nextInt();
int M = scanner.nextInt();
int[][] matrix = new int[N][M];
for(int i = 0; i < N; i++) {
for(int j = 0; j < M; j++) {
matrix[i][j] = scanner.nextInt();
}
}
int[][] maxDist = new int[N][N];
for(int i = 0; i < N; i++) {
Arrays.fill(maxDist[i], Integer.MAX_VALUE);
}
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
for(int k = j+1; k < N; k++) {
maxDist[j][k] = Math.min(maxDist[j][k], Math.abs(matrix[k][i] - matrix[j][i]));
maxDist[k][j] = maxDist[j][k];
}
}
}
int[][] distTop = new int[N][N];
for(int i = 0; i < N; i++) {
Arrays.fill(distTop[i], Integer.MAX_VALUE);
}
for(int i = 0; i < M-1; i++) {
for(int j = 0; j < N; j++) {
for(int k = 0; k < N; k++) {
distTop[j][k] = Math.min(distTop[j][k], Math.abs(matrix[j][i] - matrix[k][i+1]));
}
}
}
if (N == 1) {
System.out.println(distTop[0][0]);
System.exit(0);
}
int[] bitLoc = new int[1<<N];
for(int i = 0; i < N; i++) {
bitLoc[1 << i] = i;
}
int[][][] dp = new int[1<<N][N][N];
//iterate over every row
for(int mask = 1; mask < (1 << N); mask++) {
for(int smask = mask; smask > 0; smask &= (smask-1)) {
int i = bitLoc[Integer.lowestOneBit(smask)];
for (int ss = mask ^ 1 << i; ss > 0; ss &= ss - 1) {
int j = bitLoc[Integer.lowestOneBit(ss)];
if (mask == (1 << i ^ 1 << j))
dp[mask][i][j] = maxDist[i][j];
else {
int x = 0;
for (int sss = mask ^ 1 << i ^ 1 << j; sss > 0; sss &= sss - 1) {
int k = bitLoc[sss & -sss];
x = Math.max(x, Math.min(dp[mask ^ 1 << j][i][k], maxDist[k][j]));
}
dp[mask][i][j] = x;
}
}
}
}
int mxMsk = (1 << N) -1;
int max = 0;
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
if (i==j) continue;
max = Math.max(max, Math.min(dp[mxMsk][i][j], distTop[i][j]));
}
}
System.out.println(max);
}
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;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
}
}
| np | 1102_F. Elongated Matrix | CODEFORCES |
import java.io.*;
import java.util.*;
public class E
{
private static final int oo = 1000000000;
public static void main(String[] args) throws Exception
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
if(n > m)
{
int t = n;
n = m;
m = t;
}
int [][] curr = new int[1<<n][1<<n];
fill(curr, oo);
Arrays.fill(curr[0], 0);
for(int j = 0 ; j < m ; j++)
{
int [][] next = new int[1<<n][1<<n];
fill(next, oo);
for(int c0 = 0 ; c0 < 1<<n ; c0++)
for(int c1 = 0 ; c1 < 1<<n ; c1++)
if(curr[c0][c1] != oo)
for(int c2 = 0 ; c2 < (j == m-1 ? 1 : 1<<n) ; c2++)
{
int done = 0;
for(int i = 0 ; i < n ; i++)
if(((1<<i) & c1) == 0)
{
int up = i-1;
int down = i+1;
if(up >= 0 && ((1<<up) & c1) != 0)
done |= 1<<i;
if(down < n && ((1<<down) & c1) != 0)
done |= 1<<i;
if(((1<<i) & c0) != 0)
done |= 1<<i;
if(((1<<i) & c2) != 0)
done |= 1<<i;
}
next[c1][c2] = Math.min(next[c1][c2], curr[c0][c1] + n - Integer.bitCount(done));
}
curr = next;
}
int res = oo;
for(int i = 0 ; i < 1<<n ; i++)
for(int j = 0 ; j < 1<<n ; j++)
res = Math.min(res, curr[i][j]);
System.out.println(n*m - res);
}
private static void fill(int[][] array, int val)
{
for(int [] fill : array)
Arrays.fill(fill, val);
}
} | np | 112_E. Petya and Spiders | CODEFORCES |
import java.util.*;
public class cf112e {
static int n,m,s;
static int[][][] memo;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
m = in.nextInt();
if(n > m) {
int tmp = n;
n = m;
m = tmp;
}
s = (1<<n);
memo = new int[s][s][m];
for(int i=0; i<s; i++)
for(int j=0; j<s; j++)
Arrays.fill(memo[i][j], -1);
int ret = go(0,0,0);
System.out.println(n*m - ret);
}
static int go(int last, int trans, int r) {
if(r==m) {
if(trans == 0) return 0;
return 100;
}
if(memo[last][trans][r] != -1) return memo[last][trans][r];
int best = 100;
for(int crnt = 0; crnt < s; crnt++) {
if((trans & ~crnt) != 0) continue; //certain ones have to be here
for(int pass = 0; pass < s; pass++) {
int tmp = ((1<<n)-1) & ~last; //move back the ones you can
if((pass & ~tmp) != 0) continue; //certain ones have to move on
tmp = tmp & ~pass; //find which ones stay
boolean fail = false;
for(int k=0; k<n; k++) //make sure that the ones that stay
if(isSet(tmp,k) && !(isSet(crnt,k-1) || isSet(crnt,k) || isSet(crnt,k+1)))
fail = true;
if(fail) continue;
best = Math.min(best, Integer.bitCount(crnt) + go(crnt,pass,r+1));
}
}
return memo[last][trans][r] = best;
}
static boolean isSet(int x, int p) {
if(p < 0 || p >= n) return false;
return (x & (1<<p)) != 0;
}
}
| np | 112_E. Petya and Spiders | CODEFORCES |
import java.util.Arrays;
/**
* 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 TaskC {
final int INF = 123456;
int[][][] memo;
int N, M;
int solve(int row, int prevFreeMask, int curStayMask) {
if(row == N) return (curStayMask == 0) ? 0 : -INF;
if(memo[row][prevFreeMask][curStayMask] != -1) return memo[row][prevFreeMask][curStayMask];
int res = 0;
for(int mask = 0; mask < (1<<M); mask++) {
if((mask & curStayMask) == curStayMask) {
int freeCellsMask = (1<<M) - 1 - mask;
int toMoveMask = freeCellsMask;
for(int i = 0; i < M; i++) {
if((toMoveMask & (1<<i)) > 0) {
if(i > 0) {
if((mask & (1<<(i - 1))) > 0) {
toMoveMask -= (1<<i);
continue;
}
}
if(i < M - 1) {
if((mask & (1<<(i + 1))) > 0) {
toMoveMask -= (1<<i);
continue;
}
}
}
}
if (row > 0) {
for (int prevFillMask = toMoveMask; prevFillMask > 0; prevFillMask = (prevFillMask - 1) & toMoveMask) {
int bc1 = Integer.bitCount(freeCellsMask);
int bc2 = Integer.bitCount(prevFreeMask & prevFillMask);
res = Math.max(res, bc1 - bc2 + solve(row + 1, freeCellsMask, toMoveMask ^ prevFillMask));
}
}
res = Math.max(res, Integer.bitCount(freeCellsMask) + solve(row + 1, freeCellsMask, toMoveMask));
}
}
return memo[row][prevFreeMask][curStayMask] = res;
}
void run() {
N = nextInt();
M = nextInt();
if(M > N) {
int temp = M;
M = N;
N = temp;
}
this.memo = new int[N + 1][1<<M][1<<M];
for(int[][] g : memo) for(int[] f : g) Arrays.fill(f, -1);
System.out.println(solve(0, 0, 0));
}
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 TaskC().run();
}
}
| np | 112_E. Petya and Spiders | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* Author -
* User: kansal
* Date: 9/3/11
* Time: 5:28 PM
*/
public class CF85E {
public static void main(String[] args) {
reader = new BufferedReader(new InputStreamReader(System.in));
int height = nextInt(), width = nextInt();
if (width > height) {
int t = width;
width = height;
height = t;
}
final int INF = height * width + 10;
int[][][] dp = new int[height + 1][1 << width][1 << width];
for (int[][] ints : dp) {
for (int[] anInt : ints) {
Arrays.fill(anInt, INF);
}
}
dp[0][0][0] = 0;
for(int r = 0; r < height; ++r) {
for(int uncovered = 0; uncovered < (1 << width); ++uncovered) {
for(int mask = 0; mask < (1 << width); ++mask) {
if (dp[r][uncovered][mask] == INF) {
continue;
}
for(int curMask = uncovered; curMask < (1 << width); curMask = (curMask + 1) | uncovered) {
int curUncovered = (1 << width) - 1;
for(int i = 0; i < width; ++i) {
if (hasBit(mask, i) || hasBit(curMask, i)) {
curUncovered &= ~(1 << i);
}
if (i > 0 && hasBit(curMask, i-1)) {
curUncovered &= ~(1 << i);
}
if (i < width-1 && hasBit(curMask, i+1)) {
curUncovered &= ~(1 << i);
}
}
dp[r+1][curUncovered][curMask] = Math.min(dp[r+1][curUncovered][curMask], dp[r][uncovered][mask] + Integer.bitCount(curMask));
}
}
}
}
int res = INF;
for(int x: dp[height][0]) res = Math.min(res, x);
System.out.println(height * width - res);
}
private static boolean hasBit(int mask, int bit) {
return (((mask >> bit) & 1) == 1);
}
public static BufferedReader reader;
public static StringTokenizer tokenizer = null;
static String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
static public int nextInt() {
return Integer.parseInt(nextToken());
}
static public long nextLong() {
return Long.parseLong(nextToken());
}
static public String next() {
return nextToken();
}
static public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| np | 112_E. Petya and Spiders | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* Author -
* User: kansal
* Date: 9/3/11
* Time: 5:28 PM
*/
public class CF85C {
public static void main(String[] args) {
reader = new BufferedReader(new InputStreamReader(System.in));
int height = nextInt(), width = nextInt();
if (width > height) {
int t = width;
width = height;
height = t;
}
final int INF = height * width + 10;
final int ALL_BITS = (1 << width) - 1;
int[][][] dp = new int[height + 1][1 << width][1 << width];
for (int[][] ints : dp) {
for (int[] anInt : ints) {
Arrays.fill(anInt, INF);
}
}
dp[0][0][0] = 0;
for(int r = 0; r < height; ++r) {
for(int uncovered = 0; uncovered < (1 << width); ++uncovered) {
for(int mask = 0; mask < (1 << width); ++mask) {
if (dp[r][uncovered][mask] == INF) {
continue;
}
for(int curMask = uncovered; curMask < (1 << width); curMask = (curMask + 1) | uncovered) {
int curCovered = (mask | curMask);
curCovered |= (curMask >> 1);
curCovered |= (ALL_BITS & (curMask << 1));
int curUncovered = ALL_BITS ^ curCovered;
dp[r+1][curUncovered][curMask] = Math.min(dp[r+1][curUncovered][curMask], dp[r][uncovered][mask] + Integer.bitCount(curMask));
}
}
}
}
int res = INF;
for(int x: dp[height][0]) res = Math.min(res, x);
System.out.println(height * width - res);
}
private static boolean hasBit(int mask, int bit) {
return (((mask >> bit) & 1) == 1);
}
public static BufferedReader reader;
public static StringTokenizer tokenizer = null;
static String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
static public int nextInt() {
return Integer.parseInt(nextToken());
}
static public long nextLong() {
return Long.parseLong(nextToken());
}
static public String next() {
return nextToken();
}
static public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| np | 112_E. Petya and Spiders | CODEFORCES |
/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x111C
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int R = Integer.parseInt(st.nextToken());
int C = Integer.parseInt(st.nextToken());
if(R > C)
{
int t = R;
R = C;
C = t;
}
//dp[c][m1][m2] = min spoders in first c columns
int[][][] dp = new int[C+1][1 << R][1 << R];
for(int i=0; i <= C; i++)
for(int mask=0; mask < (1<<R); mask++)
Arrays.fill(dp[i][mask], 69);
for(int mask=0; mask < (1<<R); mask++)
dp[0][0][mask] = 0;
for(int c=1; c <= C; c++)
for(int mask1=0; mask1 < (1<<R); mask1++)
for(int mask2=0; mask2 < (1<<R); mask2++)
for(int mask3=0; mask3 < (1<<R); mask3++)
{
boolean works = true;
for(int b=0; b < R; b++)
if((mask2&(1<<b)) == 0)
{
if(b > 0 && (mask2&(1<<(b-1))) > 0);
else if(b+1 < R && (mask2&(1<<(b+1))) > 0);
else if((mask1&(1<<b)) > 0);
else if((mask3&(1<<b)) > 0);
else works = false;
}
if(works)
dp[c][mask2][mask3] = Math.min(dp[c][mask2][mask3], dp[c-1][mask1][mask2]+Integer.bitCount(mask1));
}
int res = 0;
for(int mask=0; mask < (1<<R); mask++)
res = Math.max(res, R*C-(dp[C][mask][0]+Integer.bitCount(mask)));
System.out.println(res);
}
} | np | 112_E. Petya and Spiders | CODEFORCES |
import java.util.*;
public class E
{
public static void main(String[] args)
{
new E(new Scanner(System.in));
}
int N, M;
int[][][] memo;
int go(int i, int j, int mask)
{
if (i == N)
return go(0, j+1, mask);
if (j == M)
{
int mm = mask%(1<<N);
//System.out.println(Integer.toBinaryString(mm)+" "+Integer.toBinaryString(mask));
if (mm != ((1<<N)-1))
return N*M;
return 0;
}
if (memo[i][j][mask] != -1)
return memo[i][j][mask];
// Now place a spider cluster here
int nMask = mask;
int prevMask = 0;
if (i > 0)
prevMask = 1 << (N-1);
int nextMask = 0;
if (i < (N-1))
nextMask = 1 << (N+1);
int curMask = 1 << N;
int nextRowMask = 1 << (N+N);
nMask = nMask|prevMask|nextMask|curMask|nextRowMask;
nMask = nMask/2;
int res = 1+go(i+1, j, nMask);
int pr = mask%2;
if (pr == 1)
{
// We have the option to skip here
int rr = go(i+1, j, mask/2);
if (rr < res)
res = rr;
}
//System.out.printf("%d %d %s = %d%n", i, j, Integer.toBinaryString(mask), res);
memo[i][j][mask] = res;
return res;
}
public E(Scanner in)
{
int[] vals = new int[2];
vals[0] = in.nextInt();
vals[1] = in.nextInt();
Arrays.sort(vals);
N = vals[0];
M = vals[1];
memo = new int[N][M][1<<(N+N+1)];
fill3(memo, -1);
int r1 = go(0, 0, (1<<N)-1);
int res = N*M-r1;
System.out.printf("%d%n", res);
}
void fill3(int[][][] vvv, int val)
{
for (int[][] vv : vvv)
for (int[] v : vv)
Arrays.fill(v, val);
}
}
| np | 112_E. Petya and Spiders | CODEFORCES |
import java.io.*;
import java.util.*;
public class E
{
private static final int oo = 1000000000;
public static void main(String[] args) throws Exception
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
if(n > m)
{
int t = n;
n = m;
m = t;
}
int [][] curr = new int[1<<n][1<<n];
fill(curr, oo);
Arrays.fill(curr[0], 0);
for(int j = 0 ; j < m ; j++)
{
int [][] next = new int[1<<n][1<<n];
fill(next, oo);
for(int c0 = 0 ; c0 < 1<<n ; c0++)
for(int c1 = 0 ; c1 < 1<<n ; c1++)
if(curr[c0][c1] != oo)
for(int c2 = 0 ; c2 < (j == m-1 ? 1 : 1<<n) ; c2++)
{
int all = (1<<n) - 1;
int done = (all&(c1>>1)) | (all&(c1<<1)) | c0 | c2;
done &= (all^c1);
next[c1][c2] = Math.min(next[c1][c2], curr[c0][c1] + n - Integer.bitCount(done));
}
curr = next;
}
int res = oo;
for(int i = 0 ; i < 1<<n ; i++)
for(int j = 0 ; j < 1<<n ; j++)
res = Math.min(res, curr[i][j]);
System.out.println(n*m - res);
}
private static void fill(int[][] array, int val)
{
for(int [] fill : array)
Arrays.fill(fill, val);
}
} | np | 112_E. Petya and Spiders | CODEFORCES |
/*(c) gorlum0 [at] gmail.com*/
import java.io.*;
import java.util.*;
import java.math.*;
public class E
{
int bitcount(int x) {
int c = 0;
for ( ; x != 0; c++)
x &= x-1;
return c;
}
boolean bit(int x, int i)
{
if (i < 0) return false;
return (x>>i & 1) == 1 ? true : false;
}
int solve(int n, int m)
{
if (m > n) { int x = m; m = n; n = x; }
int maxmask = 1<<m;
int[][][] dp = new int[n+1][maxmask][maxmask];
for (int i = 0; i <= n; i++)
for (int j = 0; j < maxmask; j++)
for (int k = 0; k < maxmask; k++)
dp[i][j][k] = inf;
for (int i = 0; i < maxmask; i++)
dp[0][0][i] = bitcount(i);
for (int i = 1; i <= n; i++)
for (int b = 0; b < maxmask; b++)
for (int c = 0; c < maxmask; c++)
for (int a = 0; a < maxmask; a++) {
boolean nospider = false;
for (int j = 0; j < m; j++)
if (not(bit(a,j) || bit(c,j) || bit(b,j-1) || bit(b,j) || bit(b,j+1))) {
nospider = true;
break;
}
if (nospider) continue;
dp[i][b][c] = Math.min(dp[i][b][c], dp[i-1][a][b] + bitcount(c));
}
int res = inf;
for (int b = 0; b < maxmask; b++)
res = Math.min(res, dp[n][b][0]);
return n*m - res;
}
void main() throws IOException {
int n;
while ((n = nextInt()) != EOF) {
int m = nextInt();
out.println(solve(n, m));
}
}
public static void main(String[] args) {
new E().run();
}
// ======================================================================
int inf = (int) 1e9;
final int EOF = -1;
boolean not(boolean p) { return !p; }
int sqr(int x) { return x*x; }
long sqr(long x) { return x*x; }
double sqr(double x) { return x*x; }
BufferedReader fin;
StringTokenizer st;
PrintWriter out;
public void run() {
try {
fin = new BufferedReader(new InputStreamReader(System.in));
st = null;
out = new PrintWriter(System.out);
main();
fin.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = fin.readLine();
if (line == null) return "-1";
else st = new StringTokenizer(line);
}
return st.nextToken();
}
}
| np | 112_E. Petya and Spiders | CODEFORCES |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Code implements Runnable {
public static void main(String[] args) throws IOException {
new Thread(new Code()).start();
}
private void solve() throws IOException {
int n = nextInt(), m = nextInt();
if(n > m) {
n ^= m;
m ^= n;
n ^= m;
}
int[][][] dp = new int[41][64][64];
for(int i = 0; i < 41; ++i)
for(int j = 0; j < 64; ++j)
for(int k = 0; k < 64; ++k) dp[i][j][k] = Integer.MAX_VALUE / 2;
for(int i = 0; i < 64; ++i) dp[0][0][i] = countBit(i);
for(int i = 1; i <= m; ++i) {
for(int cur = 0; cur < 64; ++cur) {
for(int next = 0; next < 64; ++next) {
for(int prev = 0; prev < 64; ++prev) {
if(!isBad(prev, cur, next, n)) {
dp[i][cur][next] = min(dp[i][cur][next], dp[i - 1][prev][cur] + countBit(next));
}
}
}
}
}
int ans = Integer.MAX_VALUE;
for(int i = 0; i < 64; ++i) ans = min(ans, dp[m][i][0]);
writer.println(n * m - ans);
}
private boolean isBit(int bits, int pos) {
return pos < 0 ? false : ((bits & (1 << pos)) != 0);
}
private boolean isBad(int prev, int cur, int next, int count) {
for(int i = 0; i < count; ++i)
if(!(isBit(cur, i - 1) || isBit(cur, i) || isBit(cur, i + 1) || isBit(prev, i) || isBit(next, i))) return true;
return false;
}
private int countBit(int bits) {
int ans = 0;
for(int i = 0; i < 6; ++i) ans += (bits & (1 << i)) > 0 ? 1 : 0;
return ans;
}
private class Pair<E extends Comparable, V extends Comparable> implements Comparable<Pair<E, V>> {
public Pair(E first, V second) {
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair<E, V> obj) {
if(first == obj.first) return second.compareTo(obj.second);
return first.compareTo(obj.first);
}
@Override
public boolean equals(Object obj) {
Pair other = (Pair)obj;
return first.equals(other.first) && second.equals(other.second);
}
public E first;
public V second;
}
@Override
public void run() {
try {
if(in.equals("")) reader = new BufferedReader(new InputStreamReader(System.in));
else reader = new BufferedReader(new FileReader(in));
if(out.equals("")) writer = new PrintWriter(new OutputStreamWriter(System.out));
else writer = new PrintWriter(new FileWriter(out));
solve();
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
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());
}
private float nextFloat() throws IOException {
return Float.parseFloat(nextToken());
}
private String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(reader.readLine());
return st.nextToken();
}
private String in = "", out = "";
private BufferedReader reader;
private PrintWriter writer;
private StringTokenizer st;
} | np | 112_E. Petya and Spiders | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
public class E {
static int n;
static int m;
static int[][][] DP;
static int[] dx = { 0, 0, 1, -1 };
static int[] dy = { 1, -1, 0, 0 };
static int inf = 1000000;
public static int get(int x, int current, int last) {
if (x == n) {
if (last == 0)
return 0;
else
return -inf;
}
if (DP[x][current][last] != -1)
return DP[x][current][last];
int max = 0;
for (int mask = 0; mask < (1 << m); mask++) {
int tempLast = last;
int tempCurrent = current;
int tempNext = (1 << m) - 1;
for (int i = 0; i < m; i++)
if ((mask & (1 << i)) != 0) {
if (i > 0)
tempCurrent &= ~(1 << (i - 1));
if (i < m - 1)
tempCurrent &= ~(1 << (i + 1));
tempNext &= ~(1 << (i));
tempLast &= ~(1 << (i));
}
if (tempLast != 0)
continue;
max = Math.max(
max,
m - Integer.bitCount(mask)
+ get(x + 1, tempNext, tempCurrent & ~mask));
}
return DP[x][current][last] = max;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int y = in.nextInt();
n = Math.max(x, y);
m = Math.min(x, y);
DP = new int[n][1 << m][1 << m];
for (int i = 0; i < n; i++)
for (int j = 0; j < (1 << m); j++)
Arrays.fill(DP[i][j], -1);
System.out.println(get(0, (1 << m) - 1, 0));
}
}
| np | 112_E. Petya and Spiders | 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_E2. Rotate Columns (hard 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.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);
TaskE2 solver = new TaskE2();
solver.solve(1, in, out);
out.close();
}
static class TaskE2 {
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[] maxInColumn = new int[m];
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
maxInColumn[j] = Math.max(maxInColumn[j], a[i][j]);
}
}
Integer[] cols = new Integer[m];
for (int i = 0; i < m; i++) {
cols[i] = i;
}
Arrays.sort(cols, (u, v) -> -(maxInColumn[u] - maxInColumn[v]));
if (m > n) {
int[][] na = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
na[i][j] = a[i][cols[j]];
}
}
m = n;
a = na;
}
int[] buf = new int[n];
int[][] sums = new int[m][1 << n];
int[] sumsCur = new int[1 << n];
for (int j = 0; j < m; j++) {
for (int shift = 0; shift < n; shift++) {
for (int i = 0; i < n; i++) {
buf[i] = a[(i + shift) % n][j];
}
for (int mask = 0; mask < 1 << n; mask++) {
if (mask > 0) {
int k = Integer.numberOfTrailingZeros(mask);
sumsCur[mask] = sumsCur[mask ^ (1 << k)] + buf[k];
sums[j][mask] = Math.max(sums[j][mask], sumsCur[mask]);
}
}
}
}
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) {
nd[mask] = Math.max(nd[mask], d[mask ^ submask] + sums[j][submask]);
}
}
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_E2. Rotate Columns (hard 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_E2. Rotate Columns (hard version) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Comparator;
import java.util.Collections;
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[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
}
}
boolean[][] interesting = new boolean[n][m];
boolean[] hasInteresting = new boolean[m];
for (int i = 0; i < n; i++) {
List<Pair> list = new ArrayList<>();
for (int j = 0; j < m; j++) {
list.add(new Pair(a[i][j], j));
}
Collections.sort(list, Comparator.comparing(pair -> -pair.val));
for (int j = 0; j < m && j <= n; j++) {
interesting[i][list.get(j).pos] = true;
hasInteresting[list.get(j).pos] = true;
}
}
boolean[] goodMask = new boolean[1 << n];
for (int mask = 0; mask < 1 << n; mask++) {
int best = Integer.MAX_VALUE;
int cur = mask;
do {
best = Math.min(best, cur);
cur = (cur >> 1) | ((cur & 1) << (n - 1));
} while (cur != mask);
goodMask[mask] = (mask == best);
}
int[] dp = new int[1 << n];
for (int i = 0; i < m; i++) {
if (!hasInteresting[i]) {
continue;
}
for (int j = 0; j < n; j++) {
if (!interesting[j][i]) {
continue;
}
int supermask = (1 << n) - 1 - (1 << j);
int val = a[j][i];
for (int mask = supermask; ; mask = (mask - 1) & supermask) {
if (dp[mask] + val > dp[mask | (1 << j)]) {
dp[mask | (1 << j)] = dp[mask] + val;
}
if (mask == 0) {
break;
}
}
}
for (int mask = 0; mask < 1 << n; mask++) {
if (!goodMask[mask]) {
continue;
}
int best = 0;
int cur = mask;
do {
best = Math.max(best, dp[cur]);
cur = (cur >> 1) | ((cur & 1) << (n - 1));
} while (cur != mask);
do {
dp[cur] = best;
cur = (cur >> 1) | ((cur & 1) << (n - 1));
} while (cur != mask);
}
}
out.println(dp[(1 << n) - 1]);
}
}
class Pair {
int val;
int pos;
public Pair(int val, int pos) {
this.val = val;
this.pos = pos;
}
}
}
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_E2. Rotate Columns (hard 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_E2. Rotate Columns (hard version) | CODEFORCES |
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
public class CF1209E2 {
public static void main(String[] args) throws Exception {
boolean local = System.getSecurityManager() == null;
boolean async = false;
Charset charset = Charset.forName("ascii");
FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset);
Task task = new Task(io, new Debug(local));
if (async) {
Thread t = new Thread(null, task, "dalt", 1 << 27);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
t.join();
} else {
task.run();
}
if (local) {
io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M");
}
io.flush();
}
public static class Task implements Runnable {
final FastIO io;
final Debug debug;
int inf = (int) 1e8;
public Task(FastIO io, Debug debug) {
this.io = io;
this.debug = debug;
}
@Override
public void run() {
int t = io.readInt();
while (t-- > 0)
solve();
}
int[][] prefix = new int[12][1 << 12];
int[][] profits = new int[12][1 << 12];
Col[] cols = new Col[2000];
{
for (int i = 0; i < 2000; i++) {
cols[i] = new Col(12);
}
}
public void solve() {
int n = io.readInt();
int m = io.readInt();
for (int i = 0; i < m; i++) {
cols[i].max = 0;
cols[i].n = n;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cols[j].data[i] = io.readInt();
cols[j].max = Math.max(cols[j].max, cols[j].data[i]);
}
}
Arrays.sort(cols, 0, m, (a, b) -> -(a.max - b.max));
Col[] cols = Arrays.copyOf(this.cols, Math.min(m, n));
int mask = (1 << n) - 1;
SubsetGenerator sg = new SubsetGenerator();
SubsetGenerator2 sg2 = new SubsetGenerator2();
BitOperator bo = new BitOperator();
for (int i = 0; i < cols.length; i++) {
Arrays.fill(profits[i], 0);
for (int j = 0; j < n; j++) {
cols[i].rotate();
for (int k = 0; k < n; k++) {
sg2.values[k] = cols[i].data[k];
}
sg2.setSet(mask);
while (sg2.hasNext()) {
profits[i][sg2.next] = Math.max(profits[i][sg2.next], sg2.val);
sg2.next();
}
}
}
prefix[0] = profits[0];
for (int i = 1; i < cols.length; i++) {
for (int j = 0; j <= mask; j++) {
sg.setSet(j);
prefix[i][j] = prefix[i - 1][j];
while (sg.hasNext()) {
int next = sg.next();
prefix[i][j] = Math.max(prefix[i][j],
profits[i][next] + prefix[i - 1][j ^ next]);
}
}
}
io.cache.append(prefix[cols.length - 1][mask]).append('\n');
}
}
/**
* Bit operations
*/
public static class BitOperator {
public int bitAt(int x, int i) {
return (x >> i) & 1;
}
public int bitAt(long x, int i) {
return (int) ((x >> i) & 1);
}
public int setBit(int x, int i, boolean v) {
if (v) {
x |= 1 << i;
} else {
x &= ~(1 << i);
}
return x;
}
public long setBit(long x, int i, boolean v) {
if (v) {
x |= 1L << i;
} else {
x &= ~(1L << i);
}
return x;
}
/**
* Determine whether x is subset of y
*/
public boolean subset(long x, long y) {
return intersect(x, y) == x;
}
/**
* Merge two set
*/
public long merge(long x, long y) {
return x | y;
}
public long intersect(long x, long y) {
return x & y;
}
public long differ(long x, long y) {
return x - intersect(x, y);
}
}
public static class SubsetGenerator2 {
private int[] meanings = new int[33];
private int[] values = new int[33];
private int[] bits = new int[33];
private int remain;
private int next;
private int val;
public void setSet(int set) {
int bitCount = 0;
while (set != 0) {
meanings[bitCount] = set & -set;
bits[bitCount] = 0;
set -= meanings[bitCount];
bitCount++;
}
remain = 1 << bitCount;
next = 0;
val = 0;
}
public boolean hasNext() {
return remain > 0;
}
private void consume() {
remain = remain - 1;
int i;
for (i = 0; bits[i] == 1; i++) {
bits[i] = 0;
next -= meanings[i];
val -= values[i];
}
bits[i] = 1;
next += meanings[i];
val += values[i];
}
public int next() {
int returned = next;
consume();
return returned;
}
}
public static class SubsetGenerator {
private int[] meanings = new int[33];
private int[] bits = new int[33];
private int remain;
private int next;
public void setSet(int set) {
int bitCount = 0;
while (set != 0) {
meanings[bitCount] = set & -set;
bits[bitCount] = 0;
set -= meanings[bitCount];
bitCount++;
}
remain = 1 << bitCount;
next = 0;
}
public boolean hasNext() {
return remain > 0;
}
private void consume() {
remain = remain - 1;
int i;
for (i = 0; bits[i] == 1; i++) {
bits[i] = 0;
next -= meanings[i];
}
bits[i] = 1;
next += meanings[i];
}
public int next() {
int returned = next;
consume();
return returned;
}
}
public static class Col {
int[] data;
int max;
int n;
public void rotate() {
int end = data[n - 1];
System.arraycopy(data, 0, data, 1, n - 1);
data[0] = end;
}
public Col(int n) {
data = new int[n];
}
}
public static class FastIO {
public final StringBuilder cache = new StringBuilder(1 << 13);
private final InputStream is;
private final OutputStream os;
private final Charset charset;
private StringBuilder defaultStringBuf = new StringBuilder(1 << 13);
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastIO(InputStream is, OutputStream os, Charset charset) {
this.is = is;
this.os = os;
this.charset = charset;
}
public FastIO(InputStream is, OutputStream os) {
this(is, os, Charset.forName("ascii"));
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public long readLong() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
long val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public double readDouble() {
boolean sign = true;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+';
next = read();
}
long val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
if (next != '.') {
return sign ? val : -val;
}
next = read();
long radix = 1;
long point = 0;
while (next >= '0' && next <= '9') {
point = point * 10 + next - '0';
radix = radix * 10;
next = read();
}
double result = val + (double) point / radix;
return sign ? result : -result;
}
public String readString(StringBuilder builder) {
skipBlank();
while (next > 32) {
builder.append((char) next);
next = read();
}
return builder.toString();
}
public String readString() {
defaultStringBuf.setLength(0);
return readString(defaultStringBuf);
}
public int readLine(char[] data, int offset) {
int originalOffset = offset;
while (next != -1 && next != '\n') {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(char[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(byte[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (byte) next;
next = read();
}
return offset - originalOffset;
}
public char readChar() {
skipBlank();
char c = (char) next;
next = read();
return c;
}
public void flush() throws IOException {
os.write(cache.toString().getBytes(charset));
os.flush();
cache.setLength(0);
}
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_E2. Rotate Columns (hard 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();
Col[] cols = new Col[m];
int[][] mat = new int[m][n];
for(int i = 0; i < n; i++) {
for(int j =0; j < m; j++) {
mat[j][i] = scanner.nextInt();
}
}
for(int i = 0; i < m; i++) {
cols[i] = new Col(mat[i]);
}
Arrays.sort(cols);
int maxMask = 1 << n;
int[] dp = new int[maxMask];
Arrays.fill(dp, -1);
dp[0] = 0;
int sz = Math.min(n, m);
int[][] ss = new int[sz][maxMask];
//2^n * n^3
for(int i = 0; i < sz; i++) {
int[] curArr = cols[i].arr.clone();
for(int j = 0; j < n; j++) {
for(int mask = 0; mask < maxMask; mask++) {
int cur = 0;
for(int k = 0; k < n; k++) if ((( 1 << k) & mask) > 0) cur += curArr[k];
ss[i][mask] = Math.max(ss[i][mask], cur);
}
curArr = shift(curArr);
}
}
for(int i = 0; i < Math.min(n, m); i++) {
for(int mask = maxMask-1; mask>=0; mask--) {
for(int smask = mask; smask >= 0; smask = (smask-1)&mask) {
if (dp[smask] == -1) continue;
dp[mask] = Math.max(dp[mask], dp[smask] + ss[i][mask ^ smask]);
if (smask == 0) break;
}
}
}
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;
}
static class Col implements Comparable<Col> {
int[] arr;
int[] sorted;
public Col(int[] a) {
arr = a;
sorted= arr.clone();
Arrays.sort(sorted);
}
public int compareTo(Col col) {
return -sorted[sorted.length-1] + col.sorted[sorted.length-1];
}
}
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_E2. Rotate Columns (hard version) | CODEFORCES |
import java.io.*;
import java.util.*;
public class E2
{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// BufferedReader in;
StringTokenizer tok;
public void go() throws IOException
{
// long start = System.nanoTime();
// in = new BufferedReader(new FileReader(new File("input.txt")));
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[m][n+1];
for (int i = 0; i < n; i++)
{
ntok();
for (int e = 0; e < m; e++)
{
mat[e][i] = ipar();
}
}
for (int i = 0; i < m; i++)
{
for (int e = 0; e < n; e++)
{
mat[i][n] = Math.max(mat[i][n], mat[i][e]);
}
}
ArrayList<int[]> list = new ArrayList<>();
for (int i = 0; i < m; i++)
{
list.add(mat[i]);
}
Collections.sort(list, (a, b) -> {
return -Integer.compare(a[n], b[n]);
});
for (int i = 0; i < m; i++)
{
mat[i] = list.get(i);
}
m = Math.min(m, n);
int[][] dp = new int[1 << n][m+1];
for (int i = m-1; i >= 0; i--)
{
int[] temp = new int[1 << n];
for (int r = 0; r < n; r++)
{
for (int j = 0; j < 1 << n; j++)
{
temp[j] = dp[j][i+1];
}
for (int j = 0; j < n; j++)
{
int val = mat[i][(j+r)%n];
for (int k = 0; k < 1 << n; k++)
{
if ((k & (1 << j)) == 0)
{
temp[k | (1 << j)] = Math.max(temp[k | (1 << j)], temp[k] + val);
}
}
}
for (int j = 0; j < 1 << n; j++)
{
dp[j][i] = Math.max(dp[j][i], temp[j]);
}
}
}
out.println(dp[(1 << n) - 1][0]);
// int[][] best = new int[1 << n][m];
// for (int i = 0; i < 1 << n; i++)
// {
// for (int e = 0; e < m; e++)
// {
// best[i][e] = best(i, mat, e);
// }
// }
// int[][] dp = new int[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];
// int opposite = ~e & ((1 << n) - 1);
// for (int w = opposite; w != 0; w = (w-1) & opposite)
// {
// dp[e][i] = Math.max(dp[e][i], best[w][i] + dp[e|w][i+1]);
// }
// }
// }
// out.println(dp[0][0]);
}
// out.printf("%.3f%n", (System.nanoTime() - start) / 1000000.0);
out.flush();
in.close();
}
public int best(int mask, int[][] mat, int col)
{
int max = 0;
for (int t = 0; t < mat[0].length-1; t++)
{
int sum = 0;
int mk = mask;
for (int i = 0; i < mat[0].length-1; i++)
{
if (mk % 2 == 1)
{
sum += mat[col][(i+t)%(mat[0].length-1)];
}
mk /= 2;
}
max = Math.max(max, sum);
}
return max;
}
public void cycle(int[][] mat, int col)
{
int temp = mat[col][0];
for (int i = 0; i < mat[0].length-2; i++)
{
mat[col][i] = mat[col][i+1];
}
mat[col][mat[0].length-2] = 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 E2().go();
}
}
| np | 1209_E2. Rotate Columns (hard version) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Comparator;
import java.util.Collections;
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 n = 12;
// int m = 2000;
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();
// a[j][i] = (int)((i * 12346L + j * 789L) % 100000);
}
}
ArrayList<Integer> inds = new ArrayList<>();
for (int i = 0; i < m; ++i) {
inds.add(i);
}
int[][] finalA = a;
Collections.sort(inds, new Comparator<Integer>() {
public int compare(Integer i1, Integer i2) {
int val1 = 0, val2 = 0;
for (int i = 0; i < n; ++i) {
if (finalA[i1][i] > val1) {
val1 = finalA[i1][i];
}
}
for (int i = 0; i < n; ++i) {
if (finalA[i2][i] > val2) {
val2 = finalA[i2][i];
}
}
return -Integer.compare(val1, val2);
}
});
int newM = Math.min(m, n + 1);
int[][] na = new int[newM][];
for (int i = 0; i < newM; ++i) {
int ind = inds.get(i);
na[i] = a[ind];
}
m = newM;
a = na;
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 j = 0; j < n; ++j) {
int inc = b[j];
for (int mask = 0; mask < (1 << n); ++mask) {
if ((mask >> j) % 2 == 0) {
int val = buf[mask] + inc;
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_E2. Rotate Columns (hard version) | CODEFORCES |
/*input
3
2 3
2 5 7
4 2 4
3 6
4 1 5 2 10 4
8 6 6 4 9 10
5 4 9 5 8 7
3 3
9 9 9
1 1 1
1 1 1
*/
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.StringTokenizer;
import java.util.Random;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.*;
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);
int T = in.nextInt();
for (int cT = 1; cT <= T; cT++) {
Task solver = new Task();
solver.solve(cT, in, out);
}
out.close();
}
static class data {
int val, col;
data(int _val, int _col) {
val = _val; col = _col;
}
@Override
public String toString() {
return String.format("(%d,%d)", val, col);
}
}
static class Task {
int[][] a;
int[][] b;
int[][] dp;
int[][] mb;
ArrayList<data> all = new ArrayList<>();
Set<Integer> st = new HashSet<>();
int n, m;
int cal(int col, int mask) {
if (col == m) {
if (Integer.bitCount(mask) == n) return 0;
return (int)(-1e9);
}
int ret = dp[col][mask];
if (ret != -1) return ret;
int rmask = mask ^ ((1 << n) - 1);
// ret is not a reference
for (int mask2 = rmask; mask2 > 0; mask2 = rmask & (mask2 - 1)) {
int now = cal(col + 1, mask | mask2) + mb[col][mask2];
ret = Math.max(ret, now);
}
ret = Math.max(ret, cal(col + 1, mask));
dp[col][mask] = ret;
return ret;
}
public static int fsb(int n) {
return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
void prepMb() {
// col, cyclic, mask
for (int col = 0; col < m; col++) {
for (int mask = 1; mask < (1 << n); mask++) {
int nmask = mask;
while ((nmask & 1) == 0) nmask >>= 1;
if (nmask == mask) {
for (int shift = 0; shift < n; shift++) {
int sum = 0;
int tmask = mask;
while (tmask > 0) {
int i = Integer.numberOfTrailingZeros(tmask);
sum += b[(i + shift) % n][col]; tmask ^= (1 << i);
}
mb[col][mask] = Math.max(mb[col][mask], sum);
}
} else {
mb[col][mask] = mb[col][nmask];
}
}
}
}
void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt(); m = in.nextInt();
a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
all.add(new data(a[i][j], j));
}
}
Collections.sort(all, new Comparator<data>() {
@Override
public int compare(final data o1, final data o2) {
return -(o1.val - o2.val);
}
});
for (data it : all) {
if (st.size() == n) break;
st.add(it.col);
}
b = new int[n][st.size()];
int rcol = 0;
for (int col : st) {
for (int row = 0; row < n; row++)
b[row][rcol] = a[row][col];
rcol++;
}
m = st.size();
dp = new int[n][(1 << n)];
mb = new int[m][(1 << n)];
prepMb();
for (int i = 0; i < n; i++)
Arrays.fill(dp[i], -1);
System.out.println(cal(0, 0));
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
} | np | 1209_E2. Rotate Columns (hard 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_E2. Rotate Columns (hard 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 t=in.nextInt();
for(int i=0;i<t;i++) {
out.println(work());
}
out.flush();
}
long mod=1000000007;
long gcd(long a,long b) {
return b==0?a:gcd(b,a%b);
}
int work() {
int n=in.nextInt();
int m=in.nextInt();
int[][] A=new int[n][m];
int[][] B=new int[n][m];
int[][] R=new int[m][2];
for(int i=0;i<m;i++)R[i][1]=i;
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
A[i][j]=in.nextInt();
R[j][0]=Math.max(R[j][0], A[i][j]);
}
}
Arrays.sort(R,new Comparator<int[]>() {
public int compare(int[] arr1,int[] arr2) {
return arr2[0]-arr1[0];
}
});
for(int j=0;j<m;j++) {
int index=R[j][1];
for(int i=0;i<n;i++) {
B[i][j]=A[i][index];
}
}
m=Math.min(n, m);
int[][] dp=new int[m][1<<n];
int[][] rec=new int[m][1<<n];
for(int j=0;j<m;j++) {
for(int s=0;s<n;s++) {//转
for(int i=1;i<1<<n;i++) {
int sum=0;
for(int b=0;b<n;b++) {
if(((1<<b)&i)>0) {
sum+=B[(b+s)%n][j];
}
}
rec[j][i]=Math.max(sum, rec[j][i]);
}
}
}
for(int j=0;j<m;j++) {
for(int i=0;i<1<<n;i++) {
if(j==0) {
dp[j][i]=rec[j][i];
}else {
for(int p=i;p<1<<n;p++) {
p=p|i;
dp[j][p]=Math.max(dp[j][p], rec[j][i]+dp[j-1][p^i]);
}
}
}
}
return dp[m-1][(1<<n)-1];
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
if(st==null || !st.hasMoreElements())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
} | np | 1209_E2. Rotate Columns (hard 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_E2. Rotate Columns (hard 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.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);
TaskE2 solver = new TaskE2();
solver.solve(1, in, out);
out.close();
}
static class TaskE2 {
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();
}
}
if (m > n) {
int[] maxInColumn = new int[m];
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
maxInColumn[j] = Math.max(maxInColumn[j], a[i][j]);
}
}
Integer[] cols = new Integer[m];
for (int i = 0; i < m; i++) {
cols[i] = i;
}
Arrays.sort(cols, (u, v) -> -(maxInColumn[u] - maxInColumn[v]));
int[][] na = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
na[i][j] = a[i][cols[j]];
}
}
m = n;
a = na;
}
int[] buf = new int[n];
int[][] sums = new int[m][1 << n];
int[] sumsCur = new int[1 << n];
for (int j = 0; j < m; j++) {
for (int shift = 0; shift < n; shift++) {
for (int i = 0; i < n; i++) {
buf[i] = a[(i + shift) % n][j];
}
for (int mask = 1; mask < 1 << n; mask++) {
int k = Integer.numberOfTrailingZeros(mask);
sumsCur[mask] = sumsCur[mask ^ (1 << k)] + buf[k];
sums[j][mask] = Math.max(sums[j][mask], sumsCur[mask]);
}
}
}
int[] d = new int[1 << n];
for (int j = 0; j < m; j++) {
for (int mask = (1 << n) - 1; mask >= 0; mask--) {
for (int submask = mask; submask > 0; submask = (submask - 1) & mask) {
d[mask] = Math.max(d[mask], d[mask ^ submask] + sums[j][submask]);
}
}
}
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_E2. Rotate Columns (hard version) | CODEFORCES |
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
/**
* 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_E2. Rotate Columns (hard 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.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
E1RotateColumnsEasyVersion solver = new E1RotateColumnsEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class E1RotateColumnsEasyVersion {
int n;
int m;
int[][] arr;
int[][] mskValue;
int[][] memo;
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int q = sc.nextInt();
while (q-- > 0) {
n = sc.nextInt();
m = sc.nextInt();
arr = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = sc.nextInt();
int[][] temp = new int[m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
temp[i][j] = arr[j][i];
Arrays.sort(temp, (a, b) -> getMax(b) - getMax(a));
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
arr[j][i] = temp[i][j];
mskValue = new int[n][1 << n];
for (int i = 0; i < Math.min(n, m); i++) {
for (int j = 0; j < 1 << n; j++) {
int max = 0;
for (int shift = 0; shift < n; shift++) {
int sum = 0;
for (int k = 0; k < n; k++)
if ((j & 1 << k) != 0)
sum += arr[(k + shift) % n][i];
max = Math.max(max, sum);
}
mskValue[i][j] = max;
}
}
memo = new int[Math.min(n, m)][1 << n];
for (int[] x : memo)
Arrays.fill(x, -1);
pw.println(dp(0, 0));
}
}
private int getMax(int[] a) {
int max = 0;
for (int x : a)
max = Math.max(max, x);
return max;
}
private int dp(int idx, int msk) {
if (msk == (1 << n) - 1)
return 0;
if (idx == Math.min(n, m))
return (int) -1e9;
int max = Integer.MIN_VALUE;
if (memo[idx][msk] != -1)
return memo[idx][msk];
int availableBits = msk ^ ((1 << n) - 1);
for (int colMask = availableBits; colMask != 0; colMask = (colMask - 1) & availableBits) {
max = Math.max(max, mskValue[idx][colMask] + dp(idx + 1, msk | colMask));
}
return memo[idx][msk] = max;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| np | 1209_E2. Rotate Columns (hard version) | CODEFORCES |
//stan hu tao
//join nct ridin by first year culture reps
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1209E
{
public static void main(String hi[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
while(T-->0)
{
st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[][] grid = new int[N][M];
for(int r=0; r < N; r++)
grid[r] = readArr(M, infile, st);
ArrayList<Integer> ls = new ArrayList<Integer>();
for(int i=0; i < M; i++)
ls.add(i);
Collections.sort(ls, (x,y) -> {
int m1 = grid[0][x];
int m2 = grid[0][y];
for(int r=1; r < N; r++)
{
m1 = max(m1, grid[r][x]);
m2 = max(m2, grid[r][y]);
}
return m2-m1;
});
int[][] newgrid = new int[N][M];
for(int r=0; r < N; r++)
for(int c=0; c < M; c++)
newgrid[r][c] = grid[r][ls.get(c)];
M = min(M, N);
int[][] sums = new int[M][1<<N];
for(int i=1; i < M; i++)
for(int mask=0; mask < 1<<N; mask++)
{
//try all shifts
for(int head=0; head < N; head++)
{
int temp = 0;
for(int b=0; b < N; b++)
{
int nb = b+head;
if(nb >= N)
nb -= N;
if((mask&(1<<nb)) > 0)
temp += newgrid[b][i];
}
sums[i][mask] = max(sums[i][mask], temp);
}
}
int[][] dp = new int[M][1<<N];
for(int mask=0; mask < 1<<N; mask++)
for(int b=0; b < N; b++)
if((mask&(1<<b)) > 0)
dp[0][mask] += newgrid[b][0];
for(int i=1; i < M; i++)
for(int mask=0; mask < 1<<N; mask++)
for(int pmask=mask; pmask >= 0; pmask=(pmask-1)&mask)
{
dp[i][mask] = max(dp[i][mask], dp[i-1][pmask]+sums[i][mask-pmask]);
if(pmask == 0)
break;
}
sb.append(dp[M-1][(1<<N)-1]+"\n");
}
System.out.print(sb);
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
} | np | 1209_E2. Rotate Columns (hard 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_E2. Rotate Columns (hard 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.InputMismatchException;
// imp:12m
public class E4 {
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);
long[] mx = new long[m];
for(int i = 0;i < m;i++){
int u = 0;
for(int j = 0;j < n;j++){
u = Math.max(u, a[j][i]);
}
mx[i] = 1000000000L-u<<32|i;
}
Arrays.sort(mx);
int[] dp = new int[1<<n];
for(int i = 0;i < n && i < m;i++){
int c = (int)mx[i];
int[] ls = new int[1<<n];
for(int j = 1;j < 1<<n;j++){
ls[j] = ls[j&j-1] + a[Integer.numberOfTrailingZeros(j)][c];
}
for(int j = 1;j < 1<<n;j++){
int r = rot(j, n);
ls[r] = Math.max(ls[r], ls[j]);
}
int[] ndp = new int[1<<n];
for(int j = 0;j < 1<<n;j++){
if(rot(j, n) == j){
int cur = j;
for(int sh = 0;sh < n;sh++){
cur = cur>>1|(cur&1)<<n-1;
int mask = (1<<n)-1^cur;
for(int k = mask;k >= 0;k--){
k &= mask;
ndp[k|cur] = Math.max(
ndp[k|cur], dp[k] + ls[j]);
}
}
}
}
dp = ndp;
}
out.println(dp[(1<<n)-1]);
}
}
int rot(int x, int n)
{
int ret = x;
for(int i = 0;i < n;i++){
x = x>>>1|(x&1)<<n-1;
ret = Math.min(ret, x);
}
return ret;
}
void run() throws Exception
{
// int n = 12, m = 2000;
// 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 E4().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_E2. Rotate Columns (hard 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>=Math.min(n, m) || maxRowMask==((1<<n)-1))return 0;
if(memo[col][maxRowMask]!=-1)return memo[col][maxRowMask];
int ans=0;
int availableBits=maxRowMask^((1<<n)-1);
//all masks that don't intersect with maxRowMask
for(int colMask=availableBits;colMask!=0;colMask=(colMask-1)&availableBits) {
ans=Math.max(ans, maxMask[col][colMask]+dp(col+1, maxRowMask|colMask));
}
return memo[col][maxRowMask]=ans;
}
static int[][]sumOfMask;
static int[][]maxMask;
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();
int[]maxInCol=new int[m];
in=new int[m][n+1];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
in[j][i]=sc.nextInt();
maxInCol[j]=Math.max(maxInCol[j], in[j][i]);
in[j][n]=j;
}
}
Arrays.sort(in,(x,y)->maxInCol[y[n]]-maxInCol[x[n]]);
memo=new int[n][1<<n];
sumOfMask=new int[n][1<<n];
maxMask=new int[n][1<<n];
for(int i=0;i<n;i++) {
for(int msk=0;msk<memo[i].length;msk++) {
memo[i][msk]=-1;
if(i>=m)continue;
for(int bit=0;bit<n;bit++) {
if(((msk>>bit)&1)!=0) {
sumOfMask[i][msk]+=in[i][bit];
}
}
}
}
for(int col=0;col<n;col++) {
for(int msk=0;msk<(1<<n);msk++) {
int curMask=msk;
for(int cyclicShift=0;cyclicShift<n;cyclicShift++) {
maxMask[col][msk]=Math.max(maxMask[col][msk], sumOfMask[col][curMask]);
int lastBit=curMask&1;
curMask>>=1;
curMask|=(lastBit<<(n-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_E2. Rotate Columns (hard version) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.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;
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].vals[i] = in.nextInt();
}
}
for (E2RotateColumnsHardVersion.Column column : columns) column.initMax();
Arrays.sort(columns, new Comparator<E2RotateColumnsHardVersion.Column>() {
public int compare(E2RotateColumnsHardVersion.Column o1, E2RotateColumnsHardVersion.Column o2) {
return o2.max - o1.max;
}
});
if (columns.length > n)
columns = Arrays.copyOf(columns, n);
out.println(solveOne(columns));
}
private int solveOne(E2RotateColumnsHardVersion.Column[] columns) {
int n = columns[0].vals.length;
int[] best = new int[1 << n];
int[] next = new int[1 << n];
int[] temp = new int[1 << n];
for (E2RotateColumnsHardVersion.Column nowColumn : columns) {
System.arraycopy(best, 0, next, 0, best.length);
for (int rot = 0; rot < n; ++rot) {
System.arraycopy(best, 0, temp, 0, next.length);
for (int i = 0, pos = rot; i < n; ++i, ++pos) {
if (pos >= n) pos = 0;
int val = nowColumn.vals[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 j = 0; j < temp.length; ++j) {
next[j] = Math.max(next[j], temp[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 vv : vals) 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_E2. Rotate Columns (hard 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(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_E2. Rotate Columns (hard version) | CODEFORCES |
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
public class Test {
static PrintWriter writer =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int[][] a = new int[12][2000];
int[][] e = new int[12 * 2000][3];
Integer[] se = new Integer[12 * 2000];
boolean[] used = new boolean[2000];
int[] dp = new int[1 << 12];
int[] one = new int[1 << 12];
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();
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
a[i][j] = readInt();
int k = i * m + j;
e[k][0] = a[i][j];
e[k][1] = j;
e[k][2] = i;
}
for (int i = n * m - 1; i >= 0; i--) se[i] = i;
Arrays.sort(
se,
0,
n * m,
(i, j) -> {
int[] x = e[i], y = e[j];
return x[0] == y[0]
? (x[1] == y[1] ? Integer.compare(x[2], y[2]) : Integer.compare(x[1], y[1]))
: Integer.compare(x[0], y[0]);
});
Arrays.fill(used, 0, m, false);
Arrays.fill(dp, 0, 1 << n, -1);
dp[0] = 0;
int cc = 0;
for (int x = n * m - 1; x >= 0; x--) {
int c = e[se[x]][1];
if (used[c]) continue;
used[c] = true;
cc++;
if (cc > n) break;
Arrays.fill(one, 0, 1 << n, 0);
for (int i = (1 << n) - 1; i > 0; i--) {
for (int r = 0; r < n; r++) {
int sum = 0;
for (int j = 0; j < n; j++) if (((i >> j) & 1) != 0) sum += a[(j + r) % n][c];
one[i] = Math.max(one[i], sum);
}
}
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) {
dp[i | p] = Math.max(dp[i | p], dp[i] + one[p]);
p = (p - 1) & u;
}
}
}
writer.println(dp[(1 << n) - 1]);
}
}
}
| np | 1209_E2. Rotate Columns (hard version) | CODEFORCES |
import java.util.*;
import java.io.*;
public class E {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer>[][] nexts = new ArrayList[13][];
ArrayList<Integer>[] bs = new ArrayList[13];
int[][] index = new int[13][];
int[][] eqcl = new int[13][];
for(int n = 1; n <= 12; n++) {
eqcl[n] = new int[(1 << n)];
bs[n] = new ArrayList<Integer>();
index[n] = new int[(1 << n)];
int ind = 0;
for(int mask = 0; mask < (1 << n); mask++) {
boolean add = true;
for(int k = 0; k < n; k++) {
if(rot(mask, k, n) < mask) add = false;
}
if(add) {
bs[n].add(mask);
index[n][mask] = ind; ind++;
}
}
nexts[n] = new ArrayList[bs[n].size()];
for(int i = 0; i < bs[n].size(); i++) {
int mask = bs[n].get(i);
for(int k = 0; k < n; k++) {
eqcl[n][rot(mask, k, n)] = mask;
}
nexts[n][i] = new ArrayList<>();
for(int y = 0; y < (1 << n); y++) {
if((mask & y) == 0) {
nexts[n][i].add(y);
}
}
}
}
int T = Integer.parseInt(br.readLine());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
for(int test = 0; test < T; test++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[][] arrt = new int[m][n];
for(int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for(int j = 0; j < m; j++) {
arrt[j][i] = Integer.parseInt(st.nextToken());
}
}
Column[] cols = new Column[m];
for(int j = 0; j < m; j++) {
cols[j] = new Column(arrt[j]);
}
Arrays.sort(cols, Collections.reverseOrder());
m = Integer.min(n, m);
int[][] arr = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
arr[i][j] = cols[j].arr[i];
}
}
int[][] max = new int[m][bs[n].size()];
for(int c = 0; c < m; c++) {
for(int mask = 0; mask < (1 << n); mask++) {
int curr = 0;
for(int i = 0; i < n; i++) {
if((mask & (1 << i)) > 0) curr += arr[i][c];
}
int cl = eqcl[n][mask];
max[c][index[n][cl]] = Integer.max(max[c][index[n][cl]], curr);
}
}
int[][] dp = new int[m+1][bs[n].size()];
for(int c = 0; c < m; c++) {
for(int i = 0; i < bs[n].size(); i++) {
int mask = bs[n].get(i);
for(int next: nexts[n][i]) {
int cl = eqcl[n][next];
int dl = eqcl[n][mask | next];
if(dp[c][i] + max[c][index[n][cl]] > dp[c+1][index[n][dl]]) {
dp[c+1][index[n][dl]] = dp[c][i] + max[c][index[n][cl]];
}
}
}
}
bw.write(dp[m][bs[n].size() - 1]+"\n");
}
bw.flush();
}
static int rot(int x, int k, int n) {
int a = x << k;
int b = x >> (n - k);
return (a + b) & ((1 << n) - 1);
}
static class Column implements Comparable<Column>{
int[] arr;
int max;
public Column(int[] arr) {
this.arr = arr;
max = 0;
for(int k: arr) {
max = Integer.max(max, k);
}
}
@Override
public int compareTo(Column col) {
return max - col.max;
}
}
}
| np | 1209_E2. Rotate Columns (hard 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.Comparator;
import java.util.InputMismatchException;
// imp:12m
public class E5 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
for(int T = ni(); T> 0;T--){
int n = ni(), m = ni();
int[][] a = new int[m][n];
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
a[j][i] = ni();
}
}
int[][] mx = new int[m][];
for(int i = 0;i < m;i++){
int u = 0;
for(int j = 0;j < n;j++){
u = Math.max(u, a[i][j]);
}
mx[i] = new int[]{u, i};
}
Arrays.sort(mx, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return -(a[0] - b[0]);
}
});
int[] dp = new int[1<<n];
for(int i = 0;i < n && i < m;i++){
int c = mx[i][1];
int[] ls = new int[1<<n];
for(int j = 1;j < 1<<n;j++){
ls[j] = ls[j&j-1] + a[c][Integer.numberOfTrailingZeros(j)];
}
for(int j = 1;j < 1<<n;j++){
int r = rot(j, n);
ls[r] = Math.max(ls[r], ls[j]);
}
int[] ndp = new int[1<<n];
for(int j = 0;j < 1<<n;j++){
if(rot(j, n) == j){
int cur = j;
for(int sh = 0;sh < n;sh++){
cur = cur>>1|(cur&1)<<n-1;
int mask = (1<<n)-1^cur;
for(int k = mask;k >= 0;k--){
k &= mask;
ndp[k|cur] = Math.max(
ndp[k|cur], dp[k] + ls[j]);
}
}
}
}
dp = ndp;
}
out.println(dp[(1<<n)-1]);
}
}
int rot(int x, int n)
{
int ret = x;
for(int i = 0;i < n;i++){
x = x>>>1|(x&1)<<n-1;
ret = Math.min(ret, x);
}
return ret;
}
void run() throws Exception
{
// int n = 12, m = 2000;
// 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 E5().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_E2. Rotate Columns (hard 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 t=in.nextInt();
for(int i=0;i<t;i++) {
out.println(work());
}
out.flush();
}
long mod=1000000007;
long gcd(long a,long b) {
return b==0?a:gcd(b,a%b);
}
int work() {
int n=in.nextInt();
int m=in.nextInt();
int[][] A=new int[n][m];
int[][] B=new int[n][m];
int[][] R=new int[m][2];
for(int i=0;i<m;i++)R[i][1]=i;
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
A[i][j]=in.nextInt();
R[j][0]=Math.max(R[j][0], A[i][j]);
}
}
Arrays.sort(R,new Comparator<int[]>() {
public int compare(int[] arr1,int[] arr2) {
return arr2[0]-arr1[0];
}
});
for(int j=0;j<m;j++) {
int index=R[j][1];
for(int i=0;i<n;i++) {
B[i][j]=A[i][index];
}
}
m=Math.min(n, m);
int[][] dp=new int[m][1<<n];
int[][] rec=new int[m][1<<n];
for(int j=0;j<m;j++) {
for(int s=0;s<n;s++) {//转
for(int i=1;i<1<<n;i++) {
int sum=0;
for(int b=0;b<n;b++) {
if(((1<<b)&i)>0) {
sum+=B[(b+s)%n][j];
}
}
rec[j][i]=Math.max(sum, rec[j][i]);
}
}
}
for(int j=0;j<m;j++) {
for(int i=0;i<1<<n;i++) {
if(j==0) {
dp[j][i]=rec[j][i];
}else {
for(int p=i+1;;p++) {
if(p>=1<<n)break;
p=p|i;
dp[j][p]=Math.max(dp[j][p], rec[j][i]+dp[j-1][p^i]);
}
}
}
}
return dp[m-1][(1<<n)-1];
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
if(st==null || !st.hasMoreElements())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
} | np | 1209_E2. Rotate Columns (hard 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.Comparator;
import java.util.InputMismatchException;
public class E4 {
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[][] mx = new int[m][];
for(int i = 0;i < m;i++){
int u = 0;
for(int j = 0;j < n;j++){
u = Math.max(u, a[j][i]);
}
mx[i] = new int[]{u, i};
}
Arrays.sort(mx, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return -(a[0] - b[0]);
}
});
int[] dp = new int[1<<n];
for(int i = 0;i < n && i < m;i++){
int c = mx[i][1];
int[] ls = new int[1<<n];
for(int j = 1;j < 1<<n;j++){
ls[j] = ls[j&j-1] + a[Integer.numberOfTrailingZeros(j)][c];
}
for(int j = 1;j < 1<<n;j++){
int r = rot(j, n);
ls[r] = Math.max(ls[r], ls[j]);
}
int[] ndp = new int[1<<n];
for(int j = 0;j < 1<<n;j++){
if(rot(j, n) == j){
int cur = j;
for(int sh = 0;sh < n;sh++){
cur = cur>>1|(cur&1)<<n-1;
int mask = (1<<n)-1^cur;
for(int k = mask;k >= 0;k--){
k &= mask;
ndp[k|cur] = Math.max(
ndp[k|cur], dp[k] + ls[j]);
}
}
}
}
dp = ndp;
}
out.println(dp[(1<<n)-1]);
}
}
int rot(int x, int n)
{
int ret = x;
for(int i = 0;i < n;i++){
x = x>>>1|(x&1)<<n-1;
ret = Math.min(ret, x);
}
return ret;
}
void run() throws Exception
{
// int n = 12, m = 2000;
// 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 E4().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_E2. Rotate Columns (hard version) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.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;
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, new Comparator<E2RotateColumnsHardVersion.Column>() {
public int compare(E2RotateColumnsHardVersion.Column o1, E2RotateColumnsHardVersion.Column o2) {
return 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_E2. Rotate Columns (hard version) | CODEFORCES |
import java.util.*;
import java.io.*;
public class E1 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//optimizaciones que parece que solo son necesarias para java
ArrayList<Integer>[] reps = new ArrayList[13]; //representantes de las clases
int[][] index = new int[13][]; // mapea para cada representante un indice de 0 a |clases|-1
int[][] eqcl = new int[13][]; //mapea para cada mask, su clase
ArrayList<Integer>[][] nexts = new ArrayList[13][]; //para cada clase, los masks compatibles
for(int n = 1; n <= 12; n++) {
eqcl[n] = new int[(1 << n)];
reps[n] = new ArrayList<Integer>();
index[n] = new int[(1 << n)];
int ind = 0;
for(int mask = 0; mask < (1 << n); mask++) {
boolean add = true;
for(int k = 0; k < n; k++) {
if(rot(mask, k, n) < mask) add = false;
}
if(add) {
reps[n].add(mask);
index[n][mask] = ind; ind++;
}
}
nexts[n] = new ArrayList[reps[n].size()];
for(int i = 0; i < reps[n].size(); i++) {
int mask = reps[n].get(i);
for(int k = 0; k < n; k++) {
eqcl[n][rot(mask, k, n)] = i;
}
nexts[n][i] = new ArrayList<>();
for(int y = 0; y < (1 << n); y++) {
if((mask & y) == 0) {
nexts[n][i].add(y);
}
}
}
}
int T = Integer.parseInt(br.readLine());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
for(int test = 0; test < T; test++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[][] arrt = new int[m][n];
for(int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for(int j = 0; j < m; j++) {
arrt[j][i] = Integer.parseInt(st.nextToken());
}
}
Column[] cols = new Column[m];
for(int j = 0; j < m; j++) {
cols[j] = new Column(arrt[j]);
}
Arrays.sort(cols, Collections.reverseOrder());
m = Integer.min(n, m);
int[][] arr = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
arr[i][j] = cols[j].arr[i];
}
}
int[][] max = new int[m][reps[n].size()];
for(int c = 0; c < m; c++) {
for(int mask = 0; mask < (1 << n); mask++) {
int curr = 0;
for(int i = 0; i < n; i++) {
if((mask & (1 << i)) > 0) curr += arr[i][c];
}
int cl = eqcl[n][mask];
max[c][cl] = Integer.max(max[c][cl], curr);
}
}
int[][] dp = new int[m+1][reps[n].size()];
for(int c = 0; c < m; c++) {
for(int i = 0; i < reps[n].size(); i++) {
int mask = reps[n].get(i);
for(int next: nexts[n][i]) { //opt
int cl = eqcl[n][next];
int dl = eqcl[n][mask | next];
if(dp[c][i] + max[c][cl] > dp[c+1][dl]) { // el dp
dp[c+1][dl] = dp[c][i] + max[c][cl];
}
}
}
}
bw.write(dp[m][reps[n].size() - 1]+"\n");
}
bw.flush();
}
static int rot(int x, int k, int n) {
int a = x << k;
int b = x >> (n - k);
return (a + b) & ((1 << n) - 1);
}
static class Column implements Comparable<Column>{
int[] arr;
int max;
public Column(int[] arr) {
this.arr = arr;
max = 0;
for(int k: arr) {
max = Integer.max(max, k);
}
}
@Override
public int compareTo(Column col) {
return max - col.max;
}
}
}
| np | 1209_E2. Rotate Columns (hard version) | CODEFORCES |
import java.util.*;
import java.io.*;
/*
6
2 2
5 2
1 5
1 1
3
1 2
1 1
1 2
1 1
1 2
2 3
2 1
1
1
*/
public class e2 {
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();
long start = System.currentTimeMillis();
for(int q = 1; q <= t; q++){
n = scan.nextInt();
m = scan.nextInt();
// n = 12;
// m = 20000;
mat = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
mat[i][j] = scan.nextInt();
// mat[i][j] = 100000;
}
}
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] = max(max[i], mat[j][i]);
}
pq.add(new Item(i, max[i]));
}
ArrayList<Item> guys = new ArrayList<Item>();
while(!pq.isEmpty() && guys.size() < n){
Item tt = pq.poll();
guys.add(tt);
}
int[][] cost = new int[guys.size()][1 << n];
// long time = System.currentTimeMillis();
for(int i = 0; i < guys.size(); i++){
int g = guys.get(i).a;
for(int s = 0; s < n; s++){
for(int j = 0; j < (1 << n); j++){
int sum = 0;
for(int k = 0; k < n; k++){
if((j & (1 << k)) > 0){
sum += mat[(k+s)%n][g];
}
}
cost[i][j] = max(cost[i][j], sum);
}
}
}
// for(int i = 0; i < guys.size(); i++) System.out.println(Arrays.toString(cost[i]));
// System.out.println(System.currentTimeMillis()-time);
int full = (1 << n)-1;
// time = System.currentTimeMillis();
int[][] dp = new int[guys.size()+1][1 << n];
int ans = 0;
for(int c = 0; c < guys.size(); c++){
for(int j = 0; j < (1 << n); j++){
for(int i = j; i < (1 << n); i = (i+1)|j){
dp[c+1][i] =
max(dp[c+1][i], cost[c][j]+dp[c][i^j]);
ans = max(ans, dp[c+1][i]);
}
}
}
// for(int i = 0; i < dp.length; i++) System.out.println(Arrays.toString(dp[i]));
// System.out.println(System.currentTimeMillis()-time);
out.println(ans);
}
// System.out.println(System.currentTimeMillis()-start);
out.flush();
}
static int max(int a, int b){
return a > b? a : b;
}
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_E2. Rotate Columns (hard 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_E2. Rotate Columns (hard version) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.util.ArrayList;
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);
TaskE2 solver = new TaskE2();
solver.solve(1, in, out);
out.close();
}
static class TaskE2 {
int[][] grid;
int[][] val;
int[][] dp;
int rows;
int two(int bit) {
return 1 << bit;
}
boolean contain(int mask, int bit) {
return (mask & two(bit)) > 0;
}
int rec(int col, int mask) {
if (col == grid[0].length)
return 0;
if (dp[col][mask] != -1)
return dp[col][mask];
int res = rec(col + 1, mask);
for (int newMask = mask; newMask > 0; newMask = (mask & (newMask - 1))) {
res = Math.max(res, rec(col + 1, mask ^ newMask) + val[col][newMask]);
}
dp[col][mask] = res;
return res;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int T = in.nextInt();
for (int t = 0; t < T; t++) {
int n = in.nextInt();
int m = in.nextInt();
rows = n;
int[][] input = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
input[i][j] = in.nextInt();
}
}
ArrayList<Col> cols = new ArrayList<>();
for (int col = 0; col < m; col++) {
int maxVal = 0;
for (int row = 0; row < n; row++) {
maxVal = Math.max(maxVal, input[row][col]);
}
cols.add(new Col(maxVal, col));
}
Collections.sort(cols);
m = Math.min(n, m);
grid = new int[n][m];
for (int i = 0; i < m; i++) {
int c = cols.get(i).colID;
for (int row = 0; row < n; row++) {
grid[row][i] = input[row][c];
}
}
val = new int[m][two(n)];
for (int c = 0; c < m; c++) {
for (int mask = 0; mask < two(n); mask++) {
val[c][mask] = 0;
for (int offset = 0; offset < n; offset++) {
int sum = 0;
for (int bit = 0; bit < n; bit++) {
if (contain(mask, bit) == true)
sum += grid[(bit + offset) % n][c];
}
val[c][mask] = Math.max(val[c][mask], sum);
}
}
}
dp = new int[m][two(n)];
for (int[] aux : dp)
Arrays.fill(aux, -1);
int ans = rec(0, two(n) - 1);
out.println(ans);
}
}
class Col implements Comparable<Col> {
int maxVal;
int colID;
Col(int _maxVal, int _colID) {
this.maxVal = _maxVal;
this.colID = _colID;
}
public int compareTo(Col o) {
if (o.maxVal != this.maxVal) return this.maxVal > o.maxVal ? -1 : 1;
if (o.colID != this.colID) return this.colID < o.colID ? -1 : 1;
return 0;
}
}
}
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_E2. Rotate Columns (hard version) | CODEFORCES |
import java.io.*;
import java.util.*;
public class Sol2{
final public static int MXN = (1<<21);
public static int good[][];
public static void main(String[] args) throws IOException{
FastIO sc = new FastIO(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
int num[][] = new int[m][m];
String str = sc.next();
for(int i=0; i<str.length()-1; i++) {
int a = str.charAt(i)-'a';
int b = str.charAt(i+1)-'a';
num[a][b]++;
num[b][a]++;
}
int lowbit[] = new int[MXN];
int dp[] = new int[MXN];
for(int i=0; i<MXN; i++) {
dp[i] = Integer.MAX_VALUE;
}
dp[0] = 0;
good = new int[MXN][m];
for(int msk = 0; msk<(1<<m); msk++) {
for(int i=0; i<m; i++) {
int low = Integer.numberOfTrailingZeros(Integer.lowestOneBit(msk));
if(low==32) low = 0;
good[msk][i] = good[msk^(1<<low)][i] + num[i][low];
}
}
for(int msk = 0; msk<(1<<m); msk++) {
int bits = Integer.bitCount(msk)+1;
for(int i=0; i<m; i++) {
if((msk&(1<<i))!=0) continue;
int nxt = msk|(1<<i);
dp[nxt] = Math.min(dp[nxt], dp[msk] + bits*(good[msk][i]-good[((1<<m)-1)^nxt][i]));
}
}
out.println(dp[(1<<m)-1]);
out.close();
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static class FastIO {
// Is your Fast I/O being bad?
InputStream dis;
byte[] buffer = new byte[1 << 17];
int pointer = 0;
public FastIO(String fileName) throws IOException {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws IOException {
dis = is;
}
int nextInt() throws IOException {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
long nextLong() throws IOException {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
byte nextByte() throws IOException {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
String next() throws IOException {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
}
}
| np | 1238_E. Keyboard Purchase | 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.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jenish
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
EKeyboardPurchase solver = new EKeyboardPurchase();
solver.solve(1, in, out);
out.close();
}
static class EKeyboardPurchase {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int m = in.scanInt();
int step[][] = new int[m][m];
char arr[] = in.scanString().toCharArray();
for (int i = 0; i < n - 1; i++) {
step[arr[i] - 'a'][arr[i + 1] - 'a']++;
step[arr[i + 1] - 'a'][arr[i] - 'a']++;
}
int dp[] = new int[1 << m];
Arrays.fill(dp, Integer.MAX_VALUE / 2);
for (int i = 0; i < m; i++) dp[1 << i] = 0;
for (int i = 0; i < (1 << m); i++) {
int cost = 0;
for (int j = 0; j < m; j++) {
if (((i & (1 << j)) != 0)) {
for (int k = 0; k < m; k++) {
if (((i & (1 << k)) == 0)) {
cost += step[j][k];
}
}
}
}
for (int j = 0; j < m; j++)
if (((i & (1 << j)) == 0)) dp[i | (1 << j)] = Math.min(dp[i | (1 << j)], dp[i] + cost);
}
out.println(dp[(1 << m) - 1]);
}
}
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 I = 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') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
public String scanString() {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder RESULT = new StringBuilder();
do {
RESULT.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return RESULT.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| np | 1238_E. Keyboard Purchase | CODEFORCES |
/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x1238E
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
String input = infile.readLine();
int[][] cnt = new int[M][M];
for(int i=0; i < N-1; i++)
if(input.charAt(i) != input.charAt(i+1))
{
cnt[input.charAt(i)-'a'][input.charAt(i+1)-'a']++;
cnt[input.charAt(i+1)-'a'][input.charAt(i)-'a']++;
}
int[] dp = new int[1 << M];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for(int mask=0; mask < dp.length; mask++)
for(int b=0; b < M; b++)
if((mask&(1<<b)) == 0)
{
int submask = mask|(1<<b);
int cost = 0;
for(int c=0; c < M; c++)
{
if((mask&(1<<c)) > 0)
cost += cnt[b][c];
else
cost -= cnt[b][c];
}
dp[submask] = Math.min(dp[submask], dp[mask]+cost*Integer.bitCount(mask));
}
System.out.println(dp[(1<<M)-1]);
}
} | np | 1238_E. Keyboard Purchase | 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;
static int dp[], cnt[][], sum[];
static void solve() throws IOException
{
//initIo(true);
initIo(false);
StringBuilder sb = new StringBuilder();
n = ni();
m = ni();
dp = new int[(1<<m)];
char c[] = ne().toCharArray();
cnt = new int[m][m];
for(int i=0;i+1<n;++i) {
if(c[i]!=c[i+1]) {
++cnt[c[i] - 'a'][c[i+1] - 'a'];
++cnt[c[i+1] - 'a'][c[i] - 'a'];
}
}
sum = new int[1<<m];
calc(0, 0, 0);
Arrays.fill(dp, -1);
pl(f(0));
pw.flush();
pw.close();
}
static void calc(int mask, int S, int pos) {
if(pos==m) {
sum[mask] = S;
return;
}
calc(mask, S, pos+1);
int newSum = S;
for(int i=0;i<pos;++i) {
if((mask&(1<<i))!=0) {
newSum-=cnt[i][pos];
}
else {
newSum+=cnt[i][pos];
}
}
for(int i=pos+1;i<m;++i) {
newSum+=cnt[i][pos];
}
calc(mask|(1<<pos), newSum, pos+1);
}
static int f(int mask) {
if(mask==(1<<m) - 1) {
return 0;
}
if(dp[mask]!=-1) {
return dp[mask];
}
int min = Integer.MAX_VALUE;
for(int i=0;i<m;++i) {
if((mask&(1<<i))==0) {
min = min(min, sum[mask]+f(mask|(1<<i)));
}
}
return dp[mask] = min;
}
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 | 1238_E. Keyboard Purchase | CODEFORCES |
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
public class CF1238E {
public static void main(String[] args) throws Exception {
boolean local = System.getSecurityManager() == null;
boolean async = false;
Charset charset = Charset.forName("ascii");
FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset);
Task task = new Task(io, new Debug(local));
if (async) {
Thread t = new Thread(null, task, "dalt", 1 << 27);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
t.join();
} else {
task.run();
}
if (local) {
io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M");
}
io.flush();
}
public static class Task implements Runnable {
final FastIO io;
final Debug debug;
int inf = (int) 1e8;
long lInf = (long) 1e18;
double dInf = 1e50;
public Task(FastIO io, Debug debug) {
this.io = io;
this.debug = debug;
}
@Override
public void run() {
solve();
}
int[][] fee;
int m;
long[] dp;
int mask;
int[][] maskFee;
public void solve() {
int n = io.readInt();
m = io.readInt();
char[] s = new char[n];
io.readString(s, 0);
for (int i = 0; i < n; i++) {
s[i] -= 'a';
}
fee = new int[m][m];
for (int i = 1; i < n; i++) {
fee[s[i]][s[i - 1]]++;
fee[s[i - 1]][s[i]]++;
}
mask = (1 << m) - 1;
maskFee = new int[m][mask + 1];
SubsetGenerator sg = new SubsetGenerator();
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
sg.meanings[j] = fee[i][j];
}
for (int j = 0; j <= mask; j++) {
maskFee[i][j] = sg.next();
}
}
dp = new long[mask + 1];
Arrays.fill(dp, -1);
dp[0] = 0;
io.cache.append(dp(mask));
}
BitOperator bo = new BitOperator();
public long dp(int s) {
if (dp[s] == -1) {
long extra = 0;
int remainSet = mask - s;
for (int j = 0; j < m; j++) {
if (bo.bitAt(s, j) == 0) {
continue;
}
extra += maskFee[j][remainSet];
}
dp[s] = lInf;
for (int j = 0; j < m; j++) {
if (bo.bitAt(s, j) == 0) {
continue;
}
int ss = bo.setBit(s, j, false);
dp[s] = Math.min(dp[s], extra + dp(ss));
}
}
return dp[s];
}
}
/**
* Bit operations
*/
public static class BitOperator {
public int bitAt(int x, int i) {
return (x >> i) & 1;
}
public int bitAt(long x, int i) {
return (int) ((x >> i) & 1);
}
public int setBit(int x, int i, boolean v) {
if (v) {
x |= 1 << i;
} else {
x &= ~(1 << i);
}
return x;
}
public long setBit(long x, int i, boolean v) {
if (v) {
x |= 1L << i;
} else {
x &= ~(1L << i);
}
return x;
}
public long swapBit(long x, int i, int j) {
int bi = bitAt(x, i);
int bj = bitAt(x, j);
x = setBit(x, i, bj == 1);
x = setBit(x, j, bi == 1);
return x;
}
public int swapBit(int x, int i, int j) {
int bi = bitAt(x, i);
int bj = bitAt(x, j);
x = setBit(x, i, bj == 1);
x = setBit(x, j, bi == 1);
return x;
}
/**
* Determine whether x is subset of y
*/
public boolean subset(long x, long y) {
return intersect(x, y) == x;
}
/**
* Merge two set
*/
public long merge(long x, long y) {
return x | y;
}
public long intersect(long x, long y) {
return x & y;
}
public long differ(long x, long y) {
return x - intersect(x, y);
}
}
public static class SubsetGenerator {
private int[] meanings = new int[33];
private int[] bits = new int[33];
private int remain;
private int next;
public void setSet(int set) {
int bitCount = 0;
while (set != 0) {
meanings[bitCount] = set & -set;
bits[bitCount] = 0;
set -= meanings[bitCount];
bitCount++;
}
remain = 1 << bitCount;
next = 0;
}
public boolean hasNext() {
return remain > 0;
}
private void consume() {
remain = remain - 1;
int i;
for (i = 0; bits[i] == 1; i++) {
bits[i] = 0;
next -= meanings[i];
}
bits[i] = 1;
next += meanings[i];
}
public int next() {
int returned = next;
consume();
return returned;
}
}
public static class FastIO {
public final StringBuilder cache = new StringBuilder(1 << 13);
private final InputStream is;
private final OutputStream os;
private final Charset charset;
private StringBuilder defaultStringBuf = new StringBuilder(1 << 13);
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastIO(InputStream is, OutputStream os, Charset charset) {
this.is = is;
this.os = os;
this.charset = charset;
}
public FastIO(InputStream is, OutputStream os) {
this(is, os, Charset.forName("ascii"));
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public long readLong() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
long val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public double readDouble() {
boolean sign = true;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+';
next = read();
}
long val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
if (next != '.') {
return sign ? val : -val;
}
next = read();
long radix = 1;
long point = 0;
while (next >= '0' && next <= '9') {
point = point * 10 + next - '0';
radix = radix * 10;
next = read();
}
double result = val + (double) point / radix;
return sign ? result : -result;
}
public String readString(StringBuilder builder) {
skipBlank();
while (next > 32) {
builder.append((char) next);
next = read();
}
return builder.toString();
}
public String readString() {
defaultStringBuf.setLength(0);
return readString(defaultStringBuf);
}
public int readLine(char[] data, int offset) {
int originalOffset = offset;
while (next != -1 && next != '\n') {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(char[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(byte[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (byte) next;
next = read();
}
return offset - originalOffset;
}
public char readChar() {
skipBlank();
char c = (char) next;
next = read();
return c;
}
public void flush() throws IOException {
os.write(cache.toString().getBytes(charset));
os.flush();
cache.setLength(0);
}
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 | 1238_E. Keyboard Purchase | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class E implements Runnable {
public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();}
int n, m;
char[] str;
int[][] occs, cost;
int[] dp;
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
//where's my 420??? :(
n = fs.nextInt(); m = fs.nextInt();
byte[] str = fs.next().getBytes();
int[] occs = new int[1<<m];
for(int i = 0; i < n-1; i++) {
int l1 = str[i] - 'a';
int l2 = str[i+1] - 'a';
occs[(1<<l1) | (1<<l2)]++;
occs[(1<<l2) | (1<<l1)]++;
}
//cost[mask][v] = numPairs with v for some all bits on in mask
int all = (1<<m)-1;
cost = new int[m][1<<m];
for(int i = 0; i < m; i++) {
for(int mask = 1; mask < all; mask++) {
if(((1<<i)&mask) > 0) continue;
int lb = mask & (-mask);
int trail = Integer.numberOfTrailingZeros(lb);
int nmask = mask ^ lb;
cost[i][mask] = cost[i][nmask]+occs[1<<i | 1<<trail];
}
}
dp = new int[1<<m];
for(int mask = dp.length-2; mask >= 0; mask--) {
int addOn = 0;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
addOn += cost[nxt][mask];
}
int res = oo;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
int ret = addOn+dp[mask | (1<<nxt)];
res = min(res, ret);
}
dp[mask] = res;
}
System.out.println(dp[0]>>1);
out.close();
}
int oo = (int)1e9;
int min(int a, int b) {
if(a < b) return a;
return b;
}
class FastScanner {
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 FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
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;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.InputMismatchException;
import java.util.function.Function;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static class TaskAdapter implements Runnable {
@Override
public void run() {
long startTime = System.currentTimeMillis();
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
Output out = new Output(outputStream);
EKeyboardPurchase solver = new EKeyboardPurchase();
solver.solve(1, in, out);
out.close();
System.err.println(System.currentTimeMillis()-startTime+"ms");
}
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28);
thread.start();
thread.join();
}
static class EKeyboardPurchase {
private final int iinf = 1_000_000_000;
public EKeyboardPurchase() {
}
public void solve(int kase, InputReader in, Output pw) {
int n = in.nextInt(), m = in.nextInt();
int[] arr = in.nextIntChar(o -> o-'a');
int[][] sum = new int[m][1<<m];
{
int[][] cnt = new int[m][m];
for(int i = 0; i<n-1; i++) {
int a = arr[i], b = arr[i+1];
cnt[a][b]++;
cnt[b][a]++;
}
for(int i = 0; i<m; i++) {
for(int j = 1; j<1<<m; j++) {
int x = j&-j;
sum[i][j] = sum[i][j^x]+cnt[i][31-Integer.numberOfLeadingZeros(x)];
}
}
}
int[] mbit = new int[1<<m];
for(int i = 1; i<1<<m; i++) {
mbit[i] = Integer.numberOfTrailingZeros(i&-i);
}
int[] dp = new int[1<<m];
for(int i = 1; i<1<<m; i++) {
int ans = iinf, ci = i;
for(int j = mbit[ci]; ci>0; ci -= (1<<j), j = mbit[ci]) {
int cur = dp[i^(1<<j)]+sum[j][i^(1<<j)];
int x = ((1<<m)-1)^i;
int cm = i;
for(int k = mbit[cm]; cm>0; cm -= (1<<k), k = mbit[cm]) {
cur += sum[k][x];
}
cur -= sum[j][x];
ans = Math.min(ans, cur);
}
dp[i] = ans;
}
// dbg(dp);
pw.println(dp[dp.length-1]);
}
}
static interface InputReader {
String next();
int nextInt();
default int[] nextIntChar(Function<Character, Integer> f) {
String s = next();
int[] ret = new int[s.length()];
for(int i = 0; i<s.length(); i++) {
ret[i] = f.apply(s.charAt(i));
}
return ret;
}
}
static class FastReader implements InputReader {
final private int BUFFER_SIZE = 1<<16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer;
private int bytesRead;
public FastReader(InputStream is) {
din = new DataInputStream(is);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() {
StringBuilder ret = new StringBuilder(64);
byte c = skip();
while(c!=-1&&!isSpaceChar(c)) {
ret.appendCodePoint(c);
c = read();
}
return ret.toString();
}
public int nextInt() {
int ret = 0;
byte c = skipToDigit();
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;
}
private boolean isSpaceChar(byte b) {
return b==' '||b=='\r'||b=='\n'||b=='\t'||b=='\f';
}
private byte skip() {
byte ret;
while(isSpaceChar((ret = read()))) ;
return ret;
}
private boolean isDigit(byte b) {
return b>='0'&&b<='9';
}
private byte skipToDigit() {
byte ret;
while(!isDigit(ret = read())&&ret!='-') ;
return ret;
}
private void fillBuffer() {
try {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
}catch(IOException e) {
e.printStackTrace();
throw new InputMismatchException();
}
if(bytesRead==-1) {
buffer[0] = -1;
}
}
private byte read() {
if(bytesRead==-1) {
throw new InputMismatchException();
}else if(bufferPointer==bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
}
static class Output implements Closeable, Flushable {
public StringBuilder sb;
public OutputStream os;
public int BUFFER_SIZE;
public String lineSeparator;
public Output(OutputStream os) {
this(os, 1<<16);
}
public Output(OutputStream os, int bs) {
BUFFER_SIZE = bs;
sb = new StringBuilder(BUFFER_SIZE);
this.os = new BufferedOutputStream(os, 1<<17);
lineSeparator = System.lineSeparator();
}
public void println(int i) {
println(String.valueOf(i));
}
public void println(String s) {
sb.append(s);
println();
}
public void println() {
sb.append(lineSeparator);
}
private void flushToBuffer() {
try {
os.write(sb.toString().getBytes());
}catch(IOException e) {
e.printStackTrace();
}
sb = new StringBuilder(BUFFER_SIZE);
}
public void flush() {
try {
flushToBuffer();
os.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
public void close() {
flush();
try {
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
| np | 1238_E. Keyboard Purchase | 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(){
out.println(work());
out.flush();
}
long mod=1000000007;
long gcd(long a,long b) {
return b==0?a:gcd(b,a%b);
}
long work() {
int n=in.nextInt();
int m=in.nextInt();
String str=in.next();
long[] dp=new long[1<<m];
long[][] cnt=new long[m][m];
long[] rec=new long[1<<m];
for(int i=1;i<n;i++) {
int n1=str.charAt(i-1)-'a';
int n2=str.charAt(i)-'a';
cnt[n1][n2]++;
cnt[n2][n1]++;
}
for(int i=1;i<1<<m;i++) {
dp[i]=9999999999L;
long v=0;
int b=0;//最低位的1
for(int j=0;j<m;j++) {
if((i&(1<<j))>0) {
b=j;
break;
}
}
for(int j=0;j<m;j++) {
if((i&(1<<j))==0) {
v+=cnt[b][j];
}else {
if(b!=j)v-=cnt[b][j];
}
}
v+=rec[i-(1<<b)];
for(int j=0;j<m;j++) {
if((i&(1<<j))>0) {
dp[i]=Math.min(dp[i], dp[i-(1<<j)]+v);
}
}
rec[i]=v;
}
return dp[(1<<m)-1];
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
if(st==null || !st.hasMoreElements())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
| np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
import static java.lang.Math.cos;
import static java.lang.Math.min;
public class E_fast {
static int g[][];
static int n, m;
static char[] s;
static int dp[], inf = (int) 2e9;
static int cost[][];
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = in.nextInt();
m = in.nextInt();
s = in.next().toCharArray();
g = new int[m][m];
for (int i = 1; i < n; i++) {
int x = s[i - 1] - 'a', y = s[i] - 'a';
if (x != y) {
g[x][y]++;
g[y][x]++;
}
}
cost = new int[m][1 << m];
for (int i = 0; i < m; i++) {
int w = 0;
for (int j = 0; j < m; j++) w += g[i][j];
pre(i, 0, 0, -w);
}
dp = new int[1 << m];
Arrays.fill(dp, -1);
pw.println(solve(0, 0));
pw.close();
}
static void pre(int x, int pos, int mask, int w) {
if (pos >= m) {
cost[x][mask] = w;
return;
}
pre(x, pos + 1, mask, w);
pre(x, pos + 1, set(mask, pos), w + 2 * g[x][pos]);
}
static int solve(int pos, int mask) {
if (pos >= m) return 0;
if (dp[mask] != -1) return dp[mask];
int min = inf;
for (int i = 0; i < m; i++) {
if (!check(mask, i)) {
int res = cost[i][mask] * pos + solve(pos + 1, set(mask, i));
min = min(min, res);
}
}
return dp[mask] = min;
}
static boolean check(int N, int pos) {
return (N & (1 << pos)) != 0;
}
static int set(int N, int pos) {
return N = N | (1 << pos);
}
static int reset(int N, int pos) {
return N = N & ~(1 << pos);
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
} | np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class E implements Runnable {
public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();}
int n, m;
char[] str;
int[][] occs, cost;
int[] dp;
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
//where's my 420???? :(
long tot = 0;
for(int i = 0; i < 20000; i++) tot += i;
System.err.println(tot);
n = fs.nextInt(); m = fs.nextInt();
byte[] str = fs.next().getBytes();
int[] occs = new int[1<<m];
for(int i = 0; i < n-1; i++) {
int l1 = str[i] - 'a';
int l2 = str[i+1] - 'a';
occs[(1<<l1) | (1<<l2)]++;
occs[(1<<l2) | (1<<l1)]++;
}
//cost[mask][v] = numPairs with v for some all bits on in mask
int all = (1<<m)-1;
cost = new int[m][1<<m];
for(int i = 0; i < m; i++) {
for(int mask = 1; mask < all; mask++) {
if(((1<<i)&mask) > 0) continue;
int lb = mask & (-mask);
int trail = Integer.numberOfTrailingZeros(lb);
int nmask = mask ^ lb;
cost[i][mask] = cost[i][nmask]+occs[1<<i | 1<<trail];
}
}
dp = new int[1<<m];
for(int mask = dp.length-2; mask >= 0; mask--) {
int addOn = 0;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
addOn += cost[nxt][mask];
}
int res = oo;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
int ret = addOn+dp[mask | (1<<nxt)];
res = min(res, ret);
}
dp[mask] = res;
}
System.out.println(dp[0]>>1);
out.close();
}
int oo = (int)1e9;
int min(int a, int b) {
if(a < b) return a;
return b;
}
class FastScanner {
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 FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
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;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.util.*;
import java.io.*;
public class EdA {
static long[] mods = {1000000007, 998244353, 1000000009};
static long mod = mods[0];
public static MyScanner sc;
public static PrintWriter out;
public static void main(String[] omkar) throws Exception{
// TODO Auto-generated method stub
sc = new MyScanner();
out = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
int[][]cnt = new int[m][m];
String s = sc.next();
for(int j =0;j<n-1;j++){
if (s.charAt(j) != s.charAt(j+1)){
cnt[s.charAt(j)-'a'][s.charAt(j+1)-'a']++;
cnt[s.charAt(j+1)-'a'][s.charAt(j)-'a']++;
}
}
int[] st = new int[m+1];
for(int j = 0;j<=m;j++){
st[j] = (1<<j);
}
int[][] arr = new int[m][1<<m];
for(int j = 0;j<m;j++){
for(int k = 1;k<(1<<m);k++){
int z = Integer.lowestOneBit(k);
int count = 0;
while(z!=0 && z%2==0){
z/=2;
count++;
}
arr[j][k] = arr[j][k^(Integer.lowestOneBit(k))] + cnt[j][count];
}
}
int[] dp = new int[1<<m];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for(int j = 1;j<st[m];j++){
for(int k = 0;k<m;k++){
int y = st[k];
if ((y&j) != 0){
int sum = 2*arr[k][j] - arr[k][(1<<m)-1];
// for(int t = 0;t<m;t++){
// if (t!= k){
// if ((st[t]&j) != 0)
// sum+=cnt[t][k];
// else
// sum-=cnt[t][k];
// }
// }
dp[j] = Math.min(dp[j], dp[y^j]+sum*Integer.bitCount(j));
}
}
}
out.println(dp[(1<<m)-1]);
out.close();
}
public static void sort(int[] array){
ArrayList<Integer> copy = new ArrayList<Integer>();
for (int i : array)
copy.add(i);
Collections.sort(copy);
for(int i = 0;i<array.length;i++)
array[i] = copy.get(i);
}
static String[] readArrayString(int n){
String[] array = new String[n];
for(int j =0 ;j<n;j++)
array[j] = sc.next();
return array;
}
static int[] readArrayInt(int n){
int[] array = new int[n];
for(int j = 0;j<n;j++)
array[j] = sc.nextInt();
return array;
}
static int[] readArrayInt1(int n){
int[] array = new int[n+1];
for(int j = 1;j<=n;j++){
array[j] = sc.nextInt();
}
return array;
}
static long[] readArrayLong(int n){
long[] array = new long[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextLong();
return array;
}
static double[] readArrayDouble(int n){
double[] array = new double[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextDouble();
return array;
}
static int minIndex(int[] array){
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(long[] array){
long minValue = Long.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(double[] array){
double minValue = Double.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static long power(long x, long y){
if (y == 0)
return 1;
if (y%2 == 1)
return (x*power(x, y-1))%mod;
return power((x*x)%mod, y/2)%mod;
}
static void verdict(boolean a){
out.println(a ? "YES" : "NO");
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is | np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class E implements Runnable {
public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();}
int n, m;
char[] str;
int[][] occs, cost;
int[] dp;
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
n = fs.nextInt(); m = fs.nextInt();
str = fs.next().toCharArray();
occs = new int[m][m];
for(int i = 0; i < n-1; i++) {
occs[str[i]-'a'][str[i+1]-'a']++;
occs[str[i+1]-'a'][str[i]-'a']++;
}
//cost[mask][v] = numPairs with v for some all bits on in mask
int all = (1<<m)-1;
cost = new int[m][1<<m];
for(int i = 0; i < m; i++) {
for(int mask = 1; mask < all; mask++) {
if(((1<<i)&mask) > 0) continue;
int lb = mask & (-mask);
int trail = Integer.numberOfTrailingZeros(lb);
int nmask = mask ^ lb;
cost[i][mask] = cost[i][nmask]+occs[i][trail];
}
}
dp = new int[1<<m];
Arrays.fill(dp, -1);
System.out.println(solve(0));
out.close();
}
int oo = (int)1e9;
int solve(int mask) {
if(mask == (1<<m)-1) return 0;
if(dp[mask] != -1) return dp[mask];
int res = oo;
int addOn = 0;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
addOn += cost[nxt][mask];
}
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
int ret = addOn+solve(mask | (1<<nxt));
res = Math.min(res, ret);
}
return dp[mask] = res;
}
class FastScanner {
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 FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
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;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class E implements Runnable {
public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();}
int n, m;
char[] str;
int[][] occs, cost;
int[] dp;
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
//where's my 420???? :(
n = fs.nextInt(); m = fs.nextInt();
byte[] str = fs.next().getBytes();
int[] occs = new int[1<<m];
for(int i = 0; i < n-1; i++) {
int l1 = str[i] - 'a';
int l2 = str[i+1] - 'a';
occs[(1<<l1) | (1<<l2)]++;
occs[(1<<l2) | (1<<l1)]++;
}
//cost[mask][v] = numPairs with v for some all bits on in mask
int all = (1<<m)-1;
cost = new int[m][1<<m];
for(int i = 0; i < m; i++) {
for(int mask = 1; mask < all; mask++) {
if(((1<<i)&mask) > 0) continue;
int lb = mask & (-mask);
int trail = Integer.numberOfTrailingZeros(lb);
int nmask = mask ^ lb;
cost[i][mask] = cost[i][nmask]+occs[1<<i | 1<<trail];
}
}
dp = new int[1<<m];
for(int mask = dp.length-2; mask >= 0; mask--) {
int addOn = 0;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
addOn += cost[nxt][mask];
}
int res = oo;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
int ret = addOn+dp[mask | (1<<nxt)];
res = min(res, ret);
}
dp[mask] = res;
}
System.out.println(dp[0]>>1);
out.close();
}
int oo = (int)1e9;
int min(int a, int b) {
if(a < b) return a;
return b;
}
class FastScanner {
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 FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
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;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static int t,m,mod=998244353,maxn=1000000,q,n,k;
static int INF=(int)1e8;
void solve(PrintWriter out, Reader in) throws IOException{
n = in.nextInt();
m = in.nextInt();
String str = in.next();
int[][] pre = new int[1<<m][m];
int child=0,head,child2=0;
for(int i=0;i<n;i++){
if(i!=0) child = 1<<(str.charAt(i-1)-'a');
if(i!=n-1) child2 = 1<<(str.charAt(i+1)-'a');
head = str.charAt(i)-'a';
if(i!=0) pre[child][head]++;
if(i!=n-1) pre[child2][head]++;
}
//pre[child][head] - number of elemnts that exists in child and are adjacent to head in the string.
int rmv=0;
for(int i=0;i<m;i++){
head = i;
for(int j=1;j<1<<m;j++){
if(pre[j][i]!=0) continue;
rmv = j-(j&-j);
pre[j][head] = pre[rmv][head]+pre[j^rmv][head];
}
}
int[] dp = new int[1<<m];
for(int i=1;i<1<<m;i++) dp[i] = INF;
// dp[mask] - the minimum cost using a permutation of the set bits in the mask.
int bit=0,full=(1<<m)-1,cnt=0;
for(int j=1;j<1<<m;j++){
for(int i=0;i<m;i++){
if(((1<<i)&j)!=0){
bit = 1<<i;
cnt = cnt(j);
dp[j] = Math.min(dp[j],dp[j^bit]+pre[j^bit][i]*cnt-pre[j^full][i]*cnt);
}
}
}
out.println(dp[full]);
}
static int cnt(int x){
int res=0;
while(x>0){
res+=x&1;
x>>=1;
}
return res;
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
Reader in = new Reader();
Main solver = new Main();
solver.solve(out, in);
out.flush();
out.close();
}
} | np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class E implements Runnable {
public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();}
int n, m;
char[] str;
int[][] occs, cost;
int[] dp;
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
//where's my 420???? :(
long tot = 0;
for(int i = 0; i < 20000; i++) tot += i;
n = fs.nextInt(); m = fs.nextInt();
byte[] str = fs.next().getBytes();
int[] occs = new int[1<<m];
for(int i = 0; i < n-1; i++) {
int l1 = str[i] - 'a';
int l2 = str[i+1] - 'a';
occs[(1<<l1) | (1<<l2)]++;
occs[(1<<l2) | (1<<l1)]++;
}
//cost[mask][v] = numPairs with v for some all bits on in mask
int all = (1<<m)-1;
cost = new int[m][1<<m];
for(int i = 0; i < m; i++) {
for(int mask = 1; mask < all; mask++) {
if(((1<<i)&mask) > 0) continue;
int lb = mask & (-mask);
int trail = Integer.numberOfTrailingZeros(lb);
int nmask = mask ^ lb;
cost[i][mask] = cost[i][nmask]+occs[1<<i | 1<<trail];
}
}
dp = new int[1<<m];
for(int mask = dp.length-2; mask >= 0; mask--) {
int addOn = 0;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
addOn += cost[nxt][mask];
}
int res = oo;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
int ret = addOn+dp[mask | (1<<nxt)];
res = min(res, ret);
}
dp[mask] = res;
}
System.out.println(dp[0]>>1);
out.close();
}
int oo = (int)1e9;
int min(int a, int b) {
if(a < b) return a;
return b;
}
class FastScanner {
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 FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
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;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class KeyboardPurchase {
static final int INF = 1000000000;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out, false);
int N = in.nextInt(), M = in.nextInt();
String str = in.next();
int[][] count = new int[M][M];
for (int i = 1; i < N; i++) {
char c1 = str.charAt(i - 1), c2 = str.charAt(i);
count[c1 - 'a'][c2 - 'a']++;
count[c2 - 'a'][c1 - 'a']++;
}
int[] dp = new int[(1 << M)];
Arrays.fill(dp, INF);
dp[0] = 0;
for (int mask = 1; mask < (1 << M); mask++) {
int slow = 0;
for (int i = 0; i < M; i++) {
if ((mask & (1 << i)) != 0) {
for (int j = 0; j < M; j++) {
if ((mask & (1 << j)) == 0) {
slow += count[i][j];
}
}
}
}
for (int i = 0; i < M; i++) {
if ((mask & (1 << i)) != 0) {
dp[mask] = Math.min(dp[mask], slow + dp[mask ^ (1 << i)]);
}
}
}
out.println(dp[(1 << M) - 1]);
out.close();
System.exit(0);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
public class thing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
String s = in.next();
int[][] count = new int[m][m];
int[] dp = new int[1 << m];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for(int i = 1; i < n; i++) {
int a = s.charAt(i)-'a';
int b = s.charAt(i-1)-'a';
count[a][b]++;
count[b][a]++;
}
for(int i = 1; i < (1 << m); i++) {
int pos = set_bits(i);
for(int j = 0; (i >> j) != 0; j++) {
if(((i >> j) & 1) == 0) continue;
int sum = 0;
for(int mask = i, y = 0; y < m; mask >>= 1, y++) {
if(y == j) continue;
if((mask & 1) == 1) sum += count[j][y];
else sum -= count[j][y];
}
int calc = dp[i-(1<<j)] + pos*sum;
dp[i] = Math.min(dp[i], calc);
}
}
System.out.println(dp[(1 << m)-1]);
}
public static int set_bits(int n) {
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
}
} | np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.io.*;
import java.util.*;
public class cfe {
static DataReader input;
static int LARGE_INT = 1000000007;
//static int MAXN = 300000;
//static int[] len = new int[300000];
//static int[] price = new int[300000];
static final int[] BM = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536,
1<<17, 1<<18, 1<<19, 1<<20};
public static void main(String[] args) throws IOException {
input = new DataReader();
PrintWriter out = new PrintWriter(System.out);
int N = nextInt(), M = nextInt(), P = 1<<M;
String x = nextStr();
int c1 = x.charAt(0) - 'a';
int[][] pair_count = new int[M][M];
for (int i=1; i<N; i++) {
int c2 = x.charAt(i) - 'a';
if (c1 < c2)
pair_count[c1][c2]++;
else if (c1 > c2)
pair_count[c2][c1]++;
c1 = c2;
}
int[] group_count = new int[P];
for (int mask = 1; mask <P; mask++) {
int j;
for (j=0; j<M; j++) {
if ((mask & BM[j]) > 0) break;
}
int nmask = mask ^ BM[j];
int val = group_count[nmask];
for (int i=0; i<j; i++) {
if ((mask & BM[i]) > 0) val -= pair_count[i][j];
else val += pair_count[i][j];
}
for (int i=j+1; i<M; i++) {
if ((mask & BM[i]) > 0) val -= pair_count[j][i];
else val += pair_count[j][i];
}
group_count[mask] = val;
}
// dp[k][mask] = Accumulated cost of first K positions filled, mask position 1 letters are used
// dp[0][0] = 0;
int[][] dp = new int[M+1][P]; //
for (int mask=1; mask<P; mask++) { // each bit mask
dp[0][mask] = 0;
int k = Integer.bitCount(mask); // computing first k position filled.
int val = LARGE_INT;
for (int j=0; j<M; j++) {
if ((mask & BM[j]) > 0) {
int nmask = mask ^ BM[j];
val = Math.min(val, dp[k-1][nmask] + group_count[nmask]);
}
}
dp[k][mask] = val;
}
//out.println(Arrays.deepToString(dp));
out.println(dp[M][P-1]);
out.flush();
out.close();
}
static int nextInt() throws IOException {
return Integer.parseInt(input.next());
}
static String nextStr() throws IOException {
return input.next();
}
static class DataReader {
BufferedReader br;
StringTokenizer st;
public DataReader() throws IOException { // reading from standard in
br = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext() throws IOException {
while (st == null || !st.hasMoreElements()) {
String line = br.readLine();
if (line == null) { // end of file
return false;
}
st = new StringTokenizer(line);
}
return true;
}
String next() throws IOException {
if (hasNext())
return st.nextToken();
else
return null;
}
}
} | np | 1238_E. Keyboard Purchase | 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 n = scanner.nextInt();
int m = scanner.nextInt();
char[] str = scanner.next().toCharArray();
int maxMask = 1 << m;
long[] dp = new long[maxMask];
int[][] dists = new int[m][m];
for(int i = 1; i < n; i++) {
int c1 = str[i] - 'a';
int c2 = str[i-1] - 'a';
dists[c1][c2]++;
dists[c2][c1]++;
}
int[] pre = new int[maxMask];
for(int mask = 0; mask < maxMask; mask++) {
for(int i = 0; i < m; i++) {
if (((1 << i) & mask) == 0) continue;
for(int j = 0; j < m; j++) {
if (((1 << j) & mask) > 0) continue;
pre[mask] += dists[i][j];
}
}
}
Arrays.fill(dp, Long.MAX_VALUE/4);
dp[0] = 0;
for(int mask = 0; mask < maxMask; mask++) {
if (dp[mask] == Long.MAX_VALUE/4) continue;
for(int i = 0; i < m; i++) {
if (((1 << i) & mask) > 0) continue;
int nmask = mask | (1 << i);
dp[nmask] = Math.min(dp[nmask], dp[mask] + pre[nmask]);
}
}
out.println(dp[maxMask - 1]);
out.flush();
}
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 | 1238_E. Keyboard Purchase | CODEFORCES |
import java.util.*;
import java.io.*;
public class E
{
public static void main(String[] args) throws IOException
{new E();}
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n, m, oo = 1 << 28;
int[] dp, cost;
int[][] to;
char[] w;
E() throws IOException
{
n = in.nextInt();
m = in.nextInt();
w = in.next().toCharArray();
to = new int[m+1][m+1];
for (int i = 0; i < n-1; i++)
if (w[i] != w[i+1])
{
to[w[i]-'a'][w[i+1]-'a']++;
to[w[i+1]-'a'][w[i]-'a']++;
}
cost = new int[1 << m];
for (int i = 0; i < (1 << m); i++)
for (int j = 0; j < m; j++)
{
if (((1 << j) & i) > 0)
continue;
for (int k = 0; k < m; k++)
{
if (((1 << k) & i) == 0)
continue;
cost[i] += to[j][k];
}
}
dp = new int[1 << m];
Arrays.fill(dp, oo);
dp[0] = 0;
for (int i = 1; i < (1 << m); i++)
{
for (int j = 0; j < m; j++)
if (((i >> j) & 1) > 0)
dp[i] = Math.min(dp[i], dp[i ^ (1 << j)]);
dp[i] += cost[i];
}
out.println(dp[(1 << m)-1]);
out.close();
}
void sort(int[] x)
{
int sz = x.length;
Random r = new Random();
for (int i = 0; i < sz; i++)
{
int j = r.nextInt(sz);
x[i] = x[j]-(x[i]-(x[j] = x[i]));
}
Arrays.sort(x);
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = new StringTokenizer("");
}
public String next() throws IOException {
if(st.hasMoreTokens())
return st.nextToken();
else
st = new StringTokenizer(br.readLine());
return next();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] intarr(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
} | np | 1238_E. Keyboard Purchase | CODEFORCES |
// practice with rainboy
import java.io.*;
import java.util.*;
public class CF1238E extends PrintWriter {
CF1238E() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1238E o = new CF1238E(); o.main(); o.flush();
}
static final int INF = 0x3f3f3f3f;
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
byte[] cc = sc.next().getBytes();
int[] kk = new int[1 << m];
for (int i = 1; i < n; i++) {
int a = cc[i - 1] - 'a';
int b = cc[i] - 'a';
kk[1 << a | 1 << b]++;
}
for (int h = 0; h < m; h++)
for (int b = 0; b < 1 << m; b++)
if ((b & 1 << h) == 0)
kk[b | 1 << h] += kk[b];
int[] dp = new int[1 << m];
int m_ = (1 << m) - 1;
for (int b = 1; b < 1 << m; b++) {
int k = n - 1 - kk[b] - kk[m_ ^ b];
int x = INF;
for (int h = 0; h < m; h++)
if ((b & 1 << h) != 0) {
int b_ = b ^ 1 << h;
x = Math.min(x, dp[b_]);
}
dp[b] = x == INF ? INF : x + k;
}
println(dp[m_]);
}
}
| np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
public class E {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner(System.in);
FastPrinter out = new FastPrinter(System.out);
E runner = new E();
runner.run(sc, out);
out.close();
}
int N, L;
long[][] mat;
long[] dp;
public void run(FastScanner sc, FastPrinter out) throws Exception {
L = sc.nextInt();
N = sc.nextInt();
mat = new long[N][N];
char[] arr = sc.next().toCharArray();
for (int i = 0; i < L - 1; i++) {
int cur = arr[i] - 'a';
int next = arr[i + 1] - 'a';
if (cur != next) {
mat[cur][next]++;
mat[next][cur]++;
}
}
dp = new long[1 << N];
Arrays.fill(dp, -1);
dp[(1 << N) - 1] = 0;
long ans = solve(0);
out.println(ans);
}
private long solve(int mask) {
if (dp[mask] == -1) {
long value = 0;
for (int i = 0; i < N; i++) {
if ((mask & (1 << i)) == 0) {
for (int j = 0; j < N; j++) {
if ((mask & (1 << j)) != 0) {
value += mat[i][j];
}
}
}
}
long ans = Long.MAX_VALUE;
for (int i = 0; i < N; i++) {
if ((mask & (1 << i)) == 0) {
long temp = solve(mask | 1 << i);
if (temp < ans) {
ans = temp;
}
}
}
ans += value;
dp[mask] = ans;
}
return dp[mask];
}
public void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int r = (int) (Math.random() * arr.length);
if (i != r) {
arr[i] ^= arr[r];
arr[r] ^= arr[i];
arr[i] ^= arr[r];
}
}
}
static class FastScanner {
final private int BUFFER_SIZE = 1 << 10;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastScanner() {
this(System.in);
}
public FastScanner(InputStream stream) {
din = new DataInputStream(stream);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastScanner(String fileName) throws IOException {
Path p = Paths.get(fileName);
buffer = Files.readAllBytes(p);
bytesRead = buffer.length;
}
int[] nextIntArray(int N) throws IOException {
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = nextInt();
}
return arr;
}
String nextLine() throws IOException {
int c = read();
while (c != -1 && isEndline(c))
c = read();
if (c == -1) {
return null;
}
StringBuilder res = new StringBuilder();
do {
if (c >= 0) {
res.appendCodePoint(c);
}
c = read();
} while (!isEndline(c));
return res.toString();
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
String next() throws Exception {
int c = readOutSpaces();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
if (din == null) {
bufferPointer = 0;
bytesRead = -1;
} else {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
}
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
private int readOutSpaces() throws IOException {
while (true) {
if (bufferPointer == bytesRead) fillBuffer();
int c = buffer[bufferPointer++];
if (!isSpaceChar(c)) {
return c;
}
}
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
public int[][] readGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception {
int[][] adj = new int[N][];
int[] numNodes = new int[N];
int[][] input = new int[M][2];
for (int i = 0; i < M; i++) {
int a = nextInt();
int b = nextInt();
if (zeroIndexed) {
a--;
b--;
}
input[i][0] = a;
input[i][1] = b;
numNodes[a]++;
if (bidirectional) numNodes[b]++;
}
for (int i = 0; i < N; i++) {
adj[i] = new int[numNodes[i]];
numNodes[i] = 0;
}
for (int i = 0; i < M; i++) {
int a = input[i][0];
int b = input[i][1];
adj[a][numNodes[a]++] = b;
if (bidirectional) adj[b][numNodes[b]++] = a;
}
return adj;
}
public int[][][] readWeightedGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception {
int[][][] adj = new int[N][][];
int[] numNodes = new int[N];
int[][] input = new int[M][3];
for (int i = 0; i < M; i++) {
int a = nextInt();
int b = nextInt();
if (zeroIndexed) {
a--;
b--;
}
int d = nextInt();
input[i][0] = a;
input[i][1] = b;
input[i][2] = d;
numNodes[a]++;
if (bidirectional) numNodes[b]++;
}
for (int i = 0; i < N; i++) {
adj[i] = new int[numNodes[i]][2];
numNodes[i] = 0;
}
for (int i = 0; i < M; i++) {
int a = input[i][0];
int b = input[i][1];
int d = input[i][2];
adj[a][numNodes[a]][0] = b;
adj[a][numNodes[a]][1] = d;
numNodes[a]++;
if (bidirectional) {
adj[b][numNodes[b]][0] = a;
adj[b][numNodes[b]][1] = d;
numNodes[b]++;
}
}
return adj;
}
}
static class FastPrinter {
static final char ENDL = '\n';
StringBuilder buf;
PrintWriter pw;
public FastPrinter(OutputStream stream) {
buf = new StringBuilder();
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public FastPrinter(String fileName) throws Exception {
buf = new StringBuilder();
pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
}
public FastPrinter(StringBuilder buf) {
this.buf = buf;
}
public void print(int a) {
buf.append(a);
}
public void print(long a) {
buf.append(a);
}
public void print(char a) {
buf.append(a);
}
public void print(char[] a) {
buf.append(a);
}
public void print(double a) {
buf.append(a);
}
public void print(String a) {
buf.append(a);
}
public void print(Object a) {
buf.append(a.toString());
}
public void println() {
buf.append(ENDL);
}
public void println(int a) {
buf.append(a);
buf.append(ENDL);
}
public void println(long a) {
buf.append(a);
buf.append(ENDL);
}
public void println(char a) {
buf.append(a);
buf.append(ENDL);
}
public void println(char[] a) {
buf.append(a);
buf.append(ENDL);
}
public void println(double a) {
buf.append(a);
buf.append(ENDL);
}
public void println(String a) {
buf.append(a);
buf.append(ENDL);
}
public void println(Object a) {
buf.append(a.toString());
buf.append(ENDL);
}
public void printf(String format, Object... args) {
buf.append(String.format(format, args));
}
public void close() {
pw.print(buf);
pw.close();
}
public void flush() {
pw.print(buf);
pw.flush();
buf.setLength(0);
}
}
} | np | 1238_E. Keyboard Purchase | 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(){
out.println(work());
out.flush();
}
long mod=1000000007;
long gcd(long a,long b) {
return b==0?a:gcd(b,a%b);
}
long work() {
int n=in.nextInt();
int m=in.nextInt();
String str=in.next();
long[] dp=new long[1<<m];
long[][] cnt=new long[m][m];
for(int i=1;i<n;i++) {
int n1=str.charAt(i-1)-'a';
int n2=str.charAt(i)-'a';
cnt[n1][n2]++;
cnt[n2][n1]++;
}
for(int i=1;i<1<<m;i++) {
dp[i]=9999999999L;
long v=0;
for(int j=0;j<m;j++) {
if((i&(1<<j))>0) {//第j个字母
for(int k=0;k<m;k++) {
if((i&(1<<k))==0) {
v+=cnt[j][k];
}
}
}
}
for(int j=0;j<m;j++) {
if((i&(1<<j))>0) {
dp[i]=Math.min(dp[i], dp[i-(1<<j)]+v);
}
}
}
return dp[(1<<m)-1];
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
if(st==null || !st.hasMoreElements())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
} | np | 1238_E. Keyboard Purchase | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(),m=sc.nextInt();int g[]=new int[1<<m];
StringBuffer s=new StringBuffer(sc.next());
s=s.insert(0, 'A');
int D=(1<<m)-1;
for(int i=1;i<n;i++)
{
int x=s.charAt(i)-'a',y=s.charAt(i+1)-'a';
if(x!=y)
g[1<<x|1<<y]++;
}
for(int j=0;j<m;j++)
for(int i=0;i<=D;i++)
if((i>>j&1)!=0)
g[i]+=g[i^1<<j];
int f[]=new int[1<<m];
Arrays.fill(f, Integer.MAX_VALUE/2);
f[0]=0;
for(int i=0;i<=D;i++)
for(int j=0;j<m;j++)
if((i>>j&1)==0)
f[i|1<<j]=Math.min(f[i|1<<j], f[i]+g[D]-g[i]-g[D^i]);
System.out.println(f[D]);
}
}
| np | 1238_E. Keyboard Purchase | CODEFORCES |