src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringlengths 6
50
| from
stringclasses 1
value |
---|---|---|---|
import java.util.InputMismatchException;
import java.io.*;
import java.util.Vector;
import java.util.Collections;
import java.util.Arrays;
/**
* Generated by Contest helper plug-in
* Actual solution is at the bottom
*/
public class Main {
public static void main(String[] args) {
InputReader in = new StreamInputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in, out);
}
public static void run(InputReader in, PrintWriter out) {
Solver solver = new Sellerman();
solver.solve(1, in, out);
Exit.exit(in, out);
}
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(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++];
}
@Override
public void close() {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
abstract class InputReader {
private boolean finished = false;
public abstract int read();
public int nextInt() {
return Integer.parseInt(nextToken());
}
public String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public abstract void close();
}
interface Solver {
public void solve(int testNumber, InputReader in, PrintWriter out);
}
class Exit {
private Exit() {
}
public static void exit(InputReader in, PrintWriter out) {
in.setFinished(true);
in.close();
out.close();
}
}
class Sellerman implements Solver {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int x0 = in.nextInt();
int y0 = in.nextInt();
int n = in.nextInt() + 1;
int[] x = new int[n];
int[] y = new int[n];
x[n - 1] = x0;
y[n - 1] = y0;
for (int i = 0; i < n - 1; ++i) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int [][] g = new int[n][n];
for(int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
g[i][j] = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
}
-- n;
int[] dm = new int[1 << n];
int[] prev = new int[1 << n];
byte [] bit = new byte[1 << n];
byte [] item0 = new byte[1 << n];
byte [] item1 = new byte[1 << n];
for (int i = 0; i < n; ++i) {
bit[1 << i] = (byte) i;
}
Arrays.fill(dm, -1);
dm[0] = 0;
int tt[][] = new int[n][n];
for (int i = 0; i < n; ++i)
for (int j =0 ; j < n; ++j) {
tt[i][j] = Math.min(g[n][i] + g[i][j] + g[j][n],
g[n][j] + g[i][j] + g[i][n]);
}
for (int i = 0; i < (1 << n); ++i) {
if (dm[i] == -1)continue;
int t = (i ^ ((1 << n) - 1));
int left = bit[t - (t & (t - 1))];
for (int j = left; j < n; ++j) {
if ((i & (1 << j)) > 0) continue;
int nm = i | (1 << left) | (1 << j);
if (dm[nm] == -1 || dm[nm] > dm[i] + tt[left][j]) {
dm[nm] = dm[i] + tt[left][j];
prev[nm] = i;
item0[nm] = (byte)left;
item1[nm] = (byte)j;
}
}
}
out.println(dm[(1 << n) - 1]);
Vector<Vector<Integer>> path = new Vector<Vector<Integer>> () ;
int cmask = (1 << n) - 1;
while (cmask > 0) {
int p = prev[cmask];
Vector<Integer> tmp = new Vector<Integer> () ;
tmp.add(0);
tmp.add(item0[cmask] + 1);
tmp.add(item1[cmask] + 1);
cmask = prev[cmask];
path.add(tmp);
}
Collections.reverse(path);
int len = 0;
for (Vector<Integer> vec : path)
len += vec.size();
int ans[] = new int[len];
boolean[] valid = new boolean[len];
Arrays.fill(valid, true);
len = 0;
for (Vector<Integer> vec : path) {
for (int ttt : vec) {
ans[len ++] = ttt;
}
}
for (int i = 0; i < len - 1; ++i) {
if (ans[i] == ans[i + 1])
valid[i] = false;
}
for (int i = 0; i < len; ++i) {
if (valid[i]) {
out.print(ans[i] + " ");
}
}
out.print("0");
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigInteger;
import static java.lang.Math.*;
// Solution is at the bottom of code
public class ProblemC_008 implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new ProblemC_008(), "", 128 * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
solve();
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken(delim);
}
String readLine() throws IOException{
return in.readLine();
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() throws IOException{
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
}
char[] readCharArray() throws IOException{
return readLine().toCharArray();
}
/////////////////////////////////////////////////////////////////
int readInt() throws IOException{
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException{
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
///////////////////////////////////////////////////////////////////
long readLong() throws IOException{
return Long.parseLong(readString());
}
long[] readLongArray(int size) throws IOException{
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) throws IOException{
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
/////////////////////////////////////////////////////////////////////
Point readPoint() throws IOException{
return new Point(readInt(), readInt());
}
Point[] readPointArray(int size) throws IOException{
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
class OutputWriter extends PrintWriter{
final int DEFAULT_PRECISION = 12;
int precision;
String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
boolean check(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
void solve() throws IOException{
Point bag = readPoint();
int n = readInt();
Point[] points = new Point[n];
for (int i = 0; i < n; ++i){
points[i] = readPoint();
}
int[] dist = new int[n];
for (int i = 0; i < n; ++i){
int dx = points[i].x - bag.x;
int dy = points[i].y - bag.y;
dist[i] = dx * dx + dy * dy;
}
int[][] d = new int[n][n];
for (int i = 0; i < n; ++i){
for (int j = 0; j < n; ++j){
int dx = points[i].x - points[j].x;
int dy = points[i].y - points[j].y;
d[i][j] = dx * dx + dy * dy;
d[i][j] += dist[i] + dist[j];
}
}
int[] singleMasks = new int[n];
for (int i = 0; i < n; ++i){
singleMasks[i] = (1 << i);
}
int[][] doubleMasks = new int[n][n];
for (int i = 0; i < n; ++i){
for (int j = 0; j < n; ++j){
doubleMasks[i][j] = (singleMasks[i] | singleMasks[j]);
}
}
int lim = (1 << n);
int[] dp = new int[lim];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
int[] p = new int[lim];
Arrays.fill(p, -1);
for (int mask = 0; mask < lim; ++mask){
if (dp[mask] == Integer.MAX_VALUE){
continue;
}
int minBit = -1;
for (int bit = 0; bit < n; ++bit){
if (checkBit(mask, bit)) continue;
if (minBit == -1 || (dist[minBit] > dist[bit])){
minBit = bit;
}
}
if (minBit == -1){
continue;
}
for (int bit = 0; bit < n; ++bit){
if (checkBit(mask, bit)) continue;
int newMask = (mask | (1 << minBit) | (1 << bit));
if (dp[newMask] > dp[mask] + d[minBit][bit]){
dp[newMask] = dp[mask] + d[minBit][bit];
p[newMask] = minBit * n + bit;
}
}
}
out.println(dp[lim-1]);
int curMask = lim - 1;
while (p[curMask] != -1){
out.print("0 ");
int first = p[curMask] / n;
int second = p[curMask] % n;
out.print((first + 1) + " ");
curMask ^= (1 << first);
if (first != second){
out.print((second + 1) + " ");
curMask ^= (1 << second);
}
}
out.println("0");
}
private boolean checkBit(int mask, int bitNumber) {
return (mask & (1 << bitNumber)) != 0;
}
boolean checkMask(int mask, int innerMask){
return (mask & innerMask) == innerMask;
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Task2 {
public static void main(String[] args) throws IOException {
new Task2().solve();
}
//ArrayList<Integer>[] g;
int mod = 1000000007;
PrintWriter out;
int n;
int m;
//int[][] a = new int[1000][1000];
//int cnt = 0;
long base = (1L << 63);
long P = 31;
int[][] a;
void solve() throws IOException {
//Reader in = new Reader("in.txt");
//out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
Reader in = new Reader();
PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
//BufferedReader br = new BufferedReader( new FileReader("in.txt") );
//BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
int sx = in.nextInt();
int sy = in.nextInt();
int n = in.nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int[] dp = new int[1 << n];
int[] p = new int[1 << n];
int inf = 1000000000;
Arrays.fill(dp, inf);
dp[0] = 0;
for (int mask = 0; mask < (1 << n) - 1; mask ++) {
int k = -1;
if (dp[mask] == inf)
continue;
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) == 0) {
k = i;
break;
}
}
for (int i = k; i < n; i++) {
if ((mask & (1 << i)) == 0) {
int val = dp[mask] + dist(sx, sy, x[i], y[i]) + dist(sx, sy, x[k], y[k]) + dist(x[i], y[i], x[k], y[k]);
if (val < dp[mask | (1 << i) | (1 << k)]) {
dp[mask | (1 << i) | (1 << k)] = val;
p[mask | (1 << i) | (1 << k)] = mask;
}
}
}
}
out.println(dp[(1 << n) - 1]);
int cur = (1 << n) - 1;
out.print(0+" ");
while (cur != 0) {
int prev = p[cur];
for (int i = 0; i < n; i++) {
if (((cur & (1 << i)) ^ (prev & (1 << i))) != 0)
out.print(i+1+" ");
}
out.print(0+" ");
cur = prev;
}
out.flush();
out.close();
}
int dist(int x1, int y1, int x2, int y2) {
return (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);
}
long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a%b);
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Pair implements Comparable<Pair>{
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair p) {
if (b < p.b)
return 1;
if (b > p.b)
return -1;
return 0;
}
// @Override
// public boolean equals(Object o) {
// Pair p = (Pair) o;
// return a == p.a && b == p.b;
// }
//
// @Override
// public int hashCode() {
// return Integer.valueOf(a).hashCode() + Integer.valueOf(b).hashCode();
// }
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class LookingOrder {
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
String[] line=in.readLine().split("\\s+");
int xs= Integer.parseInt(line[0]);
int ys= Integer.parseInt(line[1]);
int n=Integer.parseInt(in.readLine());
int []x=new int[n];
int []y=new int[n];
for(int i=0;i<n;++i){
line=in.readLine().split("\\s+");
x[i]= Integer.parseInt(line[0]);
y[i]= Integer.parseInt(line[1]);
}
int maxBitmap=1<<n;
long[] dis=new long[maxBitmap];
int[] last=new int[maxBitmap];
dis[0]=0;
int ci=0;
int[][] dismap=new int[n][n];
for(int i=0;i<n;++i){
for(int j=0;j<=i;++j){
int delx,dely;
if(i==j){
delx=x[i]-xs;
dely=y[i]-ys;
}else{
delx=x[i]-x[j];
dely=y[i]-y[j];
}
dismap[i][j]=delx*delx+dely*dely;
}
}
for(int i=1;i<maxBitmap;++i){
if((i&(1<<ci))==0)
++ci;
int i2=i-(1<<ci);
long min=dis[i2]+2*dismap[ci][ci];
last[i]=ci;
for(int j=0;j<ci;++j){
if((i&(1<<j))!=0){
long m=dis[i2-(1<<j)]+dismap[ci][ci]+dismap[j][j]+dismap[ci][j];
if(m<min){
min=m;
last[i]=j;
}
}
}
dis[i]=min;
}
out.write(""+dis[maxBitmap-1]);
out.newLine();
out.write("0");
int bmap=maxBitmap-1;
ci=n-1;
while(bmap!=0){
while((bmap&(1<<ci))==0&&ci>=0)--ci;
int ci2=last[bmap];
if(ci2!=ci){
out.write(" "+(ci+1)+" "+(ci2+1)+ " 0");
bmap-=(1<<ci)+(1<<ci2);
}else{
out.write(" "+(ci+1)+" 0");
bmap-=1<<ci;
}
}
out.close();
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.util.Scanner;
public class Round8_C {
/**
* @param args
*/
int n ;
int[] X, Y ;
public Round8_C() {
info_in() ;
process() ;
}
void info_in()
{
Scanner input = new Scanner(System.in) ;
int dx = input.nextInt() ;
int dy = input.nextInt() ;
n = input.nextInt() ;
X = new int[n] ;
Y = new int[n] ;
for( int i=0;i<n;i++) {
X[i] = input.nextInt() - dx ;
Y[i] = input.nextInt() - dy ;
}
}
int[] d ;
int[] trace ;
public static int distance( int x1, int y1, int x2, int y2 )
{
return (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) ;
}
void process()
{
int gh = 1<<n ;
d = new int[gh] ;
trace = new int[gh] ;
d[0] = 0 ;
for( int i=1;i<gh;i++) {
d[i] = Integer.MAX_VALUE ;
for( int j=0;j<n;j++)
if ( (i & (1<<j)) > 0 ) {
int val = d[i^(1<<j)] + ( distance( X[j], Y[j], 0, 0 ) << 1 ) ;
if ( val < d[i] ) {
d[i] = val ;
trace[i] = j+1 ;
}
int state = i ^ (1<<j) ;
for( int p=j+1;p<n;p++)
if ( (i & (1<<p)) > 0) {
val = d[state^(1<<p)] + distance( X[j], Y[j], 0, 0 ) + distance( X[j], Y[j], X[p], Y[p] ) + distance( X[p], Y[p], 0, 0 ) ;
if ( val < d[i] ) {
d[i] = val ;
trace[i] = (j+1) * 100 + (p+1) ;
}
}
break ;
}
}
System.out.println( d[gh-1] ) ;
gh-- ;
while ( gh > 0 ) {
int v1 = trace[gh] / 100 - 1 ;
int v2 = trace[gh] % 100 - 1 ;
System.out.print(0 + " ") ;
if ( v1 != -1 ) {
System.out.print((v1+1) + " " ) ;
gh -= 1 << v1 ;
}
System.out.print( (v2+1) + " " ) ;
gh -= 1 << v2 ;
}
System.out.println(0) ;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Round8_C() ;
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class B {
final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
final PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer tokenizer;
final int[][] d;
final int n;
final int[] time;
final Action[] actions;
private static final class Action {
int a;
int b;
public Action(int a) {
this.a = this.b = a;
}
public Action(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public String toString() {
if (a == b)
return " " + (a+1);
return " " + (a+1) + " " + (b+1);
}
}
private static final int dist(int x1, int y1, int x2, int y2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}
private final boolean in(int x, int set) {
return ((1 << x) & set) != 0;
}
private final int off(int x, int set) {
return (set ^ (set & (1 << x)));
}
private final int solve(int set) {
if (time[set] > 0)
return time[set];
int min = Integer.MAX_VALUE;
if (set == 0)
min = 0;
else {
int a;
for (a = 0; a < n; a++)
if (in(a, set))
break;
int subset = off(a, set);
int aux = 2 * d[a][a] + solve(subset);
if (aux < min) {
min = aux;
actions[set] = new Action(a);
}
for (int b = a + 1; b < n; b++)
if (in(b, subset)) {
aux = d[a][a] + d[b][b] + d[a][b] + solve(off(b, subset));
if (aux < min) {
min = aux;
actions[set] = new Action(a, b);
}
}
}
time[set] = min;
return min;
}
private B() throws IOException {
int bx = nextInt();
int by = nextInt();
n = nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextInt();
y[i] = nextInt();
}
reader.close();
d = new int[n][n];
for (int i = 0; i < n; i++) {
d[i][i] = dist(bx, by, x[i], y[i]);// |A|
for (int j = i + 1; j < n; j++)
d[i][j] = dist(x[i], y[i], x[j], y[j]);// |AB|
}
int set = 1 << n;
time = new int[set];
actions = new Action[set];
set--;
printer.println(solve(set));
printer.print("0");
while (set != 0) {
solve(set);
Action action = actions[set];
printer.print(action);
printer.print(" 0");
set = off(action.a, set);
set = off(action.b, set);
}
printer.println();
printer.close();
}
private final int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private final String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static void main(String[] args) throws IOException {
new B();
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.util.*;
public class c8 {
static int n;
static int[] ds;
static int[][] g;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int x = input.nextInt(), y = input.nextInt();
int n = input.nextInt();
int[] xs = new int[n], ys = new int[n];
for(int i = 0; i<n; i++)
{
xs[i] = input.nextInt();
ys[i] = input.nextInt();
}
ds = new int[n];
g = new int[n][n];
for(int i = 0; i<n; i++)
{
ds[i] = (x - xs[i]) * (x - xs[i]) + (y - ys[i]) * (y - ys[i]);
for(int j = 0; j<n; j++)
{
g[i][j] = (xs[i] - xs[j]) * (xs[i] - xs[j]) + (ys[i] - ys[j]) * (ys[i] - ys[j]);
}
}
int[] dp = new int[1<<n];
Arrays.fill(dp, 987654321);
dp[0] = 0;
for(int i = 0; i<(1<<n); i++)
{
if(dp[i] == 987654321) continue;
for(int a = 0; a<n; a++)
{
if((i & (1<<a)) > 0) continue;
dp[i | (1<<a)] = Math.min(dp[i | (1<<a)], dp[i] + 2*ds[a]);
for(int b = a+1; b<n; b++)
{
if((i & (1<<b)) > 0) continue;
dp[i | (1<<a) | (1<<b)] = Math.min(dp[i | (1<<a) | (1<<b)], dp[i] + ds[a] + ds[b] + g[a][b]);
}
break;
}
}
Stack<Integer> stk = new Stack<Integer>();
stk.add(0);
int i = (1<<n) - 1;
//System.out.println(Arrays.toString(dp));
trace:
while(i > 0)
{
//System.out.println(i);
for(int a = 0; a<n; a++)
{
if((i & (1<<a)) == 0) continue;
if( dp[i] == dp[i - (1<<a)] + 2*ds[a])
{
stk.add(a+1);
stk.add(0);
i -= (1<<a);
continue trace;
}
for(int b = a+1; b<n; b++)
{
if((i & (1<<b)) == 0) continue;
if(dp[i] == dp[i - (1<<a) - (1<<b)] + ds[a] + ds[b] + g[a][b])
{
stk.add(a+1);
stk.add(b+1);
stk.add(0);
i -= (1<<a) + (1<<b);
continue trace;
}
}
//break;
}
}
System.out.println(dp[(1<<n) - 1]);
while(!stk.isEmpty()) System.out.print(stk.pop()+" ");
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class LookingForOrder {
static int n;
static int []x,y,memo;
static StringBuilder sb;
static int distance(int i,int j)
{
int dx=x[i]-x[j];
int dy=y[i]-y[j];
return dx*dx+dy*dy;
}
public static int dp(int msk)
{
if(msk==(1<<(n+1))-2)
return 0;
if(memo[msk]!=-1)
return memo[msk];
int ans=10000000;
boolean found=false;
for(int i=1;i<=n && !found;i++)
for(int j=i;j<=n && (msk&1<<i)==0;j++)
if((msk&1<<j)==0)
{
found=true;
int newM=msk|1<<i;
newM|=1<<j;
ans=Math.min(ans, dp(newM)+Math.min(distance(0,i)+distance(i,j)+distance(j,0), distance(0,j)+distance(j,i)+distance(i,0)));
}
return memo[msk]=ans;
}
public static void print(int msk)
{
if(msk==(1<<(n+1))-2)
return ;
for(int i=1;i<=n;i++)
for(int j=i;j<=n && (msk&1<<i)==0;j++)
if((msk&1<<j)==0)
{
int newM=msk|1<<i;
newM|=1<<j;
int d1=distance(0,i)+distance(i,j)+distance(j,0);
int d2=distance(0,j)+distance(j,i)+distance(i,0);
if(dp(msk)== dp(newM)+Math.min(d1,d2))
{
if(i==j)
sb.append("0 "+i+" ");
else if(d1<d2)
sb.append("0 "+i+" "+j+" ");
else
sb.append("0 "+j+" "+i+" ");
print(newM);
return ;
}
}
}
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
int xS=sc.nextInt(),yS=sc.nextInt();
n=sc.nextInt();
x=new int [n+1];
y=new int [n+1];
x[0]=xS;y[0]=yS;
for(int i=1;i<=n;i++)
{
x[i]=sc.nextInt();
y[i]=sc.nextInt();
}
memo=new int [1<<(n+1)];
Arrays.fill(memo,-1);
sb=new StringBuilder();
sb.append(dp(0)+"\n");
print(0);
sb.append("0");
System.out.println(sb);
}
static class Scanner
{
BufferedReader br;
StringTokenizer st;
public Scanner(InputStream s)
{
br=new BufferedReader(new InputStreamReader(s));
}
public String nextLine() throws IOException
{
return br.readLine();
}
public String next() throws IOException
{
while(st==null || !st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
public boolean ready() throws IOException
{
return br.ready();
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Bag implements Runnable {
private void solve() throws IOException {
int xs = nextInt();
int ys = nextInt();
int n = nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; ++i) {
x[i] = nextInt();
y[i] = nextInt();
}
final int[][] pair = new int[n][n];
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]);
final int[] single = new int[n];
for (int i = 0; i < n; ++i) {
single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys));
}
final int[] best = new int[1 << n];
final int[] prev = new int[1 << n];
for (int set = 1; set < (1 << n); ++set) {
int i;
for (i = 0; i < n; ++i)
if ((set & (1 << i)) != 0)
break;
best[set] = best[set ^ (1 << i)] + single[i];
prev[set] = 1 << i;
int nextSet = set ^ (1 << i);
int unoI = 1 << i;
for (int j = i + 1, unoJ = 1 << (i + 1); j < n; ++j, unoJ <<= 1)
if ((set & unoJ) != 0) {
int cur = best[nextSet ^ unoJ] + pair[i][j];
if (cur < best[set]) {
best[set] = cur;
prev[set] = unoI | unoJ;
}
}
}
writer.println(best[(1 << n) - 1]);
int now = (1 << n) - 1;
writer.print("0");
while (now > 0) {
int differents = prev[now];
for(int i = 0; i < n; i++)
if((differents & (1 << i)) != 0)
{
writer.print(" ");
writer.print(i + 1);
now ^= 1 << i;
}
writer.print(" ");
writer.print("0");
}
writer.println();
}
public static void main(String[] args) {
new Bag().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.awt.Point;
import java.util.Arrays;
import java.util.Scanner;
public class B {
static int[][] dist;
static int[] dist1;
static int [] dp;
static int [] path;
static int end,x,y;
static Point[] a;
public static int doit(int mask) {
if(mask==end) return 0;
if(dp[mask]!=-1) return dp[mask];
int min=Integer.MAX_VALUE;
int t;
int i;
for(i=0;i<dist.length;i++)
if(((1<<i)|mask)!=mask) break;
t=2*dist1[i]+doit(mask|(1<<i));
if(t<min) {
min=t;
path[mask]=(1<<i);
}
for(int j=i+1;j<dist.length;j++) {
if(((1<<j)|mask)==mask) continue;
t=dist[i][j]+doit(mask|(1<<i)|(1<<j));
if(t<min) {
min=t;
path[mask]=(1<<i)|(1<<j);
}
}
return dp[mask]=min;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
x=sc.nextInt();y=sc.nextInt();
a=new Point[sc.nextInt()];
for(int i=0;i<a.length;i++) {
a[i]=new Point(sc.nextInt(), sc.nextInt());
}
end=(1<<a.length)-1;
dp=new int[1<<a.length];
Arrays.fill(dp, -1);
dist=new int[a.length][a.length];
dist1=new int[a.length];
for(int i=0;i<a.length;i++) {
dist1[i]=(a[i].x-x)*(a[i].x-x)+(a[i].y-y)*(a[i].y-y);
for(int j=i+1;j<a.length;j++) {
dist[i][j]=dist1[i]+
(a[j].x-a[i].x)*(a[j].x-a[i].x)+(a[j].y-a[i].y)*(a[j].y-a[i].y)+
(a[j].x-x)*(a[j].x-x)+(a[j].y-y)*(a[j].y-y);
//System.out.println(dist[i][j]);
}
}
path=new int[dp.length];
System.out.println(doit(0));
int e=0;
int cur=path[e];
StringBuffer bf=new StringBuffer();
bf.append(0+" ");
int count=0;
for(int i=0;count<a.length;i++) {
//System.out.println(Integer.toBinaryString(cur)+" "+cur);
for(int j=0;j<a.length;j++) {
if(((1<<j)|cur)==cur) {
bf.append((j+1)+" "); count++;
}
}
e|=cur;
cur=path[e];
bf.append(0+" ");
}
System.out.println(bf);
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
BufferedReader kek = new BufferedReader(new InputStreamReader(System.in));
//Scanner skek = new Scanner(System.in);
PrintWriter outkek = new PrintWriter(System.out);
String[] input = kek.readLine().split(" ");
int X0 = Integer.parseInt(input[0]), Y0 = Integer.parseInt(input[1]), N = Integer.parseInt(kek.readLine());
int[] xCoords = new int[N + 1];
int[] yCoords = new int[N + 1];
int[][] distances = new int[N + 1][N + 1];
xCoords[N] = X0;
yCoords[N] = Y0;
for(int i = 0; i < N; i++){
input = kek.readLine().split(" ");
xCoords[i] = Integer.parseInt(input[0]);
yCoords[i] = Integer.parseInt(input[1]);
}
for(int i = 0; i <= N; i++){
for(int j = i + 1; j <= N; j++){
int temp = xCoords[i] - xCoords[j];
int temp2 = yCoords[i] - yCoords[j];
distances[i][j] = (temp * temp) + (temp2 * temp2);
}
}
int[] aa = new int[1 << N];
int[] bb = new int[1 << N];
for(int i = 1; i < 1 << N; i++){
int a = -1;
for(int j = 0; j < N; j++){
if((i & 1 << j) > 0){
a = j;
break;
}
}
int l = i ^ 1 << a;
int dist = distances[a][N] + distances[a][N];
aa[i] = aa[l] + dist;
bb[i] = l;
for(int k = a + 1; k < N; k++){
if((i & 1 << k) > 0) {
l = i ^ 1 << a ^ 1 << k;
dist = distances[a][N] + distances[k][N] + distances[a][k];
if(aa[l] + dist < aa[i]){
aa[i] = aa[l] + dist;
bb[i] = l;
}
}
}
}
int fin = (1 << N) - 1;
outkek.println(aa[fin]);
outkek.print('0');
while (fin != 0){
int temp1 = bb[fin];
int temp2 = fin ^ temp1;
for(int i = 0; i < N; i++){
if((temp2 & 1 << i) > 0){
outkek.print(" " + (i + 1));
}
}
outkek.print(" 0");
fin = temp1;
}
kek.close();
outkek.close();
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class CF008C {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int x = s.nextInt();
int y = s.nextInt();
int n = s.nextInt();
int[] xx = new int[n+1];
int[] yy = new int[n+1];
for(int i = 0;i<n;i++){
xx[i] = s.nextInt();
yy[i] = s.nextInt();
}
// int[][] dp = new int[n][n];
// for(int i = 0;i<n;i++){
// Arrays.fill(dp[i],-1);
// }
xx[n] = x;
yy[n] = y;
int[][] dp = new int[n + 1][n + 1];
for (int i = 0; i <= n; i++)
for (int j = i + 1; j <= n; j++) {
int dx = xx[i] - xx[j];
int dy = yy[i] - yy[j];
dp[i][j] = dx * dx + dy * dy;
}
int[] aa = new int[1 << n];
int[] bb = new int[1 << n];
for (int k = 1; k < 1 << n; k++) {
int a = -1;
for (int b = 0; b < n; b++)
if ((k & 1 << b) > 0) {
a = b;
break;
}
int l = k ^ 1 << a;
int d = dp[a][n] + dp[a][n];
aa[k] = aa[l] + d;
bb[k] = l;
for (int b = a + 1; b < n; b++)
if ((k & 1 << b) > 0) {
l = k ^ 1 << a ^ 1 << b;
d = dp[a][n] + dp[b][n] + dp[a][b];
if (aa[l] + d < aa[k]) {
aa[k] = aa[l] + d;
bb[k] = l;
}
}
}
int k = (1 << n) - 1;
System.out.println(aa[k]);
StringBuilder sb = new StringBuilder();
sb.append(0);
while (k != 0) {
int l = bb[k];
int m = k ^ l;
for (int b = 0; b < n; b++)
if ((m & 1 << b) > 0)
sb.append(' ').append(b + 1);
sb.append(' ').append(0);
k = l;
}
System.out.println(sb);
}
// int[] distFromOrigin = new int[n];
//// HashMap<Integer,Boolean> map = new HashMap<>();
// for(int i=0;i<n;i++){
// distFromOrigin[i] = (int) (Math.pow((xCoord[i] - x),2) + Math.pow(yCoord[i] - y,2));
//// map.put(i,true);
// }
// System.out.println(0);
// long sum = 0;
// String str = "0 ";
//
// while(!map.isEmpty()){
// int first = 0;
// int second = Integer.MIN_VALUE;
// if(map.size() == 1){
// first = new ArrayList<Integer>(map.keySet()).get(0) + 1;
// int min = distFromOrigin[first - 1] + distFromOrigin[first - 1];
// sum += min;
// map.remove(first - 1);
// }else {
// int min = Integer.MAX_VALUE;
//
// for (int i = 0; i < n; i++) {
// for (int j = 0; j <= i; j++) {
// if (map.containsKey(i) && map.containsKey(j) && distFromOrigin[i] + distFromOrigin[j] + dp[i][j] < min) {
// min = distFromOrigin[i] + distFromOrigin[j] + dp[i][j];
// first = i + 1;
// if(i == j){
// second = Integer.MIN_VALUE;
// }else {
// second = j + 1;
// }
// }
// }
// }
// sum += min;
// map.remove(first - 1);
// if(second != Integer.MIN_VALUE){
// map.remove(second - 1);
// }
// }
// if(second == Integer.MIN_VALUE){
// str = str + first + " ";
// }else{
// if(map.size() == 0) {
// str = str + first + " " + second + " ";
// }else{
// str = str + first + " " + second + " 0 ";
// }
// }
//// System.out.print(first + " " + second + " ");
// }
// System.out.println(sum);
// System.out.println(str + "0");
// int[] ans = new int[(int)Math.pow(2,n)];
// Arrays.fill(ans,Integer.MAX_VALUE);
// for(int i = 0;i<Math.pow(2,n);i++){
// for(int j = 0;j<n;j++){
// //I can't figure out how to do that.
// }
// }
// System.out.print(sum);
// System.out.print(0);
private static int calculateDistanceBetweenIandJ(int[] xCoord, int[] yCoord, int i, int j) {
int length = (int) (Math.pow((xCoord[i] - xCoord[j]),2) + Math.pow(yCoord[i] - yCoord[j], 2));
return length;
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
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;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int INF = 1000 * 1000 * 1000;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int x0 = in.readInt();
int y0 = in.readInt();
int n = in.readInt();
int[] xs = new int[n + 1], ys = new int[n + 1];
xs[0] = x0;
ys[0] = y0;
for (int i = 1; i <= n; i++) {
xs[i] = in.readInt();
ys[i] = in.readInt();
}
int[] one = new int[n];
for (int i = 0; i < n; i++) one[i] = dist(0, i + 1, xs, ys) * 2;
int[][] two = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
two[i][j] = dist(0, i + 1, xs, ys) + dist(0, j + 1, xs, ys) + dist(i + 1, j + 1, xs, ys);
}
}
int[] dp = new int[(1 << n)];
Arrays.fill(dp, INF);
dp[0] = 0;
int[] prev = new int[(1 << n)];
for (int mask = 0; mask < (1 << n); mask++) {
for (int i = 0; i < n; i++) {
if (((mask >> i) & 1) != 0) continue;
;
int nmask = mask | (1 << i);
int cost = one[i] + dp[mask];
if (cost < dp[nmask]) {
dp[nmask] = cost;
prev[nmask] = i;
}
for (int j = i + 1; j < n; j++) {
if (((mask >> j) & 1) != 0) continue;
int nnmask = nmask | (1 << j);
cost = two[i][j] + dp[mask];
if (cost < dp[nnmask]) {
dp[nnmask] = cost;
prev[nnmask] = n + i * n + j;
}
}
break;
}
}
int mask = (1 << n) - 1;
out.printLine(dp[mask]);
ArrayList<Integer> res = new ArrayList<>();
res.add(0);
while (mask > 0) {
if (prev[mask] < n) {
res.add(prev[mask] + 1);
mask &= ~(1 << prev[mask]);
} else {
int ii = (prev[mask] - n) / n;
int jj = (prev[mask] - n) % n;
int i = Math.max(ii, jj);
int j = Math.min(ii, jj);
res.add(i + 1);
res.add(j + 1);
mask &= ~(1 << i);
mask &= ~(1 << j);
}
res.add(0);
}
Collections.reverse(res);
for (int val : res) out.print(val + " ");
out.printLine();
}
int dist(int i, int j, int[] xs, int[] ys) {
return (xs[i] - xs[j]) * (xs[i] - xs[j]) + (ys[i] - ys[j]) * (ys[i] - ys[j]);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine() {
writer.println();
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.*;
import java.util.*;
import com.sun.swing.internal.plaf.basic.resources.basic;
public class Main {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
private void solution() throws IOException {
int sx = in.nextInt();
int sy = in.nextInt();
int n = in.nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; ++i) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int[] dp = new int[1 << n];
int[] prev = new int[1 << n];
Arrays.fill(dp, Integer.MAX_VALUE / 2);
dp[0] = 0;
prev[0] = -1;
for (int mask = 0; mask < (1 << n); ++mask) {
if (dp[mask] != Integer.MAX_VALUE / 2) {
for (int next = 0; next < n; ++next) {
if (((mask >> next) & 1) == 0) {
int nmask = mask | (1 << next);
int val = dp[mask] + 2 * getDist(sx, sy, x[next], y[next]);
if (dp[nmask] > val) {
dp[nmask] = val;
prev[nmask] = mask;
}
for (int next2 = next + 1; next2 < n; ++next2) {
if (((nmask >> next2) & 1) == 0) {
int nnmask = nmask | (1 << next2);
int nval = dp[mask] + getDist(sx, sy, x[next], y[next])
+ getDist(x[next], y[next], x[next2], y[next2])
+ getDist(x[next2], y[next2], sx, sy);
if (dp[nnmask] > nval) {
dp[nnmask] = nval;
prev[nnmask] = mask;
}
}
}
break;
}
}
}
}
List<Integer> res = new ArrayList<Integer>();
res.add(0);
int mask = (1 << n) - 1;
while (mask > 0) {
for (int i = 0; i < n; ++i) {
if (((prev[mask] >> i) & 1) == 0 && ((mask >> i) & 1) == 1) {
res.add(i + 1);
}
}
res.add(0);
mask = prev[mask];
}
Collections.reverse(res);
out.println(dp[(1 << n) - 1]);
for (int i = 0; i < res.size(); ++i) {
if (i != 0) {
out.print(" ");
}
out.print(res.get(i));
}
out.println();
out.flush();
}
private int getDist(int x1, int y1, int x2, int y2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}
private class Scanner {
private StringTokenizer tokenizer;
private BufferedReader reader;
public Scanner(Reader in) {
reader = new BufferedReader(in);
tokenizer = new StringTokenizer("");
}
public boolean hasNext() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String tmp = reader.readLine();
if (tmp == null)
return false;
tokenizer = new StringTokenizer(tmp);
}
return true;
}
public String next() throws IOException {
hasNext();
return tokenizer.nextToken();
}
public String nextLine() throws IOException {
tokenizer = new StringTokenizer("");
return reader.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
public static void main(String[] args) throws IOException {
new Main().solution();
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class BetaRound8_C implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
@Override
public void run() {
try {
long startTime = System.currentTimeMillis();
if (System.getProperty("ONLINE_JUDGE") != null) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
tok = new StringTokenizer("");
Locale.setDefault(Locale.US);
solve();
in.close();
out.close();
long endTime = System.currentTimeMillis();
long totalMemory = Runtime.getRuntime().totalMemory();
long freeMemory = Runtime.getRuntime().freeMemory();
System.err.println("Time = " + (endTime - startTime) + " ms");
System.err.println("Memory = " + ((totalMemory - freeMemory) / 1024) + " KB");
} catch (Throwable e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
public static void main(String[] args) {
new Thread(null, new BetaRound8_C(), "", 256 * 1024 * 1024).start();
}
// ------------------------------------------------------------------------------
final int INF = 1000 * 1000 * 1000;
int x0, y0;
int n;
int[] x, y;
int t(int i, int j) {
int dx = x[i] - x[j];
int dy = y[i] - y[j];
return dx * dx + dy * dy;
}
int t0(int i) {
int dx = x[i] - x0;
int dy = y[i] - y0;
return dx * dx + dy * dy;
}
int[] dp;
int[] p;
void solve() throws IOException {
x0 = readInt();
y0 = readInt();
n = readInt();
x = new int[n];
y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = readInt();
y[i] = readInt();
}
dp = new int[1 << n];
p = new int[1 << n];
Arrays.fill(dp, INF);
dp[(1 << n) - 1] = 0;
get(0);
out.println(dp[0]);
printPath();
}
int get(int mask) {
if (dp[mask] != INF) {
return dp[mask];
}
int res = INF;
for (int i = 0; i < n; i++) {
if (((1 << i) & mask) == 0) { // порядок неважен, т.к. в i все равно идти, пойдем туда сразу
int test = get(mask ^ (1 << i)) + 2 * t0(i);
if (res > test) {
res = test;
p[mask] = mask ^ (1 << i);
}
for (int j = i + 1; j < n; j++) {
if (((1 << j) & mask) == 0) {
test = get(mask ^ (1 << i) ^ (1 << j)) + t0(i)
+ t(i, j) + t0(j);
if (res > test) {
res = test;
p[mask] = mask ^ (1 << i) ^ (1 << j);
}
}
}
break;
}
}
return dp[mask] = res;
}
void printPath() {
ArrayList<Integer> ans = new ArrayList<Integer>();
ans.add(0);
int mask = 0;
while (mask != (1 << n) - 1) {
for (int i = 0; i < n; i++) {
if (((mask ^ p[mask]) & (1 << i)) != 0) {
ans.add(i + 1);
}
}
mask = p[mask];
ans.add(0);
}
for (int x : ans) {
out.print(x + " ");
}
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
private void run() throws IOException {
int cx = in.nextInt();
int cy = in.nextInt();
int n = in.nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; ++i) {
x[i] = in.nextInt() - cx;
y[i] = in.nextInt() - cy;
}
int[] dp = new int[1 << n];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
int[] prev = new int[1 << n];
for (int mask = 0; mask < (1 << n); ++mask) {
if (dp[mask] == Integer.MAX_VALUE) {
continue;
}
for (int i = 0; i < n; ++i) {
if (((mask >> i) & 1) == 0) {
if (dp[mask | (1 << i)] > dp[mask] + dist(x[i], y[i])) {
dp[mask | (1 << i)] = dp[mask] + dist(x[i], y[i]);
prev[mask | (1 << i)] = mask;
}
for (int j = i + 1; j < n; ++j) {
if (((mask >> j) & 1) == 0) {
if (dp[mask | (1 << i) | (1 << j)] > dp[mask] + dist(x[i], y[i], x[j], y[j])) {
dp[mask | (1 << i) | (1 << j)] = dp[mask] + dist(x[i], y[i], x[j], y[j]);
prev[mask | (1 << i) | (1 << j)] = mask;
}
}
}
break;
}
}
}
out.println(dp[(1 << n) - 1]);
int mask = (1 << n) - 1;
out.print(0);
while (mask != 0) {
int p = prev[mask];
int cur = p ^ mask;
List<Integer> who = new ArrayList<Integer>();
for (int i = 0; i < n; ++i) {
if (((cur >> i) & 1) != 0) {
who.add(i + 1);
}
}
for (int t : who) {
out.print(" " + t);
}
out.print(" " + 0);
mask = p;
}
out.flush();
}
private int dist(int x, int y, int x2, int y2) {
return x * x + y * y + x2 * x2 + y2 * y2 + (x2 - x) * (x2 - x) + (y2 - y) * (y2 - y);
}
private int dist(int x, int y) {
return 2 * (x * x + y * y);
}
private class Scanner {
private StringTokenizer tokenizer;
private BufferedReader reader;
public Scanner(Reader in) {
reader = new BufferedReader(in);
tokenizer = new StringTokenizer("");
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean hasNext() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String next = reader.readLine();
if (next == null)
return false;
tokenizer = new StringTokenizer(next);
}
return true;
}
public String next() throws IOException {
hasNext();
return tokenizer.nextToken();
}
public String nextLine() throws IOException {
tokenizer = new StringTokenizer("");
return reader.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
public static void main(String[] args) throws IOException {
new Main().run();
}
Scanner in = new Scanner(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
}
| np | 8_C. Looking for Order | 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 MainC {
private FastScanner in;
private PrintWriter out;
private int N;
private Dist[] dists;
private int countDists;
private int[][] minLeft;// startsFrom, count
private int[] minOrder;
private int minOrderCount = 10000000;
public void solve() throws IOException {
int xb = in.nextInt();
int yb = in.nextInt();
N = in.nextInt();
int[] x, y;
boolean isOdd;
if (N % 2 == 0) {
x = new int[N];
y = new int[N];
isOdd = false;
}
else {
x = new int[N + 1];
y = new int[N + 1];
isOdd = true;
}
for (int i = 0; i < N; i++) {
x[i] = in.nextInt() - xb;
y[i] = in.nextInt() - yb;
}
if (N % 2 == 1) {
N++;
x[N - 1] = 0;
y[N - 1] = 0;
}
countDists = N * (N - 1) / 2;
dists = new Dist[countDists];
int c = 0;
int commonSum = 0;
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
dists[c] = new Dist();
dists[c].from = i;
dists[c].to = j;
dists[c].dist = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j])
* (y[i] - y[j]);
dists[c].dist = Math.min(dists[c].dist, x[i] * x[i] + y[i]
* y[i] + x[j] * x[j] + y[j] * y[j]);
c++;
}
commonSum += x[i] * x[i] + y[i] * y[i];
}
Arrays.sort(dists);
minLeft = new int[countDists][N + 1];
for (int i = 0; i < countDists; i++) {
int sum = 0;
for (int j = 1; j <= N; j++) {
if (i + j - 1 < countDists) {
sum = sum + dists[i + j - 1].dist;
minLeft[i][j] = sum;
}
else {
minLeft[i][j] = 100000000;
}
}
}
order(0, new int[N], 0, 0);
out.println(minOrderCount + commonSum);
for (int i = 1; i <= N / 2; i++) {
int first = -1;
int second = -1;
for (int j = 0; j < N; j++) {
if (minOrder[j] == i) {
if (first == -1) {
first = j;
}
else {
second = j;
}
}
}
if (isOdd && (first == N - 1 || second == N - 1)) {
first++;
second++;
out.print("0 " + (first + second - N) + " ");
}
else if (x[first] * x[first] + y[first] * y[first] + x[second]
* x[second] + y[second] * y[second] < (x[first] - x[second])
* (x[first] - x[second])
+ (y[first] - y[second])
* (y[first] - y[second])) {
first++;
second++;
out.print("0 " + first + " 0 " + second + " ");
}
else {
first++;
second++;
out.print("0 " + first + " " + second + " ");
}
}
out.println("0");
}
private void order(int countOrdered, int[] order, int startsFrom, int sum) {
if (countOrdered == N) {
if (sum < minOrderCount) {
minOrder = Arrays.copyOf(order, N);
minOrderCount = sum;
}
return;
}
while (startsFrom < countDists) {
if (order[dists[startsFrom].from] == 0
&& order[dists[startsFrom].to] == 0) {
if (minLeft[startsFrom][(N - countOrdered) / 2] + sum >= minOrderCount) {
break;
}
order[dists[startsFrom].from] = countOrdered / 2 + 1;
order[dists[startsFrom].to] = countOrdered / 2 + 1;
order(countOrdered + 2, order, startsFrom + 1, sum
+ dists[startsFrom].dist);
order[dists[startsFrom].from] = 0;
order[dists[startsFrom].to] = 0;
}
startsFrom++;
}
}
private class Dist implements Comparable<Dist> {
int from;
int to;
int dist;
@Override
public int compareTo(Dist o) {
if (dist < o.dist) {
return -1;
}
if (dist == o.dist) {
return 0;
}
return 1;
}
}
public void run() {
try {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] arg) {
new MainC().run();
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class C {
public static void main(String[] args) {
//long t = System.currentTimeMillis();
new C().run();
//System.out.println(System.currentTimeMillis() - t);
}
private void run() {
Scanner sc = new Scanner(System.in);
int sx = sc.nextInt();
int sy = sc.nextInt();
int n = sc.nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
sc.close();
int[] w = new int[n * n];
int[] pMask = new int[n * n];
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int ind = i * n + j;
if (i == j) {
w[ind] = 2 * dist(sx, sy, x[i], y[i]);
pMask[ind] = 1 << i;
} else {
w[ind] = dist(sx, sy, x[i], y[i]) + dist(x[i], y[i], x[j], y[j]) + dist(x[j], y[j], sx, sy);
pMask[ind] = 1 << i | 1 << j;
}
}
}
int max = 1 << n;
int[] p = new int[max];
int[] dist = new int[max];
Arrays.fill(dist, Integer.MAX_VALUE / 2);
dist[0] = 0;
int[] available = new int[n * n];
for (int mask = 0; mask < max; mask++) {
int ac = 0;
for (int i = 0; i < n; i++) {
if (((mask >> i) & 1) == 0) {
available[ac++] = i;
}
}
int s = 0;
//for (int i = 0; i < ac; i++) {
for (int j = s; j < ac; j++) {
int a = available[s];
int b = available[j];
int ind = a * n + b;
int nextMask = mask | pMask[ind];
int newD = dist[mask] + w[ind];
if (newD < dist[nextMask]) {
dist[nextMask] = newD;
//p[nextMask] = a * n + b;
p[nextMask] = ind;
}
}
//}
}
System.out.println(dist[max - 1]);
ArrayList<Integer> steps = new ArrayList<Integer>();
int mask = max - 1;
while (mask > 0) {
int msk = p[mask];
steps.add(msk);
int a = msk / n;
int b = msk % n;
if (a == b) {
mask ^= 1 << a;
} else {
mask ^= 1 << a;
mask ^= 1 << b;
}
}
System.out.print(0);
for (int i = steps.size() - 1; i >= 0; i--) {
int msk = steps.get(i);
int a = msk / n;
int b = msk % n;
if (a == b) {
System.out.printf(" %d 0", a + 1);
} else {
System.out.printf(" %d %d 0", a + 1, b + 1);
}
}
System.out.println();
}
private int dist(int x1, int y1, int x2, int y2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.util.*;
public class c8 {
static int n;
static int[] ds;
static int[][] g;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int x = input.nextInt(), y = input.nextInt();
n = input.nextInt();
int[] xs = new int[n], ys = new int[n];
for(int i = 0; i<n; i++)
{
xs[i] = input.nextInt();
ys[i] = input.nextInt();
}
ds = new int[n];
g = new int[n][n];
for(int i = 0; i<n; i++)
{
ds[i] = (x - xs[i]) * (x - xs[i]) + (y - ys[i]) * (y - ys[i]);
for(int j = 0; j<n; j++)
{
g[i][j] = (xs[i] - xs[j]) * (xs[i] - xs[j]) + (ys[i] - ys[j]) * (ys[i] - ys[j]);
}
}
int[] dp = new int[1<<n];
Arrays.fill(dp, 987654321);
dp[0] = 0;
for(int i = 0; i<(1<<n); i++)
{
if(dp[i] == 987654321) continue;
for(int a = 0; a<n; a++)
{
if((i & (1<<a)) > 0) continue;
dp[i | (1<<a)] = Math.min(dp[i | (1<<a)], dp[i] + 2*ds[a]);
for(int b = a+1; b<n; b++)
{
if((i & (1<<b)) > 0) continue;
dp[i | (1<<a) | (1<<b)] = Math.min(dp[i | (1<<a) | (1<<b)], dp[i] + ds[a] + ds[b] + g[a][b]);
}
break;
}
}
Stack<Integer> stk = new Stack<Integer>();
stk.add(0);
int i = (1<<n) - 1;
//System.out.println(Arrays.toString(dp));
trace:
while(i > 0)
{
//System.out.println(i);
for(int a = 0; a<n; a++)
{
if((i & (1<<a)) == 0) continue;
if( dp[i] == dp[i - (1<<a)] + 2*ds[a])
{
stk.add(a+1);
stk.add(0);
i -= (1<<a);
continue trace;
}
for(int b = a+1; b<n; b++)
{
if((i & (1<<b)) == 0) continue;
if(dp[i] == dp[i - (1<<a) - (1<<b)] + ds[a] + ds[b] + g[a][b])
{
stk.add(a+1);
stk.add(b+1);
stk.add(0);
i -= (1<<a) + (1<<b);
continue trace;
}
}
//break;
}
}
System.out.println(dp[(1<<n) - 1]);
while(!stk.isEmpty()) System.out.print(stk.pop()+" ");
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.util.*;
import java.io.*;
public class C0008 {
public static void main(String args[]) throws Exception {
new C0008();
}
int n;
int target;
int pow[];
int dp[];
int next[];
int dist[][];
C0008() throws Exception {
PandaScanner sc = null;
PrintWriter out = null;
try {
sc = new PandaScanner(System.in);
out = new PrintWriter(System.out);
} catch (Exception ignored) {
}
pow = new int[26];
for (int i = 0; i < 26; i++) {
pow[i] = 1 << i;
}
dist = new int[26][26];
int[][] p = new int[26][];
p[25] = new int[] {sc.nextInt(), sc.nextInt()};
n = sc.nextInt();
target = (1 << n) - 1;
for (int i = 0; i < n; i++) {
p[i] = new int[] {sc.nextInt(), sc.nextInt()};
dist[i][25] = getDist(p[i], p[25]);
for (int j = 0; j < i; j++) {
dist[j][i] = getDist(p[j], p[i]);
}
}
next = new int[1 << n];
dp = new int[1 << n];
Arrays.fill(dp, -1);
out.println(go(0));
ArrayList<Integer> paths = new ArrayList<Integer>();
paths.add(0);
int curr = 0;
while (curr != target) {
for (Integer i: getBits(next[curr], true)) {
paths.add(i + 1);
}
paths.add(0);
curr |= next[curr];
}
out.println(paths.toString().replaceAll("[^ 0-9]", ""));
out.close();
System.exit(0);
}
int go(int mask) {
if (mask == target) {
return 0;
}
if (dp[mask] != -1) {
return dp[mask];
}
ArrayList<Integer> notDone = getBits(mask, false);
dp[mask] = Integer.MAX_VALUE;
for (Integer i: notDone) {
int oneD = (dist[i][25] << 1) + go(mask | pow[i]);
if (dp[mask] > oneD) {
dp[mask] = oneD;
next[mask] = 1 << i;
}
for (Integer j: notDone) {
if (j == i) continue;
int d = (dist[j][25] + dist[i][j] + dist[i][25]) + go(mask | pow[i] | pow[j]);
if (dp[mask] > d) {
dp[mask] = d;
next[mask] = (1 << i) | (1 << j);
}
}
break;
}
return dp[mask];
}
int getDist(int[] p1, int[] p2) {
return sq(p1[0] - p2[0]) + sq(p1[1] - p2[1]);
}
int sq(int a) {
return a * a;
}
ArrayList<Integer> getBits(int mask, boolean on) {
ArrayList<Integer> res = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (((mask & (1 << i)) == 0) ^ on) {
res.add(i);
}
}
return res;
}
//The PandaScanner class, for Panda fast scanning!
public class PandaScanner {
BufferedReader br;
StringTokenizer st;
InputStream in;
PandaScanner(InputStream in) throws Exception {
br = new BufferedReader(new InputStreamReader(this.in = in));
}
public String next() throws Exception {
if (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine().trim());
return next();
}
return st.nextToken();
}
public boolean hasNext() throws Exception {
return (st != null && st.hasMoreTokens()) || in.available() > 0;
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import static java.util.Arrays.*;
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
public class Main implements Runnable
{
public static void main(String [] args) throws IOException
{
new Thread(null, new Main(), "", 1 << 20).start();
}
String file = "input";
BufferedReader input;
PrintWriter out;
public void run()
{
try
{
//input = new BufferedReader(new FileReader(file + ".in"));
input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
solve();
input.close();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
int[] x = new int[25];
int[] y = new int[25];
int[][] dist = new int[25][25];
int[] single = new int[25];
int[] c = new int[25];
int INF = 1 << 30;
void solve() throws IOException
{
StringTokenizer st = tokens();
x[0] = nextInt(st);
y[0] = nextInt(st);
int n = nextInt();
for(int i = 1; i <= n; i++)
{
st = tokens();
x[i] = nextInt(st);
y[i] = nextInt(st);
}
for(int i = 1; i <= n; i++)
single[i] = 2 * ((x[i] - x[0]) * (x[i] - x[0]) + (y[i] - y[0]) * (y[i] - y[0]));
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
dist[i][j] = single[i] / 2 + single[j] / 2 + (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
int[] dp = new int[1 << n];
int[] prev = new int[1 << n];
fill(dp, INF);
dp[0] = 0;
for(int i = 1; i < 1 << n; i++)
{
for(int j = 0; j < n; j++)
{
if((i >> j & 1) != 0)
{
if(dp[i] > dp[i ^ (1 << j)] + single[j + 1])
{
dp[i] = dp[i ^ (1 << j)] + single[j + 1];
prev[i] = j + 1;
}
for(int k = j + 1; k < n; k++)
if((i >> k & 1) != 0)
{
if(dp[i] > dp[i ^ (1 << j) ^ (1 << k)] + dist[j + 1][k + 1])
{
dp[i] = dp[i ^ (1 << j) ^ (1 << k)] + dist[j + 1][k + 1];
prev[i] = (j + 1) * 100 + (k + 1);
}
}
break;
}
}
}
out.println(dp[(1 << n) - 1]);
out.print("0 ");
int mask = (1 << n) - 1;
while(mask > 0)
{
int s = prev[mask];
int x = s / 100;
int y = s % 100;
if(x == 0)
{
out.print(y + " " + 0 + " ");
mask -= 1 << (y - 1);
}
else
{
out.print(x + " " + y + " " + 0 + " ");
mask -= 1 << (y - 1);
mask -= 1 << (x - 1);
}
}
}
StringTokenizer tokens() throws IOException
{
return new StringTokenizer(input.readLine());
}
String next(StringTokenizer st)
{
return st.nextToken();
}
int nextInt() throws IOException
{
return Integer.parseInt(input.readLine());
}
int nextInt(StringTokenizer st)
{
return Integer.parseInt(st.nextToken());
}
double nextDouble() throws IOException
{
return Double.parseDouble(input.readLine());
}
double nextDouble(StringTokenizer st)
{
return Double.parseDouble(st.nextToken());
}
void print(Object... o)
{
out.println(deepToString(o));
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.io.*;
import java.util.*;
public class LookingForOrder
{
public Scanner in = new Scanner(System.in);
public PrintStream out = System.out;
public int[] go;
public int[][] cost;
public int [] sol;
public Pair[] how;
public int n, lim;
public Pair bag;
public Pair[] obj;
public void main()
{
bag = new Pair(in.nextInt(), in.nextInt());
n = in.nextInt();
obj = new Pair[n];
for(int i=0;i<n;++i) obj[i] = new Pair(in.nextInt(), in.nextInt());
go = new int[n];
cost = new int[n][n];
for(int i=0;i<n;++i)
{
go[i] = squDist(bag, obj[i]);
for(int j=0;j<n;++j) cost[i][j] = squDist(obj[i], obj[j]);
}
lim = (1<<n);
sol = new int[lim];
Arrays.fill(sol, -1);
how = new Pair[lim];
out.println(solve(lim-1));
Pair T;
int set = lim-1;
out.print("0");
while(set > 0)
{
solve(set);
T = how[set];
out.print(" "+(T.x+1));
set = off(T.x, set);
if(T.y >= 0)
{
out.print(" " + (T.y+1));
set = off(T.y, set);
}
out.print(" 0");
}
out.println();
}//end public void main()
public int oo = 987654321;
public boolean in(int x, int set) { return ((1<<x) & set) != 0; }
//Turn on bit x
public int on(int x, int set) { return (set | (1<<x)); }
//Turn off bit x
public int off(int x, int set) { return (set ^ (set & (1<<x)) ); }
public int solve(int set)
{
if(sol[set] >= 0) return sol[set];
int ret;
if(set == 0) ret = 0;
else
{
ret = oo;
int x, y, sub, c;
for(x=0;x<n;++x) if(in(x, set)) break;
sub = off(x, set);
c = go[x]+go[x]+solve(sub);
if(c < ret)
{
how[set] = new Pair(x, -1);
ret = c;
}
for(y=x+1;y<n;++y) if(in(y, set))
{
c = go[x]+cost[x][y]+go[y] + solve(off(y, sub));
if(c < ret)
{
ret = c;
how[set] = new Pair(x, y);
}
}
}
return sol[set] = ret;
}
public int squDist(int ax, int ay, int bx, int by)
{
int dx, dy;
dx = ax - bx;
dy = ay - by;
return dx*dx + dy*dy;
}
public int squDist(Pair p, Pair q)
{
return squDist(p.x, p.y, q.x, q.y);
}
//int pair
private class Pair implements Comparable<Pair>
{
public int x, y;
public Pair(int xx, int yy) { x = xx; y = yy; }
public int compareTo(Pair u)
{
if(x!=u.x) return x-u.x;
return y-u.y;
}
public String toString() { return "(" + x + "," + y + ")"; }
}
public static void main(String[] args)
{
(new LookingForOrder()).main();
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class LookingForOrder {
static int[][] pos;
static int[] dp;
static int[] nextstate;
static int[][] dist;
static int r;
static int v;
static void print(int mask) {
if (mask < v) {
int c = 0;
int x = mask ^ nextstate[mask];
for (int i = 0; i < dist.length - 1; i++) {
if((x & (1<<i))>0) {
System.out.print(i+1 + " ");
c++;
}
}
System.out.print("0 ");
print(nextstate[mask]);
}
}
static int distace(int x1, int x2, int y1, int y2) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
static int solve(int mask) {
if (mask == v) {
nextstate[mask] = r;
return 0;
}
if (nextstate[mask] != 0) {
return dp[mask];
}
dp[mask] = (int) 1e9;
for (int i = 1; i < pos.length; i++) {
int u = (1 << (i - 1));
int z = mask | u;
if ((mask & u) == 0) {
int x = 2 * dist[i][0] + solve(z);
if (dp[mask] > x) {
dp[mask] = x;
nextstate[mask] = z;
}
for (int j = 1; j < pos.length; j++) {
int m = (1 << j - 1);
int y = z | m;
if ((z & m) == 0) {
x = dist[i][0] + solve(y) + dist[i][j] + dist[j][0];
if (dp[mask] > x) {
dp[mask] = x;
nextstate[mask]= y;
}
}
}
break;
}
}
return dp[mask];
}
public static void main(String[] args) {
InputReader0 in = new InputReader0(System.in);
int x = in.nextInt(), y = in.nextInt();
int n = in.nextInt();
r = 1 << n;
v = r - 1;
dp = new int[r];
nextstate = new int[r];
pos = new int[n + 1][2];
pos[0][0] = x;
pos[0][1] = y;
for (int i = 1; i < pos.length; i++) {
pos[i][0] = in.nextInt();
pos[i][1] = in.nextInt();
}
dist = new int[n + 1][n + 1];
for (int i = 0; i < dist.length; i++) {
for (int j = i + 1; j < dist.length; j++) {
dist[i][j] = dist[j][i] = distace(pos[i][0], pos[j][0], pos[i][1], pos[j][1]);
}
}
System.out.println(solve(0));
System.out.print("0 ");
print(0);
}
}
class InputReader0 {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader0(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
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 long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Bag implements Runnable {
private void solve() throws IOException {
int xs = nextInt();
int ys = nextInt();
int n = nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; ++i) {
x[i] = nextInt();
y[i] = nextInt();
}
int[][] pair = new int[n][n];
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]);
int[] single = new int[n];
for (int i = 0; i < n; ++i) {
single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys));
}
int[] best = new int[1 << n];
int[] prev = new int[1 << n];
for (int set = 1; set < (1 << n); ++set) {
int i;
for (i = 0; i < n; ++i)
if ((set & (1 << i)) != 0)
break;
best[set] = best[set ^ (1 << i)] + single[i];
prev[set] = i + 1;
for (int j = i + 1; j < n; ++j)
if ((set & (1 << j)) != 0) {
int cur = best[set ^ (1 << i) ^ (1 << j)] + pair[i][j];
if (cur < best[set]) {
best[set] = cur;
prev[set] = (i + 1) * 100 + (j + 1);
}
}
}
writer.println(best[(1 << n) - 1]);
int now = (1 << n) - 1;
writer.print("0");
while (now > 0) {
int what = prev[now];
int wa = what % 100 - 1;
int wb = what / 100 - 1;
if (wa >= 0) {
writer.print(" ");
writer.print(wa + 1);
now ^= 1 << wa;
}
if (wb >= 0) {
writer.print(" ");
writer.print(wb + 1);
now ^= 1 << wb;
}
writer.print(" ");
writer.print("0");
}
writer.println();
}
public static void main(String[] args) {
new Bag().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.util.*;
import static java.lang.Math.*;
public class C {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
hx = sc.nextInt();
hy = sc.nextInt();
N = sc.nextInt();
X = new int[N];
Y = new int[N];
for(int i = 0; i < N;i++){
X[i] = sc.nextInt();
Y[i] = sc.nextInt();
}
DP = new int[1<<N];
Arrays.fill(DP,-1);
int ans = recur(0);
ArrayList<Integer> aa = new ArrayList<Integer>();
int U = 0;
aa.add(0);
int test = 0;
while(U != (1<<N)-1){
int a = 0;
for(int i = 0; i < N;i++)
if(((1<<i)&U) == 0){
a = i;
break;
}
int ans2 = recur(U|(1<<a))+2*(pw(X[a]-hx)+pw(Y[a]-hy));
int temp = 2*(pw(X[a]-hx)+pw(Y[a]-hy));
int best = -1;
for(int i = a+1;i<N;i++){
if(((1<<i)&U) == 0){
int ans3 = pw(X[a]-X[i])+pw(Y[a]-Y[i])+pw(X[a]-hx)+pw(Y[a]-hy)+pw(X[i]-hx)+pw(Y[i]-hy)+recur(U|(1<<a)|(1<<i));
if(ans3 < ans2){
ans2 = ans3;
best = i;
temp = pw(X[a]-X[i])+pw(Y[a]-Y[i])+pw(X[a]-hx)+pw(Y[a]-hy)+pw(X[i]-hx)+pw(Y[i]-hy);
}
}
}
if(best == -1){
aa.add(a+1);
aa.add(0);
U |= (1<<a);
}else{
aa.add(a+1);
aa.add(best+1);
aa.add(0);
U |= (1<<a) | (1<<best);
}
test += temp;
}
// System.out.println(test);
if(test != ans)
throw new RuntimeException();
System.out.println(ans);
for(int i = 0; i < aa.size();i++)
System.out.print(aa.get(i)+(i == aa.size()-1?"":" "));
System.out.println();
}
private static int recur(int U) {
if(DP[U] != -1)
return DP[U];
if(U == (1<<N)-1)
return 0;
int a = 0;
for(int i = 0; i < N;i++)
if(((1<<i)&U) == 0){
a = i;
break;
}
int ans = recur(U|(1<<a))+2*(pw(X[a]-hx)+pw(Y[a]-hy));
for(int i = a+1;i<N;i++){
if(((1<<i)&U) == 0){
ans = min(ans,pw(X[a]-X[i])+pw(Y[a]-Y[i])+pw(X[a]-hx)+pw(Y[a]-hy)+pw(X[i]-hx)+pw(Y[i]-hy)+recur(U|(1<<a)|(1<<i)));
}
}
DP[U] = ans;
return ans;
}
static int pw(int a){
return a*a;
}
static int hx,hy;
static int[] X,Y;
static int N;
static int[] DP;
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
int INF = Integer.MAX_VALUE >> 1;
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
/* Input */
int x0 = nextInt();
int y0 = nextInt();
int N = nextInt();
int FULL_MASK = (1 << N) - 1;
int[] xs = new int [N];
int[] ys = new int [N];
for (int i = 0; i < N; i++) {
xs[i] = nextInt();
ys[i] = nextInt();
}
/* Precalc */
int[][] dist = new int [N][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
dist[i][j] = dist(x0, y0, xs[i], ys[i]) + dist(xs[i], ys[i], xs[j], ys[j]) + dist(xs[j], ys[j], x0, y0);
/* DP */
int[] dp = new int [1 << N];
int[] pr = new int [1 << N];
Arrays.fill(dp, INF);
dp[0] = 0;
for (int mask = 0; mask < FULL_MASK; mask++) {
int i = Integer.numberOfTrailingZeros(~mask); // hack: use first non-zero bit
int imask = mask | (1 << i);
for (int j = i; j < N; j++) {
int jmask = mask | (1 << j);
if (jmask == mask) continue;
int ijmask = imask | jmask;
int nval = dp[mask] + dist[i][j];
if (dp[ijmask] > nval) {
dp[ijmask] = nval;
pr[ijmask] = mask;
}
}
}
/* Output */
out.println(dp[FULL_MASK]);
out.print("0");
for (int mask = FULL_MASK; mask != 0; mask = pr[mask]) {
int diff = mask ^ pr[mask];
int i = Integer.numberOfTrailingZeros(diff);
diff &= ~(1 << i);
int j = Integer.numberOfTrailingZeros(diff);
if (i != 32) out.print(" " + (i + 1));
if (j != 32) out.print(" " + (j + 1));
out.print(" 0");
}
out.println();
out.close();
}
/***************************************************************
* Utility
**************************************************************/
int dist(int x1, int y1, int x2, int y2) {
return sqr(x2 - x1) + sqr(y2 - y1);
}
int sqr(int x) {
return x * x;
}
/***************************************************************
* Input
**************************************************************/
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CodeD
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String nextLine()
{
try
{
return br.readLine();
}
catch(Exception e)
{
throw(new RuntimeException());
}
}
public String next()
{
while(!st.hasMoreTokens())
{
String l = nextLine();
if(l == null)
return null;
st = new StringTokenizer(l);
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
public int[] nextIntArray(int n)
{
int[] res = new int[n];
for(int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public long[] nextLongArray(int n)
{
long[] res = new long[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public double[] nextDoubleArray(int n)
{
double[] res = new double[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public void sortIntArray(int[] array)
{
Integer[] vals = new Integer[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortLongArray(long[] array)
{
Long[] vals = new Long[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortDoubleArray(double[] array)
{
Double[] vals = new Double[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
}
static final Scanner sc;
static final int n;
static final int[][] distancias;
static final int[] distancia;
static final int[] dp;
static final int[] dpNext;
static final int X;
static final int Y;
static
{
sc = new Scanner();
X = sc.nextInt();
Y = sc.nextInt();
n = sc.nextInt();
distancias = new int[n][n];
distancia = new int[n];
dp = new int[1 << n];
Arrays.fill(dp, -1);
dpNext = new int[1 << n];
}
static int dp(int mascara)
{
if(dp[mascara] != -1)
return dp[mascara];
int highest = -1;
for(int i = 0, tmp = mascara; tmp != 0; i++, tmp >>= 1)
{
if((tmp & 1) == 1)
highest = i;
}
if(highest == -1)
return 0;
int nextMsc = mascara ^ (1 << highest);
int costHighest = distancia[highest];
int best = (costHighest << 1) + dp(nextMsc);
int bestNext = nextMsc;
for(int i = 0, tmp = nextMsc, iC = 1; tmp != 0; i++, tmp >>= 1, iC <<= 1)
{
if((tmp & 1) == 1)
{
int msc = nextMsc ^ iC;
int possibleA = costHighest + distancias[highest][i] + distancia[i] + dp(msc);
if(possibleA < best)
{
best = possibleA;
bestNext = msc;
}
}
}
dpNext[mascara] = bestNext;
return dp[mascara] = best;
}
public static void main(String[] args)
{
int[][] objetos = new int[n][2];
for(int i = 0; i < n; i++)
{
objetos[i][0] = sc.nextInt();
objetos[i][1] = sc.nextInt();
distancia[i] = (X - objetos[i][0]) * (X - objetos[i][0]) + (Y - objetos[i][1]) * (Y - objetos[i][1]);
}
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
distancias[i][j] = (objetos[i][0] - objetos[j][0]) * (objetos[i][0] - objetos[j][0]) + (objetos[i][1] - objetos[j][1]) * (objetos[i][1] - objetos[j][1]);
int ans = dp((1 << n) - 1);
System.out.println(ans);
int current = (1 << n) - 1;
while(current != 0)
{
int next = dpNext[current];
int differents = next ^ current;
System.out.print("0 ");
for(int i = 0; i < n; i++)
if((differents & (1 << i)) != 0)
System.out.print((i + 1) + " ");
current = next;
}
System.out.println("0");
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class _8C {
static int[] x = new int[30], y = new int[30];
static int[][] dist = new int[30][30];
static int n;
static final int M = 1000;
static int[] bitPos = new int[M];
static {
Arrays.fill(bitPos, -1);
for (int i=0; i<24; i++)
bitPos[(1 << i) % M] = i;
}
static int sqr(int i) {
return i * i;
}
public static void main(String[] args) throws Exception {
Reader.init(System.in);
BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));
x[0] = Reader.nextInt();
y[0] = Reader.nextInt();
n = Reader.nextInt();
for (int i=1; i<=n; i++) {
x[i] = Reader.nextInt();
y[i] = Reader.nextInt();
}
for (int i=0; i<=n; i++)
for (int j=0; j<=n; j++)
dist[i][j] = sqr(x[i] - x[j]) + sqr(y[i] - y[j]);
int[] f = new int[1 << n];
int[] r = new int[1 << n];
for (int mask=1; mask<(1 << n); mask++) {
int lowbit = mask & -mask;
int lowbitPos = bitPos[lowbit % M];
f[mask] = dist[lowbitPos + 1][0] * 2 + f[mask ^ lowbit];
r[mask] = lowbit;
for (int i=mask^(lowbit); i>0; i=i^(i & -i)) {
int otherBit = i & -i;
int otherBitPos = bitPos[otherBit % M];
int tmp = dist[0][lowbitPos + 1] + dist[lowbitPos + 1][otherBitPos + 1] + dist[otherBitPos + 1][0] + f[mask ^ otherBit ^ lowbit];
if (tmp < f[mask]) {
f[mask] = tmp;
r[mask] = lowbit | otherBit;
}
}
}
System.out.println(f[(1 << n) - 1]);
int mask = (1 << n) - 1;
while(mask > 0) {
if ((r[mask] ^ (r[mask] & -r[mask])) == 0) {
System.out.print("0 " + (bitPos[r[mask] % M] + 1) + " ");
}
else {
int bit1 = r[mask] & -r[mask];
int bit2 = r[mask] ^ bit1;
System.out.print("0 " + (bitPos[bit1 % M] + 1) + " " + (bitPos[bit2 % M] + 1) + " ");
}
mask ^= r[mask];
}
System.out.println("0");
cout.close();
}
static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
final U _1;
final V _2;
private Pair(U key, V val) {
this._1 = key;
this._2 = val;
}
public static <U extends Comparable<U>, V extends Comparable<V>> Pair<U, V> instanceOf(U _1, V _2) {
return new Pair<U, V>(_1, _2);
}
@Override
public String toString() {
return _1 + " " + _2;
}
@Override
public int hashCode() {
int res = 17;
res = res * 31 + _1.hashCode();
res = res * 31 + _2.hashCode();
return res;
}
@Override
public int compareTo(Pair<U, V> that) {
int res = this._1.compareTo(that._1);
if (res < 0 || res > 0)
return res;
else
return this._2.compareTo(that._2);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Pair))
return false;
Pair<?, ?> that = (Pair<?, ?>) obj;
return _1.equals(that._1) && _2.equals(that._2);
}
}
/** Class for buffered reading int and double values */
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
// TODO add check for eof if necessary
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
static class ArrayUtil {
static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(long[] a, int i, int j) {
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(double[] a, int i, int j) {
double tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(char[] a, int i, int j) {
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(boolean[] a, int i, int j) {
boolean tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void reverse(int[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(long[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(double[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(char[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(boolean[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static long sum(int[] a) {
int sum = 0;
for (int i : a)
sum += i;
return sum;
}
static long sum(long[] a) {
long sum = 0;
for (long i : a)
sum += i;
return sum;
}
static double sum(double[] a) {
double sum = 0;
for (double i : a)
sum += i;
return sum;
}
static int max(int[] a) {
int max = Integer.MIN_VALUE;
for (int i : a)
if (i > max)
max = i;
return max;
}
static int min(int[] a) {
int min = Integer.MAX_VALUE;
for (int i : a)
if (i < min)
min = i;
return min;
}
static long max(long[] a) {
long max = Long.MIN_VALUE;
for (long i : a)
if (i > max)
max = i;
return max;
}
static long min(long[] a) {
long min = Long.MAX_VALUE;
for (long i : a)
if (i < min)
min = i;
return min;
}
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.util.*;
import java.lang.Math.*;
public class Main {
static Scanner in = new Scanner(System.in);
static Coor[] p;
static Coor ori;
static int n;
static int dp[];
static Coor pre[];
public static void main(String[] args) {
ori = new Coor(in.nextInt(),in.nextInt());
n = in.nextInt();
p = new Coor[n];
dp = new int[1<<n];
pre = new Coor[1<<n];
for (int i = 0;i < n;i++) {
p[i] = new Coor(in.nextInt(),in.nextInt());
}
Arrays.fill(dp,-1);
dp[0] = 0;
System.out.println( getdp((1<<n)-1));
//System.out.printf("%d",0);
System.out.printf("%d",0);
trace((1<<n)-1);
System.out.println();
}
static void trace(int mask) {
if (mask == 0) return;
if (pre[mask].y == -1) {
System.out.printf(" %d %d",pre[mask].x+1,0);
trace( mask - ( 1<< pre[mask].x ) );
} else {
System.out.printf(" %d %d %d",pre[mask].x+1,pre[mask].y+1,0);
trace( mask - ( 1<< pre[mask].x ) - (1<<pre[mask].y));
}
}
static int getdp(int mask) {
if (dp[mask] != -1)
return dp[mask];
int fr = 0;
for (int i = 0;i < n;i++)
if ( (mask & (1 << i)) != 0 ) {
fr = i;
break;
}
dp[mask] = getdp( mask - (1 << fr) ) + 2 * p[fr].dist(ori);
pre[mask] = new Coor(fr,-1);
for (int i = fr+1;i < n;i++) {
int to = i;
if ( (mask & (1 << i)) != 0) {
int tmp = getdp( mask - (1<<fr) - (1<<i) ) + p[fr].dist(ori) + p[to].dist(ori) + p[fr].dist(p[to]);
if (tmp < dp[mask]) {
dp[mask] = tmp;
pre[mask].y = i;
}
}
}
return dp[mask];
}
}
class Coor {
int x,y;
Coor(int _x,int _y) {
x = _x;y = _y;
}
int dist(Coor o) {
return ( (x-o.x) * (x-o.x) + (y-o.y) * (y-o.y) );
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Bag implements Runnable {
private void solve() throws IOException {
int xs = nextInt();
int ys = nextInt();
int n = nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; ++i) {
x[i] = nextInt();
y[i] = nextInt();
}
int[][] pair = new int[n][n];
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]);
int[] single = new int[n];
for (int i = 0; i < n; ++i) {
single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys));
}
int[] best = new int[1 << n];
int[] prev = new int[1 << n];
for (int set = 1; set < (1 << n); ++set) {
int i;
for (i = 0; i < n; ++i)
if ((set & (1 << i)) != 0)
break;
best[set] = best[set ^ (1 << i)] + single[i];
prev[set] = i + 1;
for (int j = i + 1; j < n; ++j)
if ((set & (1 << j)) != 0) {
int cur = best[set ^ (1 << i) ^ (1 << j)] + pair[i][j];
if (cur < best[set]) {
best[set] = cur;
prev[set] = (i + 1) * 100 + (j + 1);
}
}
}
writer.println(best[(1 << n) - 1]);
int now = (1 << n) - 1;
writer.print("0");
while (now > 0) {
int what = prev[now];
int wa = what % 100 - 1;
int wb = what / 100 - 1;
if (wa >= 0) {
writer.print(" ");
writer.print(wa + 1);
now ^= 1 << wa;
}
if (wb >= 0) {
writer.print(" ");
writer.print(wb + 1);
now ^= 1 << wb;
}
writer.print(" ");
writer.print("0");
}
writer.println();
}
public static void main(String[] args) {
new Bag().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* CodeForces 8C - Looking for Order
* Created by Darren on 14-10-1.
*/
public class Main {
Reader in = new Reader(System.in);
PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
new Main().run();
}
int n;
int[] x, y;
int[][] time;
int status;
int[] dp;
int[] pre;
void run() throws IOException {
int xs = in.nextInt(), ys = in.nextInt();
n = in.nextInt();
x = new int[n+1];
y = new int[n+1];
for (int i = 0; i < n; i++) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
x[n] = xs;
y[n] = ys;
computeTime();
status = (1<<n);
dp = new int[1<<n];
pre = new int[1<<n];
Arrays.fill(dp, -1);
dp[0] = 0;
for (int i = 0; i < status; i++) {
if (dp[i] == -1)
continue;
for (int j = 0; j < n; j++) {
if (((1<<j) & i) == 0) {
int t1 = ((1<<j) | i), temp1 = dp[i] + 2 * time[n][j];
if (dp[t1] == -1 || dp[t1] > temp1) {
dp[t1] = temp1;
pre[t1] = i;
}
for (int k = 0; k < n; k++) {
if (((1<<k) & t1) == 0) {
int t2 = ((1<<k) | t1),
temp2 = dp[i] + time[n][j] + time[j][k] + time[k][n];
if (dp[t2] == -1 || dp[t2] > temp2) {
dp[t2] = temp2;
pre[t2] = i;
}
}
}
break;
}
}
}
int cur = (1 << n) - 1;
out.println(dp[cur]);
out.print(0);
while (cur > 0) {
int last = pre[cur], diff = cur ^ last;
int obj1 = -1, obj2 = -1;
for (int i = 0; i < n; i++) {
if (((1<<i) & diff) > 0) {
obj2 = obj1;
obj1 = i;
}
}
if (obj2 >= 0)
out.printf(" %d %d %d", obj1+1, obj2+1, 0);
else
out.printf(" %d %d", obj1+1, 0);
cur = last;
}
out.flush();
}
void computeTime() {
time = new int[n+1][n+1];
for (int i = 0; i <= n; i++) {
for (int j = i+1; j <= n; j++)
time[i][j] = time[j][i] = (x[i]- x[j])*(x[i]- x[j]) +
(y[i]- y[j])*(y[i]- y[j]);
}
}
static class Reader {
BufferedReader reader;
StringTokenizer tokenizer;
public Reader(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/** get next word */
String nextToken() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer( reader.readLine() );
}
return tokenizer.nextToken();
}
String readLine() throws IOException {
return reader.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt( nextToken() );
}
long nextLong() throws IOException {
return Long.parseLong( nextToken() );
}
double nextDouble() throws IOException {
return Double.parseDouble( nextToken() );
}
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.*;
import java.util.*;
public class AMain {
static int n;
static int[] best;
static int[][] dist;
static int[] home;
static LinkedList<Integer> ret;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
State curr = new State(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
n = Integer.parseInt(br.readLine());
State[] list = new State[n];
for(int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
list[i] = new State(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
}
dist = new int[n][n];
home = new int[n];
for(int i = 0; i < n; i++) {
home[i] = dist(curr, list[i]);
}
for(int i = 0; i < n; i++) {
dist[i][i] = 2 * home[i];
for(int j = i+1; j < n; j++) {
dist[i][j] = dist(list[i], list[j]) + home[i] + home[j];
}
}
best = new int[1 << (n)];
Arrays.fill(best, -1);
best[0] = 0;
System.out.println(solve(-1 + (1<<n)));
ret = new LinkedList<Integer>();
resolve(-1 + (1<<n));
for(int x: ret)
System.out.print(x + " ");
}
public static int dist(State a, State b) {
int x = a.x-b.x;
int y = a.y-b.y;
return x*x+y*y;
}
public static void resolve(int curr) {
ret.addLast(0);
for(int i = 0; i < n; i++) {
if((curr & (1<<i)) == 0)
continue;
for(int j = i+1; j < n; j++) {
if((curr & (1 << j)) == 0) {
continue;
}
if(dist[i][j] + solve(curr ^ (1<<i) ^ (1 << j)) == best[curr]) {
ret.addLast(i+1);
ret.addLast(j+1);
resolve(curr - (1<<i) - (1<<j));
return;
}
}
if(best[curr] == dist[i][i] + solve(curr ^ (1<<i))) {
ret.addLast(i+1);
resolve(curr - (1<<i));
return;
}
}
}
public static int solve(int curr) {
if(best[curr] != -1)
return best[curr];
int ret = Integer.MAX_VALUE;
for(int i = 0; i < n; i++) {
if((curr & (1<<i)) == 0)
continue;
for(int j = i+1; j < n; j++) {
if((curr & (1 << j)) == 0) {
continue;
}
ret = Math.min(ret, dist[i][j] + solve(curr ^ (1<<i) ^ (1 << j)));
}
ret = Math.min(ret, dist[i][i] + solve(curr ^ (1<<i)));
break;
}
best[curr] = ret;
return ret;
}
static class State {
public int x,y;
public State(int a, int b) {
x=a;
y=b;
}
}
}
| np | 8_C. Looking for Order | 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 C8 {
static int[] mem;
static int[] bag;
static int[][] items;
static int[] close;
static PrintWriter pw;
static int n;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
pw = new PrintWriter(System.out);
bag = new int[2];
bag[0] = sc.nextInt();
bag[1] = sc.nextInt();
n = sc.nextInt();
items = new int[n][2];
for(int i = 0;i<n;i++)
{
items[i][0] = sc.nextInt();
items[i][1] = sc.nextInt();
}
//System.out.println((items[0][1]-bag[1])*(items[0][1]-bag[1]));
mem = new int[1<<n];
Arrays.fill(mem, -1);
pw.println(dp(0));
trace(0);
pw.print(0);
pw.flush();
}
static int dp(int mask){
if(mask==(1<<n)-1)
return 0;
if(mem[mask]!=-1)
return mem[mask];
int ans = (int)1e9;
for(int i = 0;i<n;i++)
if((1<<i&mask)==0)
{
ans = getDisBag(i)*2+dp(mask|1<<i);
for(int j = i+1;j<n;j++)
if((1<<j&mask)==0)
ans = Math.min(ans, getDisBag(i)+getDis(i,j)+getDisBag(j)+dp(mask|1<<i|1<<j));
break;
}
return mem[mask] = ans;
}
static int getDis(int i, int j){
return (items[i][0]-items[j][0])*(items[i][0]-items[j][0])+(items[i][1]-items[j][1])*(items[i][1]-items[j][1]);
}
static int getDisBag(int i){
return (items[i][0]-bag[0])*(items[i][0]-bag[0])+(items[i][1]-bag[1])*(items[i][1]-bag[1]);
}
static int getClosest(int i, int mask){
int ret = -1;
for(int j = 0;j<n;j++)
if(i!=j&&(mask&1<<j)==0)
if(ret==-1||getDis(i, j)<getDis(i, ret))
ret = j;
return ret;
}
static void trace(int mask){
if(mask==(1<<n)-1)
return;
int ans = (int)1e9;
for(int i = 0;i<n;i++)
if((1<<i&mask)==0)
{
ans = getDisBag(i)*2+dp(mask|1<<i);
if(mem[mask]==ans)
{
pw.print(0+" "+(i+1)+" ");
trace(mask|1<<i);
return;
}
for(int j = i+1;j<n;j++)
if((1<<j&mask)==0)
if(mem[mask] == getDisBag(i)+getDis(i,j)+getDisBag(j)+dp(mask|1<<i|1<<j))
{
pw.print(0+" "+(i+1)+" "+(j+1)+" ");
trace(mask|1<<i|1<<j);
return;
}
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nguyen Trung Hieu - [email protected]
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int xs = in.readInt();
int ys = in.readInt();
int n = in.readInt();
int[] x = new int[n];
int[] y = new int[n];
IOUtils.readIntArrays(in, x, y);
int[] res = new int[1 << n];
int[] last = new int[1 << n];
Arrays.fill(res, Integer.MAX_VALUE);
int[] ds = new int[n];
for (int i = 0; i < n; i++) {
ds[i] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys);
}
int[][] d = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
d[i][j] = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
}
res[0] = 0;
for (int i = 1; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
if (((i >> j) & 1) != 0) {
if (res[i - (1 << j)] + 2 * ds[j] < res[i]) {
res[i] = res[i - (1 << j)] + 2 * ds[j];
last[i] = i - (1 << j);
}
for (int k = j + 1; k < n; k++) {
if (((i >> k) & 1) != 0) {
if (res[i - (1 << j) - (1 << k)] + ds[j] + ds[k] + d[j][k] < res[i]) {
res[i] = res[i - (1 << j) - (1 << k)] + ds[j] + ds[k] + d[j][k];
last[i] = i - (1 << j) - (1 << k);
}
}
}
break;
}
}
}
int cur = (1 << n) - 1;
out.printLine(res[cur]);
while (cur != 0) {
out.print("0 ");
int dif = cur - last[cur];
for (int i = 0; i < n && dif != 0; i++) {
if (((dif >> i) & 1) != 0) {
out.print((i + 1) + " ");
dif -= (1 << i);
}
}
cur = last[cur];
}
out.printLine("0");
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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();
}
}
class IOUtils {
public static void readIntArrays(InputReader in, int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readInt();
}
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.util.*;
import static java.lang.System.out;
public final class LookingForOrder {
private static Map<Integer, Integer> es = new HashMap<Integer, Integer>();
private static void init() { for (int i = 0; i <= 24; i++) es.put(1 << i, i); }
private static int x, y;
private static int[] xs, ys;
private static int sqr(int i) { return i * i; }
private static int dist(int i, int j) {
return sqr(x - xs[i]) + sqr(y - ys[i]) +
sqr(xs[i] - xs[j]) + sqr(ys[i] - ys[j]) +
sqr(x - xs[j]) + sqr(y - ys[j]);
}
private static int n;
private static int[] tb, prevs;
private static int recur(int j) {
if (j == 0 || es.get(j) != null || tb[j] != 0) return tb[j];
int bl = j & -j;
int b = j ^ bl;
tb[j] = recur(bl) + recur(b);
prevs[j] = bl;
for (int i = es.get(bl) + 1; i <25; i++) {
if (((1 << i) & b) == 0) continue;
int k = bl | 1 << i;
int v = dist(es.get(bl), es.get(1 << i)) + recur(j ^ k);
if (v >= tb[j]) continue;
tb[j] = v;
prevs[j] = k;
}
return tb[j];
}
public static void main(String[] args) {
init();
Scanner s = new Scanner(System.in);
x = s.nextInt(); y = s.nextInt();
n = s.nextInt();
xs = new int[n]; ys = new int[n];
tb = new int[1 << n]; prevs = new int[1 << n];
for (int i = 0; i < n; i++) {
xs[i] = s.nextInt(); ys[i] = s.nextInt();
tb[1 << i] = sqr(x - xs[i]) + sqr(y - ys[i]) << 1;
}
int all = (1 << n) - 1;
out.println(recur(all));
StringBuilder sb = new StringBuilder();
int p = prevs[all];
int c = all;
while(p != 0 && p != c) {
if ((p ^ (p & -p)) == 0) sb.append("0 " + (es.get(p & -p) + 1) + " ");
else sb.append("0 " + (es.get(p & -p) + 1) + " " + (es.get(p ^ (p & -p)) + 1) + " ");
c = c ^ p;
p = prevs[c];
}
if ((c ^ (c & -c)) == 0) sb.append("0 " + (es.get(c & -c) + 1) + " 0");
else sb.append("0 " + (es.get(c & -c) + 1) + " " + (es.get(c ^ (c & -c)) + 1) + " 0");
out.println(sb);
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* Created by James on 1/29/2015.
*/
public class Driver {
private static int [][] distances, parents;
private static int [] distance, parent;
private static String [][] longNames;
private static String [] shortNames, answers;
private static int N;
public static void main(String [] args) throws IOException {
BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in));
String [] pieces = scanner.readLine().split("\\s+");
//totally had to steal the vast majority of this from http://codeforces.com/contest/8/submission/9745593
Point origin = new Point(Integer.parseInt(pieces[0]), Integer.parseInt(pieces[1]));
N = Integer.parseInt(scanner.readLine());
Point [] points = new Point[N + 1];
distances = new int[N + 1][N + 1];
parents = new int[N + 1][N + 1];
longNames = new String[N][N];
shortNames = new String[N];
for (int i = 0; i < N; ++i) {
pieces = scanner.readLine().split("\\s+");
points[i] = new Point(Integer.parseInt(pieces[0]), Integer.parseInt(pieces[1]));
}
points[N] = origin;
for (int i = 0; i <= N; ++i) {
if (i < N) {
shortNames[i] = (i + 1) + " ";
}
for (int j = 0; j <= N; ++j) {
if (i < N && j < N) {
longNames[i][j] = (i + 1) + " " + (j + 1) + " ";
}
distances[i][j] = 2 * points[i].distance(points[j]);
parents[i][j] = points[i].distance(points[N]) + points[i].distance(points[j]) + points[j].distance(points[N]);
}
}
distance = new int[1 << N];
parent = new int[1 << N];
answers = new String[1 << N];
Arrays.fill(distance, -1);
distance[0] = 0;
int result = rec((1 << N) - 1);
StringBuilder answer = new StringBuilder();
for (int i = distance.length - 1; parent[i] != i; i = parent[i]) {
answer.append("0 ");
answer.append(answers[i]);
}
answer.append("0");
System.out.println(result);
System.out.println(answer.toString());
}
private static int rec(int mask) {
if (distance[mask] != -1) {
return distance[mask];
}
int min = 0;
while (((1 << min) & mask) == 0) {
min++;
}
int newMask = mask & (~(1 << min));
distance[mask] = rec(newMask) + distances[min][N];
parent[mask] = newMask;
answers[mask] = shortNames[min];
for (int i = min + 1; i < N; i++) {
if (((1 << i) & mask) > 0) {
newMask = mask & (~(1 << i)) & (~(1 << min));
int temp = rec(newMask) + parents[i][min];
if (temp< distance[mask]) {
distance[mask] = temp;
parent[mask] = newMask;
answers[mask] = longNames[min][i];
}
}
}
return distance[mask];
}
private static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int distance(Point p) {
return (int)(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2));
}
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
int[] x;
int[] y;
int n;
int X, Y;
int[] d;
int[][] dist;
int sqr(int a) {
return a * a;
}
int dist(int X, int Y, int i) {
return sqr(X - x[i]) + sqr(Y - y[i]);
}
int[] dp;
byte[][] pred;
int rec(int mask) {
if (dp[mask] == -1) {
int res = 1 << 29;
boolean ok = false;
for (int i = 0; i < n; ++i)
if ((mask & (1 << i)) > 0) {
ok = true;
int mm = mask & ~(1 << i);
for (int j = i; j < n; j++)
if ((mask & (1 << j)) > 0) {
int nmask = mm & ~(1 << j);
int a = rec(nmask) + d[i] + d[j] + dist[i][j];
if (a < res) {
res = a;
pred[0][mask] = (byte) (i);
pred[1][mask] = (byte) (j);
}
}
break;
}
if (!ok)
res = 0;
dp[mask] = res;
}
return dp[mask];
}
void solve() throws IOException {
X = ni();
Y = ni();
n = ni();
// if (n > 5)
// return;
x = new int[n];
y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = ni();
y[i] = ni();
}
d = new int[n];
dist = new int[n][n];
for (int i = 0; i < n; ++i)
d[i] = dist(X, Y, i);
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; j++) {
dist[i][j] = dist(x[i], y[i], j);
}
pred = new byte[2][1 << n];
dp = new int[1 << n];
Arrays.fill(dp, -1);
out.println(rec((1 << n) - 1));
int a = (1 << n) - 1;
while (a > 0) {
if (pred[0][a] != pred[1][a])
out.print(0 + " " + (pred[0][a] + 1) + " " + (pred[1][a] + 1)
+ " ");
else
out.print(0 + " " + (pred[0][a] + 1) + " ");
int na = a & ~(1 << pred[0][a]);
na &= ~(1 << pred[1][a]);
a = na;
}
out.println(0);
}
public Solution() throws IOException {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
String ns() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int ni() throws IOException {
return Integer.valueOf(ns());
}
long nl() throws IOException {
return Long.valueOf(ns());
}
double nd() throws IOException {
return Double.valueOf(ns());
}
public static void main(String[] args) throws IOException,
InterruptedException {
Thread th = new Thread(null, new Solution(), "", 536870912);
th.start();
th.join();
}
@Override
public void run() {
try {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
| np | 8_C. Looking for Order | CODEFORCES |
/**
* DA-IICT
* Author : PARTH PATEL
*/
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class C8
{
public static long mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
static int n;
static int x,y;
static int[] xx;
static int[] yy;
static int[] dist;
static int[][] g;
static int[] dp;
public static int square(int x)
{
return abs(x*x);
}
static class Pair
{
int x,y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
}
public static void main(String[] args)
{
x=in.nextInt();
y=in.nextInt();
n=in.nextInt();
xx=new int[n];
yy=new int[n];
dp=new int[1<<n];
for(int i=0;i<n;i++)
{
xx[i]=in.nextInt();
yy[i]=in.nextInt();
}
dist=new int[n];
g=new int[n][n];
for(int i=0;i<n;i++)
{
dist[i]=square(abs(xx[i]-x))+square(abs(yy[i]-y));
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
g[i][j]=square(abs(xx[i]-xx[j]))+square(yy[i]-yy[j]);
//System.out.println("i "+i+" j "+j+" "+g[i][j]);
}
}
Arrays.fill(dp, Integer.MAX_VALUE/2);
dp[0]=0;
for(int i=0;i<(1<<n);i++)
{
//we have to find dp[i]
for(int j=0;j<n;j++)
{
if((i&(1<<j))>0) //not visited j
continue;
dp[i|(1<<j)]=min(dp[i|(1<<j)], dp[i]+2*dist[j]);
for(int k=j+1;k<n;k++)
{
if((i&(1<<k))>0)
continue;
dp[i|(1<<j)|(1<<k)]=min(dp[i|(1<<j)|(1<<k)], dp[i]+dist[j]+dist[k]+g[j][k]);
}
break;
}
}
out.println(dp[(1<<n)-1]);
Stack<Integer> stack=new Stack<>();
stack.push(0);
int i=(1<<n)-1;
while(i>0)
{
boolean tocontinue=false;
for(int a=0;a<n;a++)
{
if((i&(1<<a))==0)
continue;
if(dp[i]==(dp[i^(1<<a)]+2*dist[a]))
{
stack.push(a+1);
stack.push(0);
i-=(1<<a);
tocontinue=true;
}
if(tocontinue)
continue;
for(int b=a+1;b<n;b++)
{
if((i & (1<<b)) == 0) continue;
if(dp[i]==(dp[i^(1<<a)^(1<<b)]+dist[a]+dist[b]+g[a][b]))
{
i-=(1<<a);
i-=(1<<b);
stack.push(a+1);
stack.push(b+1);
stack.push(0);
tocontinue=true;
}
if(tocontinue)
break;
}
if(tocontinue)
break;
}
}
for(int ii : stack)
out.print(ii+" ");
out.close();
}
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class FastScanner2
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 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 nextString()
{
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 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 int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream)
{
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine()
{
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
fullLine = reader.readLine();
} catch (IOException e)
{
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
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 long nextLong()
{
return Long.parseLong(next());
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class LookingForOrder {
static int[] x, y;
static int[] dp;
static int n;
static int dist(int i, int j) {
return ((x[i] - x[j]) * (x[i] - x[j]))
+ ((y[i] - y[j]) * (y[i] - y[j]));
}
static int solve(int mask) {
if (mask == (1 << n) - 1)
return 0;
if (dp[mask] != -1)
return dp[mask];
int ans = Integer.MAX_VALUE;
int j = 0;
for (int i = 1; i < n; i++)
if ((mask & (1 << i)) == 0) {
if (j == 0) {
ans = Math
.min(ans, 2 * dist(0, i) + solve(mask | (1 << i)));
j = i;
} else
ans = Math.min(ans, dist(0, i) + dist(i, j) + dist(j, 0)
+ solve(mask | (1 << i) | (1 << j)));
}
return dp[mask] = ans;
}
static void prnt(int mask) {
if (mask == (1 << n) - 1)
return;
int j = 0;
for (int i = 1; i < n; i++)
if ((mask & (1 << i)) == 0) {
if (j == 0) {
j = i;
if (dp[mask] == 2 * dist(0, i) + solve(mask | (1 << i))) {
out.print(" " + i + " 0");
prnt(mask | (1 << i));
return;
}
} else if (dp[mask] == dist(0, i) + dist(i, j) + dist(j, 0)
+ solve(mask | (1 << i) | (1 << j))) {
out.print(" " + i + " " + j + " 0");
prnt(mask | (1 << i) | (1 << j));
return;
}
}
}
public static void main(String[] args) throws IOException {
sc = new StringTokenizer(br.readLine());
int a = nxtInt();
int b = nxtInt();
n = nxtInt() + 1;
x = new int[n];
y = new int[n];
dp = new int[1 << n];
Arrays.fill(dp, -1);
x[0] = a;
y[0] = b;
for (int i = 1; i < n; i++) {
x[i] = nxtInt();
y[i] = nxtInt();
}
out.println(solve(1 << 0));
out.print(0);
prnt(1 << 0);
out.println();
br.close();
out.close();
}
static BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
static PrintWriter out = new PrintWriter(System.out);
static StringTokenizer sc;
static String nxtTok() throws IOException {
while (!sc.hasMoreTokens())
sc = new StringTokenizer(br.readLine());
return sc.nextToken();
}
static int nxtInt() throws IOException {
return Integer.parseInt(nxtTok());
}
static long nxtLng() throws IOException {
return Long.parseLong(nxtTok());
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
public class LookingForOrder {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int bx = in.nextInt();
int by = in.nextInt();
in.nextLine();
int n = in.nextInt();
int[][] objects = new int[n][2];
for (int i = 0; i < n; i++) {
objects[i][0] = in.nextInt();
objects[i][1] = in.nextInt();
}
int[] cs = new int[n];
for (int i = 0; i < n; i++) {
cs[i] = 2 * time(objects[i], new int[] { bx, by });
}
int[][] cd = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
cd[j][i] = cd[i][j] = time(objects[i], new int[] { bx, by }) + time(objects[j], new int[] { bx, by }) + time(objects[i], objects[j]);
}
}
int maxMask = 1 << n;
int[] dp = new int[maxMask];
int[] path = new int[maxMask];
Arrays.fill(dp, -1);
dp[0] = 0;
for (int g = 1; g < maxMask; g++) {
int min = Integer.MAX_VALUE;
int minPath = 0;
int h = 31;
while ((g & (1 << h)) == 0)
h--;
h++;
int l = 0;
while ((g & (1 << l)) == 0)
l++;
if ((g & 1 << l) > 0) {
int oneleft = g ^ (1 << l);
int t = cs[l] + dp[oneleft];
if (t < min) {
min = t;
minPath = oneleft;
}
for (int j = l + 1; j < h; j++) {
if ((oneleft & 1 << j) > 0) {
int twoleft = oneleft ^ (1 << j);
t = cd[l][j] + dp[twoleft];
if (t < min) {
min = t;
minPath = twoleft;
}
}
}
}
dp[g] = min;
path[g] = minPath;
}
System.out.println(dp[maxMask - 1]);
int previous = maxMask - 1;
int pathElt = path[previous];
System.out.print("0 ");
while (previous > 0) {
int bits = previous - pathElt;
int h = 31;
while ((bits & (1 << h)) == 0)
h--;
int l = 0;
while ((bits & (1 << l)) == 0)
l++;
String el = h == l ? "" + (h + 1) : (h + 1) + " " + (l + 1);
System.out.print(el + " " + 0 + " ");
previous = pathElt;
pathElt = path[pathElt];
}
System.out.println();
}
static int time(int[] a, int[] b) {
int x = b[0] - a[0];
int y = b[1] - a[1];
return x * x + y * y;
}
}
| np | 8_C. Looking for Order | 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.awt.Point;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
Point bag = new Point(in.ni(), in.ni());
int n = in.ni();
Point[] arr = new Point[n];
for (int i = 0; i < n; ++i)
arr[i] = new Point(in.ni(), in.ni());
int[] dist = new int[n];
for (int i = 0; i < n; ++i) {
int dx = arr[i].x - bag.x;
int dy = arr[i].y - bag.y;
dist[i] = dx * dx + dy * dy;
}
int[][] d = new int[n][n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int dx = arr[i].x - arr[j].x;
int dy = arr[i].y - arr[j].y;
d[i][j] = dx * dx + dy * dy + dist[i] + dist[j];
}
}
int lim = (1 << n);
int[] dp = new int[lim];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
int[] p = new int[lim];
Arrays.fill(p, -1);
for (int mask = 0; mask < lim; ++mask) {
if (dp[mask] == Integer.MAX_VALUE)
continue;
int minBit = -1;
for (int bit = 0; bit < n; ++bit) {
if (checkBit(mask, bit))
continue;
if (minBit == -1 || (dist[minBit] > dist[bit]))
minBit = bit;
}
if (minBit == -1)
continue;
for (int bit = 0; bit < n; ++bit) {
if (checkBit(mask, bit))
continue;
int newMask = (mask | (1 << minBit) | (1 << bit));
if (dp[newMask] > dp[mask] + d[minBit][bit]) {
dp[newMask] = dp[mask] + d[minBit][bit];
p[newMask] = minBit * n + bit;
}
}
}
out.println(dp[lim - 1]);
int curMask = lim - 1;
while (p[curMask] != -1) {
out.print("0 ");
int first = p[curMask] / n;
int second = p[curMask] % n;
out.print(first + 1 + " ");
curMask ^= (1 << first);
if (first != second) {
out.print(second + 1 + " ");
curMask ^= (1 << second);
}
}
out.println(0);
}
boolean checkBit(int mask, int bitNumber) {
return (mask & (1 << bitNumber)) != 0;
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String n() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(n());
}
}
}
| np | 8_C. Looking for Order | 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.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class CF8C {
static int n;
static int[] mem;
static HashMap<Integer, String> map;
static int INF = (int) 1e9;
static StringBuilder sb;
public static void main(String[] args) throws IOException {
MyScanner sc = new MyScanner(System.in);
String s = sc.nextLine();
n = sc.nextInt();
mem = new int[1 << n];
Arrays.fill(mem, -1);
map = new HashMap<>();
map.put(0, s);
for (int i = 1; i <= n; i++) {
map.put(i, sc.nextLine());
}
int val = dp(0);
PrintWriter pw = new PrintWriter(System.out);
pw.println(val);
sb = new StringBuilder();
sb.append("0 ");
build(0);
pw.println(sb);
pw.flush();
}
// node == 0 -- > count 0 // state == 0 has 1 // state == 1 has 2
private static int dp(int msk) {
if (msk == (1 << n) - 1)
return 0;
if(mem[msk] != -1)
return mem[msk];
boolean foundFirst = false;
int val = (int)1e9;
int mark = -1;
for (int i = 1; i <= n; i++) {
if ((msk & 1 << (i - 1)) == 0){
if(!foundFirst){
foundFirst = true;
mark = i;
val = dist(0, mark)*2 + dp(msk | 1 << (mark - 1));
}else{
val = Math.min(val, dist(0, mark) + dist(mark, i) + dist(i, 0) + dp((msk|1 << (mark - 1))|1 << (i - 1)));
}
}
}
return mem[msk] = val;
}
private static int dist(int node, int i) {
String from = map.get(i);
String to = map.get(node);
String[] fromco = from.split(" ");
String[] toco = to.split(" ");
int xs = Integer.parseInt(fromco[0]);
int ys = Integer.parseInt(fromco[1]);
int xf = Integer.parseInt(toco[0]);
int yf = Integer.parseInt(toco[1]);
return (xs - xf) * (xs - xf) + (ys - yf) * (ys - yf);
}
private static void build(int msk) {
if (msk == (1 << n) - 1)
return;
boolean foundFirst = false;
int ans = dp(msk);
int mark = -1;
int val = (int)1e9;
for (int i = 1; i <= n; i++) {
if ((msk & 1 << (i - 1)) == 0){
if(!foundFirst){
foundFirst = true;
mark = i;
val = dist(0, mark)*2 + dp(msk | 1 << (mark - 1));
if(val == ans){
sb.append(mark + " 0 ");
build(msk | 1 << (mark - 1));
return;
}
}else{
val = dist(0, mark) + dist(mark, i) + dist(i, 0) + dp(msk|1 << (mark - 1)|1 << (i - 1));
if(val == ans){
sb.append(mark + " " + i + " 0 ");
build(msk|1 << (mark - 1)|1 << (i - 1));
return;
}
}
}
}
}
static class MyScanner {
StringTokenizer st;
BufferedReader br;
public MyScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public MyScanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
/**
* 9:50 ~
*
*/
public class Main {
public static int n, x, y;
public static int[] a,b;
public static int dp[], before[];
public static int dx[];
public static int d[][];
public static final int INF = 24 * 201 * 201;
public static void main(String[] argv) {
FastScanner scan = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
x = scan.nextInt();
y = scan.nextInt();
n = scan.nextInt();
a = new int[n+1];
b = new int[n+1];
dx = new int[n+1];
d = new int[n+1][n+1];
for(int i = 0; i < n; ++i){
a[i] = scan.nextInt();
b[i] = scan.nextInt();
}
for(int i = 0; i < n; ++i){
dx[i] = dist(i);
}
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
d[i][j] = dist(i,j);
}
}
dp = new int[1 << n];
before = new int[1 << n];
Arrays.fill(dp, INF);
dp[0] = 0;
for(int state = 0; state < (1<<n); state++){
//if(dp[state] == INF) continue;
for(int i = 0; i < n; ++i){
int ii = (1 << i);
if((state & ii) > 0){
if(dp[state - ii] == INF) continue;
int newdist = dp[state - ii] + dx[i] + dx[i];
if(dp[state] > newdist){
dp[state] = newdist;
before[state] = state - ii;
}
} else continue;
for(int j = i + 1; j < n; ++j){
if(i == j) continue;
int jj = (1 << j);
if((state & jj) > 0){
if(dp[state - ii - jj] == INF) continue;
int newdist = dp[state - ii - jj] + dx[i] + d[i][j] + dx[j];
if(dp[state] > newdist){
dp[state] = newdist;
before[state] = state - ii - jj;
}
}
}
break;
}
}
System.out.println(dp[(1<<n)-1]);
int state = (1<<n) - 1;
StringBuffer ret = new StringBuffer();
while(state > 0){
int nstate = before[state];
boolean find = false;
String made = "";
for(int i = 0; i < n; ++i){
if(((state & (1<<i)) > 0) && ((nstate & (1<<i)) == 0)){
find = true;
made = made + " " + (i + 1);
}
}
if(find){
made = made + " 0";
ret.append(made, 0, made.length());
}
state = nstate;
}
out.println("0" + ret.toString());
out.close();
}
public static int dist(int to){
return Math.abs(a[to] - x) * Math.abs(a[to] - x) + Math.abs(b[to] - y) * Math.abs(b[to] - y);
}
public static int dist(int from, int to){
return Math.abs(a[from]-a[to]) * Math.abs(a[from]-a[to]) + Math.abs(b[from]-b[to]) * Math.abs(b[from]-b[to]);
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream is) {
try {
br = new BufferedReader(new InputStreamReader(is));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
return null;
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.valueOf(next());
}
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.util.Scanner;
public class CF_8C {
public static void main(String[] args) {
// Hooray bitmasks! I'm good at these :)
Scanner in = new Scanner(System.in);
// Handbag coordinates..
int hb_x = in.nextInt(), hb_y = in.nextInt();
int n = in.nextInt();
int[] ox = new int[n];
int[] oy = new int[n];
// Dynamic programming: Also store a matrix of the time to reach one
// object from the other.
// This considers the handbag to be object 0
int[][] dt = new int[n][n];
int[] hbd = new int[n];
for (int i = 0; i < n; i++) {
ox[i] = in.nextInt();
oy[i] = in.nextInt();
hbd[i] = (ox[i] - hb_x) * (ox[i] - hb_x)
+ (oy[i] - hb_y) * (oy[i] - hb_y);
}
// Compute elapsed times...
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dt[i][j] = (ox[i] - ox[j]) * (ox[i] - ox[j])
+ (oy[i] - oy[j]) * (oy[i] - oy[j]);
}
}
// Fill up an array with the amount of time it takes to grab
// all objects with the specified bitmask.
int[] sofar = new int[1 << n];
int[] masks = new int[1 << n];
sofar[0] = 0;
for (int i = 1; i < (1 << n); i++) {
sofar[i] = -1;
}
for (int i = 0; i < (1 << n); i++) {
if (sofar[i] != -1) {
for (int maskbit = 0; maskbit < n; maskbit++) {
// Look for first object in bitmask to grab...
if (((1 << maskbit) & i) == 0) {
int iffirst = ((1 << maskbit) | i);
int fromold = sofar[i] + 2 * hbd[maskbit];
if (sofar[iffirst] == -1 || sofar[iffirst] > fromold) {
// A better way to get to position J was found, use it.
sofar[iffirst] = fromold;
masks[iffirst] = i;
}
// Find another thing while you're out...
for (int otherone = 0; otherone < n; otherone++) {
if (((1 << otherone) & iffirst) == 0) {
int iffollow = ((1 << otherone) | iffirst);
int fromi = sofar[i] + hbd[maskbit] + dt[maskbit][otherone] + hbd[otherone];
// Did we find a better way to get to iffollow state?
if (sofar[iffollow] == -1 || sofar[iffollow] > fromi) {
sofar[iffollow] = fromi;
masks[iffollow] = i;
}
}
}
break;
}
}
}
}
// After all this time, we have an answer.
// The minimum time will be the value of sofar at the very end,
// which will have the case of if all objects were picked up.
// Clever, no?
// The logic came from http://www.darrensun.com/codeforces-round-8/
// Wish I could claim it mine, but it is not so.
int end_val = (1 << n) - 1;
System.out.println(sofar[end_val]);
System.out.print(0);
while (end_val > 0) {
// Which objects were collected in the prvious trip?
int diff = end_val ^ masks[end_val];
int obj1 = -1, obj2 = -1;
for (int i = 0; i < n; i++) {
if (((1 << i) & diff) > 0) {
obj2 = obj1;
obj1 = i;
}
}
if (obj2 >= 0) {
// Two objects were collected this trip, output them both.
System.out.print(" " + (obj1 + 1) + " " + (obj2 + 1) + " 0");
} else {
// Only one object was collected here.
System.out.print(" " + (obj1 + 1) + " 0");
}
end_val = masks[end_val];
}
in.close();
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.util.*;
import java.awt.Polygon;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.*;
import java.util.Collection;
public class Solution {
/**
* @param args
* @throws IOException
*/
static StringTokenizer st;
static BufferedReader reader;
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
int xs = NextInt();
int ys = NextInt();
int n = NextInt();
int x[] = new int[n];
int y[] = new int[n];
int single[] = new int[n];
int pair[][] = new int[n][n];
for (int i = 0; i < n; ++i) {
x[i] = NextInt();
y[i] = NextInt();
}
for (int i = 0; i < n; ++i)
single[i] = 2 * dist(xs, ys, x[i], y[i]);
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
pair[i][j] = dist(xs, ys, x[i], y[i]) +
dist(x[i], y[i], x[j], y[j]) +
dist(x[j], y[j], xs, ys);
int dp[] = new int[1 << n];
int prev[] = new int[1 << n];
for (int mask = 0; mask < (1 << n); ++mask) {
int p = -1;
for (int i = 0; i < n; ++i)
if (((mask >> i) & 1) != 0) {
p = i;
break;
}
if (p == -1) continue;
dp[mask] = dp[mask ^ (1 << p)] + single[p];
prev[mask] = p;
for (int j = p + 1; j < n; ++j) {
if (((mask >> j) & 1) != 0) {
int res = pair[p][j] + dp[mask ^ (1 << p) ^ (1 << j)];
if (res < dp[mask]) {
dp[mask] = res;
prev[mask] = p + 100 * j;
}
}
}
}
int cur = (1 << n) - 1;
System.out.printf("%d\n0 ", dp[cur]);
while(cur != 0) {
if (prev[cur] < 100) {
System.out.printf("%d %d ", prev[cur] + 1, 0);
cur ^= (1 << prev[cur]);
} else {
int i = prev[cur] / 100;
int j = prev[cur] % 100;
System.out.printf("%d %d %d ", i + 1, j + 1, 0);
cur = cur ^ (1 << i) ^ (1 << j);
}
}
}
static int dist(int x0, int y0, int x1, int y1) {
return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);
}
static int NextInt() throws NumberFormatException, IOException {
return Integer.parseInt(NextToken());
}
static String NextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(reader.readLine());
}
return st.nextToken();
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.util.*;
import java.io.*;
public class Main {
static final int MAXN = 24;
int[] x = new int[MAXN];
int[] y = new int[MAXN];
int[][] dist = new int[MAXN][MAXN];
int[] single = new int[MAXN];
int sqr(int x) { return x * x; }
void run(int nT) {
int xs = cin.nextInt();
int ys = cin.nextInt();
int n = cin.nextInt();
for (int i = 0; i < n; ++i) {
x[i] = cin.nextInt();
y[i] = cin.nextInt();
}
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
dist[i][j] = sqr(x[i] - xs) + sqr(y[i] - ys)
+ sqr(x[i] - x[j]) + sqr(y[i] - y[j]) + sqr(x[j] - xs) + sqr(y[j] - ys);
}
}
for (int i = 0; i < n; ++i) {
single[i] = (sqr(x[i] - xs) + sqr(y[i] - ys)) * 2;
}
int[] dp = new int[1 << n];
int[] pre = new int[1 << n];
int tot = 1 << n;
for (int s = 1; s < tot; ++s) {
int i;
for (i = 0; i < n; ++i) {
if ((s & (1 << i)) != 0) break;
}
dp[s] = dp[s^(1<<i)] + single[i];
pre[s] = i + 1;
for (int j = i + 1; j < n; ++j) {
if ((s & (1 << j)) != 0) {
int cur = dp[s^(1 << i) ^(1<<j)] + dist[i][j];
if (cur < dp[s]) {
dp[s] = cur;
pre[s] = (i + 1) * 100 + (j + 1);
}
}
}
}
out.println(dp[tot - 1]);
int now = tot - 1;
out.print("0");
while (now > 0) {
int what = pre[now];
int px = what % 100 - 1;
int py = what / 100 - 1;
if (px >= 0) {
out.print(" ");
out.print(px + 1);
now ^= 1 << px;
}
if (py >= 0) {
out.print(" ");
out.print(py + 1);
now ^= 1 << py;
}
out.print(" ");
out.print("0");
}
out.println("");
}
public static void main(String[] argv) {
Main solved = new Main();
int T = 1;
// T = solved.cin.nextInt();
for (int nT = 1; nT <= T; ++nT) {
solved.run(nT);
}
solved.out.close();
}
InputReader cin = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
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());
}
} | np | 8_C. Looking for Order | CODEFORCES |
import java.util.*;
public class Main {
static Scanner cin = new Scanner(System.in);
private int xs, ys, n;
private int[] x, y;
public static void main(String[] args) throws Exception {
new Main().run();
}
class Item implements Comparable<Item> {
int w, h, idx;
Item(int w, int h, int idx) {
this.w = w;
this.h = h;
this.idx = idx;
}
@Override
public int compareTo(Item o) {
if (this.w == o.w) {
return this.h - o.h;
}
return this.w - o.w;
}
}
private void run() throws Exception {
xs = cin.nextInt();
ys = cin.nextInt();
n = cin.nextInt();
x = new int[n + 1];
y = new int[n + 1];
for (int i = 0; i < n; i++) {
x[i] = cin.nextInt();
y[i] = cin.nextInt();
}
int[] res = new int[1 << n];
Arrays.fill(res, Integer.MAX_VALUE);
int[] ds = new int[n];
for (int i = 0; i < n; i++) {
ds[i] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys);
}
int[][] d = new int[n + 1][n + 1];
int[] tr = new int[1 << n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
d[i][j] = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
}
}
//----------------------
res[0] = 0;
for (int i = 1; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
if (((i >> j) & 1) != 0) {
if (res[i - (1 << j)] + 2 * ds[j] < res[i]) {
res[i] = res[i - (1 << j)] + 2 * ds[j];
tr[i] = i - (1 << j);
}
for (int k = j + 1; k < n; k++) {
if (((i >> k) & 1) != 0) {
if (res[i - (1 << j) - (1 << k)] + ds[k] + ds[j] + d[k][j] < res[i]) {
res[i] = res[i - (1 << j) - (1 << k)] + ds[k] + ds[j] + d[k][j];
tr[i] = i - (1 << j) - (1 << k);
}
}
}
break;
}
}
}
System.out.println(res[(1 << n) - 1]);
int now = (1 << n) - 1;
while (now != 0) {
System.out.print("0 ");
int dif = now - tr[now];
for (int i = 0; i < n && dif != 0; i++) {
if (((dif >> i) & 1) != 0) {
System.out.print((i + 1) + " ");
dif -= (1 << i);
}
}
now=tr[now];
}
System.out.print("0");
}
}
| np | 8_C. Looking for Order | CODEFORCES |
import java.util.*;
public class cf16e {
static int n;
static double[][] prob;
static double[] memo;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
prob = new double[n][n];
memo = new double[1<<n];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
prob[i][j] = in.nextDouble();
memo[(1<<n)-1] = 1;
for(int k=(1<<n)-1; k>0; k--) {
int numWays = Integer.bitCount(k);
numWays = (numWays*(numWays-1))/2;
for(int first = 0; first < n; first++) {
if(!isSet(k,first)) continue;
for(int second = first+1; second < n; second++) {
if(!isSet(k,second)) continue;
memo[reset(k,first)] += prob[second][first]*memo[k]/numWays;
memo[reset(k,second)] += prob[first][second]*memo[k]/numWays;
}
}
}
for(int i=0; i<n; i++)
System.out.printf("%.6f ", memo[set(0,i)]);
System.out.println();
}
static boolean isSet(int x, int p) {
return (x&(1<<p)) != 0;
}
static int set(int x, int p) {
return x|(1<<p);
}
static int reset(int x, int p) {
return x&~(1<<p);
}
static boolean isDone(int x) {
return Integer.bitCount(x)==n-1;
}
}
| np | 16_E. Fish | CODEFORCES |
/**
* Created by IntelliJ IDEA.
* User: Taras_Brzezinsky
* Date: 8/14/11
* Time: 9:53 PM
* To change this template use File | Settings | File Templates.
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.FileReader;
import java.util.StringTokenizer;
import java.io.IOException;
import java.util.Arrays;
public class Fish extends Thread {
public Fish() {
this.input = new BufferedReader(new InputStreamReader(System.in));
this.output = new PrintWriter(System.out);
this.setPriority(Thread.MAX_PRIORITY);
}
static int getOnes(int mask) {
int result = 0;
while (mask != 0) {
mask &= mask - 1;
++result;
}
return result;
}
private void solve() throws Throwable {
int n = nextInt();
double[][] a = new double[n][n];
double[] dp = new double[(1 << n)];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
a[i][j] = nextDouble();
}
}
int limit = (1 << n) - 1;
//dp[mask] = probability of current subset (mask) to remain in the end
dp[limit] = 1.0;
for (int mask = limit; mask > 0; --mask) {
int cardinality = getOnes(mask);
if (cardinality < 2) {
continue;
}
int probability = cardinality * (cardinality - 1) / 2;
for (int first = 0; first < n; ++first) {
if ((mask & powers[first]) != 0) {
for (int second = first + 1; second < n; ++second) {
if ((mask & powers[second]) != 0) {
dp[mask - powers[first]] += dp[mask] * a[second][first] / probability;
dp[mask - powers[second]] += dp[mask] * a[first][second] / probability;
}
}
}
}
}
for (int i = 0; i < n; ++i) {
output.printf("%.10f ", dp[powers[i]]);
}
}
public void run() {
try {
solve();
} catch (Throwable e) {
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(666);
} finally {
output.flush();
output.close();
}
}
public static void main(String[] args) {
new Fish().start();
}
private String nextToken() throws IOException {
while (tokens == null || !tokens.hasMoreTokens()) {
tokens = new StringTokenizer(input.readLine());
}
return tokens.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static final int powers[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144};
private BufferedReader input;
private PrintWriter output;
private StringTokenizer tokens = null;
}
| np | 16_E. Fish | CODEFORCES |
import java.util.*;
import java.text.*;
import java.math.*;
public class Main{
static double EPS=1e-10;
static double PI=Math.acos(-1.0);
static double p[][]=new double[25][25];
static double f[]=new double[1<<20];
static int n;
public static void PR(String s){
System.out.print(s);
}
public static void PR(double s)
{
java.text.DecimalFormat d=new java.text.DecimalFormat("#.0000000");
System.out.print(d.format(s));
}
public static void DP()
{
int i,j,k,cnt;
for(i=0;i<(1<<n);i++) f[i]=0;
f[(1<<n)-1]=1;
for(k=(1<<n)-1;k>=0;k--)
{
cnt=0;
for(i=0;i<n;i++) if((k&(1<<i))!=0) cnt++;
for(i=0;i<n;i++) if((k&(1<<i))!=0)
{
for(j=0;j<n;j++) if(i!=j&&(k&(1<<j))!=0)
{
f[k^(1<<j)]+=f[k]*p[i][j]/((cnt-1)*cnt/2);
}
}
}
}
public static void main(String[] args){
Scanner S=new Scanner(System.in);
while(S.hasNext())
{
n=S.nextInt();
int i,j;
for(i=0;i<n;i++) for(j=0;j<n;j++) p[i][j]=S.nextDouble();
DP();
for(i=0;i<n;i++)
{
if(i!=0) PR(" ");
PR(f[1<<i]);
}
PR("\n");
}
}
} | np | 16_E. Fish | CODEFORCES |
import java.util.*;
import java.text.*;
import java.math.*;
public class Main{
static double EPS=1e-10;
static double PI=Math.acos(-1.0);
static double p[][]=new double[25][25];
static double f[]=new double[1<<20];
static int n;
public static void PR(String s){
System.out.print(s);
}
public static void PR(double s)
{
java.text.DecimalFormat d=new java.text.DecimalFormat("#.0000000");
System.out.print(d.format(s));
}
public static void DP()
{
int i,j,k,cnt;
for(i=0;i<(1<<n);i++) f[i]=0;
f[(1<<n)-1]=1;
for(k=(1<<n)-1;k>=0;k--)
{
cnt=0;
for(i=0;i<n;i++) if((k&(1<<i))!=0) cnt++;
for(i=0;i<n;i++) if((k&(1<<i))!=0)
{
for(j=0;j<n;j++) if(i!=j&&(k&(1<<j))!=0)
{
f[k^(1<<j)]+=f[k]*p[i][j]/((cnt-1)*cnt/2);
}
}
}
}
public static void main(String[] args){
Scanner S=new Scanner(System.in);
while(S.hasNext())
{
n=S.nextInt();
int i,j;
for(i=0;i<n;i++) for(j=0;j<n;j++) p[i][j]=S.nextDouble();
DP();
for(i=0;i<n;i++)
{
if(i!=0) PR(" ");
PR(f[1<<i]);
}
PR("\n");
}
}
}
| np | 16_E. Fish | CODEFORCES |
import java.text.DecimalFormat;
import java.util.Scanner;
/**
*
* @author Alvaro
*/
public class Main{
public static int n;
public static double [] dp;
public static double [][] p;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
dp = new double[1<<n];
p = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
p[i][j]= in.nextDouble();
}
}
for (int i = 0; i <(1<<n); i++) {
dp[i] = -1;
}
dp[(1<<n)-1]=1;
DecimalFormat d = new DecimalFormat("0.000000");
System.out.print(d.format(f(1<<0)));
for (int i = 1; i < n; i++) {
System.out.print(" "+d.format(f(1<<i)));
}
}
public static double f(int mask) {
if(dp[mask]>-0.5) return dp[mask];
dp[mask] = 0;
int vivos = 1;
for (int i = 0; i < n; i++)
if((mask>>i)%2==1) vivos++;
double pares = (vivos*(vivos-1))/2;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if((mask&(1<<i))!=0&&(mask&(1<<j))==0){
dp[mask]+=f(mask|(1<<j))*p[i][j]/pares;
}
}
}
return dp[mask];
}
}
| np | 16_E. Fish | CODEFORCES |
import java.util.HashMap;
import java.util.Scanner;
import javax.swing.text.html.HTMLDocument.Iterator;
public class Main
{
public static double p[];
static double s[];
static double m[];
static int n;
public static double a[][];
public static int index=0;
public static boolean vis[];
public static HashMap<Integer, Integer> permMap;
public static void main(String g[])
{
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
m = new double[(1<<n) +1];
vis = new boolean[(1<<n) +1];
a = new double[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
//System.out.println("read"+(c++));
a[i][j] = sc.nextDouble();
}
}
s = new double[1<<n]; // 2^n
int perm=0;
m[0]=1;
p();
// System.out.println("answers : ");
int c=((1<<n)-1);
for(int i=0;i<n;i++)
{
perm = c-(1<<i);
// System.out.printf("permutation = %x, prob = %f\n",perm,m[perm]);
System.out.printf("%.6f ",m[perm]);
}
// getPerms(0);
// p(perm);
// double res[] = new double[n];
// for(int i=0;i<n;i++)
{
// for(int j=0;j<n;j++)
// if((i&(i-1))!=0)
// continue;
// res[i] =
// p(perm,n);
// System.out.println(m[i][j]);
}
// int cur=(1<<n)-1;
//
//int i=0;
// for(i=0;i<n;i++)
// {
// int val=(cur-(1<<i));
// int L = n-1;
// System.out.printf("running for %x .... P = %f\n",val,getProb(val,L));
//
// }
//getP((1<<n)-1));
// for(int i=0;i<m.length;i++)
// {
// System.out.println(m[perm]);
// }
}
public static void p()
{
for(int k=0;k<(1<<n);k++)
{
int perm=k;
for(int j=0;j<n;j++)
{
if(bitTest(perm, j))
{
continue;
}
int newPerm=perm|(1<<j); // j got eaten
for(int i=0;i<n;i++)
{
if( (i==j) || bitTest(newPerm,i))
{
continue;
}
// i eats j
int L=n-countO(perm);
if(L<2)
{
continue;
}
//System.out.println("L="+L);
double pm = 2.0/(L*(L-1));
// System.out.printf("Left with %d,%d eats %d \n",L,i,j);
m[newPerm]+=m[perm]*a[i][j]*pm;
// System.out.printf("p(%x)= %f \n",newPerm,m[newPerm]);
//System.out.printf("p(%x)= %f \n",newPerm2,m[newPerm2]);
}
// System.out.printf("p(%x)= %f \n",newPerm,m[newPerm]);
// System.out.println("here-------------------->");
}
}
}
private static int countO(int marked) {
// TODO Auto-generated method stub
int count=0;
for(int i=0;i<n;i++)
{
int test = (1<<i);
if((test&marked)==(test))
count++;
}
return count;
}
private static boolean bitTest(int perm, int i) {
// TODO Auto-generated method stub
int test = (1<<i);
if((test&perm)==test)
return true;
return false;
}
private static int bitSet(int perm, int i) {
// TODO Auto-generated method stub
int np = (1<<i);
return np;
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.*;
public class Main
{
static double arr[][];
public static void main(String[] args)
{
try
{
Parserdoubt pd=new Parserdoubt(System.in);
PrintWriter pw=new PrintWriter(System.out);
int fishes=pd.nextInt();
arr=new double[fishes][fishes];
for(int i=0;i<fishes;i++)
for(int j=0;j<fishes;j++)
arr[i][j]=Double.parseDouble(pd.nextString());
double dp[]=new double[(1<<fishes)];
dp[dp.length-1]=1.0;
for(int c=dp.length-1;c>=0;c--)
{
if((c&(c-1))==0)
continue;
for(int i=0;i<fishes;i++)
for(int j=i+1;j<fishes;j++)
{
if(((1<<i)&c)!=0&&((1<<j)&c)!=0)
{
dp[c&~(1<<j)]+=arr[i][j]*dp[c];
dp[c&~(1<<i)]+=arr[j][i]*dp[c];
}
}
}
double s=0.0;
for(int i=0;i<fishes;i++)
s+=dp[1<<i];
for(int i=0;i<fishes;i++)
dp[1<<i]/=s;
int i=0;
for(i=0;i<fishes-1;i++)
pw.printf("%.6f ",dp[1<<i]);
pw.printf("%.6f\n",dp[1<<i]);
pw.close();
}
catch(Exception e)
{}
}
}
class Parserdoubt
{
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parserdoubt(InputStream in)
{
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws Exception
{
StringBuffer sb=new StringBuffer("");
byte c = read();
while (c <= ' ') c = read();
do
{
sb.append((char)c);
c=read();
}while(c>' ');
return sb.toString();
}
public char nextChar() throws Exception
{
byte c=read();
while(c<=' ') c= read();
return (char)c;
}
public int nextInt() throws Exception
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
public long nextLong() throws Exception
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
| np | 16_E. Fish | CODEFORCES |
/**
* Created by IntelliJ IDEA.
* User: Taras_Brzezinsky
* Date: 8/14/11
* Time: 9:53 PM
* To change this template use File | Settings | File Templates.
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.FileReader;
import java.util.StringTokenizer;
import java.io.IOException;
import java.util.Arrays;
public class Fish extends Thread {
public Fish() {
this.input = new BufferedReader(new InputStreamReader(System.in));
this.output = new PrintWriter(System.out);
this.setPriority(Thread.MAX_PRIORITY);
}
static int getOnes(int mask) {
int result = 0;
while (mask != 0) {
mask &= mask - 1;
++result;
}
return result;
}
private void solve() throws Throwable {
int n = nextInt();
double[][] a = new double[n][n];
double[] dp = new double[(1 << n)];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
a[i][j] = nextDouble();
}
}
int limit = (1 << n) - 1;
//dp[mask] = probability of current subset (mask) to remain in the end
dp[limit] = 1.0;
for (int mask = limit; mask > 0; --mask) {
int cardinality = getOnes(mask);
int probability = cardinality * (cardinality - 1) / 2;
for (int first = 0; first < n; ++first) {
if ((mask & powers[first]) != 0) {
for (int second = first + 1; second < n; ++second) {
if ((mask & powers[second]) != 0) {
dp[mask - powers[first]] += dp[mask] * a[second][first] / probability;
dp[mask - powers[second]] += dp[mask] * a[first][second] / probability;
}
}
}
}
}
for (int i = 0; i < n; ++i) {
output.printf("%.10f ", dp[powers[i]]);
}
}
public void run() {
try {
solve();
} catch (Throwable e) {
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(666);
} finally {
output.flush();
output.close();
}
}
public static void main(String[] args) {
new Fish().start();
}
private String nextToken() throws IOException {
while (tokens == null || !tokens.hasMoreTokens()) {
tokens = new StringTokenizer(input.readLine());
}
return tokens.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static final int powers[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144};
private BufferedReader input;
private PrintWriter output;
private StringTokenizer tokens = null;
}
| np | 16_E. Fish | CODEFORCES |
/**
* Created by IntelliJ IDEA.
* User: aircube
* Date: 11.01.11
* Time: 4:14
* To change this template use File | Settings | File Templates.
*/
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.Exchanger;
public class Template {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
public static void main(String[] args) throws IOException {
new Template().run();
}
void run() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
st = null;
out = new PrintWriter(System.out);
solve();
br.close();
out.close();
}
double dm[];
double a[][];
boolean fil[];
int p[];
int n;
// x & (x - 1)
// 10
//
void solve() throws IOException {
n = nextInt();
a = new double[n][n];
for(int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
a[i][j] = nextDouble();
}
dm = new double[1 << n];
dm[(1 << n) - 1] = 1;
for(int mask = (1 << n) - 1; mask >= 1; --mask) {
int c = Integer.bitCount(mask);
if (c == 1) continue ;
double p = 2.0 / (double)(c - 1) / (double) c;
for(int i = 0; i < n; ++i) {
for (int j =0 ; j < n; ++j) {
if (i != j && (mask & (1 << i)) > 0 && (mask & (1 << j)) > 0) {
dm[mask ^ (1 << j)] += a[i][j] * dm[mask] * p;
}
}
}
}
for(int i = 0; i < n; ++i) {
out.print(dm[1 << i] + " ");
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
} | np | 16_E. Fish | CODEFORCES |
import java.util.*;
public class E
{
public static void main(String[] args)
{
new E(new Scanner(System.in));
}
public E(Scanner in)
{
int N = in.nextInt();
double[][] g = new double[N][N];
for (int j=0; j<N; j++)
for (int i=0; i<N; i++)
g[i][j] = in.nextDouble();
double[] memo = new double[1<<N];
memo[(1<<N)-1] = 1.0;
for (int m=(1<<N)-1; m>0; m--)
{
int cnt = 0;
for (int i=0; i<N; i++)
{
int m1 = 1 << i;
if ((m1&m) > 0)
cnt++;
}
int sum = (cnt*(cnt-1))/2;
for (int i=0; i<N; i++)
{
int m1 = 1 << i;
if ((m1&m) == 0) continue;
for (int j=i+1; j<N; j++)
{
int m2 = 1 << j;
if ((m2&m) == 0) continue;
memo[m-m1] += (g[i][j]*memo[m])/sum;
memo[m-m2] += (g[j][i]*memo[m])/sum;
}
}
}
StringBuilder sb = new StringBuilder();
for (int i=0; i<N; i++)
{
double res = memo[1<<i];
sb.append(String.format("%.8f", res));
sb.append(' ');
}
System.out.println(sb.toString().trim());
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
import java.util.regex.*;
/**
*
* @author jon
*/
public class Fish {
double memo[] = new double[(1<<18)];
int N, FULL;
double prob[][] = new double[18][18];
Fish() {
Scanner in = new Scanner(System.in);
Arrays.fill(memo, -1);
N = in.nextInt();
FULL = (1<<N) - 1;
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
prob[i][j] = in.nextDouble();
}
}
for(int i = 0; i < N; i++) {
System.out.printf("%.6f ", go((1<<i)));
}
System.out.println();
}
public double go(int mask) {
if(mask == FULL) return 1.0;
if(memo[mask] >= 0) return memo[mask];
double ret = 0;
double mult = Integer.bitCount(mask) + 1;
mult *= (mult-1)/2.0;
for(int i = 0; i < N; i++) {
if(((1<<i) & mask) != 0) {
for(int j = 0; j < N; j++) {
if(((1<<j) & mask) == 0) {
ret += go(mask | (1<<j)) * prob[i][j];
}
}
}
}
ret /= mult;
memo[mask] = ret;
return ret;
}
public static void main(String args[]) {
new Fish();
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A {
static double[][] a;
static int N;
static double[][] memo;
static double[] dp(int alive)
{
int count = Integer.bitCount(alive);
if(count == 1)
{
double[] ret = new double[N];
for(int i = 0; i < N; ++i)
if((alive & (1<<i)) != 0)
{
ret[i] = 1;
break;
}
return memo[alive] = ret;
}
if(memo[alive] != null)
return memo[alive];
double[] ret = new double[N];
for(int j = 0; j < N; ++j)
if((alive & (1<<j)) != 0)
{
double[] nxt = dp(alive & ~(1<<j));
for(int i = 0; i < N; ++i)
ret[i] += die[j][alive] * nxt[i];
}
return memo[alive] = ret;
}
static double[][] die;
static void f()
{
die = new double[N][1<<N];
for(int i = 0; i < N; ++i)
for(int j = 0; j < 1<<N; ++j)
{
int count = Integer.bitCount(j);
if(count <= 1)
continue;
double prop = 1.0 / (count * (count - 1) >> 1);
for(int k = 0; k < N; ++k)
if((j & (1<<k)) != 0)
die[i][j] += prop * a[k][i];
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
N = sc.nextInt();
a = new double[N][N];
for(int i = 0; i < N; ++i)
for(int j = 0; j < N; ++j)
a[i][j] = sc.nextDouble();
memo = new double[1<<N][];
f();
double[] ret = dp((1<<N) - 1);
for(int i = 0; i < N - 1; ++i)
out.printf("%.8f ",ret[i]);
out.printf("%.8f\n", ret[N-1]);
out.flush();
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready();}
}
} | np | 16_E. Fish | CODEFORCES |
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author AlexFetisov
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
}
class TaskE {
private int n;
private double[] dp;
private double[][] p;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
p = new double[n][n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
p[i][j] = in.nextDouble();
}
}
dp = new double[1 << n];
Arrays.fill(dp, -1);
for (int i = 0; i < n; ++i) {
out.printf("%.6f ", rec(1 << i));
}
out.println();
}
private double rec(int mask) {
if (mask == (1 << n) - 1) return 1;
if (dp[mask] > -0.5) return dp[mask];
double res = 0;
int nn = Integer.bitCount(mask);
int total = (nn * (nn + 1)) / 2;
for (int i = 0; i < n; ++i) if (BitUtils.checkBit(mask, i)) for (int j = 0; j < n; ++j) if (!BitUtils.checkBit(mask, j)) {
res += rec(BitUtils.setBit(mask, j)) * p[i][j];
}
res /= total;
dp[mask] = res;
return res;
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine().trim();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public double nextDouble() {
return Double.parseDouble(nextString());
}
}
class BitUtils {
public static boolean checkBit(int mask, int bit) {
return (mask & (1 << bit)) > 0;
}
public static int setBit(int mask, int bit) {
return (mask | (1 << bit));
}
}
| np | 16_E. Fish | CODEFORCES |
import java.util.*;
import java.io.*;
public class e{
int n;
double f[];
double a[][];
public void run(){
Locale.setDefault(Locale.US);
Scanner in = new Scanner(System.in);
n = in.nextInt();
a = new double[n][n];
for(int i=0;i<n;i++) for(int j=0;j<n;j++) a[i][j] = in.nextDouble();
f = new double[1<<n];
for(int i=0;i<1<<n;i++) f[i] = -1;
f[(1<<n)-1] = 1.0;
for(int i=0;i<n;i++) System.out.print(doIt(1<<i) + " ");
}
private double doIt(int mask){
if (f[mask] >=0) return f[mask];
f[mask] = 0;
double k = getBits(mask);
k*=(k-1)/2.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)
f[mask]+=doIt(mask|(1<<j))*a[i][j]/k;
return f[mask];
}
private int getBits(int x){
int cnt = 0;
while(x > 0){
x&=(x-1);
cnt++;
}
return cnt+1;
}
public static void main(String args[]){
new e().run();
}
} | np | 16_E. Fish | CODEFORCES |
import java.util.*;
import java.io.*;
public class Fish
{
static double[][] prob= new double[18][18];
static double[][] dp= new double[2][1<<18];
static ArrayList<Integer>[] adj= new ArrayList[1<<18];
static int n;
public static void init()
{
for(int i=0; i<(1<<18); i++)
adj[i]= new ArrayList<Integer>();
for(int i=0; i<(1<<18); i++)
for(int j=0; j<18; j++)
if(((i>>j)&1)==1)
adj[i].add(i^(1<<j));
}
public static double value(int cur, int next)
{
int i=0;
int z= cur^next;
double p=0;
int alive= Integer.bitCount(cur);
while((z>>i)!=1)
i++;
for(int k=0; k<n; k++)
if( ((next>>k)&1)==1)
p+= prob[k][i];
p/= alive*(alive-1)/2;
return p;
}
public static void main(String[] args)throws Exception
{
Scanner scan= new Scanner(System.in);
init();
n=scan.nextInt();
int m= (1<<n)-1;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
prob[i][j]= scan.nextDouble();
dp[0][m]=1;
for(int i=0; i<(n-1); i++)
{
for(int j=0; j<=m; j++)
if(dp[i%2][j]>0)
for(Integer next: adj[j])
dp[(i+1)%2][next]+= value(j,next)*dp[i%2][j];
Arrays.fill(dp[i%2],0);
}
for(int i=0; i<n; i++)
{
if(i!=0)
System.out.print(" ");
System.out.printf("%.6f",dp[(n-1)%2][1<<i]);
}
}
}
| np | 16_E. Fish | CODEFORCES |
import java.util.*;
import java.io.*;
public class e {
private void main() {
Scanner stdin = new Scanner(System.in);
PrintStream stdout = System.out;
int n = stdin.nextInt();
double[][] p = new double[n][n];
double[][] ans = new double[1<<n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
p[i][j] = stdin.nextDouble();
double[] dieChance = new double[n];
ArrayList<Integer> sel = new ArrayList<Integer>();
for(int i = 0; i < (1<<n); i++) {
sel.clear();
for(int k = 0; k < n; k++) {
if((i & (1<<k)) != 0)
sel.add(k);
}
if(sel.size() == 1) {
ans[i][sel.get(0)] = 0;
continue;
}
for(int j : sel)
dieChance[j] = 0;
for(int j : sel)
for(int k : sel)
dieChance[k] += p[j][k];
for(int j : sel)
dieChance[j] /= sel.size()*(sel.size()-1)/2;
for(int j : sel) {
ans[i][j] = dieChance[j];
for(int k : sel)
ans[i][j] += dieChance[k] * ans[i-(1<<k)][j];
}
}
for(double d : ans[(1<<n)-1])
stdout.format("%f ", 1-d);
stdout.println();
}
public static void main(String[] args) {
new e().main();
}
}
| np | 16_E. Fish | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
public class P16E {
int n;
double [][]prob;
double []dp;
public P16E() {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
prob = new double [n][n];
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
prob[i][j] = sc.nextDouble();
}
}
sc.close();
dp = new double[(1<<n)];
Arrays.fill(dp, -1);
for (int i = 0; i < n; i++) {
int a = 1 << i;
System.out.print(compute(a) + " ");
}
}
double compute (int mask){
if (mask == (1<<n) - 1){
return 1;
}
if (dp[mask] != -1){
return dp[mask];
}
double result = 0;
int c = 0;
for (int i = 0; i < n; i++) {
int a = 1 << i;
if ((a & mask) != 0) {
c++;
for (int j = 0; j < n; j++) {
int b = 1 << j;
if ((b & mask) == 0) {
result += (prob[i][j] * compute(mask | b));
}
}
}
}
int nC2 = (c + 1) * c / 2;
dp[mask] = result / nC2;
return dp[mask];
}
public static void main (String []args){
new P16E();
}
}
| np | 16_E. Fish | CODEFORCES |
import java.util.*;
import java.text.*;
import java.math.*;
public class Main{
static double EPS=1e-10;
static double PI=Math.acos(-1.0);
static double p[][]=new double[25][25];
static double f[]=new double[1<<20];
static int n;
public static void PR(String s){
System.out.print(s);
}
public static void PR(double s)
{
java.text.DecimalFormat d=new java.text.DecimalFormat("#.0000000");
System.out.print(d.format(s));
}
public static void DP()
{
int i,j,k,cnt;
for(i=0;i<(1<<n);i++) f[i]=0;
f[(1<<n)-1]=1;
for(k=(1<<n)-1;k>=0;k--)
{
cnt=0;
for(i=0;i<n;i++) if((k&(1<<i))!=0) cnt++;
for(i=0;i<n;i++) if((k&(1<<i))!=0)
{
for(j=0;j<n;j++) if(i!=j&&(k&(1<<j))!=0)
{
f[k^(1<<j)]+=f[k]*p[i][j]/((cnt-1)*cnt/2);
}
}
}
}
public static void main(String[] args){
Scanner S=new Scanner(System.in);
while(S.hasNext())
{
n=S.nextInt();
int i,j;
for(i=0;i<n;i++) for(j=0;j<n;j++) p[i][j]=S.nextDouble();
DP();
for(i=0;i<n;i++)
{
if(i!=0) PR(" ");
PR(f[1<<i]);
}
PR("\n");
}
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
//System.setIn(new FileInputStream("1"));
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = nextInt();
double[][] a = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = nextDouble();
}
}
double[] dp = new double[1 << n];
dp[(1 << n) - 1] = 1.0;
for (int mask = (1 << n) - 2; mask > 0; mask--) {
int count = Integer.bitCount(mask);
double pPair = 2.0 / (count * (count + 1));
double ans = 0.0;
for (int i = 0; i < n; i++) {
if (((1 << i) & mask) == 0) {
double p = dp[(1 << i) | mask];
double s = 0.0;
for (int j = 0; j < n; j++) {
if (((1 << j) & mask) != 0)
s += a[j][i];
}
ans += pPair * p * s;
}
}
dp[mask] = ans;
}
for (int i = 0; i < n; i++) {
out.print(dp[1 << i]);
out.print(' ');
}
in.close();
out.close();
}
static StringTokenizer st;
static BufferedReader in;
static PrintWriter out;
static int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextString());
}
static String nextString() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
}
| np | 16_E. Fish | CODEFORCES |
import java.util.*;
public class Main {
public static void main(String [] args){
Scanner in=new Scanner(System.in);
int n=in.nextInt();
double value[][]=new double[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)value[i][j]=in.nextDouble();
double ans[]=new double[1<<n];
int mask=(1<<n);
ans[(1<<n)-1]=1.0;
for(int i=mask-1;i>=0;i--){
int cnt=Integer.bitCount(i);
int pairs=cnt*(cnt-1)/2;
for(int j=0;j<n;j++){
if(((i>>j)&1)==0)continue;
for(int k=j+1;k<n;k++){
if(((i>>k)&1)==0)continue;
ans[i^(1<<k)]+=ans[i]*value[j][k]/pairs;
ans[i^(1<<j)]+=ans[i]*value[k][j]/pairs;
}
}
}
for(int i=0;i<n;i++)
System.out.print(ans[1<<i]+" ");
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
InputReader input;
PrintWriter output;
void run(){
output = new PrintWriter(new OutputStreamWriter(System.out));
input = new InputReader(System.in);
solve();
output.flush();
}
public static void main(String[] args){
new Main().run();
}
boolean isBitSet(int mask, int i) {
return (mask&(1<<i)) != 0;
}
int unSet(int mask, int i) {
return mask & ~(1<<i);
}
void solve() {
int n = input.ni();
double[][] prb = new double[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
prb[i][j] = input.readDouble();
}
}
double[] dp = new double[1<<n];
dp[0] = 1.0;
for(int i = 0; i < 1<<n; i++) {
int remaining = n-Integer.bitCount(i);
double remainingProbability = remaining*(remaining-1)/2;
for(int j = 0; j < n; j++) {
if(!isBitSet(i, j)) { //jth fish is alive
for(int k = 0; k < n; k++) { //candidates to kill jth fish
if(!isBitSet(i, k))
dp[i|(1<<j)] += dp[i]*prb[k][j]/(remainingProbability);
}
}
}
}
for(int i = 0; i < n; i++) {
output.printf("%.7f ",dp[unSet((1<<n)-1, i)]);
}
output.println();
}
class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public int ni() {
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 nl() {
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 String ns() {
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 isWhitespace(c);
}
public boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(ns());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
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, ni());
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, ni());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean eof() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
public String next() {
return ns();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
| np | 16_E. Fish | CODEFORCES |
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Ideone
{
static double p[][];
static double dp[];
static int n;
public static int BitCount(int u) {
int uCount;
uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
return ((uCount + (uCount >> 3)) & 030707070707) % 63;
}
public static double f(int mask) {
if (dp[mask] > -0.5)
return dp[mask];
dp[mask] = 0;
int ones = BitCount(mask);
double pairs = (((ones * (ones + 1))) >> 1);
//System.out.println(pairs);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((mask & (1 << i)) != 0 && (mask & (1 << j)) == 0)
dp[mask] += f(mask | (1 << j)) * p[i][j] / pairs;
}
}
return dp[mask];
}
public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(bf.readLine());
p = new double[n][n];
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(bf.readLine());
for (int j = 0; j < n; j++) {
p[i][j] = Double.parseDouble(st.nextToken());
}
}
dp = new double[1 << n];
Arrays.fill(dp, -1.0);
dp[(1 << n) - 1] = 1.;
for (int i = 0; i < n - 1; i++) {
System.out.print(f(1 << i) + " ");
}
System.out.println(f((1 << (n - 1))));
}
} | np | 16_E. Fish | CODEFORCES |
/**
* Codeforces Beta Round 16
*
* @author ProjectYoung
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class CF16E {
private void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
double[][] prob = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
prob[i][j] = in.nextDouble();
}
}
int[] fish = new int[n];
for (int i = 0; i < n; i++) {
fish[i] = 1 << i;
}
double[] res = new double[1 << n];
res[0] = 1.0;
for (int mask = 1; mask < (1 << n) - 1; mask++) {
for (int i = 0; i < n; i++) {
if ((mask & fish[i]) == 0) {
continue;
}
int lastMask = mask ^ fish[i];
int live = n;
for (int j = 0; j < n; j++) {
if ((lastMask & fish[j]) != 0) {
live--;
}
}
double p = 0.0;
for (int j = 0; j < n; j++) {
if ((lastMask & fish[j]) != 0 || j == i) {
continue;
}
p += prob[j][i];
}
res[mask] += res[lastMask] * p * 2 / live / (live - 1);
}
}
for (int i = 0; i < n; i++) {
out.printf("%.6f ", res[((1 << n) - 1) ^ fish[i]]);
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
new CF16E().solve(in, out);
out.close();
}
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 double nextDouble() {
return Double.parseDouble(next());
}
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int n, exp;
static double arr[][],dp[], dies[][];
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = new Integer(br.readLine());
arr = new double[n][n];
StringTokenizer st;
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < n; j++) {
arr[i][j] = Double.parseDouble(st.nextToken());
}
}
exp = 1<<n;
dp = new double[exp];
dies = new double[n][exp];
for (int all = 0; all < exp; all++) {
dp[all] = -1;
int countAlive = 0;
for (int i = 0; i < n; i++) {
if((all&(1<<i))!=0)
countAlive++;
}
if(countAlive <2)continue;
double x=1.0/(countAlive*(countAlive-1)/2.0);
for(int i=0; i<n; i++){
dies[i][all]=0;
int mask=1<<i;
if((mask&all)>0){
for(int j=0; j<n; j++)
{
int mask2=1<<j;
if((mask2&all)>0)
dies[i][all]+=arr[j][i];
}
dies[i][all]*=x;
}
}
}
for(int myFish=0; myFish<n; myFish++){
if(myFish>0)System.out.printf(" ");
System.out.printf("%.6f",ff(1<<myFish));
}
System.out.println();
}
static double ff(int state){
if(state==exp-1)return 1;
if(dp[state]!=-1)return dp[state];
double ans=0;
for(int i=0; i<n; i++)
{
int mask=1<<i;
if((mask &state)==0)
{
ans+=dies[i][state+mask]*ff(state+mask);
}
}
return dp[state]=ans;
}
} | np | 16_E. Fish | CODEFORCES |
import java.util.Locale;
import java.util.Scanner;
public class E {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double[][]p = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
p[i][j] = sc.nextDouble();
}
}
double[]dp = new double[1<<n];
dp[(1 << n)-1] = 1;
for (int mask = (1 << n)-1; mask > 0; mask--) {
int t = Integer.bitCount(mask);
if (t==1)
continue;
double p0 = 1.0/(t*(t-1)/2);
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0) {
for (int j = 0; j < n; j++) {
if (j != i && (mask & (1 << j)) != 0)
dp[(mask ^ (1 << i))] += dp[mask] * p[j][i]*p0;
}
}
}
}
for (int i = 0; i < n; i++) {
System.out.print(dp[1 << i]+" ");
}
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
import java.util.regex.*;
/**
*
* @author jon
*/
public class Fish {
double memo[] = new double[(1<<18)];
int N, FULL;
double prob[][] = new double[18][18];
Fish() {
Scanner in = new Scanner(System.in);
Arrays.fill(memo, -1);
N = in.nextInt();
FULL = (1<<N) - 1;
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
prob[i][j] = in.nextDouble();
}
}
for(int i = 0; i < N; i++) {
System.out.printf("%.6f ", go((1<<i)));
}
System.out.println();
}
public double go(int mask) {
if(mask == FULL) return 1.0;
if(memo[mask] >= 0) return memo[mask];
double ret = 0;
double mult = Integer.bitCount(mask) + 1;
mult *= (mult-1)/2.0;
// double k = getBits(mask);
// System.out.println(k + " " + mult);
// k *= (k-1)/2.0;
for(int i = 0; i < N; i++) {
if(((1<<i) & mask) != 0) {
for(int j = 0; j < N; j++) {
if(((1<<j) & mask) == 0) {
ret += go(mask | (1<<j)) * prob[i][j] / mult;
}
}
}
}
//ret /= (double)mult;
memo[mask] = ret;
return ret;
}
private int getBits(int x){
int cnt = 0;
while(x > 0){
x&=(x-1);
cnt++;
}
return cnt+1;
}
public static void main(String args[]) {
new Fish();
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.Locale;
public class E16 {
static StreamTokenizer in;
static PrintWriter out;
static int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
static double nextDouble() throws IOException {
in.nextToken();
return in.nval;
}
static String nextString() throws IOException {
in.nextToken();
return in.sval;
}
public static void main(String[] args) throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
n = nextInt();
t = 1 << n;
m = new double[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
m[i][j] = nextDouble();
memo = new double[t];
Arrays.fill(memo, Double.POSITIVE_INFINITY);
for (int i = 0; i < n; i++) out.print(String.format(Locale.US, "%.6f", solve(1 << i)) + " ");
out.println();
out.flush();
}
static int n, t;
static double[][] m;
static double[] memo;
static double solve(int mask) {
if (memo[mask] != Double.POSITIVE_INFINITY) return memo[mask];
if (mask == t-1) return memo[mask] = 1;
int k = Integer.bitCount(mask);
k = (k+1)*k/2;
double res = 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)
res += m[i][j]*solve(mask|(1 << j));
return memo[mask] = res/k;
}
}
| np | 16_E. Fish | CODEFORCES |
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;
public class Fish {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
in.useLocale(Locale.US);
int n = in.nextInt();
double[] dp = new double[1 << n];
Arrays.fill(dp, 0);
dp[(1 << n) - 1] = 1;//?
double[][] prob = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
prob[i][j] = in.nextDouble();
}
}
for (int t = (1 << n) - 1; t >= 0; t--) {
int k = Integer.bitCount(t);
for (int i = 0; i < n; i++) {
if ((t & (1 << i)) > 0) {
for (int j = 0; j < n; j++) {
if ((t & (1 << j)) > 0) {
if (i != j) {
dp[t - (1 << j)] += dp[t] * prob[i][j] / (k*(k-1)/2);
}
}
}
}
}
}
for (int i = 0; i < n; i++) {
System.out.print(dp[1 << i] + " ");
}
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.*;
import java.util.*;
public class CF16E {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
double[][] aa = new double[n][n];
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for (int j = 0; j < n; j++)
aa[i][j] = Double.parseDouble(st.nextToken());
}
double[][] pp = new double[1 << n][n];
for (int k = 0; k < n; k++)
pp[1 << k][k] = 1;
for (int b = 1; b < 1 << n; b++) {
int c = 0;
for (int i = 0; i < n; i++) {
if ((b & 1 << i) == 0)
continue;
c++;
for (int j = i + 1; j < n; j++) {
if ((b & 1 << j) == 0)
continue;
for (int k = 0; k < n; k++) {
if ((b & 1 << k) == 0)
continue;
pp[b][k] += aa[i][j] * pp[b ^ 1 << j][k];
pp[b][k] += aa[j][i] * pp[b ^ 1 << i][k];
}
}
}
if (c > 1) {
double p = (double) c * (c - 1) / 2;
for (int k = 0; k < n; k++)
pp[b][k] /= p;
}
}
StringBuilder sb = new StringBuilder();
int b = (1 << n) - 1;
for (int k = 0; k < n; k++)
sb.append(pp[b][k]).append(k == n - 1 ? '\n' : ' ');
System.out.print(sb);
}
}
| np | 16_E. Fish | CODEFORCES |
/*
Author : Imran Khan
Language: Java
*/
import java.io.*;
import java.util.*;
public class Main
{
public class BasicInputOutput
{
private StringTokenizer strtoken;
private BufferedReader bufferReader;
private BufferedWriter bufferWriter;
private String delim = " \t\n\r\f";
BasicInputOutput()
{
delim = " \t\n\r\f";
initialize();
}
BasicInputOutput( String s )
{
delim = s;
initialize();
}
private void initialize()
{
bufferReader = new BufferedReader( new InputStreamReader( System.in ));
bufferWriter = new BufferedWriter( new PrintWriter( System.out ));
strtoken = null;
}
private void checkStringTokenizer()throws IOException
{
if ( strtoken == null || strtoken.hasMoreTokens() == false )
strtoken = new StringTokenizer( bufferReader.readLine(), delim );
}
public int getNextInt()throws IOException
{
checkStringTokenizer();
return Integer.parseInt( strtoken.nextToken());
}
public long getNextLong()throws IOException
{
checkStringTokenizer();
return Long.parseLong( strtoken.nextToken());
}
public double getNextDouble()throws IOException
{
checkStringTokenizer();
return Double.parseDouble( strtoken.nextToken());
}
public float getNextFloat()throws IOException
{
checkStringTokenizer();
return Float.parseFloat( strtoken.nextToken());
}
public String getNextString()throws IOException
{
checkStringTokenizer();
return strtoken.nextToken();
}
public String getNextLine()throws IOException
{
checkStringTokenizer();
return bufferReader.readLine();
}
public void skipCurrentLine()throws IOException
{
checkStringTokenizer();
strtoken = null;
}
public void write( String var )throws IOException
{
bufferWriter.write( var );
}
public < T > void write( char sep, T... var )throws IOException
{
if ( var.length == 0 )
return ;
bufferWriter.write( var[0].toString());
for ( int i = 1; i < var.length; i++ )
bufferWriter.write( sep + var[i].toString());
}
public void flush()throws IOException
{
bufferWriter.flush();
}
}
public static void main(String[] args)
{
try
{
new Main().run();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
private BasicInputOutput iohandler;
private int n;
private double[][] mat;
private double[][] sum;
private double[] dp;
private int tolive;
private void run()throws Exception
{
initialize();
solve();
}
private void initialize() throws Exception
{
iohandler=new BasicInputOutput();
n=iohandler.getNextInt();
mat=new double[n][n];
sum=new double[(1<<n)+10][n];
dp=new double[1<<n];
for(int i=0;i<n;i++) for(int j=0;j<n;j++)
{
mat[i][j]=iohandler.getNextDouble();
}
}
private int bitCount(int mask)
{
int ret=0;
while(mask>0) {
ret++;
mask&=(mask-1);
}
return ret;
}
private void solve() throws Exception
{
double[] ans=new double[n];
int ub=1<<n;
for(int i=1;i<ub;i++) {
for(int j=0;j<n;j++) {
sum[i][j]=0;
for(int k=0;k<n;k++) if ((i&(1<<k))!=0) sum[i][j]+=mat[k][j];
int cntbit=bitCount(i);
if (cntbit>1)
sum[i][j]/=((double)cntbit*(cntbit-1.))/2.;
}
}
for(int i=0;i<n;i++)
{
for(int mask=1;mask<ub;mask++) {
dp[mask]=0;
if ((mask&(1<<i))==0) continue;
if (bitCount(mask)==1)
{
dp[mask]=1.;
} else
for(int k=0;k<n;k++) {
if ((mask&(1<<k))==0) continue;
if (i==k) continue;
dp[mask]+=sum[mask][k]*dp[mask-(1<<k)];
}
}
ans[i]=dp[ub-1];
}
iohandler.write(ans[0]+"");
for(int i=1;i<n;i++) iohandler.write(" "+ans[i]);
iohandler.write("\n");
iohandler.flush();
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.*;
public class Main
{
static double arr[][];
public static void main(String[] args)
{
try
{
Parserdoubt pd=new Parserdoubt(System.in);
PrintWriter pw=new PrintWriter(System.out);
int fishes=pd.nextInt();
arr=new double[fishes][fishes];
for(int i=0;i<fishes;i++)
for(int j=0;j<fishes;j++)
arr[i][j]=Double.parseDouble(pd.nextString());
double dp[]=new double[(1<<fishes)];
dp[dp.length-1]=1.0;
for(int c=dp.length-1;c>=0;c--)
{
int count=Integer.bitCount(c);
if(count<=1)
continue;
for(int i=0;i<fishes;i++)
for(int j=i+1;j<fishes;j++)
{
if(((1<<i)&c)!=0&&((1<<j)&c)!=0)
{
dp[c&~(1<<j)]+=arr[i][j]*dp[c];
dp[c&~(1<<i)]+=arr[j][i]*dp[c];
}
}
}
double s=0.0;
for(int i=0;i<fishes;i++)
s+=dp[1<<i];
for(int i=0;i<fishes;i++)
dp[1<<i]/=s;
int i=0;
for(i=0;i<fishes-1;i++)
pw.printf("%.6f ",dp[1<<i]);
pw.printf("%.6f\n",dp[1<<i]);
pw.close();
}
catch(Exception e)
{}
}
}
class Parserdoubt
{
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parserdoubt(InputStream in)
{
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws Exception
{
StringBuffer sb=new StringBuffer("");
byte c = read();
while (c <= ' ') c = read();
do
{
sb.append((char)c);
c=read();
}while(c>' ');
return sb.toString();
}
public char nextChar() throws Exception
{
byte c=read();
while(c<=' ') c= read();
return (char)c;
}
public int nextInt() throws Exception
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
public long nextLong() throws Exception
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.*;
import java.util.*;
public class E16 {
static double[][] grid;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
grid = new double[n][n];
for(int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j = 0; j < n; j++) {
grid[i][j] = Double.parseDouble(st.nextToken());
}
}
boolean[] seen = new boolean[1<<n];
double[] prob = new double[1<<n];
prob[(1<<n)-1] = 1;
LinkedList<Integer> q = new LinkedList<Integer>();
q.add((1<<n)-1);
while(!q.isEmpty()) {
int curr = q.removeFirst();
if(Integer.bitCount(curr) == 1)
continue;
for(int i = 0; i < n; i++) {
if((curr & (1 << i)) == 0)
continue;
for(int j = i+1; j < n; j++) {
if((curr & (1<<j)) == 0)
continue;
prob[curr-(1<<i)] += prob[curr] * grid[j][i];
prob[curr-(1<<j)] += prob[curr] * grid[i][j];
if(!seen[curr-(1<<i)]) {
q.addLast(curr-(1<<i));
seen[curr-(1<<i)] = true;
}
if(!seen[curr-(1<<j)]) {
q.addLast(curr-(1<<j));
seen[curr-(1<<j)] = true;
}
}
}
prob[curr] = 0;
}
double sum = 0;
for(int i = 0; i < n; i++) {
sum += prob[1<<i];
}
for(int i = 0; i < n-1; i++) {
System.out.print(prob[1<<i]/sum + " ");
}
System.out.println(prob[1<<(n-1)]/sum);
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Problem {
public static void main(String[] arg){
FastScanner scan = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt();
double ncr[][] = new double[n+1][n+1];
ncr[1][0] = ncr[0][1] = ncr[1][1] = 1.0;
for(int i = 2; i <= n; i++){
for(int j = 0; j <= i; j++){
if(j == 0 || j == i) ncr[i][j] = 1.0;
else ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1];
//System.out.print(ncr[i][j] + " ");
}
//System.out.println();
}
double a[][] = new double[n+1][n+1];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
a[i][j] = scan.nextDouble();
double dp[] = new double[1<<19];
dp[(1<<n) - 1] = 1.0;
for(int state = (1 << n) - 1; state >= 0; state--){
int len = 0;
for(int i = 0; i < n; i++)
if((state & (1 << i)) > 0) len++;
for(int i = 0; i < n; i++){
if(((1 << i) & state) == 0) continue;
for(int j = 0; j < i; j++){
if(((1 << j) & state) == 0) continue;
dp[state & (~(1<<i))] += (dp[state] * a[j][i] / ncr[len][2]);
dp[state & (~(1<<j))] += (dp[state] * a[i][j] / ncr[len][2]);
//System.out.println(state + " / " + (state & (~(1<<i))) + " / " + dp[state] + " / " + a[j][i] + " / " + (dp[state] * a[j][i]) + " / " + dp[state & (~(1<<i))]);
//System.out.println(state + " / " + (state & (~(1<<j))) + " / " + dp[state] + " / " + a[i][j] + " / " + (dp[state] * a[i][j]) + " / " + dp[state & (~(1<<j))]);
//System.out.println();
}
}
}
for(int i = 0; i < n; i++)
System.out.print(String.format("%.6f", dp[1<<i]) + " ");
out.close();
}
public static long gcd(long a, long b){
if(b == 0) return a;
if(a < b) return gcd(b, a);
return gcd(b, a % b);
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream is) {
try {
br = new BufferedReader(new InputStreamReader(is));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
return null;
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.valueOf(next());
}
}
}
| np | 16_E. Fish | 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 A {
static double[][] a;
static int N;
static double[] memo;
static double dp(int alive)
{
int count = Integer.bitCount(alive);
if(count == N)
return 1;
if(memo[alive] > -5)
return memo[alive];
double ret = 0;
for(int j = 0; j < N; ++j)
if((alive & (1<<j)) == 0)
ret += die[j][alive | 1<<j] * dp(alive | 1<<j);
return memo[alive] = ret;
}
static double[][] die;
static void f()
{
die = new double[N][1<<N];
for(int i = 0; i < N; ++i)
for(int j = 0; j < 1<<N; ++j)
{
int count = Integer.bitCount(j);
if(count <= 1)
continue;
double prop = 1.0 / (count * (count - 1) >> 1);
for(int k = 0; k < N; ++k)
if((j & (1<<k)) != 0)
die[i][j] += prop * a[k][i];
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
N = sc.nextInt();
a = new double[N][N];
for(int i = 0; i < N; ++i)
for(int j = 0; j < N; ++j)
a[i][j] = sc.nextDouble();
memo = new double[1<<N];
f();
Arrays.fill(memo, -10);
for(int i = 0; i < N - 1; ++i)
out.printf("%.8f ", dp(1 << i));
out.printf("%.8f\n", dp(1 << N - 1));
out.flush();
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready();}
}
} | np | 16_E. Fish | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.Locale;
public class E16 {
static StreamTokenizer in;
static PrintWriter out;
static int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
static double nextDouble() throws IOException {
in.nextToken();
return in.nval;
}
static String nextString() throws IOException {
in.nextToken();
return in.sval;
}
public static void main(String[] args) throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
n = nextInt();
t = 1 << n;
m = new double[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
m[i][j] = nextDouble();
memo = new double[t];
Arrays.fill(memo, Double.POSITIVE_INFINITY);
for (int i = 0; i < n; i++) out.print(String.format(Locale.US, "%.6f", solve(1 << i)) + " ");
out.println();
out.flush();
}
static int n, t;
static double[][] m;
static double[] memo;
static double solve(int mask) {
if (memo[mask] != Double.POSITIVE_INFINITY) return memo[mask];
if (mask == t-1) return memo[mask] = 1;
int k = Integer.bitCount(mask);
k = (k+1)*k/2;
double res = 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)
res += m[i][j]*solve(mask|(1 << j));
return memo[mask] = res/k;
}
}
| np | 16_E. Fish | CODEFORCES |
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class ProblemE_16 {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException{
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException{
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException{
return Integer.parseInt(readString());
}
long readLong() throws IOException{
return Long.parseLong(readString());
}
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
public static void main(String[] args){
new ProblemE_16().run();
}
public void run(){
try{
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = "+(t2-t1));
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
void solve() throws IOException{
int n = readInt();
double[][] a = new double[n][n];
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
a[i][j] = readDouble();
}
}
double[] d = new double[1<<n];
d[(1 << n) - 1] = 1;
for (int i = (1 << n) - 1; i > 0; i--){
ArrayList<Integer> list = new ArrayList<Integer>();
for (int j = 0; j < n; j++){
if ((i & (1 << j)) != 0) list.add(j);
}
double s = 0;
for (int j = 0; j < list.size(); j++){
s = 0;
for (int k = 0; k < list.size(); k++){
s += a[list.get(k)][list.get(j)];
}
d[i ^ (1 << list.get(j))] += s * d[i] * 2 / list.size() / (list.size() - 1);
}
}
for (int i = 0; i < n; i++){
out.printf(Locale.US, "%.9f", d[1 << i]);
out.print(" ");
}
}
static int[][] step8 = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, -1}, {-1, 1}, {1, 1}};
static int[][] stepKnight = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}};
static long gcd(long a, long b){
if (a == 0) return b;
return gcd(b % a, a);
}
static long lcm(long a, long b){
return a / gcd(a, b)*b;
}
static long[] gcdPlus(long a, long b){
long[] d = new long[3];
if (a == 0){
d[0] = b;
d[1] = 0;
d[2] = 1;
}else{
d = gcdPlus(b % a, a);
long r = d[1];
d[1] = d[2] - b/a*d[1];
d[2] = r;
}
return d;
}
static long binpow(long a, int n){
if (n == 0) return 1;
if ((n & 1) == 0){
long b = binpow(a, n/2);
return b*b;
}else return binpow(a, n - 1)*a;
}
static long binpowmod(long a, int n, long m){
if (m == 1) return 0;
if (n == 0) return 1;
if ((n & 1) == 0){
long b = binpowmod(a, n/2, m);
return (b*b) % m;
}else return binpowmod(a, n - 1, m)*a % m;
}
static long phi(long n){
int[] p = Sieve((int)ceil(sqrt(n)) + 2);
long phi = 1;
for (int i = 0; i < p.length; i++){
long x = 1;
while (n % p[i] == 0){
n /= p[i];
x *= p[i];
}
phi *= x - x/p[i];
}
if (n != 1) phi *= n - 1;
return phi;
}
static long f(long n, int x, int k){ //Кол-во десятичных чисел (включая 0), содержащих в себе цифры от 0 до k-1
if (n == 0) return 1;
long b = binpow(10, x - 1);
long c = n / b;
return (c < k? c: k)*binpow(k, x - 1) + (c < k? 1: 0)*f(n % b, x - 1, k);
}
static long fib(int n){
if (n == 0) return 0;
if ((n & 1) == 0){
long f1 = fib(n/2 - 1);
long f2 = fib(n/2 + 1);
return f2*f2 - f1*f1;
}else{
long f1 = fib(n/2);
long f2 = fib(n/2 + 1);
return f1*f1 + f2*f2;
}
}
static BigInteger BigFib(int n){
if (n == 0) return BigInteger.ZERO;
if ((n & 1) == 0){
BigInteger f1 = BigFib(n/2 - 1);
f1 = f1.multiply(f1);
BigInteger f2 = BigFib(n/2 + 1);
f2 = f2.multiply(f2);
return f2.subtract(f1);
}else{
BigInteger f1 = BigFib(n/2);
f1 = f1.multiply(f1);
BigInteger f2 = BigFib(n/2 + 1);
f2 = f2.multiply(f2);
return f2.add(f1);
}
}
static public class PointD{
double x, y;
public PointD(double x, double y){
this.x = x;
this.y = y;
}
}
static double d(Point p1, Point p2){
return sqrt(d2(p1, p2));
}
static public double d(PointD p1, PointD p2){
return sqrt(d2(p1, p2));
}
static double d2(Point p1, Point p2){
return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
}
static public double d2(PointD p1, PointD p2){
return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
}
static boolean IsProbablyPrime(long n){
if (n == 1) return false;
if ((n & 1) == 0) return false;
for (int j = 3; j < sqrt(n) + 1; j += 2){
if (n % j == 0) return false;
}
return true;
}
static int[] Sieve(int n){
boolean[] b = new boolean[n+1];
Arrays.fill(b, true);
b[0] = false;
b[1] = false;
long nLong = n;
int j=0;
for (int i = 1; i <= n; i++) {
if (b[i]){
j++;
if (((long)i)*i <= nLong) {
for (int k = i*i; k <= n; k += i) {
b[k] = false;
}
}
}
}
int[] p = new int[j];
Arrays.fill(p, 0);
j=0;
for (int i = 2; i <= n; i++) {
if (b[i]){
p[j]=i;
j++;
}
}
return p;
}
static int[][] Palindromes(String s){
char[] c = s.toCharArray();
int n = c.length;
int[][] d = new int[2][n];
int l = 0, r = -1;
for (int i = 0; i < n; i++){
int j = (i > r? 0: min(d[0][l+r-i+1], r-i+1)) + 1;
for (; i - j >= 0 && i + j - 1< n && c[i-j] == c[i+j-1]; j++);
d[0][i] = --j;
if (i + d[0][i] - 1 > r){
r = i + d[0][i] - 1;
l = i - d[0][i];
}
}
l = 0;
r = -1;
for (int i = 0; i < n; i++){
int j = (i > r? 0: min(d[1][l+r-i], r-i)) + 1;
for (; i - j >= 0 && i + j < n && c[i-j] == c[i+j]; j++);
d[1][i] = --j;
if (i + d[1][i] > r){
r = i + d[1][i];
l = i - d[1][i];
}
}
return d;
}
static public class Permutation {
int[] a;
int n;
public Permutation(int n){
this.n=n;
a=new int[n];
for (int i=0; i<n; i++){
a[i]=i;
}
}
public boolean nextPermutation(){ //Пишется с do{}while(nextPermutation(a));
int i=n-1;
for (i=n-2; i>=0; i--){
if (a[i]<a[i+1]){
break;
}
}
if (i==-1){
return false;
}
int jMin=i+1;
for (int j=n-1; j>i; j--){
if (a[i]<a[j]&&a[j]<a[jMin]){
jMin=j;
}
}
swap(i, jMin);
for (int j=1; j<=(n-i)/2; j++){
swap(i+j, n-j);
}
return true;
}
public int get(int i){
return a[i];
}
void swap(int i, int j){
int r=a[i];
a[i]=a[j];
a[j]=r;
}
}
static public class Fraction implements Comparable<Fraction>, Cloneable{
public final Fraction FRACTION_ZERO = new Fraction();
public final Fraction FRACTION_ONE = new Fraction(1);
public long numerator = 0;
public long denominator = 1;
public Fraction(){
numerator = 0;
denominator = 1;
}
public Fraction(long numerator){
this.numerator = numerator;
denominator = 1;
}
public Fraction(long numerator, long denominator){
this.numerator = numerator;
this.denominator = denominator;
Cancellation();
}
public Fraction(double numerator, double denominator, int accuracy){
this.numerator = (long)(numerator*pow(10,accuracy));
this.denominator = (long)(denominator*pow(10,accuracy));
Cancellation();
}
public Fraction(String s){
if (s.charAt(0) == '-'){
denominator = -1;
s = s.substring(1);
}
if (s.indexOf("/") != -1){
denominator *= Integer.parseInt(s.substring(s.indexOf("/") + 1));
}
if (s.indexOf(" ") != -1){
numerator = Integer.parseInt(s.substring(0, s.indexOf(" "))) * abs(denominator) + Integer.parseInt(s.substring(s.indexOf(" ") + 1, s.indexOf("/")));
}else{
if (s.indexOf("/") != -1){
numerator = Integer.parseInt(s.substring(0, s.indexOf("/")));
}else{
numerator = Integer.parseInt(s)*abs(denominator);
}
}
this.Cancellation();
}
void Cancellation(){
long g = gcd(abs(numerator), abs(denominator));
numerator /= g;
denominator /= g;
if (denominator < 0){
numerator *= -1;
denominator *= -1;
}
}
public String toString(){
String s = "";
if (numerator == 0){
return "0";
}
if (numerator < 0){
s += "-";
}
if (abs(numerator) >= denominator){
s += Long.toString(abs(numerator) / denominator) + " ";
}
if (abs(numerator) % denominator != 0){
s += Long.toString(abs(numerator) % denominator);
}else{
s = s.substring(0, s.length()-1);
}
if (denominator != 1){
s += "/" + Long.toString(denominator);
}
return s;
}
public Fraction add(Fraction f){
Fraction fResult = new Fraction();
fResult.denominator = lcm(denominator, f.denominator);
fResult.numerator = numerator * fResult.denominator / denominator + f.numerator * fResult.denominator / f.denominator;
fResult.Cancellation();
return fResult;
}
public Fraction subtract(Fraction f){
Fraction fResult = new Fraction();
fResult.denominator = lcm(denominator, f.denominator);
fResult.numerator = numerator * fResult.denominator / denominator - f.numerator * fResult.denominator / f.denominator;
fResult.Cancellation();
return fResult;
}
public Fraction multiply(Fraction f){
Fraction fResult = new Fraction();
fResult.numerator = numerator * f.numerator;
fResult.denominator = denominator * f.denominator;
fResult.Cancellation();
return fResult;
}
public Fraction divide(Fraction f){
Fraction fResult = new Fraction();
fResult.numerator = numerator * f.denominator;
fResult.denominator = denominator * f.numerator;
fResult.Cancellation();
return fResult;
}
@Override
public int compareTo(Fraction f){
long g = gcd(denominator, f.denominator);
long res = numerator * (f.denominator / g) - f.numerator * (denominator / g);
if (res < 0){
return -1;
}
if (res > 0){
return 1;
}
return 0;
}
public Fraction clone(){
Fraction fResult = new Fraction(numerator, denominator);
return fResult;
}
public Fraction floor(){
Fraction fResult = this.clone();
fResult.numerator = (fResult.numerator / fResult.denominator) * fResult.denominator;
return fResult;
}
public Fraction ceil(){
Fraction fResult = this.clone();
fResult.numerator = (fResult.numerator/fResult.denominator + 1) * fResult.denominator;
return fResult;
}
public Fraction binpow(int n){
if (n==0) return FRACTION_ONE;
if ((n&1)==0){
Fraction f=this.binpow(n/2);
return f.multiply(f);
}else return binpow(n-1).multiply(this);
}
}
static public class FenwickTree_1{ //One-dimensional array
int n;
long[] t;
public FenwickTree_1(int n){
this.n = n;
t = new long[n];
}
public long sum(int xl, int xr){
return sum(xr) - sum(xl);
}
public long sum(int x){
long result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1){
result += t[i];
}
return result;
}
public void update(int x, long delta){
for (int i = x; i < n; i = (i | (i + 1))){
t[i] += delta;
}
}
}
static public class FenwickTree_2{ //Two-dimensional array
int n, m;
long[][] t;
public FenwickTree_2(int n, int m){
this.n = n;
this.m = m;
t = new long[n][m];
}
public long sum(int xl, int yl, int xr, int yr){
return sum(xr, yr) - sum(xl - 1, yr) - sum(xr, yl - 1) + sum(xl - 1, yl - 1);
}
public long sum(int x, int y){
long result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1){
for (int j = y; j >= 0; j = (j & (j + 1)) - 1){
result+=t[i][j];
}
}
return result;
}
public void update(int x, int y, long delta){
for (int i = x; i < n; i = (i | (i + 1))){
for (int j = y; j < m; j = (j | (j + 1))){
t[i][j] += delta;
}
}
}
}
static public class FenwickTree_3{ //Three-dimensional array
int n, m, l;
long[][][] t;
public FenwickTree_3(int n, int m, int l){
this.n = n;
this.m = m;
this.l = l;
t = new long[n][m][l];
}
public long sum(int xl, int yl, int zl, int xr, int yr, int zr){
return sum(xr, yr, zr) - sum(xl - 1, yr, zr)
+ sum(xl - 1, yr, zl - 1) - sum(xr, yr, zl - 1)
- sum(xr, yl - 1, zr) + sum(xl - 1, yl - 1, zr)
- sum(xl - 1, yl - 1, zl - 1) + sum(xr, yl - 1, zl - 1);
}
public long sum(int x, int y, int z){
long result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1){
for (int j = y; j >= 0; j = (j & (j + 1)) - 1){
for (int k = z; k >= 0; k = (k & (k + 1)) - 1){
result += t[i][j][k];
}
}
}
return result;
}
public void update(int x, int y, int z, long delta){
for (int i = x; i < n; i = (i | (i + 1))){
for (int j = y; j < n; j = (j | (j + 1))){
for (int k = z; k < n; k = (k | (k + 1))){
t[i][j][k] += delta;
}
}
}
}
}
}
| np | 16_E. Fish | CODEFORCES |
/*
Author : Imran Khan
Language: Java
*/
import java.io.*;
import java.util.*;
public class Main
{
public class BasicInputOutput
{
private StringTokenizer strtoken;
private BufferedReader bufferReader;
private BufferedWriter bufferWriter;
private String delim = " \t\n\r\f";
BasicInputOutput()
{
delim = " \t\n\r\f";
initialize();
}
BasicInputOutput( String s )
{
delim = s;
initialize();
}
private void initialize()
{
bufferReader = new BufferedReader( new InputStreamReader( System.in ));
bufferWriter = new BufferedWriter( new PrintWriter( System.out ));
strtoken = null;
}
private void checkStringTokenizer()throws IOException
{
if ( strtoken == null || strtoken.hasMoreTokens() == false )
strtoken = new StringTokenizer( bufferReader.readLine(), delim );
}
public int getNextInt()throws IOException
{
checkStringTokenizer();
return Integer.parseInt( strtoken.nextToken());
}
public long getNextLong()throws IOException
{
checkStringTokenizer();
return Long.parseLong( strtoken.nextToken());
}
public double getNextDouble()throws IOException
{
checkStringTokenizer();
return Double.parseDouble( strtoken.nextToken());
}
public float getNextFloat()throws IOException
{
checkStringTokenizer();
return Float.parseFloat( strtoken.nextToken());
}
public String getNextString()throws IOException
{
checkStringTokenizer();
return strtoken.nextToken();
}
public String getNextLine()throws IOException
{
checkStringTokenizer();
return bufferReader.readLine();
}
public void skipCurrentLine()throws IOException
{
checkStringTokenizer();
strtoken = null;
}
public void write( String var )throws IOException
{
bufferWriter.write( var );
}
public < T > void write( char sep, T... var )throws IOException
{
if ( var.length == 0 )
return ;
bufferWriter.write( var[0].toString());
for ( int i = 1; i < var.length; i++ )
bufferWriter.write( sep + var[i].toString());
}
public void flush()throws IOException
{
bufferWriter.flush();
}
}
public static void main(String[] args)
{
try
{
new Main().run();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
private BasicInputOutput iohandler;
private int n;
private double[][] mat;
private double[][] sum;
private double[] dp;
private int tolive;
private void run()throws Exception
{
initialize();
solve();
}
private void initialize() throws Exception
{
iohandler=new BasicInputOutput();
n=iohandler.getNextInt();
mat=new double[n][n];
sum=new double[(1<<n)+10][n];
dp=new double[1<<n];
for(int i=0;i<n;i++) for(int j=0;j<n;j++)
{
mat[i][j]=iohandler.getNextDouble();
}
}
private int bitCount(int mask)
{
int ret=0;
while(mask>0) {
ret++;
mask&=(mask-1);
}
return ret;
}
private void solve() throws Exception
{
double[] ans=new double[n];
int ub=1<<n;
for(int i=1;i<ub;i++) {
for(int j=0;j<n;j++) {
sum[i][j]=0;
for(int k=0;k<n;k++) if ((i&(1<<k))!=0) sum[i][j]+=mat[k][j];
int cntbit=bitCount(i);
if (cntbit>1)
sum[i][j]/=((double)cntbit*(cntbit-1.))/2.;
}
}
dp[ub-1]=1.;
for(int mask=ub-1;mask>=1;mask--) {
if (dp[mask]==0.) continue;
for(int i=0;i<n;i++) {
if ((mask&(1<<i))==0) continue;
dp[mask-(1<<i)]+=sum[mask][i]*dp[mask];
}
}
for(int i=0;i<n;i++)
ans[i]=dp[1<<i];
/*
for(int i=0;i<n;i++)
{
for(int mask=1;mask<ub;mask++) {
dp[mask]=0;
if ((mask&(1<<i))==0) continue;
if (bitCount(mask)==1)
{
dp[mask]=1.;
} else
for(int k=0;k<n;k++) {
if ((mask&(1<<k))==0) continue;
if (i==k) continue;
dp[mask]+=sum[mask][k]*dp[mask-(1<<k)];
}
}
ans[i]=dp[ub-1];
}*/
iohandler.write(ans[0]+"");
for(int i=1;i<n;i++) iohandler.write(" "+ans[i]);
iohandler.write("\n");
iohandler.flush();
}
}
| np | 16_E. Fish | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static double[] dp;
static double[][] P;
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
int n = r.nextInt();
double[][] g = new double[n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
g[i][j] = r.nextDouble();
dp = new double[1 << n];
P = new double[1 << n][n];
for(int mask = 0; mask < 1 << n; mask++){
for(int d = 0; d < n; d++)if((mask & (1 << d)) == 0)
for(int i = 0; i < n; i++)if((mask & (1 << i)) == 0){
if(i == d)continue;
P[mask][d] += g[i][d];
}
}
for(int i = 0; i < n; i++){
Arrays.fill(dp, -1);
double res = go(i, 0, g, n, n);
System.out.println(res);
}
}
private static double go(int a, int v, double[][] g, int cnt, int n) {
if(dp[v] != -1)return dp[v];
if(cnt == 1){
return 1;
}else{
double ret = 0;
for(int d = 0; d < n; d++)if((v & (1 << d)) == 0 && d != a){
double current = P[v][d] * go(a, v | 1 << d, g, cnt-1, n);
ret += current;
}
return dp[v] = ret/(cnt * (cnt-1) /2);
}
}
}
| np | 16_E. Fish | CODEFORCES |
import java.util.Scanner;
public class A {
public static int n;
public static double[] masks;
public static double[][] matrix;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
matrix = new double[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix[i][j] = scan.nextDouble();
masks = new double[1 << n];
masks[(1 << n) - 1] = 1;
for (int i = 0; (1 << i) < (1 << n); i++)
fillDP(1 << i);
for (int i = 0; (1 << i) < (1 << n); i++)
System.out.printf("%.6f ", masks[1 << i]);
}
public static double fillDP(int mask) {
int bitCount = Integer.bitCount(mask);
if (masks[mask] != 0)
return masks[mask];
double matchProba = 2.0 / (((double) (bitCount)) * ((double) (bitCount + 1)));
double totalProba = 0;
for (int i = 0; i < n; i++) {
int iPower = 1 << i;
if ((mask & iPower) != iPower)
continue;
for (int j = 0; j < n; j++) {
int jPower = 1 << j;
if ((mask & jPower) == jPower || i == j)
continue;
// still alive
totalProba += (matchProba * matrix[i][j] * fillDP(mask | jPower));
}
}
return masks[mask] = totalProba;
}
} | np | 16_E. Fish | CODEFORCES |
/**
* Created by IntelliJ IDEA.
* User: Taras_Brzezinsky
* Date: 8/14/11
* Time: 9:53 PM
* To change this template use File | Settings | File Templates.
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.FileReader;
import java.util.StringTokenizer;
import java.io.IOException;
import java.util.Arrays;
public class Fish extends Thread {
public Fish() {
this.input = new BufferedReader(new InputStreamReader(System.in));
this.output = new PrintWriter(System.out);
this.setPriority(Thread.MAX_PRIORITY);
}
static int getOnes(int mask) {
int result = 0;
while (mask != 0) {
mask &= mask - 1;
++result;
}
return result;
}
private void solve() throws Throwable {
int n = nextInt();
double[][] a = new double[n][n];
double[] dp = new double[(1 << n)];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
a[i][j] = nextDouble();
}
}
int limit = (1 << n) - 1;
//dp[mask] = probability of current subset (mask) to remain in the end
dp[limit] = 1.0;
for (int mask = limit; mask > 0; --mask) {
int cardinality = getOnes(mask);
int probability = cardinality * (cardinality - 1) / 2;
for (int first = 0; first < n; ++first) {
if ((mask & powers[first]) != 0) {
for (int second = first + 1; second < n; ++second) {
if ((mask & powers[second]) != 0) {
dp[mask - powers[first]] += dp[mask] * a[second][first] / probability;
dp[mask - powers[second]] += dp[mask] * a[first][second] / probability;
}
}
}
}
}
for (int i = 0; i < n; ++i) {
output.printf("%.10f ", dp[powers[i]]);
}
}
public void run() {
try {
solve();
} catch (Throwable e) {
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(666);
} finally {
output.flush();
output.close();
}
}
public static void main(String[] args) {
new Fish().start();
}
private String nextToken() throws IOException {
while (tokens == null || !tokens.hasMoreTokens()) {
tokens = new StringTokenizer(input.readLine());
}
return tokens.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static int powers[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144};
private BufferedReader input;
private PrintWriter output;
private StringTokenizer tokens = null;
}
| np | 16_E. Fish | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main16E {
private FastScanner in;
private PrintWriter out;
public void solve() throws IOException {
int n = in.nextInt();
double[][] a = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = in.nextDouble();
}
}
int k = 1 << n;
double[] p = new double[k];
int[][] b = new int[n + 1][];
for (int i = 0; i <= n; i++) {
b[i] = new int[comb(i, n)];
}
int[] bl = new int[n + 1];
for(int i = 0; i < k; i++) {
int c = c2(i);
b[c][bl[c]] = i;
bl[c]++;
}
p[k - 1] = 1;
for (int i = n; i >= 2; i--) {
for (int j = 0; j < b[i].length; j++) {
int t = b[i][j];
double pm = 1;
pm /= (i * (i - 1) / 2);
for (int x = 0; x < n; x++) {
for (int y = x + 1; y < n; y++) {
if ((t & (1 << x)) > 0 && (t & (1 << y)) > 0) {
p[t & ~(1 << x)] += p[t] * pm * a[y][x];
p[t & ~(1 << y)] += p[t] * pm * a[x][y];
}
}
}
}
}
for (int i = 0; i < n; i++) {
out.print(p[1 << i] + " ");
}
}
int comb(int n, int m) {
int res = 1;
for (int i = 1; i <= n; i++) {
res = res * (m - i + 1);
res /= i;
}
return res;
}
int c2(int k) {
int res = 0;
while (k > 0) {
if (k % 2 == 1) {
res ++;
}
k /= 2;
}
return res;
}
public void run() {
try {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] arg) {
new Main16E().run();
}
} | np | 16_E. Fish | CODEFORCES |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
public class ProblemE {
static final int INF = 1000000;
public static void main(String[] args) throws IOException {
BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.valueOf(s.readLine());
double[][] prob = new double[n][n];
double[] dp = new double[1<<n];
for (int i = 0 ; i < n ; i++) {
String[] line = s.readLine().split(" ");
for (int j = 0 ; j < n ; j++) {
prob[i][j] = Double.valueOf(line[j]);
}
}
dp[(1<<n)-1] = 1.0d;
for (int p = (1<<n)-1 ; p >= 1 ; p--) {
if (dp[p] > 0.0d) {
int left = Integer.bitCount(p);
if (left == 1) {
continue;
}
double baseProb = 1.0d / (left * (left - 1) / 2);
for (int i = 0 ; i < n ; i++) {
if ((p & (1<<i)) == 0) {
continue;
}
for (int j = i+1 ; j < n ; j++) {
if ((p & (1<<j)) == 0) {
continue;
}
dp[p-(1<<i)] += dp[p] * baseProb * prob[j][i];
dp[p-(1<<j)] += dp[p] * baseProb * prob[i][j];
}
}
}
}
StringBuffer b = new StringBuffer();
for (int i = 0 ; i < n ; i++) {
b.append(" ").append(dp[1<<i]);
}
out.println(b.substring(1));
out.flush();
}
public static void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
} | np | 16_E. Fish | CODEFORCES |
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
Fish solver = new Fish();
solver.solve(1, in, out);
out.close();
}
}
class Fish {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
double[][] p = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
p[i][j] = in.nextDouble();
}
}
double[] dp = new double[1 << n];
dp[(1 << n) - 1] = 1;
for (int mask = (1 << n) - 1; mask >= 0; mask--) {
int countPairs = Integer.bitCount(mask);
countPairs = countPairs * (countPairs - 1) / 2;
for (int i = 0; i < n; i++) {
if (((mask >> i) & 1) == 0) {
continue;
}
for (int j = i + 1; j < n; j++) {
if (((mask >> j) & 1) == 0) {
continue;
}
dp[mask ^ (1 << j)] += dp[mask] * p[i][j] / countPairs;
dp[mask ^ (1 << i)] += dp[mask] * p[j][i] / countPairs;
}
}
}
for (int i = 0; i < n; i++) {
out.print(dp[1 << i] + " ");
}
}
}
class FastScanner extends BufferedReader {
boolean isEOF;
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
if (isEOF && ret < 0) {
throw new InputMismatchException();
}
isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
while (!isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= -1 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (!isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Locale;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.AbstractList;
import java.io.Writer;
import java.util.Collection;
import java.util.List;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Jacob Jiang
*/
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);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
}
class TaskE {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
double[][] probability = in.next2DDoubleArray(n, n);
double[] dp = new double[1 << n];
dp[dp.length - 1] = 1;
for (int mask = (1 << n) - 1; mask >= 0; mask--) {
int count = Integer.bitCount(mask);
if (count <= 1) continue;
double multi = 1. / calc(count);
for (int i = 0; i < n; i++) {
if (NumberUtils.checkBit(mask, i)) {
for (int j = i + 1; j < n; j++) {
if (NumberUtils.checkBit(mask, j)) {
// i eat j
dp[mask - (1 << j)] += multi * probability[i][j] * dp[mask];
// j eat i
dp[mask - (1 << i)] += multi * probability[j][i] * dp[mask];
}
}
}
}
}
double[] answer = new double[n];
for (int i = 0; i < n; i++) {
answer[i] = dp[1 << i];
}
out.printLine(ArrayUtils.asList(answer).toArray());
}
private static int calc(int x) {
return x * (x - 1) / 2;
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
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 double[] nextDoubleArray(int count) {
double[] result = new double[count];
for (int i = 0; i < count; i++) {
result[i] = nextDouble();
}
return result;
}
public double[][] next2DDoubleArray(int n, int m) {
double[][] result = new double[n][];
for (int i = 0; i < n; i++) {
result[i] = nextDoubleArray(m);
}
return result;
}
}
class OutputWriter {
PrintWriter writer;
public OutputWriter(OutputStream stream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object obj) {
writer.print(obj);
}
public void println() {
writer.println();
}
public void print(char c) {
writer.print(c);
}
public void close() {
writer.close();
}
public void printItems(Object... items) {
for (int i = 0; i < items.length; i++) {
if (i != 0) {
print(' ');
}
print(items[i]);
}
}
public void printLine(Object... items) {
printItems(items);
println();
}
}
class NumberUtils {
public static boolean checkBit(int mask, int bit) {
return (mask & (1 << bit)) != 0;
}
}
class ArrayUtils {
private ArrayUtils() {
}
public static List<Double> asList(double[] array) {
return new DoubleList(array);
}
private static class DoubleList extends AbstractList<Double> {
double[] array;
private DoubleList(double[] array) {
this.array = array;
}
public Double set(int index, Double element) {
double result = array[index];
array[index] = element;
return result;
}
public Double get(int index) {
return array[index];
}
public int size() {
return array.length;
}
}
}
| np | 16_E. Fish | CODEFORCES |
import java.util.*;
import java.io.*;
public class Fish
{
public static void main(String[] args) throws Exception { new Fish(); }
public Fish() throws Exception
{
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
double[][] P = new double[N][N];
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++)
P[i][j] = sc.nextDouble();
double[] best = new double[1 << N];
best[(1 << N)-1] = 1;
for(int mask = (1 << N)-1; mask > 0; mask--)
{
int C = Integer.bitCount(mask);
if(C == 1) continue;
for(int i = 0; i < N; i++) if (on(mask, i))
for(int j = i+1; j < N; j++) if(on(mask, j))
{
int nmask = mask & ~(1 << j);
best[nmask] += P[i][j] * best[mask] * 2.0 / (C*(C-1.0));
nmask = mask & ~(1 << i);
best[nmask] += P[j][i] * best[mask] * 2.0/ (C*(C-1.0));
}
}
for(int i = 0; i < N; i++)
System.out.printf("%.7f ", best[1 << i] + 1e-9);
System.out.println();
}
boolean on(int mask, int pos) { return (mask & (1 << pos)) > 0; }
}
| np | 16_E. Fish | CODEFORCES |
import java.util.Arrays;
import java.util.Scanner;
public class E {
static double[] dp;
static int[] oneCount;
static int end;
static int n;
static double[][] prob;
public static double solve(int mask) {
if(mask==end) return 1;
int oneC=0,zeroC=0;
for(int i=0;i<n;i++) {
if((mask|(1<<i))==mask) oneC++;
else zeroC++;
}
double res=0;
for(int i=0;i<n;i++) {
if((mask|(1<<i))!=mask) continue;
for(int j=0;j<n;j++) {
//
if((mask|(1<<j))==mask) continue;
//System.out.println(i+" "+j+" "+prob[i][j]+" "+Integer.toBinaryString(mask)+" "+oneC+" "+zeroC);
res+=(1.0/((oneC*(oneC+1))/2))*prob[i][j]*solve(mask|(1<<j));
}
}
return dp[mask]=res;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
prob=new double[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
prob[i][j]=sc.nextDouble();
dp=new double[1<<n];
oneCount=new int[1<<n];
int c;
for(int i=0;i<dp.length;i++) {
c=0;
for(int j=0;j<n;j++) {
if((i|(1<<j))==i) c++;
}
oneCount[i]=c;
}
end=(1<<n)-1;
double res,rad;
int count;
for(int k=end;k>0;k--) {
if(k==end) dp[k]=1;
else {
res=0;
count=oneCount[k];
count=count*(count+1);
count>>=1;
rad=1.0/count;
//System.out.println(rad+" "+count);
for(int i=0;i<n;i++) {
if((k|(1<<i))!=k) continue;
for(int j=0;j<n;j++) {
//
if((k|(1<<j))==k) continue;
//System.out.println(i+" "+j+" "+prob[i][j]+" "+Integer.toBinaryString(mask)+" "+oneC+" "+zeroC);
res+=rad*prob[i][j]*dp[k|(1<<j)];
}
}
dp[k]=res;
}
}
//Arrays.fill(dp, -1);
for(int i=0;i<n;i++)
System.out.print(dp[1<<i]+" ");
//System.out.print(solve(1<<i)+" ");
// for(int i=0;i<18;i++){
// for(int k=0;k<18;k++)
// System.out.print(Math.random()+" ");
// System.out.println();
// }
}
} | np | 16_E. Fish | CODEFORCES |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;
public class Main {
public static void main(String[] args) throws IOException {
try {
if (new File("input.txt").exists()) {
System.setIn(new FileInputStream("input.txt"));
}
} catch (SecurityException e) {
}
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int N = nextInt();
double[][] a = new double [N][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
a[i][j] = nextDouble();
int NN = 1 << N;
double[] dp = new double [NN];
dp[NN - 1] = 1.0;
for (int mask = NN - 1; mask > 0; mask--) {
int b = Integer.bitCount(mask);
if (b <= 1)
continue;
double k = 2.0 / (b * (b - 1));
for (int i = 0; i < N; i++) {
if ((mask & (1 << i)) == 0)
continue;
for (int j = i + 1; j < N; j++) {
if ((mask & (1 << j)) == 0)
continue;
double p = a[i][j];
dp[mask & (~(1 << j))] += k * p * dp[mask];
dp[mask & (~(1 << i))] += k * (1.0 - p) * dp[mask];
}
}
}
out.printf(Locale.US, "%.8f", dp[1]);
for (int i = 1, ind = 2; i < N; ind <<= 1, i++)
out.printf(Locale.US, " %.8f", dp[ind]);
out.println();
out.close();
}
String nextToken() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
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 nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
| np | 16_E. Fish | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
static Scanner in;
static PrintWriter out;
// static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;}
public static void main(String[] args) throws Exception {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
// in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
int n = in.nextInt();
double[][] p = new double[n][n];
for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) p[i][j] = in.nextDouble();
double[] q = new double[1 << n];
q[(1 << n) - 1] = 1;
for (int mask = (1 << n) - 1; mask > 0; mask--) {
int count = 0;
for (int t = 0; t < n; t++) if (((1 << t) & mask) != 0) count++;
if (count <= 1) continue;
count = count*(count - 1)/2;
for (int t = 0; t < n; t++) if (((1 << t) & mask) != 0)
for (int s = 0; s < t; s++) if (((1 << s) & mask) != 0) {
q[mask - (1 << t)] += q[mask] / count * p[s][t];
q[mask - (1 << s)] += q[mask] / count * p[t][s];
}
}
for (int i = 0; i < n; i++) out.print(q[1 << i] + " ");
out.close();
}
} | np | 16_E. Fish | CODEFORCES |
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class BetaRound16_E implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args) {
new Thread(null, new BetaRound16_E(), "", 256 * (1L << 20)).start();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
if (System.getProperty("ONLINE_JUDGE") != null) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
Locale.setDefault(Locale.US);
solve();
in.close();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Throwable t) {
t.printStackTrace(System.err);
System.exit(-1);
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
// solution
double[] p;
int n;
double[][] a;
void solve() throws IOException {
n = readInt();
a = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = readDouble();
}
}
p = new double[1 << n];
Arrays.fill(p, -1);
p[(1 << n) - 1] = 1;
for (int i = 0; i < n; i++) {
out.printf("%.12f ", p(1 << i));
}
}
double p(int mask) {
if (p[mask] != -1) return p[mask];
double ans = 0;
for (int eaten = 0; eaten < n; eaten++) {
int prev = mask | (1 << eaten);
if (prev != mask) {
for (int eats = 0; eats < n; eats++) {
if ((mask & (1 << eats)) != 0) {
ans += a[eats][eaten] * p(prev);
}
}
}
}
int bc = Integer.bitCount(mask);
int norm = bc * (bc + 1) / 2;
return p[mask] = ans / norm;
}
}
| np | 16_E. Fish | CODEFORCES |
// by agus.mw
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws Exception {
new Main().doWork();
}
void doWork() throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
int ncase = Integer.valueOf(reader.readLine());
double[][] p = new double[ncase][];
for(int icase=0;icase<ncase;icase++){
p[icase] = toDoubleArray(reader.readLine());
}
double[] prob = new double[1<<ncase];
prob[0] = 1;
for(int x=0;x<(1<<ncase);x++){
double cp = prob[x];
int count = 0;
for(int i=0;i<ncase;i++){
if((x&(1<<i))!=0) continue;
count ++;
}
if(count == 1) continue;
double np = cp*2.0/(count)/(count-1);
for(int i=0;i<ncase;i++){
if((x&(1<<i))!=0) continue;
for(int j=i+1;j<ncase;j++){
if((x&(1<<j))!=0) continue;
prob[x^(1<<j)] += np*p[i][j];
prob[x^(1<<i)] += np*p[j][i];
}
}
}
String out = "";
for(int i=0;i<ncase;i++){
if(i>0) out += " ";
int index = ((1<<ncase)-1)^(1<<i);
out += String.format("%.6f",prob[index]);
}
out += "\r\n";
writer.write(out,0,out.length());
writer.flush();
writer.close();
reader.close();
}
String process(){
return "1";
}
double[] toDoubleArray(String line){
String[] p = line.split("[ ]+");
double[] out = new double[p.length];
for(int i=0;i<p.length;i++) out[i] = Double.valueOf(p[i]);
return out;
}
} | np | 16_E. Fish | CODEFORCES |
import java.io.*;
import java.util.*;
import static java.util.Arrays.*;
public class E implements Runnable
{
public static void main(String[] args) throws IOException
{
new Thread(null, new E(), "", 1 << 20).start();
}
BufferedReader input;
PrintWriter out;
String file = "input";
public void run()
{
try
{
//input = new BufferedReader(new FileReader(file + ".in"));
input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
solve();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
void solve() throws IOException
{
int n = Integer.parseInt(input.readLine());
double[][] p = new double[n][n];
for(int i = 0; i < n; i++)
{
StringTokenizer st = new StringTokenizer(input.readLine());
for(int j = 0; j < n; j++)
{
p[i][j] = Double.parseDouble(st.nextToken());
}
}
double[] dp = new double[1 << n];
int mask = (1 << n) - 1;
dp[mask] = 1;
for(int w = mask; w > 0; w--)
{
int count = 0;
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
if((w >> i & 1) != 0 && (w >> j & 1) != 0) count++;
if(count == 0) continue;
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
if((w >> i & 1) != 0 && (w >> j & 1) != 0)
{
dp[w ^ (1 << i)] += 1.0 / count * p[j][i] * dp[w];
dp[w ^ (1 << j)] += 1.0 / count * p[i][j] * dp[w];
}
}
for(int i = 0; i < n; i++)
System.out.print(dp[1 << i] + " ");
}
} | np | 16_E. Fish | CODEFORCES |
import java.io.*;
import java.util.*;
public class f {
static int n;
static double[][] g;
public static void main(String[] args) throws IOException {
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
n = input.nextInt();
g = new double[n][n];
for(int i = 0; i<n; i++)
for(int j = 0; j<n; j++)
g[i][j] = input.nextDouble();
for(int i = 0; i<n; i++)
for(int j = 0; j<n; j++)
g[j][i] = 1 - g[i][j];
for(int i = 0; i<n; i++)
{
double[] dp = new double[1<<n];
for(int mask = 0; mask < (1<<n); mask++)
{
if((mask & (1<<i)) == 0)
{
dp[mask] = 0;
continue;
}
if(mask == (1<<i))
{
dp[mask] = 1;
continue;
}
int count = Integer.bitCount(mask);
double prob = 1.0 / (count * (count-1)/2);
for(int a = 0; a<n; a++)
{
if((mask & (1<<a)) == 0) continue;
for(int b = a+1; b<n; b++)
{
if((mask & (1<<b)) == 0) continue;
double p = g[a][b] * dp[mask ^ (1<<b)] + g[b][a] * dp[mask ^ (1<<a)];
dp[mask] += p;
}
}
dp[mask] *= prob;
}
out.print(dp[(1<<n)-1]+" ");
}
out.close();
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
| np | 16_E. Fish | CODEFORCES |
/**
* Created by IntelliJ IDEA.
* User: aircube
* Date: 11.01.11
* Time: 4:14
* To change this template use File | Settings | File Templates.
*/
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.Exchanger;
public class Template {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
public static void main(String[] args) throws IOException {
new Template().run();
}
void run() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
st = null;
out = new PrintWriter(System.out);
solve();
br.close();
out.close();
}
double dm[];
double a[][];
boolean fil[];
int p[];
int n;
// x & (x - 1)
// 10
//
void solve() throws IOException {
n = nextInt();
a = new double[n][n];
for(int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
a[i][j] = nextDouble();
}
dm = new double[1 << n];
fil = new boolean[1 << n];
for(int i = 0; i < n; ++i) {
out.print(brute((1 << i)) + " ");
}
}
private double brute(int mask) {
if (Integer.bitCount(mask) == n) return 1;
if (fil[mask]) return dm[mask];
int c = Integer.bitCount(mask);
double res = 0;
double p = 2.0 / (double) (c + 1) / (double)(c ) ;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
if ((mask & (1 << i)) == 0 && (mask & (1 << j)) > 0) {
res += a[j][i] * brute(mask ^ (1 << i));
}
}
}
res *= p;
dm[mask] = res;
fil[mask] = true;
return dm[mask];
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
} | np | 16_E. Fish | CODEFORCES |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.