src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; import java.util.Comparator; public class Main { private static StreamTokenizer in; private static PrintWriter out; static { in = new StreamTokenizer(new BufferedReader(new InputStreamReader( System.in))); out = new PrintWriter(System.out); } private static int nextInt() throws Exception { in.nextToken(); return (int) in.nval; } private static double nextDouble() throws Exception { in.nextToken(); return in.nval; } private static String nextString() throws Exception { in.nextToken(); return in.sval; } public static void main(String[] args) throws Exception { int n = nextInt(), k = nextInt(), A = nextInt(), r = n + k - 1; int[][] s = new int[n][]; for (int i = 0; i < n; i++) { s[i] = new int[] { nextInt(), nextInt() }; } double max = 0; int[] prb = new int[n]; for (int u = (1 << r); u >= 0; u--) { // проверим на n-1 единичек int ones = 0; for (int i = 0; i < r; i++) { if ((u & (1 << i)) != 0) { ones++; } } if (ones != n - 1) { continue; } // проверили. расставляем массив ones = 0; int p = 0; for (int i = 0; i < r; i++) { if ((u & (1 << i)) == 0) { ones++; } else { prb[p] = ones * 10; p++; ones = 0; } } prb[p] = ones * 10; p++; ones = 0; double sum = 0; for (int i = 0; i < n; i++) { if (prb[i] > 100 - s[i][1]) prb[i] = 100 - s[i][1]; s[i][1] = prb[i] + s[i][1]; } for (int i = (1 << n) - 1; i >= 0; i--) { double prob = 1; int lvl = 0; int kill = 0; for (int j = 0; j < n; j++) { if ((i & (1 << j)) != 0) { prob *= s[j][1] / 100.0; kill--; } else { lvl += s[j][0]; prob *= (1 - s[j][1] / 100.0); kill++; } } if (kill >= 0) { sum += prob * ((double) A / (A + lvl)); } else { sum += prob; } } for (int i = 0; i < n; i++) { s[i][1] = -prb[i] + s[i][1]; } max = Math.max(max, sum); } out.println(max); out.flush(); } }
np
105_B. Dark Assembly
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; import static java.lang.Math.*; public class Main{ public void go(){ int n=sc.nextInt(), k=sc.nextInt(), A=sc.nextInt(); ArrayList< ArrayList< Integer > > waysGiveCandies = doit1(n, k, new ArrayList< Integer >()); /* System.out.printf("%d\n", waysGiveCandies.size()); for(ArrayList< Integer > x : waysGiveCandies){ for(int i : x) System.out.printf("%d ", i); System.out.printf("\n"); } */ int[] lvl = new int[n], loyal = new int[n]; for(int i=0; i<n; ++i){ lvl[i] = sc.nextInt(); loyal[i] = sc.nextInt(); } double ret = 0; for(ArrayList< Integer > distribution : waysGiveCandies){ double[] Loyal = new double[n]; for(int i=0; i<n; ++i) Loyal[i] = min(loyal[i]+10*distribution.get(i), 100)/100.0; double pWin = 0; for(int i=0; i<1<<n; ++i){ double pVoteOccurs = 1; for(int j=0; j<n; ++j) if((i&(1<<j))!=0) // if winner pVoteOccurs *= Loyal[j]; else // if loser pVoteOccurs *= 1-Loyal[j]; int B = 0; for(int j=0; j<n; ++j) if((i&(1<<j))==0) B += lvl[j]; double pWinFight = (double)A/(A+B); // if win vote, don't need to fight if(bit_count(i)*2 > n) pWinFight = 1; pWin += pVoteOccurs * pWinFight; } ret = max(ret, pWin); } System.out.printf("%.9f\n", ret); } ArrayList< ArrayList< Integer > > doit1(int n, int k, ArrayList< Integer > soFar){ ArrayList< ArrayList< Integer > > ret = new ArrayList< ArrayList< Integer > >(); // base case if(n==1){ soFar.add(k); ret.add(soFar); return ret; } // general case for(int i=0; i<k+1; ++i){ ArrayList< Integer > tmp = new ArrayList< Integer >(soFar); tmp.add(i); ret.addAll(doit1(n-1, k-i, tmp)); } return ret; } // syntax // ArrayList<Integer>[] myMat = (ArrayList<Integer>[]) new ArrayList[nB]; // Pairs public class ii implements Comparable< ii >{ int x, y; public ii(){} public ii(int xx, int yy){ x=xx; y=yy; } public int compareTo(ii p){ return x!=p.x ? x-p.x : y-p.y; } public int hashCode(){ return 31*x+y; } public boolean equals(Object o){ if(!(o instanceof ii)) return false; ii p = (ii) o; return x==p.x && y==p.y; } public String toString(){ return "("+x+", "+y+")"; } } /* public class pair< X extends Comparable< X >,Y extends Comparable< Y > > implements Comparable< pair< X,Y > >{ X x; Y y; public pair(){} public pair(X xx, Y yy){ x=xx; y=yy; } public int compareTo(pair< X,Y > p){ return x.compareTo(p.x)!=0 ? x.compareTo(p.x) : y.compareTo(p.y); } public int hashCode(){ return 31*x.hashCode()+y.hashCode(); } public boolean equals(Object o){ if((o.getClass() != this.getClass())) return false; pair< X,Y > p = (pair< X,Y >) o; return x.equals(p.x) && y.equals(p.y); } public String toString(){ return "("+x+", "+y+")"; } } */ // my stuff public static final int INF = 1000*1000*1000+7; public static final double EPS = 1e-9; public static final double PI = 2*acos(0.0); public void rev(Object[] a){ for(int i=0; i<a.length/2; ++i){ Object t=a[i]; a[i]=a[a.length-1-i]; a[a.length-1-i]=t; } } public void rev(int[] a){ for(int i=0; i<a.length/2; ++i){ int t=a[i]; a[i]=a[a.length-1-i]; a[a.length-1-i]=t; } } public int bit_count(long x){ return x==0 ? 0 : 1+bit_count(x&(x-1)); } public int low_bit(int x){ return x&-x; } // 0011 0100 returns 0000 0100 public int sign(int x){ return x<0 ? -1 : x>0 ? 1 : 0; } public int sign(double x){ return x<-EPS ? -1 : x>EPS ? 1 : 0; } int[] unpack(ArrayList< Integer > a){ int[] ret = new int[a.size()]; for(int i=0; i<a.size(); ++i) ret[i] = a.get(i); return ret; } // generic main stuff static myScanner sc; static PrintWriter pw; static long startTime; public static void main(String[] args) throws Exception{ // sc = new Scanner(System.in); sc = (new Main()).new myScanner(new BufferedReader(new InputStreamReader(System.in))); pw = new PrintWriter(System.out); startTime = System.nanoTime(); (new Main()).go(); // errprintln("nanoTime="+(System.nanoTime()-startTime)/1000000/1000.0); pw.flush(); System.exit(0); } // capable of reading 2.86M 6dp doubles per second // 2.16M 12dp doubles per second // 2.75M int per second public class myScanner{ private BufferedReader f; private StringTokenizer st; public myScanner(BufferedReader ff){ f=ff; st=new StringTokenizer(""); } public int nextInt(){ return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public String nextLine(){ st=new StringTokenizer(""); String ret=""; try{ ret=f.readLine(); }catch(Exception e){} return ret; } public String nextToken(){ while(!st.hasMoreTokens()) try{ st=new StringTokenizer(f.readLine()); } catch(Exception e){} return st.nextToken(); } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class ProblemB { public static int _gnum; public static int _cnum; public static int _needs; public static int _level; public static double _maxans = 0; public static double votedfs(int[][] grl, int g, int votes) { if (votes >= _needs) { return 1.0d; } if (g >= _gnum) { return 0.0d; } double agrees = (double)grl[g][1] / 100; return agrees * votedfs(grl, g+1, votes+1) + (1.0d - agrees) * votedfs(grl, g+1, votes); } public static double battledfs(int[][] grl, int g, int votes, int levels) { if (votes >= _needs) { return 0.0d; } if (g >= _gnum) { return (double)_level / (_level + levels); } double agrees = (double)grl[g][1] / 100; return agrees * battledfs(grl, g+1, votes+1, levels) + (1.0d - agrees) * battledfs(grl, g+1, votes, levels + grl[g][0]); } public static void candydfs(int[][] grl, int g, int n) { if (g >= _gnum) { double na = votedfs(grl, 0, 0) + battledfs(grl, 0, 0, 0); _maxans = Math.max(_maxans, na); return; } int rem = grl[g][1]; candydfs(grl, g+1, n); for (int i = 1 ; i <= n ; i++) { if (grl[g][1] < 100) { grl[g][1] += 10; candydfs(grl, g+1, n-i); } } grl[g][1] = rem; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); String[] d = line.split(" "); int gnum = Integer.valueOf(d[0]); int cnum = Integer.valueOf(d[1]); int level = Integer.valueOf(d[2]); _gnum = gnum; _cnum = cnum; _needs = (gnum + 1) / 2; if (gnum % 2 == 0) { _needs += 1; } _level = level; int[][] grl = new int[gnum][2]; for (int g = 0 ; g < gnum ; g++) { line = br.readLine(); String[] gg = line.split(" "); grl[g][0] = Integer.valueOf(gg[0]); grl[g][1] = Integer.valueOf(gg[1]); } for (int a = 0 ; a < gnum ; a++) { for (int b = 0 ; b < gnum - 1 ; b++) { if (grl[b][1] < grl[b+1][1]) { int tmp = grl[b][0]; grl[b][0] = grl[b+1][0]; grl[b+1][0] = tmp; tmp = grl[b][1]; grl[b][1] = grl[b+1][1]; grl[b+1][1] = tmp; } } } int ag = 0; int xnum = cnum; for (int g = 0 ; g < gnum ; g++) { int needs = (100 - grl[g][1]) / 10; int roy = 0; if (needs <= xnum) { xnum -= needs; roy = 100; } else { roy = grl[g][1] + xnum * 10; xnum = 0; } if (roy >= 100) { ag++; } } if (ag >= _needs) { System.out.println(1.0); return; } candydfs(grl, 0, _cnum); System.out.println(_maxans); br.close(); } }
np
105_B. Dark Assembly
CODEFORCES
import javax.print.Doc; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class taskB { public static void main(String[] args) throws IOException { new taskB().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; static String TASK = ""; void run() throws IOException { try { // reader = new BufferedReader(new FileReader(TASK + ".in")); reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); // writer = new PrintWriter(TASK + ".out"); tokenizer = null; solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int b[]; int l[]; int add[]; int n, k, A; double ans = 0; void solve() throws IOException { n = nextInt(); k = nextInt(); A = nextInt(); b = new int[n]; l = new int[n]; add = new int[n]; for (int i = 0; i < n; ++i) { b[i] = nextInt(); l[i] = nextInt(); } brute(0, k); writer.printf("%.10f", ans); } private void brute(int pos, int yet) { if (pos == n) { /*double prob[][] = new double[n + 1][n + 1]; prob[0][0] = 1; for (int i = 1; i <= n; ++i) { for (int sayYes = 1; sayYes <= i; ++sayYes) { prob[i][sayYes] = p[i - 1] * prob[i - 1][sayYes - 1]; } for (int sayYes = 0; sayYes <= i; ++sayYes) { prob[i][sayYes] = (1 - p[i - 1]) * prob[i - 1][sayYes]; } } double nowYes = 0; for (int i = 0; i <= n; ++i) { if (i >= (n + 2) / 2 ) nowYes += prob[n][i]; } */ double p[] = new double[n]; for (int i = 0; i < n; ++i) { p[i] = (l[i] + add[i]) / 100.0; } double r = 0; for (int i =0; i < (1 << n); ++i) { double pr =1 ; int sm = 0; for (int j =0 ; j < n; ++j) { if ((i & (1 << j)) > 0) { pr *= p[j]; } else { pr *= (1 - p[j]); sm += b[j]; } } int c = Integer.bitCount(i); if (c >= (n + 2) / 2) { r += pr; } else { r += pr * (1.0 * A / (A + sm)); } } ans = Math.max(ans, r); } else { for (int i = 0; i <= yet; ++i) { if (l[pos] + 10 * i > 100) continue; add[pos] = 10 * i; brute(pos + 1, yet - i); } } } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { double ans = 0; int[] candy; int[] b; int[] l; int[] curLoyal; int n; int k; int A; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); k = in.nextInt(); A = in.nextInt(); b = new int[n]; l = new int[n]; for (int i = 0; i < n; i++) { b[i] = in.nextInt(); l[i] = in.nextInt(); } candy = new int[n]; curLoyal = new int[n]; comb(0, k); out.println(ans); } void comb(int ind, int unusedCandy) { if (ind == n) { for (int i = 0; i < n; i++) { curLoyal[i] = Math.min(candy[i] * 10 + l[i], 100); } calc(); } else { for (int i = 0; i <= unusedCandy; i++) { candy[ind] = i; comb(ind + 1, unusedCandy - i); } } } void calc() { double res = 0; int allBits = (1 << n) - 1; for (int vote = 0; vote <= allBits; vote++) { double curProb = 1; int sumPower = A; int enemyCnt = 0; for (int voteInd = 0; voteInd < n; voteInd++) { if ((vote & (1 << voteInd)) == 0) { curProb *= 100 - curLoyal[voteInd]; sumPower += b[voteInd]; enemyCnt++; } else { curProb *= curLoyal[voteInd]; } curProb /= 100; } if (2 * enemyCnt >= n) { curProb *= A; curProb /= sumPower; } res += curProb; } ans = Math.max(ans, res); } } static 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(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.*; import java.util.*; public class Main { StreamTokenizer in; PrintWriter out; public static void main(String[] args) throws Exception { new Main().run(); } public void run() throws Exception { Locale.setDefault(Locale.US); in = new StreamTokenizer (new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); } public int nextInt() throws Exception { in.nextToken(); return (int) in.nval; } public String next() throws Exception { in.nextToken(); return in.sval; } class Senator { int b; int l; public Senator (int b,int l) { this.b=b; this.l=l; } } int n,k,A; double max=Integer.MIN_VALUE; Senator[] a; public void check (int step,int candy) { if (step==n) { double tmp = 0.0; for (int mask=0; mask<(1<<n);mask++) { double P = 1.0; int q = 0; for (int i=0; i<n;i++) { if ((mask>>i&1)!=0) { P*=a[i].l/100.; } else { P*=1.0-a[i].l/100.; q+=a[i].b; } } if (Integer.bitCount(mask)>n/2) { tmp+=P; } else { tmp+=P*A/(A+q); } max=Math.max(tmp,max); } } else { for (int i=0;i<=Math.min(k,(100-a[step].l)/10);i++) { a[step].l+=10*i; check(step+1,k-i); a[step].l-=10*i; } } } public void solve() throws Exception { n=nextInt(); k=nextInt(); A=nextInt(); a = new Senator [n]; for (int i=0; i<n;i++) { Senator q = new Senator(nextInt(),nextInt()); a[i]=q; } double ans=0; for(int mask=0;mask<1<<(n+k-1);mask++) { if(Integer.bitCount(mask)!=k) continue; int[] b = new int[n]; int x = mask; for(int i=0;i<n;i++) { b[i] = a[i].l; while(x%2==1) { b[i]+=10; x/=2; } b[i]=Math.min(b[i],100); x/=2; } double tmp=0; for(int w=0; w<(1<<n);w++) { double p = 1.; double B = 0; for(int i = 0; i < n; i++) if((w >> i & 1) != 0) p *= b[i] / 100.; else { p *= 1- b[i]/100.; B += a[i].b; } if(Integer.bitCount(w)> n/2) tmp += p; else tmp += p * (A / (A + B)); } ans = Math.max(ans, tmp); } out.printf("%.10f\n", ans); } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.*; import java.util.*; public class TemnayaAssambleya implements Runnable { public static void main(String[] args) { new Thread(new TemnayaAssambleya()).run(); } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer in; PrintWriter out = new PrintWriter(System.out); public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int[] l; int[] ln; int[] pw; int[] p; int A; double max = 0; public void gen(int n, int k) { if (n == 0) { n = p.length; p[0] = k; for (int i = 0; i < n; i++) { ln[i] = l[i] + p[i] * 10; if (ln[i] > 100) ln[i] = 100; } double ans = 0; for (int mask = 0; mask < 1 << n; mask++) { int z = 0; double pos = 1; int power = 0; for (int i = 0; i < n; i++) { if ((mask & (1 << i)) > 0) { z++; pos *= ln[i] * 1. / 100; } else { pos *= (100 - ln[i]) * 1. / 100; power += pw[i]; } } if (z > n / 2) { ans += pos; } else { ans += pos * A / (A + power); } } max = Math.max(ans, max); return; } for (int i = 0; i <= Math.min(k, 10 - l[n] / 10); i++) { p[n] = i; gen(n - 1, k - i); } } public void solve() throws IOException { int n = nextInt(); int k = nextInt(); A = nextInt(); p = new int[n]; pw = new int[n]; l = new int[n]; ln = new int[n]; for (int i = 0; i < n; i++) { pw[i] = nextInt(); l[i] = nextInt(); } gen(n - 1, k); out.println(max); } public void run() { try { solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class B implements Runnable { int a; int[] b; int[] l; public void solve() throws IOException { int n = in.nextInt(); int k = in.nextInt(); a = in.nextInt(); b = new int[n]; l = new int[n]; for ( int i = 0; i < n; i ++ ) { b[i] = in.nextInt(); l[i] = in.nextInt(); } out.println( best( 0, k )); } double best( int cur, int left ) { double r = 0.0; if ( cur < l.length ) { for ( int i = 0; i <= left && l[cur] + 10 * i <= 100; i ++ ) { l[cur] += i * 10; r = Math.max( r, best( cur + 1, left - i ) ); l[cur] -= i * 10; } } else { for ( int m = 0; m < ( 1 << l.length ); m ++ ) { int sum = 0; double p = 1.0; int pro = 0; for ( int i = 0; i < l.length; i ++ ) { if ( ( m & ( 1 << i ) ) == 0 ) { p *= 1.0 - l[i] * 0.01; sum += b[i]; } else { p *= l[i] * 0.01; pro ++; } } if ( pro * 2 > l.length ) { r += p; } else { r += ( p * a ) / ( a + sum ); } } } return r; } public Scanner in; public PrintWriter out; B() throws IOException { in = new Scanner(System.in); // in = new StreamTokenizer( new InputStreamReader( System.in ) ); out = new PrintWriter(System.out); } // int nextInt() throws IOException { // in.nextToken(); // return ( int ) in.nval; // } void check(boolean f, String msg) { if (!f) { out.close(); throw new RuntimeException(msg); } } void close() throws IOException { out.close(); } public void run() { try { solve(); close(); } catch (Exception e) { e.printStackTrace(out); out.flush(); throw new RuntimeException(e); } } public static void main(String[] args) throws IOException { new Thread(new B()).start(); } }
np
105_B. Dark Assembly
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 8/13/11 * Time: 6:10 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.io.IOException; public class DarkAssembly extends Thread { public DarkAssembly() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } static class Senator { int loyalty; int level; public Senator(int level, int loyalty) { this.level = level; this.loyalty = loyalty; } } private static double doIt(Senator[] senators, int A) { double probability = .0; for (int mask = 0; mask < (1 << senators.length); ++mask) { int sum = A; double current = 1.0; for (int i = 0; i < senators.length; ++i) { if ((mask & (1 << i)) != 0) { current *= .01 * senators[i].loyalty; } else { current *= .01 * (100 - senators[i].loyalty); sum += senators[i].level; } } if (Integer.bitCount(mask) > senators.length / 2) { probability += current; } else { probability += current * (double) A / sum; } } return probability; } private static double go(Senator[] senators, int candies, int A, int current) { if (current == senators.length) { return doIt(senators, A); } else { double result = go(senators, candies, A, current + 1); if (candies > 0 && senators[current].loyalty < 100) { senators[current].loyalty += 10; result = Math.max(result, go(senators, candies - 1, A, current)); senators[current].loyalty -= 10; } return result; } } private void solve() throws Throwable { int n = nextInt(); int k = nextInt(); int A = nextInt(); Senator[] senators = new Senator[n]; for (int i = 0; i < n; ++i) { senators[i] = new Senator(nextInt(), nextInt()); } output.printf("%.10f", go(senators, k, A, 0)); } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { output.flush(); output.close(); } } public static void main(String[] args) { new DarkAssembly().start(); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
105_B. Dark Assembly
CODEFORCES
import java.util.Scanner; public class B { static int n; static double A; static int[] L; static int[] B; static double max = 0; public static void rec(int index, int k) { if (k < 0) return; if (index == n) { double prob = 0; for (int i = 0; i < (1 << n); i++) { double b = 0; double temp = 1.0; for (int j = 0; j < n; j++) { if (L[j] > 100) return; if ((i & (1 << j)) == 0) { b += B[j]; temp *= (100 - L[j]) / 100.0; } else temp *= L[j] / 100.0; } if (Integer.bitCount(i) * 2 <= n) temp *= A / (A + b); prob += temp; } max = Math.max(max, prob); return; } L[index] += 10; rec(index, k - 1); L[index] -= 10; rec(index + 1, k); } public static void main(String[] args) { Scanner in = new Scanner(System.in); n = in.nextInt(); int k = in.nextInt(); A = in.nextDouble(); B = new int[n]; L = new int[n]; for (int i = 0; i < n; i++) { B[i] = in.nextInt(); L[i] = in.nextInt(); } rec(0, k); System.out.println(max); } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Locale; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Map.Entry; public class Solution implements Runnable { public static void main(String[] args) { (new Thread(new Solution())).start(); } BufferedReader in; PrintWriter out; StringTokenizer st; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String r = in.readLine(); if (r == null) return null; st = new StringTokenizer(r); } 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()); } int n; int[] b, l; double ans; int[] sw; int a; void sol() { for (int i = 0; i < n; i++) l[i] += sw[i] * 10; double yes = 0; for (int q = 0; q < (1 << n); q++) { double p = 1; int bb = 0; int cnt = 0; for (int i = 0; i < n; i++) { if ((q & (1 << i)) == 0) { p *= (1.0 - (double)l[i] / 100); bb += b[i]; } else { p *= 1.0 * (double)l[i] / 100; cnt++; } } if (cnt > n / 2) { yes += p; } else { yes += p * (double)a / (double)(a + bb); } } if (ans < yes) ans = yes; for (int i = 0; i < n; i++) l[i] -= sw[i] * 10; } void rek(int i, int k) { if (i == n) sol(); else { for (int q = 0; q <= k && l[i] + q * 10 <= 100; q++) { sw[i] = q; rek(i + 1, k - q); } } } void solve() throws Exception { n = nextInt(); int k = nextInt(); a = nextInt(); b = new int[n]; l = new int[n]; sw = new int[n]; for (int i = 0; i < n; i++) { b[i] = nextInt(); l[i] = nextInt(); } rek(0, k); out.printf("%.10f", ans); } public void run() { Locale.setDefault(Locale.UK); try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // in = new BufferedReader(new FileReader("knights.in")); // out = new PrintWriter("knights.out"); solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { out.flush(); } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.*; import java.util.*; public class B { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; int[] level; int[] loyal; double ans; int n, k, plLev, needVotes; double check() { //System.err.println(Arrays.toString(loyal)); double res = 0; for (int mask = 0; mask < (1 << n); mask++) { double prob = 1; int vote = 0; int kill = 0; for (int i = 0; i < n; i++) if (((mask >> i) & 1) == 1) { prob *= loyal[i] / 100.0; vote++; } else { prob *= 1 - loyal[i] / 100.0; kill += level[i]; } if (vote >= needVotes) res += prob; else res += prob * plLev / (kill + plLev); } return res; } void go(int ind, int candy) { if (ind == n) { ans = Math.max(ans, check()); return; } for (int i = 0; i <= candy; i++) { loyal[ind] += 10 * i; if (loyal[ind] > 100) { loyal[ind] -= 10 * i; break; } go(ind + 1, candy - i); loyal[ind] -= 10 * i; } } void solve() throws IOException { n = nextInt(); k = nextInt(); plLev = nextInt(); needVotes = n / 2 + 1; ans = 0; level = new int[n]; loyal = new int[n]; for (int i = 0; i < n; i++) { level[i] = nextInt(); loyal[i] = nextInt(); } go(0, k); out.printf("%.12f", ans); } void inp() throws IOException { Locale.setDefault(Locale.US); br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new B().inp(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "0"; } } return st.nextToken(); } String nextString() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "0"; } } return st.nextToken("\n"); } 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
105_B. Dark Assembly
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; public class B{ public static void main(String[] args) throws Exception{ new B().run(); } double ans = 0; int n, candy, A, half; void run() throws Exception{ Scanner sc = new Scanner(System.in); //BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); // only sc.readLine() is available n = sc.nextInt(); candy = sc.nextInt(); A = sc.nextInt(); half = n/2; //int[] level = new int[n]; //int[] loyal = new int[n]; S[] ss = new S[n]; for(int i = 0; i < n; i++){ ss[i] = new S(sc.nextInt(), sc.nextInt()); } Arrays.sort(ss); int need = 0; for(int i = n-1; i >= n-half-1; i--) need += (100-ss[i].loyal)/10; if(need <= candy){ System.out.println(1.0); return; } tra(ss, 0, candy); /* while(candy > 0){ int ind = 0; for(int i = 1; i < n; i++) if(ss[i].loyal < 100 && ss[ind].level < ss[i].level) ind = i; ss[ind].loyal += 10; ss[ind].loyal = min(100, ss[ind].loyal); candy--; } */ System.out.printf("%.10f\n", ans); } void tra(S[] ss, int pos, int rest){ if(pos == n){ double sum = 0; int lim = 1<<n; for(int m = 0; m < lim; m++){ int app = Integer.bitCount(m); double p = 1; int B = 0; for(int i = 0; i < n; i++){ if(((m>>i) & 1) == 1){ p = p * ss[i].loyal / 100; }else{ p = p * (100 - ss[i].loyal) / 100; B += ss[i].level; } } if(app > half)sum += p; else{ sum += p * A / (A+B); } } ans = max(ans, sum); return; } for(int i = 0; i <= rest; i++){ int old = ss[pos].loyal; int nl = ss[pos].loyal + i * 10; if(nl > 100)break; ss[pos].loyal = nl; tra(ss, pos+1, rest-i); ss[pos].loyal = old; } } } class S implements Comparable<S>{ int level, loyal; S(int a, int b){ level = a; loyal = b; } public int compareTo(S s){ return this.loyal - s.loyal; } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main implements Runnable { int[] conf, L, B; int n, k, A, sz; double[] kill; double best = 0; double solv() { double res = 0; double[] a = new double[n]; for (int i=0; i<n; i++) a[i] = Math.min(100, L[i]+10*conf[i])/100.0; double[] dp1 = new double[sz]; double[] dp2 = new double[sz]; dp1[0] = 1; for (int i=0; i<n; i++) { for (int msk=0; msk<sz; msk++) { dp2[msk] += dp1[msk]*a[i]; dp2[msk|(1<<i)] += dp1[msk]*(1-a[i]); } for (int msk=0; msk<sz; msk++) { dp1[msk] = dp2[msk]; dp2[msk] = 0; } } /*for (int msk=0; msk<sz; msk++) { double p = 1; int cnt = 0; for (int i=0; i<n; i++) if ((msk&(1<<i))>0) { p *= (100-a[i])/100.0; } else { p *= a[i]/100.0; cnt++; } if (cnt>n/2) res += p; else res += p*kill[msk]; } res /= sz;*/ for (int msk=0; msk<sz; msk++){ if (n-Integer.bitCount(msk) > n/2) res += dp1[msk]; else res += dp1[msk]*kill[msk]; } return res; } void gen(int n, int k) { if (n==0) { conf[0] = k; //conf[0] = 2; conf[1] = 1; conf[2] = 3; double x = solv(); if (x>best) best = x; return; } for (int i=0; i<=k; i++) { conf[n] = i; gen(n-1, k-i); } conf[n] = 0; } void solve() throws IOException { n = nextInt(); k = nextInt(); A = nextInt(); B = new int[n]; L = new int[n]; for (int i=0; i<n; i++) { B[i] = nextInt(); L[i] = nextInt(); } sz = 1<<n; conf = new int[n]; kill = new double[sz]; for (int msk=0; msk<sz; msk++) { int sum = 0; for (int i=0; i<n; i++) if ((msk&(1<<i))>0) { sum += B[i]; } kill[msk] = A*1./(A+sum); } gen(n-1, k); out.printf(Locale.US, "%1.9f", best); } BufferedReader br; StringTokenizer st; PrintWriter out; public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // br = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter("output.txt"); solve(); br.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(123); } } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String s = br.readLine(); if (s == null) return null; st = new StringTokenizer(s,", \t"); } return st.nextToken(); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } public static void main(String[] args) { new Thread(new Main()).start(); } }
np
105_B. Dark Assembly
CODEFORCES
//package contest10D; import java.math.*; import java.util.*; import static java.math.BigInteger.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class Main { static void debug(Object... os) { System.err.println(deepToString(os)); } public static void main(String[] args) { new Main().run(); } void run() { Scanner sc = new Scanner(System.in); int n=sc.nextInt(),m=sc.nextInt(); boolean[][] bs=new boolean[n][n]; for (int i = 0; i < m; i++) { int s=sc.nextInt()-1,t=sc.nextInt()-1; bs[s][t] = bs[t][s] = true; } long res = 0; for(int i=0;i<n;i++){ res += calc(bs,n-1-i); } System.out.println(res/2); } long calc(boolean[][] bs,int n){//start is n. long[][] dp=new long[1<<n][n]; // set,last -> number of path n -> last. for(int i=0;i<n;i++){ if(bs[i][n]) dp[1<<i][i] ++; } for(int i=1;i<1<<n;i++){ for(int j=0;j<n;j++)if(((i>>j)&1)==1) for(int k=0;k<n;k++)if(((i>>k)&1)==0 && bs[j][k]){//add dp[i|(1<<k)][k] += dp[i][j]; } } long res=0; for(int i=0;i<1<<n;i++)for(int j=0;j<n;j++)if(Integer.bitCount(i)>=2&&bs[j][n])res+=dp[i][j]; return res; } }
np
11_D. A Simple Task
CODEFORCES
import java.awt.List; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Locale; import java.util.TimeZone; public class Cycle { public static void main(String[] args) { Locale.setDefault(Locale.US); InputStream inputstream = System.in; OutputStream outputstream = System.out; FastReader in = new FastReader(inputstream); PrintWriter out = new PrintWriter(outputstream); TaskA solver = new TaskA(); // int testcase = in.ni(); for (int i = 0; i < 1; i++) solver.solve(i, in, out); out.close(); } } class TaskA { public void solve(int testnumber, FastReader in, PrintWriter out) { int n = in.ni(); int m = in.ni(); boolean graph[][] = new boolean[n][n]; for (int i = 0; i < m; i++) { int a = in.ni() - 1; int b = in.ni() - 1; graph[a][b] = true; graph[b][a] = true; } /* * dp[mask][i] be the number of Hamiltonian walks over the subset mask, * starting at the vertex first(mask) and ending at the vertex i */ long dp[][] = new long[1 << n][n]; for (int i = 0; i < n; i++) { dp[1 << i][i] = 1; } long answer = 0; for (int mask = 1; mask < (1 << n); mask++) { int start = Integer.numberOfTrailingZeros(mask); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) == 0) { continue; } for (int j = start + 1; j < n; j++) { if (graph[i][j] && (mask & (1 << j)) == 0) { dp[mask + (1 << j)][j] += dp[mask][i]; } } if (graph[i][start]) { answer += dp[mask][i]; } } } out.println((answer - m) / 2); } } class FastReader { public InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public FastReader() { } 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 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 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 static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] iArr(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String next() { return ns(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Darshandarji */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); boolean[][] g = new boolean[n][n]; for (int i = 0; i < m; ++i) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; g[a][b] = true; g[b][a] = true; } /*for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) g[i][j] = true;*/ long[] am = new long[n + 1]; long[][] ways = new long[1 << n][n]; for (int start = 0; start < n; ++start) { for (int mask = 0; mask < (1 << (n - start)); ++mask) for (int last = start; last < n; ++last) { ways[mask][last - start] = 0; } ways[1][0] = 1; for (int mask = 0; mask < (1 << (n - start)); ++mask) { int cnt = 0; int tmp = mask; while (tmp > 0) { ++cnt; tmp = tmp & (tmp - 1); } for (int last = start; last < n; ++last) if (ways[mask][last - start] > 0) { long amm = ways[mask][last - start]; for (int i = start; i < n; ++i) if ((mask & (1 << (i - start))) == 0 && g[last][i]) { ways[mask | (1 << (i - start))][i - start] += amm; } if (g[last][start]) am[cnt] += ways[mask][last - start]; } } } long res = 0; for (int cnt = 3; cnt <= n; ++cnt) { if (am[cnt] % (2) != 0) throw new RuntimeException(); res += am[cnt] / (2); } out.println(res); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; /** * Created by Tejas on 18-10-2018. */ public class Main { static HashSet<Integer> adjList[]; public static void main(String[]args)throws IOException{ BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in)); StringBuilder stringBuilder=new StringBuilder(); String temp[]=bufferedReader.readLine().split(" "); int V=Integer.parseInt(temp[0]); int E=Integer.parseInt(temp[1]); adjList=new HashSet[V]; for(int i=0;i<V;i++) adjList[i]=new HashSet<>(); for(int i=0;i<E;i++){ temp=bufferedReader.readLine().split(" "); int x=Integer.parseInt(temp[0])-1; int y=Integer.parseInt(temp[1])-1; adjList[y].add(x); adjList[x].add(y); } stringBuilder.append(solve(V)+"\n"); System.out.println(stringBuilder); } private static long solve(int V) { long dp[][]=new long[(1<<V)][V]; long count=0; for(int i=0;i<V;i++) dp[(1<<i)][i]=1; for(int mask=1;mask<(1<<V);mask++){ // HW starting at pos first and ending at j. int first = Integer.numberOfTrailingZeros(mask); for(int i=0;i<V;i++){ if((mask&(1<<i))==0 || first==i) continue; for (int j = 0; j < V; j++) if (adjList[i].contains(j) && (mask & (1<<j))!=0) dp[mask][i] += dp[mask ^ (1 << i)][j]; //Calculating simple cycles if (Integer.bitCount(mask)>=3) if(adjList[first].contains(i)) count+=dp[mask][i]; } } return count/2; } }
np
11_D. A Simple Task
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int n; ArrayList<Integer>[] adj; long[] mem; int start; long cycles(int cur, int visited) { if (cur == start && visited > 0) { return Integer.bitCount(visited) >= 3 ? 1 : 0; } int index = visited * n + cur; if (mem[index] != -1) return mem[index]; long res = 0; int newvisited = visited | (1 << cur); for (int nxt : adj[cur]) { if (nxt >= start && (nxt == start || ((visited >> nxt) & 1) == 0)) { res += cycles(nxt, newvisited); } } return mem[index] = res; } public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.readInt(); int m = in.readInt(); adj = new ArrayList[n]; mem = new long[n * (1 << n)]; for (int i = 0; i < adj.length; i++) adj[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int a = in.readInt() - 1, b = in.readInt() - 1; adj[a].add(b); adj[b].add(a); } long res = 0; for (int start = 0; start < n; start++) { Arrays.fill(mem, -1); this.start = start; res += cycles(start, 0) / 2; } out.printLine(res); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } 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); } } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { new Main().run(); } boolean[][] graph; public void run() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); graph = new boolean[n][n]; for (int i = 0; i < m; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; graph[a][b] = true; graph[b][a] = true; } long res = 0; for (int i = 3; i <= n; i++) { res += solve(i); } System.out.println(res); } long solve(int n) { // [0, n)の頂点だけで、n-1 スタートだけ考える long[][] dp = new long[1 << n][n]; dp[1 << (n-1)][n-1] = 1; for (int i = 0; i < (1 << n); ++i) { for (int l = 0; l < n; ++l) if (dp[i][l] > 0) { for (int x = 0; x < n - 1; ++x) if (graph[l][x] && (i >> x & 1) == 0) { dp[i | (1 << x)][x] += dp[i][l]; } } } long res = 0; for (int i = 0; i < (1 << n); ++i) if (Integer.bitCount(i) >= 3) { for (int l = 0; l < n; ++l) { if (graph[l][n-1]) res += dp[i][l]; } } return res / 2; // n-1 を含むサイクルを右回りと左回り数えてしまったので2で割る } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); boolean[][] graph = new boolean[n][n]; for(int i = 0; i < m; i++) { int from = in.nextInt() - 1; int to = in.nextInt() - 1; graph[from][to] = true; graph[to][from] = true; } int max = 1 << n; long[][] dp = new long[max][n]; for(int mask = 1; mask < max; mask++) { for(int i = 0; i < n; i++) { int countMask = Integer.bitCount(mask); boolean existSubSeti = (mask & (1 << i)) > 0; if(countMask == 1 && existSubSeti) { dp[mask][i] = 1; } else if(countMask > 1 && existSubSeti) { int mask1 = mask ^ (1 << i); for(int j = 0; j < n; j++) { if(((mask1 & (1 << j)) > 0) && graph[j][i] && i != firstMask(mask, n)) { dp[mask][i] += dp[mask1][j]; } } } } } long counter = 0; for(int mask = 1; mask < max; mask++) { for(int i = 0; i < n; i++) { if(Integer.bitCount(mask) >= 3 && graph[firstMask(mask, n)][i]) { counter += dp[mask][i]; } } } System.out.println(counter / 2); in.close(); } public static int firstMask(int mask, int n) { for(int i = 0; i < n; i++) { if((mask & (1 << i)) > 0) return i; } return -1; } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; public class Solution { public void doMain() throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(); boolean[][] adj = new boolean[n][n]; for (int i=0; i<m; i++) { int a = sc.nextInt()-1, b = sc.nextInt()-1; adj[a][b] = adj[b][a] = true; } long res = 0; for (int st=0; st+1<n; st++) { //System.out.println("st="+st); long[][] numWays = new long[1<<(n-st-1)][n-st-1]; for (int i=st+1; i<n; i++) if (adj[st][i]) numWays[1<<(i-st-1)][i-st-1] = 1; for (int mask=1; mask < (1<<(n-st-1)); mask++) { boolean simple = ((mask & (mask-1)) == 0); for (int last=0; last<n-st-1; last++) if (numWays[mask][last]!=0) { if (adj[last+st+1][st] && !simple) res += numWays[mask][last]; for (int next=0; next<n-st-1; next++) if (adj[last+st+1][next+st+1] && (mask & (1<<next)) == 0) numWays[mask | (1<<next)][next] += numWays[mask][last]; } } } System.out.println(res/2); } public static void main(String[] args) throws Exception { (new Solution()).doMain(); } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); boolean[][] graph = new boolean[n][n]; for(int i = 0; i < m; i++) { int from = in.nextInt() - 1; int to = in.nextInt() - 1; graph[from][to] = true; graph[to][from] = true; } int max = 1 << n; long[][] dp = new long[max][n]; for(int mask = 1; mask < max; mask++) { for(int i = 0; i < n; i++) { int countMask = Integer.bitCount(mask); boolean existSubSeti = (mask & (1 << i)) > 0; if(countMask == 1 && existSubSeti) { dp[mask][i] = 1; } else if(countMask > 1 && existSubSeti) { int mask1 = mask ^ (1 << i); for(int j = 0; j < n; j++) { if(graph[j][i] && i != firstMask(mask, n)) { dp[mask][i] += dp[mask1][j]; } } } } } long counter = 0; for(int mask = 1; mask < max; mask++) { for(int i = 0; i < n; i++) { if(Integer.bitCount(mask) >= 3 && graph[firstMask(mask, n)][i]) { counter += dp[mask][i]; } } } System.out.println(counter / 2); in.close(); } public static int firstMask(int mask, int n) { for(int i = 0; i < n; i++) { if((mask & (1 << i)) > 0) return i; } return -1; } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Arrays; /** * Created by IntelliJ IDEA. * User: piyushd * Date: 12/31/10 * Time: 1:30 PM * To change this template use File | Settings | File Templates. */ public class SimpleCycle { int first(int x){ return x - (x & (x - 1)); } void run(){ int N = nextInt(), M = nextInt(); int[] graph = new int[N]; for(int i = 0; i < M; i++){ int a = nextInt() - 1, b = nextInt() - 1; graph[a] |= (1<<b); graph[b] |= (1<<a); } int[] bitcount = new int[1<<N]; for(int i = 0; i < (1<<N); i++){ bitcount[i] = bitcount[i>>1]; if(i % 2 == 1) bitcount[i]++; } long[][] dp = new long[1<<N][N]; for(long[] f : dp) Arrays.fill(f, 0); long ans = 0; for(int mask = 1; mask < (1<<N); mask++){ for(int i = 0; i < N; i++)if((mask & (1<<i)) > 0){ if(bitcount[mask] == 1) dp[mask][i] = 1; else{ if(first(mask) != (1<<i)){ for(int j = 0; j < N; j++)if((graph[i] & (1<<j)) > 0 && (mask & (1<<j)) > 0){ dp[mask][i] += dp[mask - (1<<i)][j]; } } } if(bitcount[mask] >= 3 && (graph[i] & first(mask)) > 0) ans += dp[mask][i]; } } System.out.println(ans / 2); } int nextInt(){ try{ int c = System.in.read(); if(c == -1) return c; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return c; } if(c == '-') return -nextInt(); int res = 0; do{ res *= 10; res += c - '0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c = System.in.read(); if(c == -1) return -1; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return -1; } if(c == '-') return -nextLong(); long res = 0; do{ res *= 10; res += c-'0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(Character.isWhitespace(c)) c = System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(c == '\r' || c == '\n') c = System.in.read(); do{ res.append((char)c); c = System.in.read(); }while(c != '\r' && c != '\n'); return res.toString(); }catch(Exception e){ return null; } } public static void main(String[] args){ new SimpleCycle().run(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class ProblemD { static int N; static boolean[][] graph; public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] data = s.readLine().split(" "); int n = Integer.valueOf(data[0]); N = n; int m = Integer.valueOf(data[1]); graph = new boolean[n][n]; for (int i = 0 ; i < m ; i++) { String[] line = s.readLine().split(" "); int a = Integer.valueOf(line[0])-1; int b = Integer.valueOf(line[1])-1; graph[a][b] = true; graph[b][a] = true; } long ans = 0; for (int i = 0 ; i < n ; i++) { ans += doit(i); } ans /= 2; out.println(ans); out.flush(); } static long doit(int n) { long[][] dp = new long[1<<n][n]; for (int i = 0 ; i < n ; i++) { if (graph[i][n]) { dp[1<<i][i] = 1; } } for (int i = 0 ; i < (1<<n) ; i++) { for (int j = 0 ; j < n ; j++) { if (dp[i][j] >= 1) { for (int k = 0 ; k < n ; k++) { if (graph[j][k] && (i & (1<<k)) == 0) { dp[i|1<<k][k] += dp[i][j]; } } } } } long ret = 0; for (int i = 0 ; i < (1<<n) ; i++) { if (Integer.bitCount(i) >= 2) { for (int j = 0 ; j < n ; j++) { if (graph[j][n]) { ret += dp[i][j]; } } } } return ret; } static void generateLarge() { System.out.println("19 171"); for (int i = 1 ; i <= 19 ; i++) { for (int j = i+1 ; j <= 19 ; j++) { System.out.println(i + " " + j); } } } public static void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } }
np
11_D. A Simple Task
CODEFORCES
/** * JUDGE_ID : 104262PN * User : Денис * Date : 09.05.11 * Time : 22:48 * ICQ : 785625 * Email : [email protected] */ import java.io.*; public class s11_d { public static void main(String[] args) throws IOException { new s11_d().run(); } int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } String nextString() throws IOException { in.nextToken(); return (String) in.sval; } StreamTokenizer in; Writer writer; Reader reader; void run() throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; reader = oj ? new InputStreamReader(System.in, "ISO-8859-1") : new FileReader("input/is11_d.txt"); writer = new OutputStreamWriter(System.out, "ISO-8859-1"); in = new StreamTokenizer(new BufferedReader(reader)); PrintWriter out = new PrintWriter(writer); int n = nextInt(); int e = nextInt(); boolean[][] is = new boolean[n + 1][n + 1]; for (int i = 0; i < e;i++) { int a = nextInt() - 1; int b = nextInt() - 1; is[a][b] = true; is[b][a] = true; } // calculating dp long[] am = new long[n + 1]; long[][] ways = new long[1 << (n - 1)][n]; for (int start = 0; start < n; ++start) { for (int mask = 0; mask < (1 << (n - start - 1)); ++mask) for (int last = start; last < n; ++last) { ways[mask][last - start] = 0; } ways[1 >> 1][0] = 1; for (int mask = 1; mask < (1 << (n - start)); mask += 2) { int cnt = 0; int tmp = mask; while (tmp > 0) { ++cnt; tmp = tmp & (tmp - 1); } for (int last = start; last < n; ++last) if (ways[mask >> 1][last - start] > 0) { long amm = ways[mask >> 1][last - start]; for (int i = start; i < n; ++i) if ((mask & (1 << (i - start))) == 0 && is[last][i]) { ways[(mask | (1 << (i - start))) >> 1][i - start] += amm; } if (is[last][start]) am[cnt] += ways[mask >> 1][last - start]; } } } long res = 0; for (int cnt = 3; cnt <= n; ++cnt) { if (am[cnt] % (2) != 0) throw new RuntimeException(); res += am[cnt] / (2); } out.println(res); out.flush(); out.close(); } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Scanner; public class SimpleTask { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); boolean[][] graph = new boolean[n][n]; for (int i = 0; i < m; i++) { int u = scan.nextInt() - 1; int v = scan.nextInt() - 1; graph[u][v] = true; graph[v][u] = true; } long[][] dp = new long[1 << n][n]; for (int i = 0; i < n; i++) dp[1 << i][i] = 1; for (int mask = 1; mask < (1 << n); mask++) { int first = Integer.numberOfTrailingZeros(mask); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) == 0 || first == i) continue; for (int j = 0; j < n; j++) { if (graph[i][j]) dp[mask][i] += dp[mask ^ 1 << i][j]; } } } long answer = 0; for (int mask = 1; mask < (1 << n); mask++) { if (Integer.bitCount(mask) < 3) continue; int first = Integer.numberOfTrailingZeros(mask); for (int i = 0; i < n; i++) { if (graph[first][i]) answer += dp[mask][i]; } } System.out.println(answer / 2); scan.close(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class CF { void realSolve() { int n = in.nextInt(); int m = in.nextInt(); boolean[][] f = new boolean[n][n]; for (int i = 0; i < m; i++) { int fr = in.nextInt() - 1; int to = in.nextInt() - 1; f[fr][to] = f[to][fr] = true; } long[][] dp = new long[n][1 << n]; for (int i = 0; i < n; i++) dp[i][1 << i] = 1; long res = 0; int[] len = new int[n + 1]; for (int st = 0; st < 1 << n; st++) { int from = Integer.lowestOneBit(st); for (int i =0; i < n;i++) if (((1<<i) & st) != 0) { from =i; break; } for (int to = 0; to < n; to++) if (dp[to][st] != 0) for (int next = from; next < n; next++) if (f[to][next] && ((((1 << next) & st) == 0) || next == from)) if (next == from) { if (Integer.bitCount(st) > 2) { res += dp[to][st]; len[Integer.bitCount(st)] += dp[to][st]; } } else { dp[next][st | (1 << next)] += dp[to][st]; } } out.println(res / 2); } private class InputReader { StringTokenizer st; BufferedReader br; public InputReader(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreElements()) { String s; try { s = br.readLine(); } catch (IOException e) { return null; } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } boolean hasMoreElements() { while (st == null || !st.hasMoreElements()) { String s; try { s = br.readLine(); } catch (IOException e) { return false; } st = new StringTokenizer(s); } return st.hasMoreElements(); } long nextLong() { return Long.parseLong(next()); } } InputReader in; PrintWriter out; void solve() { in = new InputReader(new File("object.in")); try { out = new PrintWriter(new File("object.out")); } catch (FileNotFoundException e) { e.printStackTrace(); } realSolve(); out.close(); } void solveIO() { in = new InputReader(System.in); out = new PrintWriter(System.out); realSolve(); out.close(); } public static void main(String[] args) { new CF().solveIO(); } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Scanner; public class SimpleTask { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); boolean[][] graph = new boolean[n][n]; for (int i = 0; i < m; i++) { int u = scan.nextInt() - 1; int v = scan.nextInt() - 1; graph[u][v] = true; graph[v][u] = true; } long[][] dp = new long[1 << n][n]; long sum = 0; for (int i = 0; i < n; i++) dp[1 << i][i] = 1; for (int mask = 1; mask < (1 << n); mask++) { int first = Integer.numberOfTrailingZeros(mask); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) == 0 || first == i) continue; for (int j = 0; j < n; j++) { if (graph[i][j] && (mask & (1 << j)) != 0) dp[mask][i] += dp[mask ^ 1 << i][j]; } if (Integer.bitCount(mask) >= 3 && graph[i][first]) sum += dp[mask][i]; } } System.out.println(sum / 2); scan.close(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class Main{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int x,y; boolean graph[][]=new boolean[n][n]; for(int i=0;i<m;i++){ x=sc.nextInt()-1; y=sc.nextInt()-1; graph[x][y]=graph[y][x]=true; } long dp[][]=new long[1<<n][n]; long res=0; for(int i=0;i<n;i++){ dp[1<<i][i]=1; } for(int mask=1;mask<(1<<n);mask++){ int first=-1; for(int f=0;f<n;f++){ if((mask&(1<<f))!=0){ first=f; break; } } for(int i=0;i<n;i++){ if((mask&(1<<i))!=0&&i!=first){ for(int j=0;j<n;j++){ if(graph[j][i]&&((mask&1<<j)!=0)){ dp[mask][i]+=dp[mask^1<<i][j]; } } } if(Integer.bitCount(mask)>2&&graph[first][i]){ res+=dp[mask][i]; } } } System.out.println(res/2); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.lang.*; public class P11D{ static long mod=1000000007; public static void main(String[] args) throws Exception{ InputReader in = new InputReader(System.in); PrintWriter pw=new PrintWriter(System.out); //int t=in.readInt(); //while(t-->0) //{ int n=in.readInt(); int m=in.readInt(); boolean v[][]=new boolean[n][n]; for(int i=0;i<m;i++) { int x=in.readInt()-1; int y=in.readInt()-1; v[x][y]=true; v[y][x]=true; } long dp[][]=new long[1<<n][n]; for(int i=0;i<n;i++) { dp[1<<i][i]=1; } long ans=0; for(int mask=1;mask<(1<<n);mask++) { int s=-1; for(int i=0;i<n;i++) { if((mask&(1<<i))!=0) { s=i; break; } } for(int i=0;i<n;i++) { if(i!=s&&((1<<i)&mask)!=0) { for(int j=0;j<n;j++) { if((1<<j)!=0&&i!=j&&v[i][j]) { int rem=(1<<i)^mask; dp[mask][i]+=dp[rem][j]; } } int c=Integer.bitCount(mask); if(c>=3&&v[i][s]) { ans+=dp[mask][i]; } } } } ans/=2; pw.println(ans); //} pw.close(); } public static long gcd(long x,long y) { if(x%y==0) return y; else return gcd(y,x%y); } public static int gcd(int x,int y) { if(x%y==0) return y; else return gcd(y,x%y); } public static int abs(int a,int b) { return (int)Math.abs(a-b); } public static long abs(long a,long b) { return (long)Math.abs(a-b); } public static int max(int a,int b) { if(a>b) return a; else return b; } public static int min(int a,int b) { if(a>b) return b; else return a; } public static long max(long a,long b) { if(a>b) return a; else return b; } public static long min(long a,long b) { if(a>b) return b; else return a; } public static long pow(long n,long p,long m) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static class Pair implements Comparable<Pair> { int a,b; Pair (int a,int b) { this.a=a; this.b=b; } public int compareTo(Pair o) { // TODO Auto-generated method stub if(this.a!=o.a) return Integer.compare(this.a,o.a); else return Integer.compare(this.b, o.b); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.a == a && p.b == b; } return false; } public int hashCode() { return new Integer(a).hashCode() * 31 + new Integer(b).hashCode(); } } static long sort(int a[]) { int n=a.length; int b[]=new int[n]; return mergeSort(a,b,0,n-1);} static long mergeSort(int a[],int b[],long left,long right) { long c=0;if(left<right) { long mid=left+(right-left)/2; c= mergeSort(a,b,left,mid); c+=mergeSort(a,b,mid+1,right); c+=merge(a,b,left,mid+1,right); } return c; } static long merge(int a[],int b[],long left,long mid,long right) {long c=0;int i=(int)left;int j=(int)mid; int k=(int)left; while(i<=(int)mid-1&&j<=(int)right) { if(a[i]<=a[j]) {b[k++]=a[i++]; } else { b[k++]=a[j++];c+=mid-i;}} while (i <= (int)mid - 1) b[k++] = a[i++]; while (j <= (int)right) b[k++] = a[j++]; for (i=(int)left; i <= (int)right; i++) a[i] = b[i]; return c; } public static int[] radixSort(int[] f) { int[] to = new int[f.length]; { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i]; int[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to;to = d; } return f; } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String readLine() { 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 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, readInt()); 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, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //StringBuilder sb=new StringBuilder(""); //InputReader in = new InputReader(System.in); //PrintWriter pw=new PrintWriter(System.out); //String line=br.readLine().trim(); //int t=Integer.parseInt(br.readLine()); // while(t-->0) //{ //int n=Integer.parseInt(br.readLine()); //long n=Long.parseLong(br.readLine()); //String l[]=br.readLine().split(" "); //int m=Integer.parseInt(l[0]); //int k=Integer.parseInt(l[1]); //String l[]=br.readLine().split(" "); //l=br.readLine().split(" "); /*int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=Integer.parseInt(l[i]); }*/ //System.out.println(" "); //} }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.io.*; public class Main implements Runnable { private void solution() throws IOException { int n = in.nextInt(); int m = in.nextInt(); boolean[][] adj = new boolean[n][n]; long res = 0; for (int i = 0; i < m; ++i) { int x = in.nextInt(); int y = in.nextInt(); adj[x - 1][y - 1] = true; adj[y - 1][x - 1] = true; } for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (adj[i][j]) { --res; } } } for (int i = 0; i < n; ++i) { long[][] dp = new long[1 << (n - i)][n - i]; dp[0][0] = 1; for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { if (dp[mask][j] != 0) { for (int k = 0; k < n - i; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) { dp[mask | (1 << k)][k] += dp[mask][j]; } } } } if (((mask >> 0) & 1) != 0) { res += dp[mask][0]; } } } out.println(res / 2); } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private class Scanner { BufferedReader reader; StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""); } 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 int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) throws IOException { new Thread(null, new Main(), "", 1 << 28).start(); } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Scanner in = new Scanner(new InputStreamReader(System.in)); }
np
11_D. A Simple Task
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); boolean[][] graph = new boolean[n][n]; for (int i = 0; i < m; i++) { int u = scan.nextInt() - 1; int v = scan.nextInt() - 1; graph[u][v] = true; graph[v][u] = true; } long[][] dp = new long[1 << n][n]; long sum = 0; for (int i = 0; i < n; i++) dp[1 << i][i] = 1; for (int mask = 1; mask < (1 << n); mask++) { int first = Integer.numberOfTrailingZeros(mask); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) == 0 || first == i) continue; for (int j = 0; j < n; j++) { if (graph[i][j] && (mask & (1 << j)) != 0) dp[mask][i] += dp[mask ^ 1 << i][j]; } if (Integer.bitCount(mask) >= 3 && graph[i][first]) sum += dp[mask][i]; } } System.out.println(sum / 2); scan.close(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.InputMismatchException; /** * @author Egor Kulikov ([email protected]) * Created on 14.03.2010 */ public class TaskD implements Runnable { private InputReader in; private PrintWriter out; private int n; private int m; private boolean[][] e; private long[][] qp; private static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int 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 long readLong() { 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 readString() { 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; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { 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(readString()); } 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 < '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 < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } public static void main(String[] args) { // new Thread(new Template()).start(); new TaskD().run(); } public TaskD() { // String id = getClass().getName().toLowerCase(); // try { // System.setIn(new FileInputStream(id + ".in")); // System.setOut(new PrintStream(new FileOutputStream(id + ".out"))); // } catch (FileNotFoundException e) { // throw new RuntimeException(); // } in = new InputReader(System.in); out = new PrintWriter(System.out); } public void run() { // int numTests = in.readInt(); // for (int testNumber = 0; testNumber < numTests; testNumber++) { // } n = in.readInt(); m = in.readInt(); e = new boolean[n][n]; for (int i = 0; i < m; i++) { int a = in.readInt() - 1; int b = in.readInt() - 1; e[a][b] = e[b][a] = true; } // n = 19; // e = new boolean[n][n]; // for (int i = 0; i < n; i++) { // for (int j = 0; j < n; j++) // e[i][j] = i != j; // } int msk = (1 << n) - 1; qp = new long[n - 1][1 << (n - 1)]; long ans = 0; for (int i = n - 1; i >= 0; i--) { msk -= (1 << i); for (int k = 0; k < i; k++) Arrays.fill(qp[k], 0, 1 << i, -1); for (int j = 0; j < i; j++) { if (e[i][j]) { e[i][j] = e[j][i] = false; ans += go(j, msk - (1 << j), i); e[i][j] = e[j][i] = true; } } } out.println(ans / 2); out.close(); } private long go(int v, int msk, int u) { if (qp[v][msk] != -1) return qp[v][msk]; qp[v][msk] = 0; if (e[v][u]) qp[v][msk] = 1; for (int i = 0; i < u; i++) { if (e[v][i] && ((msk >> i) & 1) != 0) qp[v][msk] += go(i, msk - (1 << i), u); } return qp[v][msk]; } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class Main { public static BufferedReader in; public static PrintWriter out; public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); boolean showLineError = true; if (showLineError) { solve(); out.close(); } else { try { solve(); } catch (Exception e) { } finally { out.close(); } } } static void debug(Object... os) { out.println(Arrays.deepToString(os)); } private static void solve() throws IOException { String[] line = nss(); int n = Integer.parseInt(line[0]); int m = Integer.parseInt(line[1]); boolean[][] matrix = new boolean[n][n]; for (int i = 0; i < m; i++) { line = nss(); int u = Integer.parseInt(line[0]) - 1; int v = Integer.parseInt(line[1]) - 1; matrix[u][v] = matrix[v][u] = true; } long[][] dp = new long[1<<n][n]; for(int i=0;i<n;i++) dp[1<<i][i]=1; long ret=0; for(int mask =0;mask< 1<<n;mask++){ for(int last =0;last<n;last++) if((mask & (1<<last))!=0){ int first=-1; for(first=0;first<n;first++) if((mask & (1<<first))!=0) break; for(int add =first;add<n;add++) if((mask & (1<<add))==0 && matrix[last][add]) dp[mask+ (1<<add)][add]+=dp[mask][last]; if(Long.bitCount(mask)>2 && matrix[first][last]) ret+=dp[mask][last]; } } out.println(ret/2L); } private static String[] nss() throws IOException { return in.readLine().split(" "); } private static int ni() throws NumberFormatException, IOException { return Integer.parseInt(in.readLine()); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class CF11D { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); boolean[][] ee = new boolean[n][n]; while (m-- > 0) { st = new StringTokenizer(br.readLine()); int i = Integer.parseInt(st.nextToken()) - 1; int j = Integer.parseInt(st.nextToken()) - 1; ee[i][j] = ee[j][i] = true; } long cnt = 0; // how many cycles through i with intermediate vertices before i for (int i = 2; i < n; i++) { long[][] dp = new long[1 << i][i]; for (int j = 0; j < i; j++) dp[0][j] = ee[i][j] ? 1 : 0; // dp[b][j]: how many paths from i to j with intermediate vertices in b for (int b = 1; b < 1 << i; b++) for (int j = 0; j < i; j++) { if ((b & 1 << j) > 0) continue; for (int k = 0; k < i; k++) { if ((b & 1 << k) == 0) continue; if (ee[k][j]) dp[b][j] += dp[b ^ 1 << k][k]; } if (dp[b][j] > 0 && ee[j][i]) cnt += dp[b][j]; } } System.out.println(cnt / 2); } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.math.*; public class task { public static void main(String args[]) { Scanner a = new Scanner(System.in); while(a.hasNext()) { int n = a.nextInt(); int m = a.nextInt(); if(n == 0 && m == 0) break; boolean[][] adj = new boolean[n][n]; long res = 0; for (int i = 0; i < m; ++i) { int x = a.nextInt(); int y = a.nextInt(); adj[x - 1][y - 1] = true; adj[y - 1][x - 1] = true; } for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) if (adj[i][j]) --res; for (int i = 0; i < n; ++i) { long[][] dp = new long[n - i][1 << (n - i)]; dp[0][0] = 1; for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { if (dp[j][mask] != 0) { for (int k = 0; k < n - i; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) dp[k][mask | (1 << k)] += dp[j][mask]; } } } if (((mask >> 0) & 1) != 0) { res += dp[0][mask]; } } } System.out.println(res/2); } } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Scanner; public class D { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][]a = new int[n][n]; for (int i = 1; i <= m; i++) { int v1 = sc.nextInt(); int v2 = sc.nextInt(); v1--; v2--; a[v1][v2] = a[v2][v1] = 1; } long[][]dp = new long[1 << n][n]; for (int i = 0; i < n; i++) { dp[1 << i][i] = 1; } for (int mask = 0; mask < (1 << n); mask++) { if (Integer.bitCount(mask) > 1) { for (int i = 0; i < n; i++) { if (i==Integer.numberOfTrailingZeros(mask)) continue; if ((mask & (1 << i)) != 0) { for (int j = 0; j < n; j++) { if ((mask & (1 << j)) != 0 && a[j][i]==1) { dp[mask][i] += dp[(mask ^ (1 << i))][j]; } } } } } } long ans = 0; for (int mask = 0; mask < (1 << n); mask++) { if (Integer.bitCount(mask) >= 3) { int t = Integer.numberOfTrailingZeros(mask); for (int i = 0; i < n; i++) { if (a[t][i]==1) ans += dp[mask][i]; } } } ans /= 2; System.out.println(ans); } }
np
11_D. A Simple Task
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; public class D11 { static StreamTokenizer in; static PrintWriter out; static int nextInt() throws IOException { in.nextToken(); return (int)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(); m = nextInt(); g = new boolean[n][n]; for (int i = 0; i < m; i++) { int a = nextInt()-1, b = nextInt()-1; g[a][b] = g[b][a] = true; } long ans = 0; for (int i = n; i > 0; i--) { //long cur = solve(i); long cur = calc(g, i-1); ans += cur; } out.println(ans/2); out.flush(); } static int n, m, V; static boolean[][] g; /*static long solve(int V) { int v = V-1; long[][] memo = new long[V][1 << V]; memo[v][1 << v] = 1; for (int mask = 1; mask < (1 << V); mask++) for (int i = 0; i < V; i++) if ((mask&(1 << i)) != 0) for (int j = 0; j < V; j++) if (g[i][j] && (mask&(1 << j)) == 0) memo[j][mask|(1 << j)] += memo[i][mask]; long res = 0; for (int mask = 1; mask < (1 << V); mask++) for (int i = 0; i < V; i++) if (Integer.bitCount(mask) > 2 && g[v][i]) res += memo[i][mask]; return res/2; }*/ static long calc(boolean[][] bs,int n){ long[][] dp=new long[1<<n][n]; for(int i=0;i<n;i++){ if(bs[i][n]) dp[1<<i][i] ++; } for(int i=1;i<1<<n;i++){ for(int j=0;j<n;j++)if(((i>>j)&1)==1) for(int k=0;k<n;k++)if(((i>>k)&1)==0 && bs[j][k]){//add dp[i|(1<<k)][k] += dp[i][j]; } } long res=0; for(int i=0;i<1<<n;i++)for(int j=0;j<n;j++)if(Integer.bitCount(i)>=2&&bs[j][n])res+=dp[i][j]; return res; } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.io.*; public class Main implements Runnable { private void solution() throws IOException { int n = in.nextInt(); int m = in.nextInt(); boolean[][] adj = new boolean[n][n]; long res = 0; for (int i = 0; i < m; ++i) { int x = in.nextInt(); int y = in.nextInt(); adj[x - 1][y - 1] = true; adj[y - 1][x - 1] = true; } final long[][] dp = new long[1 << n][n]; for (int i = 0; i < n; ++i) { for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { dp[mask][j] = 0; } } dp[0][0] = 1; for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { if (dp[mask][j] != 0) { long am = dp[mask][j]; for (int k = 0; k < n - i; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) { dp[mask | (1 << k)][k] += am; } } } } if (((mask >> 0) & 1) != 0) { res += dp[mask][0]; } } } out.println((res - m) / 2); } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private class Scanner { BufferedReader reader; StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""); } 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 int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) throws IOException { new Thread(null, new Main(), "", 1 << 28).start(); } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Scanner in = new Scanner(new InputStreamReader(System.in)); }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.StringTokenizer; /** * Created by Darren on 14-10-21. */ public class D { Reader in = new Reader(System.in); PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { new D().run(); } int n, m; boolean[][] adjacency; void run() throws IOException { n = in.nextInt(); m = in.nextInt(); adjacency = new boolean[n+1][n]; for (int i = 0; i < m; i++) { int u = in.nextInt(), v = in.nextInt(); adjacency[u-1][v-1] = adjacency[v-1][u-1] = true; } final int MAX_MASK = (1 << n) - 1; long[][] dp = new long[MAX_MASK+1][n]; for (int i = 0; i < n; i++) dp[1<<i][i] = 1; long sum = 0; for (int mask = 1; mask <= MAX_MASK; mask++) { int lowestBit = first(mask); for (int i = 0; i < n; i++) { if (bit(i, mask) && i != lowestBit) { for (int j = 0; j < n; j++) { if (adjacency[j][i]) { dp[mask][i] += dp[mask^(1<<i)][j]; } } if (count(mask) >= 3 && adjacency[lowestBit][i]) sum += dp[mask][i]; } else { // dp[mask][i] = 0 } } } out.println(sum / 2); out.flush(); } int count(int mask) { int count = 0; while (mask > 0) { if ((mask & 1) == 1) count++; mask >>= 1; } return count; } int first(int mask) { int index = 0; while (mask > 0) { if ((mask & 1) == 1) return index; mask >>= 1; index++; } return -1; } boolean bit(int index, int mask) { return ((1 << index) & mask) > 0; } 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
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Main { /** * @param args */ static int N, M; static long[] C; static int[][] g; static long[][] DP; public static void main(String[] args) { InputReader r = new InputReader(System.in); N = r.nextInt(); M = r.nextInt(); g = new int[N][N]; C = new long[N + 1]; DP = new long[1 << N][N]; for(int k = 0; k < M; k++){ int i = r.nextInt() - 1; int j = r.nextInt() - 1; g[i][j] = g[j][i] = 1; } for(long[] i : DP) Arrays.fill(i, -1); long ret = 0; for(int s = 0; s < N; s++){ ret += go(s, 1 << s, s); } System.out.println(ret / 2); } private static long go(int s, int m, int e) { if(DP[m][e] != -1)return DP[m][e]; long cnt = 0; for(int j = s; j < N; j++)if(g[e][j] == 1){ if((m & (1 << j)) != 0){ if(s == j && Integer.bitCount(m) >= 3){ cnt++; } }else{ cnt += go(s, m | 1 << j, j); } } return DP[m][e] = cnt; } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class D implements Runnable { public static void main(String[] args) { new D().run(); } class FastScanner { BufferedReader br; StringTokenizer st; boolean eof; String buf; public FastScanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); nextToken(); } public FastScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); nextToken(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; break; } } String ret = buf; buf = eof ? "-1" : st.nextToken(); return ret; } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } void close() { try { br.close(); } catch (Exception e) { } } boolean isEOF() { return eof; } } FastScanner sc; PrintWriter out; public void run() { Locale.setDefault(Locale.US); try { sc = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); sc.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } int nextInt() { return sc.nextInt(); } String nextToken() { return sc.nextToken(); } long nextLong() { return sc.nextLong(); } double nextDouble() { return sc.nextDouble(); } void solve() { // long time = System.currentTimeMillis(); int n = nextInt(); int m = nextInt(); boolean[][] edges = new boolean[n][n]; boolean[] edge = new boolean[(n << 5) | n]; for (int i = 0; i < m; i++) { int x = nextInt() - 1; int y = nextInt() - 1; edges[x][y] = edges[y][x] = true; edge[(x << 5) | y] = edge[(y << 5) | x] = true; } long[][] dp = new long[n][1 << n]; long ans = 0; for (int i = 0; i < n; i++) { for (int mask2 = 1; mask2 < 1 << (n - i - 1); ++mask2) { for (int j = i + 1; j < n; j++) { dp[j][mask2 << i << 1] = 0; } } for (int j = i + 1; j < n; j++) { if (edges[i][j]) { dp[j][1 << j] = 1; } } for (int mask2 = 1; mask2 < 1 << (n - i - 1); ++mask2) { int mask = (mask2 << i << 1); if ((mask & (mask - 1)) == 0) { continue; } for (int j = i + 1; j < n; j++) { if (((mask >> j) & 1) == 0) { continue; } dp[j][mask] = 0; for (int k = i + 1; k < n; k++) { if (((mask >> k) & 1) == 0 || !edge[(j << 5) | k]) { continue; } dp[j][mask] += dp[k][mask & ~(1 << j)]; } if (edge[(i << 5) | j]) { ans += dp[j][mask]; } } } } // if (n >= 3) { // if (edges[n - 3][n - 2] && edges[n - 3][n - 1] // && edges[n - 2][n - 1]) { // ans += 2; // } // } out.println(ans / 2); // System.err.println(System.currentTimeMillis() - time); // out.println(19 + " " + 19 * 9); // for (int i = 0; i < 19; ++i) { // for (int j = i + 1; j < 19; ++j) { // out.println((i + 1) + " " + (j + 1)); // } // } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Inet4Address; import java.util.Arrays; import java.util.StringTokenizer; /** * Created by shirsh.bansal on 07/08/16. */ public class Main { public static void main(String[] args) throws IOException { FastScanner scanner = new FastScanner(); int n = scanner.nextInt(); int m = scanner.nextInt(); boolean graph[][] = new boolean[n][n]; for (int i = 0; i < m; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); graph[a-1][b-1] = true; graph[b-1][a-1] = true; } if(n <= 2) { System.out.println(0); return; } long dp[][] = new long[1<<n][n]; for (int i = 0; i < (1<<n); i++) { Arrays.fill(dp[i], -1); } for (int i = 1; i < (1<<n); i++) { for (int j = 0; j < n; j++) { f(i, j, dp, graph, n); } } long sum = 0; // for (int i = 7; i < (1 << n); i++) { // if(Integer.bitCount(i) < 3) continue; // for (int j = 0; j < n; j++) { // int startNode = Integer.numberOfTrailingZeros(Integer.highestOneBit(i)); // int endNode = j; // // if(graph[startNode][endNode] && dp[i][j] != -1) { //// System.out.println(i + " " + startNode + " " + endNode + " " + dp[i][j]); // sum += dp[i][j]; // } // } // } for (int i = 0; i < n; i++) { for (int j = 0; j < (1 << n); j++) { if(Integer.bitCount(j) >= 3 && graph[Integer.numberOfTrailingZeros(j)][i]) { sum += dp[j][i]; } } } System.out.println(sum/2); } private static long f(int mask, int i, long[][] dp, boolean[][] graph, int n) { if(dp[mask][i] != -1) return dp[mask][i]; if(Integer.bitCount(mask) == 1 && (mask&(1<<i)) != 0) { dp[mask][i] = 1; } else if(Integer.bitCount(mask) > 1 && (mask&(1<<i)) != 0 && i != Integer.numberOfTrailingZeros(mask)) { dp[mask][i] = 0; for (int j = 0; j < n; j++) { if(graph[i][j]) dp[mask][i] = dp[mask][i] + f(mask^(1<<i), j, dp, graph, n); } } else { dp[mask][i] = 0; } // int tmpMask = mask ^ (1<<i); // for (int j = 0; j <= firstNode; j++) { // if(((1<<j)&tmpMask) != 0 && graph[i][j]) { // dp[mask][i] += f(tmpMask, j, dp, graph, n, firstNode); // } // } // return dp[mask][i]; } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { InputStream fin = System.in; //fin = new FileInputStream("in.txt"); Scanner cin = new Scanner(fin); int n = cin.nextInt(); int m = cin.nextInt(); int bound = 1 << n; boolean[][] mp = new boolean[n][n]; long[][] dp = new long[bound][n]; int used = 0; long ret = 0; for (int i = 0; i < n; i++) { Arrays.fill(mp[i], false); } for (int i = 0; i < m; i++) { int u = cin.nextInt() - 1; int v = cin.nextInt() - 1; mp[u][v] = mp[v][u] = true; } for (int k = 0; k < n; k++) { for (int i = k; i < bound; i++) { Arrays.fill(dp[i], 0); } dp[1 << k][k] = 1; for (int mask = 1 << k; mask < bound; mask++) { if ((mask & used) != 0) continue; for (int i = k; i < n; i++) { if (dp[mask][i] != 0) { if (mp[k][i] && bitcount(mask) > 2) ret += dp[mask][i]; for (int j = k; j < n; j++) { if ((mask & (1 << j)) == 0 && mp[i][j]) { dp[mask ^ (1 << j)][j] += dp[mask][i]; } } } } } used |= 1 << k; } System.out.println(ret / 2); fin.close(); cin.close(); } private static int bitcount(int mask) { // TODO Auto-generated method stub int ret = 0; while (mask > 0) { ret += mask & 1; mask >>= 1; } return ret; } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class Template implements Runnable { private void solve() throws IOException { int n = nextInt(); int m = nextInt(); boolean[][] g = new boolean[n][n]; for (int i = 0; i < m; ++i) { int a = nextInt() - 1; int b = nextInt() - 1; g[a][b] = true; g[b][a] = true; } /*for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) g[i][j] = true;*/ long[] am = new long[n + 1]; long[][] ways = new long[1 << n][n]; for (int start = 0; start < n; ++start) { for (int mask = 0; mask < (1 << (n - start)); ++mask) for (int last = start; last < n; ++last) { ways[mask][last - start] = 0; } ways[1][0] = 1; for (int mask = 0; mask < (1 << (n - start)); ++mask) { int cnt = 0; int tmp = mask; while (tmp > 0) { ++cnt; tmp = tmp & (tmp - 1); } for (int last = start; last < n; ++last) if (ways[mask][last - start] > 0) { long amm = ways[mask][last - start]; for (int i = start; i < n; ++i) if ((mask & (1 << (i - start))) == 0 && g[last][i]) { ways[mask | (1 << (i - start))][i - start] += amm; } if (g[last][start]) am[cnt] += ways[mask][last - start]; } } } long res = 0; for (int cnt = 3; cnt <= n; ++cnt) { if (am[cnt] % (2) != 0) throw new RuntimeException(); res += am[cnt] / (2); } writer.println(res); } public static void main(String[] args) { new Template().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
11_D. A Simple Task
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int n; ArrayList<Integer>[] adj; long[] mem; long cycles(int cur, int start, int visited) { if (cur == start && visited > 0) { return Integer.bitCount(visited) >= 3 ? 1 : 0; } int index = n * visited + cur; if (mem[index] != -1) return mem[index]; long res = 0; int newvisited = visited | (1 << cur); for (int nxt : adj[cur]) { if (nxt >= start && (nxt == start || ((visited >> nxt) & 1) == 0)) { res += cycles(nxt, start, newvisited); } } return mem[index] = res; } public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.readInt(); int m = in.readInt(); adj = new ArrayList[n]; mem = new long[n * (1 << n)]; for (int i = 0; i < adj.length; i++) adj[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int a = in.readInt() - 1, b = in.readInt() - 1; adj[a].add(b); adj[b].add(a); } long res = 0; for (int start = 0; start < n; start++) { Arrays.fill(mem, -1); res += cycles(start, start, 0) / 2; } out.printLine(res); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } 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); } } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.io.*; public class ASimpleTask { /************************ SOLUTION STARTS HERE ***********************/ private static void solve(FastScanner s1, PrintWriter out){ int V = s1.nextInt(); int E = s1.nextInt(); int graph[] = new int[V]; long DP[][] = new long[1 << V][V]; while(E-->0) { int u = s1.nextInt() - 1; int v = s1.nextInt() - 1; graph[u] |= (1 << v); graph[v] |= (1 << u); } for(int i=0;i<V;i++) DP[1 << i][i] = 1; for(int mask = 1 , end = 1 << V;mask < end;mask++) { for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); for(int fromSet = mask ^ (1 << u);fromSet > 0; fromSet ^= Integer.lowestOneBit(fromSet)) { int v = Integer.numberOfTrailingZeros(fromSet); // System.out.printf("mask = %s , u = %d , v = %d\n" , Integer.toBinaryString(mask) , u , v); if((graph[u] & (1 << v)) != 0) DP[mask][u] += DP[mask ^ (1 << u)][v]; } } } long totalCycles = 0; for(int mask = 1 , end = 1 << V;mask < end;mask++) { if(Integer.bitCount(mask) >= 3) { int start = Integer.numberOfTrailingZeros(mask); for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); if((graph[u] & (1 << start)) != 0) totalCycles += DP[mask][u]; } } } totalCycles /= 2; /* for(long l[] : DP) out.println(Arrays.toString(l));*/ out.println(totalCycles); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE *********************/ public static void main(String []args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); solve(in, out); in.close(); out.close(); } static class FastScanner{ BufferedReader reader; StringTokenizer st; FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;} String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble(){return Double.parseDouble(next());} char nextChar() {return next().charAt(0);} int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}} } /************************ TEMPLATE ENDS HERE ************************/ }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.io.*; public class ASimpleTask { /************************ SOLUTION STARTS HERE ***********************/ static long memo[][]; static int graph[]; static long hamiltonianPath(int mask , int u) { if(memo[mask][u] != -1) return memo[mask][u]; else if(u == Integer.numberOfTrailingZeros(mask)) return 0; else { long sum = 0; for(int fromSet = mask ^ (1 << u);fromSet > 0; fromSet ^= Integer.lowestOneBit(fromSet)) { int v = Integer.numberOfTrailingZeros(fromSet); // System.out.printf("mask = %s , u = %d , v = %d\n" , Integer.toBinaryString(mask) , u , v); if((graph[u] & (1 << v)) != 0) sum += hamiltonianPath(mask ^ (1 << u), v); } return memo[mask][u] = sum; } } private static void solveBottomUp(FastScanner s1, PrintWriter out){ int V = s1.nextInt(); int E = s1.nextInt(); graph = new int[V]; long DP[][] = new long[1 << V][V]; while(E-->0) { int u = s1.nextInt() - 1; int v = s1.nextInt() - 1; graph[u] |= (1 << v); graph[v] |= (1 << u); } for(int i=0;i<V;i++) DP[1 << i][i] = 1; for(int mask = 1 , end = 1 << V;mask < end;mask++) { for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); for(int fromSet = mask ^ (1 << u);fromSet > 0; fromSet ^= Integer.lowestOneBit(fromSet)) { int v = Integer.numberOfTrailingZeros(fromSet); // System.out.printf("mask = %s , u = %d , v = %d\n" , Integer.toBinaryString(mask) , u , v); if((graph[u] & (1 << v)) != 0) DP[mask][u] += DP[mask ^ (1 << u)][v]; } } } long totalCycles = 0; for(int mask = 1 , end = 1 << V;mask < end;mask++) { if(Integer.bitCount(mask) >= 3) { int start = Integer.numberOfTrailingZeros(mask); for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); if((graph[u] & (1 << start)) != 0) totalCycles += DP[mask][u]; } } } totalCycles /= 2; /* for(long l[] : DP) out.println(Arrays.toString(l));*/ out.println(totalCycles); } private static void solveTopDown(FastScanner s1, PrintWriter out){ int V = s1.nextInt(); int E = s1.nextInt(); graph = new int[V]; memo = new long[1 << V][V]; for(long l[] : memo) Arrays.fill(l, -1); while(E-->0) { int u = s1.nextInt() - 1; int v = s1.nextInt() - 1; graph[u] |= (1 << v); graph[v] |= (1 << u); } for(int i=0;i<V;i++) memo[1 << i][i] = 1; long totalCycles = 0; for(int mask = 1 , end = 1 << V;mask < end;mask++) { if(Integer.bitCount(mask) >= 3) { int start = Integer.numberOfTrailingZeros(mask); for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); if((graph[u] & (1 << start)) != 0) totalCycles += hamiltonianPath(mask, u); } } } totalCycles /= 2; out.println(totalCycles); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE *********************/ public static void main(String []args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); solveTopDown(in, out); in.close(); out.close(); } static class FastScanner{ BufferedReader reader; StringTokenizer st; FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;} String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble(){return Double.parseDouble(next());} char nextChar() {return next().charAt(0);} int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}} } /************************ TEMPLATE ENDS HERE ************************/ }
np
11_D. A Simple Task
CODEFORCES
import java.io.PrintWriter; import java.util.Scanner; public class D { public void run(Scanner in, PrintWriter out) { int n = in.nextInt(); int[][] graph = new int[n][n]; int m = in.nextInt(); for (int i = 0; i < m; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; graph[x][y] = 1; graph[y][x] = 1; } long[][] dyn = new long[1 << n][n]; for (int i = 0; i < n; i++) { dyn[1 << i][i] = 1; } long answer = 0; for (int mask = 1; mask < 1 << n; mask++) { int start = Integer.numberOfTrailingZeros(mask); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) == 0) continue; for (int j = start + 1; j < n; j++) { if (graph[i][j] > 0 && (mask & (1 << j)) == 0) { dyn[mask + (1 << j)][j] += dyn[mask][i]; } } if (graph[i][start] > 0) { answer += dyn[mask][i]; } } } out.println((answer - m)/ 2); } public static void main(String[] args) { try (Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out) ) { new D().run(in, out); } catch (Exception e) { e.printStackTrace(); } } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.io.*; public class Main implements Runnable { private void solution() throws IOException { int n = in.nextInt(); int m = in.nextInt(); boolean[][] adj = new boolean[n][n]; long res = 0; for (int i = 0; i < m; ++i) { int x = in.nextInt(); int y = in.nextInt(); adj[x - 1][y - 1] = true; adj[y - 1][x - 1] = true; } for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (adj[i][j]) { --res; } } } long[][] dp = new long[1 << n][n]; for (int i = 0; i < n; ++i) { for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { dp[mask][j] = 0; } } dp[0][0] = 1; for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { if (dp[mask][j] != 0) { for (int k = 0; k < n - i; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) { dp[mask | (1 << k)][k] += dp[mask][j]; } } } } if (((mask >> 0) & 1) != 0) { res += dp[mask][0]; } } } out.println(res / 2); } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private class Scanner { BufferedReader reader; StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""); } 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 int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) throws IOException { new Thread(null, new Main(), "", 1 << 28).start(); } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Scanner in = new Scanner(new InputStreamReader(System.in)); }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.io.*; public class Main implements Runnable { private void solution() throws IOException { int n = in.nextInt(); int m = in.nextInt(); boolean[][] adj = new boolean[n][n]; long res = 0; for (int i = 0; i < m; ++i) { int x = in.nextInt(); int y = in.nextInt(); adj[x - 1][y - 1] = true; adj[y - 1][x - 1] = true; } final long[][] dp = new long[1 << n][n]; for (int i = 0; i < n; ++i) { int Limit = 1 << (n - i); int nn = n - i; for (int mask = 0; mask < Limit; ++mask) { for (int j = 0; j < nn; ++j) { dp[mask][j] = 0; } } dp[0][0] = 1; for (int mask = 0; mask < Limit; ++mask) { if ((mask & 1) == 0) { for (int j = 0; j < nn; ++j) { if (dp[mask][j] != 0) { long am = dp[mask][j]; for (int k = 0; k < nn; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) { dp[mask | (1 << k)][k] += am; } } } } } else { res += dp[mask][0]; } } } out.println((res - m) / 2); } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private class Scanner { BufferedReader reader; StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""); } 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 int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) throws IOException { new Thread(null, new Main(), "", 1 << 28).start(); } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Scanner in = new Scanner(new InputStreamReader(System.in)); }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.StringTokenizer; /** * Codeforces 11D - A Simple Task * Created by Darren on 14-10-21. * O(2^n * n^2) time and O(2^n * n) space. * * Tag: dynamic programming, bitmask, graph */ public class D { Reader in = new Reader(System.in); PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { new D().run(); } int n, m; boolean[][] adjacency; // Adjacency matrix void run() throws IOException { n = in.nextInt(); m = in.nextInt(); adjacency = new boolean[n+1][n]; for (int i = 0; i < m; i++) { int u = in.nextInt(), v = in.nextInt(); adjacency[u-1][v-1] = adjacency[v-1][u-1] = true; // Converted to 0-based } final int MASK_BOUND = (1 << n); // dp[i][j]: the number of Hamiltonian walks over the subgraph formed by // the mask i, starting at the smallest vertex and ending at vertex j // dp[1<<i][i] = 1; // dp[i][j] = sum_k{dp[i^j][k]} if j is within the mask i and (k,j) is an edge long[][] dp = new long[MASK_BOUND][n]; for (int i = 0; i < n; i++) dp[1<<i][i] = 1; long sum = 0; for (int mask = 1; mask < MASK_BOUND; mask++) { int lowestVertex = (int) (Math.log(lowest(mask)) / Math.log(2)); for (int i = 0; i < n; i++) { if (bit(i, mask) && i != lowestVertex) { for (int j = 0; j < n; j++) { if (adjacency[j][i]) { dp[mask][i] += dp[mask^(1<<i)][j]; } } // A simple cycle with length not smaller than 3 if (count(mask) >= 3 && adjacency[lowestVertex][i]) sum += dp[mask][i]; } else { // dp[mask][i] = 0 } } } out.println(sum / 2); // A cycle is counted twice out.flush(); } // Return the number of '1's in the binary representation of the mask int count(int mask) { int count = 0; while (mask > 0) { if ((mask & 1) == 1) count++; mask >>= 1; } return count; } // Return an integer with only one '1' in its binary form and the position of the // only '1' is the same with the lowest '1' in mask int lowest(int mask) { // mask = x1b where b is a sequence of zeros; // -mask = x'1b', where x' and b' is formed by reversing digits in x and b; // mask & (-mask) = 0...010...0, where the only 1 is the lowest 1 in mask return mask & (-mask); } // Check whether the digit at the given index of the mask is '1' boolean bit(int index, int mask) { return ((1 << index) & mask) > 0; } 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
11_D. A Simple Task
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int n; boolean[][] adj; long[] mem; int start; long cycles(int cur, int visited) { if (cur == start && visited > 0) { return Integer.bitCount(visited) >= 3 ? 1 : 0; } int index = visited * n + cur; if (mem[index] != -1) return mem[index]; long res = 0; int newvisited = visited | (1 << cur); for (int nxt = 0; nxt < n; nxt++) if (adj[cur][nxt]) { if (nxt >= start && (nxt == start || ((visited >> nxt) & 1) == 0)) { res += cycles(nxt, newvisited); } } return mem[index] = res; } public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.readInt(); int m = in.readInt(); mem = new long[n * (1 << n)]; adj = new boolean[n][n]; for (int i = 0; i < m; i++) { int a = in.readInt() - 1, b = in.readInt() - 1; adj[a][b] = true; adj[b][a] = true; } long res = 0; for (int start = 0; start < n; start++) { Arrays.fill(mem, -1); this.start = start; res += cycles(start, 0) / 2; } out.printLine(res); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } 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); } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class D11 { static boolean[][] g; static int n, m; public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); n = input.nextInt(); m = input.nextInt(); g = new boolean[n][n]; for(int i = 0; i<m; i++) { int a = input.nextInt()-1, b = input.nextInt()-1; g[a][b] = g[b][a] = true; } long res = 0; map = new HashMap<Integer, Long>(); for(int i = n-1; i>=0; i--) { memo = new long[i+1][1<<(i+1)]; for(long[] A : memo) Arrays.fill(A, -1); res += count(i, i, 1<<i)/2; } out.println(res); out.close(); } static long[][] memo; static HashMap<Integer, Long> map; static long count(int at, int start, int mask) { if(memo[at][mask] != -1) return memo[at][mask]; int bits = Integer.bitCount(mask); if(at == start && bits > 2) return 1; long res = 0; for(int i = 0; i<=start; i++) { if(!g[at][i]) continue; if(i != start && (mask & (1<<i)) > 0) continue; if(i == start && bits <= 2) continue; res += count(i, start, mask | (1<<i)); } return memo[at][mask] = res; } 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
11_D. A Simple Task
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while ( sc.hasNextInt() ) { int n = sc.nextInt(); long m = sc.nextInt(); boolean edge[][] = new boolean[n][n]; long dp[][] = new long[1<<n][n]; for ( long i = 1 ; i<=m ; ++i ) { int u = sc.nextInt(); int v = sc.nextInt(); -- u; -- v; edge[u][v] = edge[v][u] = true; } for ( int i = 0 ; i<n ; ++i ) { dp[1<<i][i] = 1; } long res = 0; for ( int i = 1 ; i<(1<<n) ; ++i ) { int first = cal(i); for ( int j = first ; j<n ; ++j ) { if ( dp[i][j]==0 ) { continue; } for ( int k = first ; k<n ; ++k ) { if ( j==k || !edge[j][k] ) { continue; } if ( k==first && judge(i) ) { res += dp[i][j]; } if ( (i&(1<<k))==0 ) { dp[i|(1<<k)][k] += dp[i][j]; } } } } System.out.println(res/2); } } public static int cal( int x ) { int ord = 0; while ( true ) { if ( (x&(1<<ord))!=0 ) { break; } ++ ord; } return ord; } public static boolean judge( int x ) { int cnt = 0; while ( x>=1 ) { if ( (x&1)==1 ) { ++ cnt; } x >>= 1; } return cnt >= 3; } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Scanner; public class Hello { public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); boolean[][] graph = new boolean[n][n]; for(int i = 0; i < m; i++) { int from = scan.nextInt() - 1; int to = scan.nextInt() - 1; graph[from][to] = graph[to][from] = true; } int max = 1 << n; long[][] dp = new long[max][n]; for(int mask = 1; mask < max; mask++) { for(int i = 0; i < n; i++) { boolean existI = (mask & (1 << i)) > 0; if(Integer.bitCount(mask) == 1 && existI) { dp[mask][i] = 1; } else if(Integer.bitCount(mask) > 1 && existI && first(mask) != i) { long sum = 0; for(int j = 0; j < n; j++) { if(graph[i][j]) sum += dp[mask ^ (1 << i)][j]; } dp[mask][i] = sum; } } } long countCycles = 0; for(int mask = 7; mask < max; mask++) { for(int i = 0; i < n; i++) { if(Integer.bitCount(mask) >= 3 && graph[first(mask)][i]) { countCycles += dp[mask][i]; } } } System.out.println(countCycles / 2); } public static int first(int mask) { int i = 0; while((mask & (1 << i++)) == 0); return i - 1; } }
np
11_D. A Simple Task
CODEFORCES
/** * Codeforces Beta Round #10 * * @author ProjectYoung */ import java.util.Scanner; public class CF11D { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); boolean[][] map = new boolean[n][n]; long[][] dp = new long[1 << n][n]; for (int i = 0; i < m; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; map[a][b] = map[b][a] = true; dp[(1 << a) + (1 << b)][Math.max(a, b)] = 1; } long ans = 0; for (int mask = 1; mask < (1 << n); mask++) { int lowbit = 0; for (; (mask & (1 << lowbit)) == 0; lowbit++); for (int i = lowbit + 1; i < n; i++) { if ((mask & (1 << i)) == 0) { continue; } for (int j = lowbit + 1; j < n; j++) { if ((mask & (1 << j)) == 0 || j == i) { continue; } if (map[i][j]) { dp[mask][i] += dp[mask ^ (1 << i)][j]; } } if (map[lowbit][i]) { ans += dp[mask][i]; } } } System.out.println((ans - m) / 2); sc.close(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class D11 { static StreamTokenizer in; static PrintWriter out; static int nextInt() throws IOException { in.nextToken(); return (int)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(); m = nextInt(); g = new boolean[n][n]; for (int i = 0; i < m; i++) { int a = nextInt()-1, b = nextInt()-1; g[a][b] = g[b][a] = true; } long ans = 0; for (int i = n-1; i >= 0; i--) { long cur = solve(i); ans += cur; } out.println(ans/2); out.flush(); } static int n, m; static boolean[][] g; static long solve(int v) { long[][] memo = new long[v][1 << v]; for (int i = 0; i < v; i++) if (g[v][i]) memo[i][1 << i] = 1; for (int mask = 1; mask < (1 << v); mask++) for (int i = 0; i < v; i++) if ((mask&(1 << i)) != 0) for (int j = 0; j < v; j++) if (g[i][j] && (mask&(1 << j)) == 0) memo[j][mask|(1 << j)] += memo[i][mask]; long res = 0; for (int mask = 1; mask < (1 << v); mask++) for (int i = 0; i < v; i++) if (Integer.bitCount(mask) > 1 && g[v][i]) res += memo[i][mask]; return res; } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.io.*; public class Main implements Runnable { private void solution() throws IOException { int n = in.nextInt(); int m = in.nextInt(); boolean[][] adj = new boolean[n][n]; long res = 0; for (int i = 0; i < m; ++i) { int x = in.nextInt(); int y = in.nextInt(); adj[x - 1][y - 1] = true; adj[y - 1][x - 1] = true; } for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (adj[i][j]) { --res; } } } for (int i = 0; i < n; ++i) { long[][] dp = new long[n - i][1 << (n - i)]; dp[0][0] = 1; for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { if (dp[j][mask] != 0) { for (int k = 0; k < n - i; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) { dp[k][mask | (1 << k)] += dp[j][mask]; } } } } if (((mask >> 0) & 1) != 0) { res += dp[0][mask]; } } } out.println(res / 2); } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private class Scanner { BufferedReader reader; StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""); } 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 int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) throws IOException { new Thread(null, new Main(), "", 1 << 28).start(); } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Scanner in = new Scanner(new InputStreamReader(System.in)); }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } class GraphBuilder { int n, m; int[] x, y; int index; int[] size; GraphBuilder(int n, int m) { this.n = n; this.m = m; x = new int[m]; y = new int[m]; size = new int[n]; } void add(int u, int v) { x[index] = u; y[index] = v; size[u]++; size[v]++; index++; } int[][] build() { int[][] graph = new int[n][]; for (int i = 0; i < n; i++) { graph[i] = new int[size[i]]; } for (int i = index - 1; i >= 0; i--) { int u = x[i]; int v = y[i]; graph[u][--size[u]] = v; graph[v][--size[v]] = u; } return graph; } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long[] readLongArray(int size) throws IOException { long[] res = new long[size]; for (int i = 0; i < size; i++) { res[i] = readLong(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Template().run(); // new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } void solve() throws IOException { int n = readInt(); int m = readInt(); int max = 1 << n; long[][] dp = new long[n][max]; for (int i = 0; i < n; i++) { dp[i][1 << i] = 1; } GraphBuilder gb = new GraphBuilder(n, m); for (int i = 0; i < m; i++) { gb.add(readInt() - 1, readInt() - 1); } int[][] graph = gb.build(); for (int mask = 1; mask < max; mask++) { int firstBit = -1; for (int i = 0; i < n; i++) { if (hasBit(mask, i)) { firstBit = i; break; } } for (int last = 0; last < n; last++) { if (dp[last][mask] == 0) continue; for (int y : graph[last]) { if (!hasBit(mask, y) && y > firstBit) { dp[y][mask | (1 << y)] += dp[last][mask]; } } } } long answer = 0; for (int i = 1; i < max; i++) { if (Integer.bitCount(i) < 3) continue; int firstBit = -1; for (int j = 0; j < n; j++) { if (hasBit(i, j)) { firstBit = j; break; } } for (int y : graph[firstBit]) { answer += dp[y][i]; } } out.println(answer / 2); } boolean hasBit(int mask, int bit) { return (mask & (1 << bit)) != 0; } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Main { private FastScanner in; private PrintWriter out; public void solve() throws IOException { int N = in.nextInt(); int M = in.nextInt(); int[][] edges = new int[N][N]; for (int i = 0; i < M; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; edges[a][b] = 1; edges[b][a] = 1; } int globalCountMasks = 1 << N; int[][] masks = new int[N + 1][]; int[] countMasks = new int[N + 1]; for (int i = 0; i <= N; i++) { masks[i] = new int[combinations(N, i)]; } for (int i = 0; i < globalCountMasks; i++) { int c = countBit1(i); masks[c][countMasks[c]] = i; countMasks[c]++; } long globalCountCycles = 0; long[][] count = new long[globalCountMasks][N]; for (int a = 0; a < N - 2; a++) { int aBit = 1 << a; count[aBit][a] = 1; long countCycles = 0; for (int i = 2; i <= N; i++) { for (int m = 0; m < countMasks[i]; m++) { int mask = masks[i][m]; if ((mask & aBit) == 0) continue; if ((mask & (aBit - 1)) > 0) continue; count[mask][a] = 0; for (int v = a + 1; v < N; v++) { int vBit = 1 << v; if ((mask & vBit) == 0) continue; count[mask][v] = 0; for (int t = a; t < N; t++) { if ((mask & (1 << t)) == 0 || t == v || edges[v][t] == 0) continue; count[mask][v] += count[mask ^ vBit][t]; } if (edges[a][v] == 1 && mask != (aBit | vBit)) { countCycles += count[mask][v]; } } } } globalCountCycles += countCycles / 2; } out.println(globalCountCycles); } private int countBit1(int k) { int c = 0; while (k > 0) { c += k & 1; k >>= 1; } return c; } private int combinations(int n, int k) { if (k > n || k < 0) { throw new IllegalArgumentException(); } int r = 1; for (int i = 1; i <= k; i++) { r = r * (n + 1 - i) / i; } return r; } 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()); } } public static void main(String[] arg) { new Main().run(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class Template implements Runnable { private void solve() throws IOException { int n = nextInt(); int m = nextInt(); boolean[][] g = new boolean[n][n]; for (int i = 0; i < m; ++i) { int a = nextInt() - 1; int b = nextInt() - 1; g[a][b] = true; g[b][a] = true; } /*for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) g[i][j] = true;*/ long[] am = new long[n + 1]; long[][] ways = new long[1 << (n - 1)][n]; for (int start = 0; start < n; ++start) { for (int mask = 0; mask < (1 << (n - start - 1)); ++mask) for (int last = start; last < n; ++last) { ways[mask][last - start] = 0; } ways[1 >> 1][0] = 1; for (int mask = 1; mask < (1 << (n - start)); mask += 2) { int cnt = 0; int tmp = mask; while (tmp > 0) { ++cnt; tmp = tmp & (tmp - 1); } for (int last = start; last < n; ++last) if (ways[mask >> 1][last - start] > 0) { long amm = ways[mask >> 1][last - start]; for (int i = start; i < n; ++i) if ((mask & (1 << (i - start))) == 0 && g[last][i]) { ways[(mask | (1 << (i - start))) >> 1][i - start] += amm; } if (g[last][start]) am[cnt] += ways[mask >> 1][last - start]; } } } long res = 0; for (int cnt = 3; cnt <= n; ++cnt) { if (am[cnt] % (2) != 0) throw new RuntimeException(); res += am[cnt] / (2); } writer.println(res); } public static void main(String[] args) { new Template().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
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; /** * 4 6 * 1 2 * 1 3 * 1 4 * 2 3 * 2 4 * 3 4 * * * * * * * @author pttrung */ public class D { public static long [][]dp; public static boolean [][]map; public static void main(String[] args) { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); // int N = 19; // System.out.println(N + " " + ((N - 1) * N / 2)); // for (int i = 1; i // <= N; i++) { // for (int j = i + 1; j <= N; j++) { // System.out.println(i + " " + j); // } // } int n = in.nextInt(); int m = in.nextInt(); dp = new long[n][1 << n + 1] ; map = new boolean[n][n]; for (int i = 0; i < m; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; map[a][b] = true; map[b][a] = true; } for(long []temp : dp){ Arrays.fill(temp, -1); } long result = 0; for(int i = 0; i < n; i++){ result += cal((1<<i),i,i,1); } out.println((result/2)); out.close(); } public static long cal(int mask, int from, int to, int len){ if(dp[to][mask]!= -1){ return dp[to][mask]; } long result = 0; if(len > 2 && map[from][to]){ result++; } for(int i = from+1; i< map.length; i++){ if(map[to][i] && (mask & (1<<i)) == 0){ result += cal(mask|(1<<i), from,i,len + 1); } } dp[to][mask] = result; return result; } public static class FT { int[] data; FT(int n) { data = new int[n]; } public void update(int index, int value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public int get(int index) { int result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val ; } else { return val * (val * a) ; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main implements Runnable { private int n; private int nn; private long[][] dp; private boolean[][] gr; // //////////////////////////////////////////////////////////////////// // Solution private void solve() throws Throwable { n = nextInt(); nn = 1 << n; gr = new boolean[n][n]; dp = new long[n][nn]; for (int i = 0; i < n; i++) { Arrays.fill(dp[i], -1); } int m = nextInt(); for (int i = 0; i < m; i++) { int a = nextInt() - 1, b = nextInt() - 1; gr[a][b] = gr[b][a] = true; } for (int i = 0; i < n; i++) { dp[i][0] = 0; } for (int mask = 1; mask < nn; mask++) { int bCount = Integer.bitCount(mask); if (bCount < 2) { dp[Integer.numberOfTrailingZeros(mask)][mask] = 0; } else if (bCount == 2) { int msk = mask; int one = Integer.numberOfTrailingZeros(msk); msk ^= (1 << one); int two = Integer.numberOfTrailingZeros(msk); dp[two][mask] = gr[one][two] ? 1 : 0; } } long count = 0; for (int mask = 1; mask < nn; mask++) { if (Integer.bitCount(mask) < 3) continue; int i = Integer.numberOfTrailingZeros(mask); for (int j = i + 1; j < n; j++) { int jj = 1 << j; if (gr[i][j] && ((jj & mask) != 0)) { count += Dp(j, mask); } } } pw.println(count / 2); } private long Dp(int j, int mask) { if (dp[j][mask] != -1) return dp[j][mask]; int i = Integer.numberOfTrailingZeros(mask); assert i < j; int m = mask ^ (1 << j); long ans = 0; for (int p = i + 1; p < n; p++) { if (!gr[p][j]) continue; if ((mask & (1 << p)) == 0) continue; ans += Dp(p, m); } dp[j][mask] = ans; return ans; } // //////////////////////////////////////////////////////////////////// // Utility functions PrintWriter pw; BufferedReader in; StringTokenizer st; void initStreams() throws FileNotFoundException { //System.setIn(new FileInputStream("2")); in = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); } String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextString()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextString()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextString()); } static Throwable sError; public static void main(String[] args) throws Throwable { Thread t = new Thread(new Main()); t.start(); t.join(); if (sError != null) { throw sError; } } public void run() { try { initStreams(); solve(); } catch (Throwable e) { sError = e; } finally { if (pw != null) pw.close(); } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { private int n; private int m; private boolean[][] g; private long[][] dp; private int[] count; private int[] first; private void solve() throws IOException { n = nextInt(); m = nextInt(); g = new boolean[n][n]; for (int i = 0; i < m; i++) { int a = nextInt() - 1; int b = nextInt() - 1; g[a][b] = true; g[b][a] = true; } count = new int[1 << n]; first = new int[1 << n]; dp = new long[1 << n][n]; for (int mask = 0; mask < (1 << n); mask++) { count[mask] = bitCount(mask); for (int i = 0; i < n; i++) { if (bit(i, mask) == 1) { first[mask] = i; break; } } } for (int mask = 0; mask < (1 << n); mask++) { for (int i = 0; i < n; i++) { if ((count[mask] == 1) && (bit(i, mask) == 1)) { dp[mask][i] = 1; } else { for (int j = 0; j < n; j++) { if (g[j][i] && (count[mask] > 1) && (bit(i, mask) == 1) && (first[mask] != i)) { dp[mask][i] += dp[mask ^ (1 << i)][j]; } } } } } long ans = 0; for (int i = 0; i < n; i++) { for (int mask = 0; mask < (1 << n); mask++) { if ((count[mask] >= 3) && (first[mask] != i) && (g[i][first[mask]])) { ans += dp[mask][i]; } } } if (ans % 2 != 0) { throw new RuntimeException("SHIT!!!"); } out.println(ans / 2); } private final int bit(int i, int mask) { return (mask & (1 << i)) != 0 ? 1 : 0; } private final int bitCount(int mask) { int ret = 0; while (mask != 0) { ret++; mask -= mask & (-mask); } return ret; } private BufferedReader in; private PrintWriter out; private StringTokenizer st; private Main() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); solve(); in.close(); out.close(); } private void eat(String s) { st = new StringTokenizer(s); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } public static void main(String[] args) throws IOException { new Main(); } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int V = in.nextInt(); int E = in.nextInt(); boolean [][] G = new boolean [V][V]; for (int i = 0; i < E; i++) { int u = in.nextInt()-1; int v = in.nextInt()-1; G[u][v] = true; G[v][u] = true; } int pset = 1 << V; long [][] dp = new long [pset][V]; long cycles = 0; for (int set = 1; set < pset; set++) { int bit = Integer.bitCount(set); int src = first(set); if (bit == 1) { dp[set][src] = 1; } else if(bit > 1) { for (int i = 0; i < V; i++) { if(i == src) continue; // Check if i is in set if ((set & (1 << i)) != 0) { int S_1 = set ^ (1 << i); for (int v = 0; v < V; v++) { if (G[v][i] == true) { dp[set][i] += dp[S_1][v]; } } } //Count Cycles: if (bit >= 3 && G[src][i]) { cycles += dp[set][i]; } } } } System.out.println(cycles/2); } public static int first(int n) { int cnt = 0; while ((n & 1) != 1) { cnt++; n >>= 1; } return cnt; } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.io.*; public class Main implements Runnable { private void solution() throws IOException { int n = in.nextInt(); int m = in.nextInt(); boolean[][] adj = new boolean[n][n]; long res = 0; for (int i = 0; i < m; ++i) { int x = in.nextInt(); int y = in.nextInt(); adj[x - 1][y - 1] = true; adj[y - 1][x - 1] = true; } for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (adj[i][j]) { --res; } } } final long[][] dp = new long[1 << n][n]; for (int i = 0; i < n; ++i) { for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { dp[mask][j] = 0; } } dp[0][0] = 1; for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { if (dp[mask][j] != 0) { for (int k = 0; k < n - i; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) { dp[mask | (1 << k)][k] += dp[mask][j]; } } } } if (((mask >> 0) & 1) != 0) { res += dp[mask][0]; } } } out.println(res / 2); } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private class Scanner { BufferedReader reader; StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""); } 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 int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) throws IOException { new Thread(null, new Main(), "", 1 << 28).start(); } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Scanner in = new Scanner(new InputStreamReader(System.in)); }
np
11_D. A Simple Task
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) {} // long time1 = System.currentTimeMillis(); new Main().run(); // checkMemory(); // long time2 = System.currentTimeMillis(); // System.err.println((time2 - time1) + " ms"); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); int vNum; int eNum; boolean[][] g; void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); vNum = nextInt(); eNum = nextInt(); g = new boolean [vNum][vNum]; for (int e = 0; e < eNum; e++) { int u = nextInt() - 1; int v = nextInt() - 1; g[u][v] = g[v][u] = true; } // for (int v = 7; v <= 11; v++) { // genFullGraph(v); // if (naiveDP() != optimizedDP()) // System.err.println("Error on " + v); // } out.println(optimizedDP()); out.close(); } /*************************************************************** * Test **************************************************************/ long naiveDP() { long[] count = new long [vNum + 1]; int size = 1 << vNum; long[][] dp = new long [size][vNum]; for (int begin = 0; begin < vNum; begin++) { for (long[] row : dp) fill(row, 0L); dp[1 << begin][begin] = 1L; for (int mask = 0; mask < size; mask++) { int len = Integer.bitCount(mask); for (int v = 0; v < vNum; v++) { long cval = dp[mask][v]; if (cval == 0L) continue; if (g[v][begin]) count[len] += cval; for (int nv = 0; nv < vNum; nv++) { if (g[v][nv]) { int nmask = mask | (1 << nv); if (nmask != mask) dp[nmask][nv] += cval; } } } } } long ret = 0L; for (int len = 3; len <= vNum; len++) { if (count[len] % (len * 2) != 0) System.err.println("ERROR!"); ret += count[len] / len / 2; } return ret; } long optimizedDP() { long[] count = new long [vNum + 1]; long[][] dp = new long [1 << vNum][vNum]; for (int last = vNum - 1; last >= 0; last--) { int size = 1 << last; for (int mask = 0; mask < size; mask++) fill(dp[mask], 0, last, 0L); for (int nv = 0; nv < last; nv++) if (g[last][nv]) dp[1 << nv][nv] = 1L; for (int mask = 0; mask < size; mask++) { int len = Integer.bitCount(mask) + 1; for (int v = 0; v < last; v++) { long cval = dp[mask][v]; if (cval == 0L) continue; if (g[v][last]) count[len] += cval; for (int nv = 0; nv < last; nv++) { if (g[v][nv]) { int nmask = mask | (1 << nv); if (nmask != mask) dp[nmask][nv] += cval; } } } } } long ret = 0L; for (int len = 3; len <= vNum; len++) { if (count[len] % 2 != 0) System.err.println("ERROR!"); ret += count[len] >> 1; } return ret; } void genFullGraph(int vNum) { this.vNum = vNum; this.eNum = vNum * (vNum - 1) / 2; g = new boolean [vNum][vNum]; for (int i = 0; i < vNum; i++) for (int j = i + 1; j < vNum; j++) g[i][j] = g[j][i] = true; } /*************************************************************** * Utility **************************************************************/ static long b2mb(long b) { return b >> 20; } static void checkMemory() { System.err.println(b2mb(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + "/" + b2mb(Runtime.getRuntime().totalMemory()) + " MB"); } /*************************************************************** * Input **************************************************************/ 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
11_D. A Simple Task
CODEFORCES
import java.io.IOException; import java.io.InputStream; public class Cycles { public static FastInputStream fis; public static void main(String[] args) throws IOException { fis = new FastInputStream(System.in); System.out.println(solve(fis.nextInt(), fis.nextInt())); fis.close(); } public static long solve(int n, int m) throws IOException { boolean[][] graph = new boolean[n][]; long[][] state = new long[1 << n][n]; for (int i = 0; i < n; i++) graph[i] = new boolean[n - i]; for (int i = 0; i < m; i++) { int a = fis.nextInt() - 1; int b = fis.nextInt() - 1; setConnected(graph, a, b); state[(1 << a) | (1 << b)][a > b ? a : b] = 1; } long res = 0; for (int i = 2; i < n; i++) { int baseCombination = (2 << i) - 1; while (baseCombination < (1 << n)) { int min = getFirstOne(baseCombination); int bits = baseCombination; while (bits != 0) { int firstBit = bits & (-bits); int firstBitPos = getFirstOne(firstBit); bits &= bits - 1; if (firstBitPos == min) continue; int leftOverBits = baseCombination - firstBit; int nextBits = leftOverBits; while (nextBits != 0) { int nextBit = nextBits & (-nextBits); int nextBitPos = getFirstOne(nextBit); nextBits &= nextBits - 1; if (nextBitPos == min) continue; if (!isConnected(graph, firstBitPos, nextBitPos)) continue; /*System.out.println("Comb: " + Integer.toBinaryString(baseCombination)); System.out.println("Bit: " + Integer.toBinaryString(firstBit)); System.out.println("(pos): " + firstBitPos); System.out.println("Left over: " + Integer.toBinaryString(leftOverBits)); System.out.println("Next bit: " + Integer.toBinaryString(nextBit)); System.out.println("(pos): " + nextBitPos); System.out.println();*/ state[baseCombination][firstBitPos] += state[leftOverBits][nextBitPos]; } if (isConnected(graph, firstBitPos, min)) res += state[baseCombination][firstBitPos]; } baseCombination = nextCombination(baseCombination); } } /*for (int i = 0; i < state.length; i++) { if ((i & (i - 1)) == 0) continue; System.out.print(String.format("%4s:", Integer.toBinaryString(i)).replace(' ', '0') + " "); for (int j = 0; j < state[i].length; j++) System.out.print(state[i][j] + " "); System.out.println(); }*/ return res >> 1; } public static boolean isConnected(boolean[][] graph, int a, int b) { if (b < a || graph[a].length <= (b - a)) return graph[b][a - b]; return graph[a][b - a]; } public static void setConnected(boolean[][] graph, int a, int b) { if (b < a || graph[a].length <= (b - a)) graph[b][a - b] = true; else graph[a][b - a] = true; } public static int nextCombination(int x) { int smallest = x & -x; int ripple = x + smallest; int ones = ((x ^ ripple) >> 2) / smallest; return ripple | ones; } public static boolean on(int bitmask, int pos) { return ((bitmask >> pos) & 1) == 1; } public static int setOn(int bitmask, int pos) { return bitmask | (1 << pos); } public static int setOff(int bitmask, int pos) { return bitmask & ~(1 << pos); } public static int getOns(int bitmask) { int amt = 0; while (bitmask != 0) { bitmask &= bitmask - 1; amt++; } return amt; } public static int getFirstOne(int bitmask) { if (bitmask == 0) return -1; int first = 0; while ((bitmask & 1) != 1) { first++; bitmask = bitmask >> 1; } return first; } public static class FastInputStream extends InputStream { private InputStream in; private byte[] buffer = new byte[512]; private int loaded = 0; private int pointer = 0; public FastInputStream(InputStream in) { this.in = in; } @Override public int read() throws IOException { if (hasNext()) return buffer[pointer++]; else return -1; } public void skipWhitespace() throws IOException { while (hasNext()) { char c = (char) buffer[pointer]; if (c == ' ' || c == '\t' || c == '\n' || c == '\r') pointer++; else return; } } public Integer nextInt() throws IOException { skipWhitespace(); if (!hasNext()) return null; byte multiplier = 1; int number = 0; if (buffer[pointer] == '-') { multiplier = -1; pointer++; } while (hasNext()) { char c = (char) buffer[pointer]; if (c >= '0' && c <= '9') { number = (number << 3) + (number << 1) + c - '0'; pointer++; } else break; } return number * multiplier; } public void close() throws IOException { in.close(); } public boolean hasNext() throws IOException { while (pointer == loaded) { loaded = in.read(buffer); pointer = 0; if (loaded == -1) return false; } return loaded != -1; } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Ok_Simple { static BufferedReader reader; static StringTokenizer tokenizer; static boolean am[][]; static long dp[][]; static int n; public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); int m; n = NextInt(); m = NextInt(); am = new boolean[n][n]; dp = new long[n][1 << n]; for (int i = 0; i < n; ++i) Arrays.fill(dp[i], -1); for (int i = 0; i < m; ++i) { int a = NextInt() - 1; int b = NextInt() - 1; am[a][b] = am[b][a] = true; }; long res = 0; for (int a = 0; a < n; ++a) res += solve(a, (1 << a)); System.out.println(res / 2); } private static long solve(int b, int mask) { int a = 0; for (int i = 0 ;i < n; ++i) if (((mask >> i) & 1) != 0) { a = i; break; } if (dp[b][mask] >= 0) return dp[b][mask]; long res = 0; if (am[b][a] && Integer.bitCount(mask) > 2) res = 1; for (int i = a + 1; i < n; ++i) if (((mask >> i) & 1) == 0 && am[b][i]) res += solve(i, mask ^ (1 << i)); return dp[b][mask] = res; } static int NextInt() throws NumberFormatException, IOException { return Integer.parseInt(NextToken()); } static double NextDouble() throws NumberFormatException, IOException { return Double.parseDouble(NextToken()); } static long NextLong() throws NumberFormatException, IOException { return Long.parseLong(NextToken()); } static String NextToken() throws IOException { while(tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
np
11_D. A Simple Task
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 N = Integer.parseInt(input[0]), M = Integer.parseInt(input[1]); boolean[][] connected = new boolean[N + 1][N]; long[][] walks = new long[1 << N][N]; long res = 0; for(int i = 0; i < M; i++){ input = kek.readLine().split(" "); int A = Integer.parseInt(input[0]) - 1, B = Integer.parseInt(input[1]) - 1; connected[A][B] = connected[B][A] = true; } for(int i = 0; i < N; i++){ walks[1 << i][i] = 1; } for(int i = 1; i < 1 << N; i++){ int temp = (int) (Math.log(i & -(i)) / 0.6931471805599453); for(int j = 0; j < N; j++){ if(((1 << j) & i) > 0 && j != temp){ for(int k = 0; k < N; k++){ if(connected[k][j]){ walks[i][j] += walks[i ^ (1 << j)][k]; } } int count = 0, track = i; while(track > 0){ if(track % 2 == 1){ count++; } track /= 2; } if(count >= 3 && connected[temp][j]){ res += walks[i][j]; } } } } outkek.println(res / 2); kek.close(); outkek.close(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class ASimpleTask { static StreamTokenizer st; static int nextInt() { try { st.nextToken(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return (int) st.nval; } static int[][] edges; static long[][] dp; public static void main(String[] args) { st = new StreamTokenizer(new BufferedReader(new InputStreamReader( System.in))); int n = nextInt(); int m = nextInt(); edges = new int[n][n]; for (int i = 0; i < m; i++) { int from = nextInt() - 1; int to = nextInt() - 1; edges[from][to] = edges[to][from] = 1; } dp = new long[(1 << n) + 1][n + 1]; for (int mask = 1; mask < (1 << n); mask++) { for (int i = 0; i < n; i++) { if (Integer.bitCount(mask) == 1 && (mask & (1 << i)) != 0) { dp[mask][i] = 1; continue; } if (Integer.bitCount(mask) > 1 && (mask & (1 << i)) != 0 && first(mask, n) != i) { for (int j = 0; j < n; j++) { if (edges[i][j] == 1) { dp[mask][i] += dp[mask ^ (1 << i)][j]; } } } } } long count = 0; for (int mask = 1; mask < (1 << n); mask++) { for (int i = 0; i < n; i++) { if (Integer.bitCount(mask) >= 3 && edges[i][first(mask, n)] != 0) count += dp[mask][i]; } } System.out.println(count / 2); } static int first(int mask, int n) { for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) return i; } return -1; } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main implements Runnable { private int n; private int nn; private boolean[][] gr; private long[][] D; // //////////////////////////////////////////////////////////////////// // Solution private void solve() throws Throwable { n = nextInt(); nn = 1 << n; gr = new boolean[n][n]; int m = nextInt(); for (int i = 0; i < m; i++) { int a = nextInt() - 1, b = nextInt() - 1; gr[a][b] = gr[b][a] = true; } D = new long[n][nn]; for (int i = 0; i < n; i++) { Arrays.fill(D[i], -1); } long count = 0; for (int i = 0; i < n; i++) { count += getD(i, i, 1, 1 << i); } pw.println(count / 2); } private long getD(int first, int last, int cnt, int mask) { if (D[last][mask] != -1) return D[last][mask]; long ans = 0; if (cnt >= 3 && gr[first][last]) ans++; for (int i = first + 1; i < n; i++) { if (gr[last][i] && (mask & (1 << i)) == 0) { ans += getD(first, i, cnt + 1, mask | (1 << i)); } } D[last][mask] = ans; return ans; } // //////////////////////////////////////////////////////////////////// // Utility functions PrintWriter pw; BufferedReader in; StringTokenizer st; void initStreams() throws FileNotFoundException { //System.setIn(new FileInputStream("2")); in = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); } String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextString()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextString()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextString()); } static Throwable sError; public static void main(String[] args) throws Throwable { Thread t = new Thread(new Main()); t.start(); t.join(); if (sError != null) { throw sError; } } public void run() { try { initStreams(); solve(); } catch (Throwable e) { sError = e; } finally { if (pw != null) pw.close(); } } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.io.*; public class ASimpleTask { /************************ SOLUTION STARTS HERE ***********************/ static long memo[][]; static int graph[]; static long hamiltonianPath(int mask , int u) { if(memo[mask][u] != -1) return memo[mask][u]; else if(u == Integer.numberOfTrailingZeros(mask)) // according to our convention A simple path is not allowed to end at the lowest vertex return 0; else { long sum = 0; for(int fromSet = mask ^ (1 << u);fromSet > 0; fromSet ^= Integer.lowestOneBit(fromSet)) { int v = Integer.numberOfTrailingZeros(fromSet); // System.out.printf("mask = %s , u = %d , v = %d\n" , Integer.toBinaryString(mask) , u , v); if((graph[u] & (1 << v)) != 0) sum += hamiltonianPath(mask ^ (1 << u), v); } return /*memo[mask][u] = */sum; } } private static void solveBottomUp(FastScanner s1, PrintWriter out){ int V = s1.nextInt(); int E = s1.nextInt(); graph = new int[V]; long DP[][] = new long[1 << V][V]; while(E-->0) { int u = s1.nextInt() - 1; int v = s1.nextInt() - 1; graph[u] |= (1 << v); graph[v] |= (1 << u); } for(int i=0;i<V;i++) DP[1 << i][i] = 1; for(int mask = 1 , end = 1 << V;mask < end;mask++) { for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); for(int fromSet = mask ^ (1 << u);fromSet > 0; fromSet ^= Integer.lowestOneBit(fromSet)) { int v = Integer.numberOfTrailingZeros(fromSet); // System.out.printf("mask = %s , u = %d , v = %d\n" , Integer.toBinaryString(mask) , u , v); if((graph[u] & (1 << v)) != 0) DP[mask][u] += DP[mask ^ (1 << u)][v]; } } } long totalCycles = 0; for(int mask = 1 , end = 1 << V;mask < end;mask++) { if(Integer.bitCount(mask) >= 3) { int start = Integer.numberOfTrailingZeros(mask); for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); if((graph[u] & (1 << start)) != 0) totalCycles += DP[mask][u]; } } } totalCycles /= 2; /* for(long l[] : DP) out.println(Arrays.toString(l));*/ out.println(totalCycles); } private static void solveTopDown(FastScanner s1, PrintWriter out){ int V = s1.nextInt(); int E = s1.nextInt(); graph = new int[V]; memo = new long[1 << V][V]; for(long l[] : memo) Arrays.fill(l, -1); while(E-->0) { int u = s1.nextInt() - 1; int v = s1.nextInt() - 1; graph[u] |= (1 << v); graph[v] |= (1 << u); } for(int i=0;i<V;i++) memo[1 << i][i] = 1; long totalCycles = 0; for(int mask = 1 , end = 1 << V;mask < end;mask++) { if(Integer.bitCount(mask) >= 3) { int start = Integer.numberOfTrailingZeros(mask); for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); if((graph[u] & (1 << start)) != 0) totalCycles += hamiltonianPath(mask, u); } } } totalCycles /= 2; out.println(totalCycles); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE *********************/ public static void main(String []args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); solveBottomUp(in, out); in.close(); out.close(); } static class FastScanner{ BufferedReader reader; StringTokenizer st; FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;} String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble(){return Double.parseDouble(next());} char nextChar() {return next().charAt(0);} int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}} } /************************ TEMPLATE ENDS HERE ************************/ }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; import java.io.*; public class Main implements Runnable { private void solution() throws IOException { int n = in.nextInt(); int m = in.nextInt(); boolean[][] adj = new boolean[n][n]; long res = 0; for (int i = 0; i < m; ++i) { int x = in.nextInt(); int y = in.nextInt(); adj[x - 1][y - 1] = true; adj[y - 1][x - 1] = true; } final long[][] dp = new long[1 << n][n]; for (int i = 0; i < n; ++i) { int Limit = 1 << (n - i); int nn = n - i; for (int mask = 0; mask < Limit; ++mask) { for (int j = 0; j < nn; ++j) { dp[mask][j] = 0; } } dp[0][0] = 1; for (int mask = 0; mask < Limit; ++mask) { for (int j = 0; j < nn; ++j) { if (dp[mask][j] != 0) { long am = dp[mask][j]; for (int k = 0; k < nn; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) { dp[mask | (1 << k)][k] += am; } } } } if (((mask >> 0) & 1) != 0) { res += dp[mask][0]; } } } out.println((res - m) / 2); } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private class Scanner { BufferedReader reader; StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""); } 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 int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) throws IOException { new Thread(null, new Main(), "", 1 << 28).start(); } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Scanner in = new Scanner(new InputStreamReader(System.in)); }
np
11_D. A Simple Task
CODEFORCES
import java.util.InputMismatchException; import java.io.*; import java.util.HashMap; /** * 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 SimpleCycles(); 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 SimpleCycles implements Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); boolean[][] g = new boolean[n][n]; for (int i = 0; i < m; ++i) { int u = in.nextInt(); int v = in.nextInt(); --u; --v; g[u][v] = g[v][u] = true; } HashMap<Integer, Integer> pointer = new HashMap<Integer, Integer> () ; for (int i =0 ; i < n; ++i) { pointer.put(1 << i, i); } long[][] dm = new long[1 << n][n]; for (int i = 0; i < n; ++i) { dm[1 << i][i] = 1; } for (int i = 0; i < (1 << n); ++i) { for (int j = 0; j < n; ++j) { if (dm[i][j] == 0) continue; int k = pointer.get(i - (i & (i - 1))); for (int u = k + 1; u < n; ++u) { if (g[j][u] && (i & (1 << u)) == 0) { dm[i | (1 << u)][u] += dm[i][j]; } } } } long res = 0; for (int i = 0; i < (1 << n); ++i) { for (int j = 0; j < n; ++j) if (Integer.bitCount(i) >= 3) { int c = pointer.get(i - (i & (i - 1))); if (g[c][j]) res += (long) dm[i][j]; } } out.print(res / 2); } }
np
11_D. A Simple Task
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 SimpleTask { public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] g = new int[n]; long[][] dp = new long[1 << n][n]; for (int i = 0; i < m; i++) { int a = in.nextInt() - 1, b = in.nextInt() - 1; g[a] |= (1 << b); g[b] |= (1 << a); } int all = (1 << n) - 1; for (int i = 0; i < n; i++) { int l = (1 << i); int left = all ^ (l - 1) ^ l; for (int j = left; j > 0; j = (j - 1) & left) if ((j & (j - 1)) != 0) { dp[j | l][i] = 1; } } for (int i = (1 << n) - 1; i > 0; i--) { int last = i & -i; for (int j = 0; j < n; j++) { if (((1 << j) == last && (i & (i - 1)) != 0) || ((1 << j) & i) == 0) continue; for (int k = 0; k < n; k++) { if ((1 << k) >= last && ((1 << k) & g[j]) != 0 && ((1 << k) == last || ((1 << k) & i) == 0)) { dp[i][j] += dp[i | (1 << k)][k]; } } } } long res = 0; for (int i = 0; i < n; i++) res += dp[(1 << i)][i]; System.out.println(res / 2); } static class InputReader { private BufferedReader reader; private 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()); } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class A{ static int n,m,start; static boolean [][] adj; static long [][] mem; public static void main(String[] args)throws Throwable { Scanner sc=new Scanner(System.in); n=sc.nextInt(); m=sc.nextInt(); adj=new boolean [n][n]; for(int i=0;i<m;i++){ int u=sc.nextInt()-1; int v=sc.nextInt()-1; adj[u][v]=true; adj[v][u]=true; } mem=new long [n+1][(1<<n)]; for(int i=0;i<=n;i++) Arrays.fill(mem[i], -1); long ans=0; for(int i=0;i<n;i++){ start=i; ans+=dp(i, (1<<i)); } System.out.println(ans/2); } public static long dp(int i,int msk){ if(mem[i][msk]!=-1) return mem[i][msk]; long ans=0; if(adj[i][start] && Integer.bitCount(msk)>2) ans++; for(int j=start+1;j<n;j++){ if(adj[i][j] && (msk & (1<<j))==0){ ans+=dp(j, msk | (1<<j)); } } return mem[i][msk]=ans; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken();} public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * Created by huhansan on 2017/12/19. * http://codeforces.com/problemset/problem/11/D * 参考 Petr http://codeforces.com/contest/11/submission/47646 * 求所有不同的环的个数 * 首先按长度分 C = C1+C2+...+Cn * 长度为i的环的数量的求解, 规定一个顺序,以最小值开头,按开头不同分治,再按不同结尾分治 * 遍历所有排列,如果长度为i的排列成环,则对应的Ci值+1 * 遍历方式的选择: * 1.integer实现bitmask,从1加到1<<n * 2.递归 */ public class CF_11D { long[][] ways; //ways[mask][endPointIndex] boolean[][] connect; int n, m, lowestIndex, mask; //n 节点数, m边数 00000...0 <--> n:n-1:n-2.....1 bitmask private static int HEAD_POINT_INDEX = 0; public void solve() throws Exception { int a, b; long total = 0; n = nextInt(); m = nextInt(); connect = new boolean[n][n]; ways = new long[1 << n][n]; for (int i = 0; i < m; i++) { a = nextInt(); b = nextInt(); connect[a - 1][b - 1] = true; connect[b - 1][a - 1] = true; } for (int i = 0; i < n; i++) { ways[1 << i][i] = 1; //初始化,单定点也视为环 } for (mask = 1; mask < 1 << n; mask++) { int tmp = mask, cnt = 0; while (tmp > 0) { tmp = tmp & (tmp - 1); cnt++; } lowestIndex = -1; for (int endPointIndex = 0; endPointIndex < n; endPointIndex++) { if ((mask & 1 << endPointIndex) != 0) { if (lowestIndex < 0) { lowestIndex = endPointIndex; } else if (lowestIndex != endPointIndex) { for (int i = lowestIndex; i < n; i++) if (connect[i][endPointIndex]) { ways[mask][endPointIndex] += ways[mask & ~(1 << endPointIndex)][i]; // P[(1,2,3)4]的数量 == 其它+P[1,2,3]的数量, 也就是1,2,3三个点可以组成的以1开头的排列数 } if (connect[endPointIndex][lowestIndex] && cnt > 2) { //以首尾定点分治,存在对称性,如 1-2-3-4-1 == 1-4-3-2-1 total += ways[mask][endPointIndex]; } } } } } writer.println(total / 2); } public static void main(String[] args) { new CF_11D().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
11_D. A Simple Task
CODEFORCES
import java.awt.List; import java.io.BufferedReader; 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.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class T { static Scanner in = new Scanner(); static PrintWriter out = new PrintWriter(System.out); static boolean adj[][]; static int n, m, from; static long memo[][]; static long Num_Cycle; public static void main(String[] args) throws IOException { n = in.nextInt(); m = in.nextInt(); adj = new boolean[n][n]; memo = new long[n][1 << n]; for (int i = 0; i < m; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; adj[u][v] = adj[v][u] = true; } for (long arr[] : memo) { Arrays.fill(arr, -1); } Num_Cycle = 0L; for (int i = 0; i < n; i++) { from = i; Num_Cycle += dp(from, (1 << i)); } out.println(Num_Cycle / 2); out.flush(); out.close(); } static long dp(int start, int mask) { if (memo[start][mask] != -1) { return (memo[start][mask]); } long ans = 0L; if (adj[start][from] && Integer.bitCount(mask) >= 3) {// Cycle has // atleast 3 // node and 3 // edges ans++; } for (int i = from + 1; i < n; i++) { if (adj[start][i] && ((mask & (1 << i)) == 0)) { ans += dp(i, mask | (1 << i)); } } return memo[start][mask] = ans; } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } String nextLine() throws IOException { return br.readLine(); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class C { static boolean[][] matrix; static long[][] dp; static int n; static int m; public static void main(String[] args) { Scanner s = new Scanner(System.in); n = s.nextInt(); m = s.nextInt(); matrix = new boolean[n][n]; for (int i=0; i<m; ++i) { int v1 = s.nextInt()-1; int v2 = s.nextInt()-1; matrix[v1][v2] = true; matrix[v2][v1] = true; } dp = new long[n][1<<n+1]; for (int i=0; i<n; ++i) Arrays.fill(dp[i], -1); long res = 0; for (int i=0; i<n; ++i) res += calc(i, i, (1<<i), 1); System.out.println(res/2); } public static long calc(int h, int c, int m, int len) { if (dp[c][m] != -1) return dp[c][m]; long ret = 0; if (len > 2 && matrix[c][h]) ret = 1; for (int i=h+1; i<n; ++i) if ((m & (1<<i)) == 0 && matrix[c][i]) ret += calc(h, i, m | (1<<i), len + 1); return dp[c][m] = ret; } }
np
11_D. A Simple Task
CODEFORCES
import java.io.IOException; import java.io.PrintStream; import java.util.*; public class Template { public static void main(String[] args) throws IOException { final Scanner in = new Scanner(System.in); final PrintStream out = System.out; int n = in.nextInt(), m = in.nextInt(); boolean[][] g = new boolean[n][n]; for (int i = 0; i < m; ++i) { int a = in.nextInt(), b = in.nextInt(); --a; --b; g[a][b] = g[b][a] = true; } final int mx = 1<<n; long[][] dp = new long[mx][n]; long res = 0; for (int mask = 0; mask < mx; ++mask) for (int i = 0; i < n; ++i) { if (mask == (1 << i)) { dp[mask][i] = 1; } else if (((mask & (1 << i)) != 0) && ((mask & ((1 << i) - 1)) != 0)) { long r = 0; int next = mask ^ (1<<i); for (int j = 0; j < n; ++j) if (g[i][j]) { r += dp[next][j]; } dp[mask][i] = r; } else { dp[mask][i] = 0; } if ((mask & (mask-1)) != 0 && g[i][lowestBit(mask)]) { res += dp[mask][i]; } } System.out.println((res-m)/2); } private static int lowestBit(int mask) { for (int i = 0;;++i) { if ((mask & (1<<i)) > 0) { return i; } } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Main11D { private FastScanner in; private PrintWriter out; public void solve() throws IOException { int N = in.nextInt(); int M = in.nextInt(); int[][] edges = new int[N][N]; for(int i = 0; i < M; i++){ int a = in.nextInt() - 1; int b = in.nextInt() - 1; edges[a][b] = 1; edges[b][a] = 1; } int globalCountMasks = 1 << N; int[][] masks = new int[N + 1][]; int[] countMasks = new int[N + 1]; for(int i = 0; i <= N; i++){ masks[i] = new int[combinations(N, i)]; } for(int i = 0; i < globalCountMasks; i++){ int c = countBit1(i); masks[c][countMasks[c]] = i; countMasks[c]++; } long globalCountCycles = 0; long[][] count = new long[globalCountMasks][N]; for(int a = 0; a < N - 2; a++){ int aBit = 1 << a; count[aBit][a] = 1; long countCycles = 0; for(int i = 2; i <= N; i++){ for(int m = 0; m < countMasks[i]; m++){ int mask = masks[i][m]; if((mask & aBit) == 0) continue; if((mask & (aBit - 1)) > 0) continue; count[mask][a] = 0; for(int v = a + 1; v < N; v++){ int vBit = 1 << v; if((mask & vBit) == 0) continue; count[mask][v] = 0; for(int t = a; t < N; t++){ if((mask & (1 << t)) == 0 || t == v || edges[v][t] == 0) continue; count[mask][v] += count[mask ^ vBit][t]; } if(edges[a][v] == 1 && mask != (aBit | vBit)){ countCycles += count[mask][v]; } } } } globalCountCycles += countCycles / 2; } out.println(globalCountCycles); } private int countBit1(int k){ int c = 0; while(k > 0){ c += k & 1; k >>= 1; } return c; } private int combinations(int n, int k){ if(k > n || k < 0){ throw new IllegalArgumentException(); } int r = 1; for(int i = 1; i <= k; i++){ r = r * (n + 1 - i) / i; } return r; } 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()); } } public static void main(String[] arg) { new Main11D().run(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import javax.sound.midi.Synthesizer; public class Main { static int V; static ArrayList<Integer> adjList []; static int first(int a){ int idx = 0; while (a > 0 && (a & 1) == 0) { idx++; a>>=1; } return idx; } static long Number_Of_Simple_Cycles () { // Time Complexity O(2 ^ n * n ^ 2) long dp [][] = new long[1 << V][V]; for (int i = 0 ; i < V ; ++i) dp[1 << i][i] = 1; for (int mask = 1 ; mask < 1 << V ; ++mask) { if (Integer.bitCount(mask) <= 1) continue; for (int current = 0 ; current < V ; ++current) { if (((1 << current) & mask) == 0) continue; for (int last : adjList[current]) if (current != first(mask)) { dp[mask][current] += dp[mask ^ (1 << current)][last]; } } } long ans = 0 ; int allVisited = (1 << V) - 1; for (int mask = 1 ; mask < 1 << V ; ++mask) { if (Integer.bitCount(mask) < 3) continue; for (int u = 0 ; u < V ; ++u) { if (adjList[u].contains(first (mask))) ans += dp[mask][u]; } } return ans >> 1; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); StringBuilder sb = new StringBuilder(); PrintWriter out = new PrintWriter(System.out); V = sc.nextInt(); adjList = new ArrayList[V]; for (int i = 0 ; i < V ; ++i) adjList[i] = new ArrayList<>(); int E = sc.nextInt(); while (E -- > 0) { int v = sc.nextInt() - 1; int u = sc.nextInt() - 1; adjList[v].add(u); adjList[u].add(v); } out.print(Number_Of_Simple_Cycles()); 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 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
11_D. A Simple Task
CODEFORCES
import java.util.*; public class cf11d { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); boolean[][] g = new boolean[n][n]; boolean[] ok = new boolean[1<<n]; int[] f = new int[1<<n]; for(int i=1; i<(1<<n); i++) { ok[i] = Integer.bitCount(i)>=3; f[i] = first(i); } for(int i=0; i<m; i++) { int a = in.nextInt()-1; int b = in.nextInt()-1; g[a][b] = g[b][a] = true; } long[][] dp = new long[n][1<<n]; for(int i=0; i<n; i++) dp[i][1<<i] = 1; for(int i=1; i<(1<<n); i++) for(int j=0; j<n; j++) for(int k=f[i]+1; k<n; k++) if((i&(1<<k)) == 0 && g[j][k]) dp[k][i^(1<<k)] += dp[j][i]; long ret = 0; for(int i=1; i<(1<<n); i++) for(int j=0; j<n; j++) if(ok[i] && j != f[i]) ret += g[j][f[i]]?dp[j][i]:0; System.out.println(ret/2); } static int first(int x) { int ret = 0; while(x%2==0) { x/=2; ret++; } return ret; } } /* 19 171 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 11 1 12 1 13 1 14 1 15 1 16 1 17 1 18 1 19 2 3 2 4 2 5 2 6 2 7 2 8 2 9 2 10 2 11 2 12 2 13 2 14 2 15 2 16 2 17 2 18 2 19 3 4 3 5 3 6 3 7 3 8 3 9 3 10 3 11 3 12 3 13 3 14 3 15 3 16 3 17 3 18 3 19 4 5 4 6 4 7 4 8 4 9 4 10 4 11 4 12 4 13 4 14 4 15 4 16 4 17 4 18 4 19 5 6 5 7 5 8 5 9 5 10 5 11 5 12 5 13 5 14 5 15 5 16 5 17 5 18 5 19 6 7 6 8 6 9 6 10 6 11 6 12 6 13 6 14 6 15 6 16 6 17 6 18 6 19 7 8 7 9 7 10 7 11 7 12 7 13 7 14 7 15 7 16 7 17 7 18 7 19 8 9 8 10 8 11 8 12 8 13 8 14 8 15 8 16 8 17 8 18 8 19 9 10 9 11 9 12 9 13 9 14 9 15 9 16 9 17 9 18 9 19 10 11 10 12 10 13 10 14 10 15 10 16 10 17 10 18 10 19 11 12 11 13 11 14 11 15 11 16 11 17 11 18 11 19 12 13 12 14 12 15 12 16 12 17 12 18 12 19 13 14 13 15 13 16 13 17 13 18 13 19 14 15 14 16 14 17 14 18 14 19 15 16 15 17 15 18 15 19 16 17 16 18 16 19 17 18 17 19 18 19 */
np
11_D. A Simple Task
CODEFORCES
//package round11; import java.io.BufferedOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; import java.util.Arrays; import java.util.Scanner; public class D { private Scanner in; private PrintWriter out; private boolean[][] g; public void solve() { n = ni(); int m = ni(); g = new boolean[n][n]; for(int i = 0;i < m;i++){ int f = ni(); int t = ni(); g[f-1][t-1] = true; g[t-1][f-1] = true; } long ret = 0L; cache = new long[20 << 19]; for(int i = 0;i < n;i++){ start = i; ret += rec(1 << start, i, 0); } out.println(ret/2); } private long[] cache; private int n; private int start; private long rec(int passed, int cur, int depth) { int code = cur << 19 | passed; if(cache[code] != 0)return cache[code]; long ret = 0L; if(g[cur][start] && depth >= 2)ret++; for(int i = start + 1;i < n;i++){ if((passed & (1 << i)) == 0 && g[cur][i]){ ret += rec(passed | (1 << i), i, depth + 1); } } cache[code] = ret; return ret; } public void run() throws Exception { // int m = 19; // StringBuilder sb = new StringBuilder(); // sb.append(m + " "); // sb.append((m*(m-1)/2) + " "); // for(int i = 1;i <= m;i++){ // for(int j = i + 1;j <= m;j++){ // sb.append(i + " " + j + "\n"); // } // } // // in = new Scanner(new StringReader(sb.toString())); // in = new Scanner(new StringReader("4 6 1 2 1 3 1 4 2 3 2 4 3 4")); in = new Scanner(System.in); System.setOut(new PrintStream(new BufferedOutputStream(System.out))); out = new PrintWriter(System.out); // int n = in.nextInt(); int n = 1; for(int i = 1;i <= n;i++){ long t = System.currentTimeMillis(); solve(); out.flush(); System.err.printf("%04d/%04d %7d%n", i, n, System.currentTimeMillis() - t); } } public static void main(String[] args) throws Exception { new D().run(); } private int ni() { return Integer.parseInt(in.next()); } private static void tr(Object... o) { System.out.println(o.length == 1 ? o[0] : Arrays.toString(o)); } private void tra(int[] a) {System.out.println(Arrays.toString(a));} private void tra(int[][] a) { for(int[] e : a){ System.out.println(Arrays.toString(e)); } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class B { static int first(int n) { int res = 0; while(n > 0 && (n & 1) == 0){ n >>= 1; res++; } return res; } public static void main(String[] args) throws Exception { Scanner bf = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = bf.nextInt(), m = bf.nextInt(); ArrayList<Integer> [] adjList = new ArrayList[n]; for (int i = 0; i < adjList.length; i++) { adjList[i] = new ArrayList<Integer>(); } for (int i = 0; i < m; i++) { int u = bf.nextInt()-1, v = bf.nextInt()-1; adjList[u].add(v); adjList[v].add(u); } long [][] memo = new long[(1<<n)][n]; for (int i = 0; i < n; i++) { memo[1<<i][i] = 1; } long ans = 0; for (int i = 1; i < 1<<n; i++) { if(Integer.bitCount(i) == 1) continue; for (int j = 0; j < n; j++) { if((i & (1<<j)) == 0 || j == first(i)) continue; for(int v:adjList[j]) memo[i][j] += memo[i^(1<<j)][v]; } } for (int i = 1; i < 1<<n; i++) { if(Integer.bitCount(i) < 3) continue; int t = first(i); for (int j = 0; j < n; j++) { if(adjList[j].contains(t)) ans += memo[i][j]; } } out.println(ans/2); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader fileReader) { br = new BufferedReader(fileReader); } 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 boolean ready() throws IOException { return br.ready(); } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static long[][] memo; static boolean[][] adjMat; static int N, endNode; static ArrayList<Integer>[] bits; static long dp(int idx, int msk) //complexity = N * 2^(N + 1) { if(memo[idx][msk] != -1) return memo[idx][msk]; long ret = adjMat[idx][endNode] ? 1 : 0; for(int i = 0, sz = bits[msk].size(); i < sz; ++i) { int j = bits[msk].get(i); if(j > endNode) break; if(adjMat[idx][j]) ret += dp(j, msk | 1 << j); } return memo[idx][msk] = ret; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); adjMat = new boolean[N][N]; bits = new ArrayList[1 << N]; for(int i = 0; i < 1 << N; ++i) { bits[i] = new ArrayList<>(1); for(int j = 0; j < N; ++j) if((i & 1 << j) == 0) bits[i].add(j); } int M = sc.nextInt(); while(M-->0) { int u = sc.nextInt() - 1, v = sc.nextInt() - 1; adjMat[u][v] = adjMat[v][u] = true; } long ans = 0; for(int i = N; i > 1; --i) { memo = new long[i][1 << i]; for(long[] x: memo) Arrays.fill(x, -1); ans += dp(endNode = i - 1, 1 << endNode); } for(int i = 0; i < N; ++i) for(int j = i + 1; j < N; ++j) if(adjMat[i][j]) --ans; out.println(ans >> 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 int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class D11 { static boolean[][] g; static int n, m; public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); n = input.nextInt(); m = input.nextInt(); g = new boolean[n][n]; for(int i = 0; i<m; i++) { int a = input.nextInt()-1, b = input.nextInt()-1; g[a][b] = g[b][a] = true; } long res = 0; map = new HashMap<Integer, Long>(); for(int i = n-1; i>=0; i--) { memo = new long[i+1][1<<(i+1)]; for(long[] A : memo) Arrays.fill(A, -1); res += count(i, i, 1<<i)/2; } out.println(res); out.close(); } static long[][] memo; static HashMap<Integer, Long> map; static long count(int at, int start, int mask) { if(memo[at][mask] != -1) return memo[at][mask]; int bits = Integer.bitCount(mask); if(at == start && bits > 2) return 1; long res = 0; for(int i = 0; i<=start; i++) { if(!g[at][i]) continue; if(i != start && (mask & (1<<i)) > 0) continue; if(i == start && bits <= 2) continue; res += count(i, start, mask | (1<<i)); } return memo[at][mask] = res; } 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
11_D. A Simple Task
CODEFORCES
import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.BufferedReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStreamReader; import java.io.IOException; /** * Built using CHelper plug-in * Actual solution is at the top * * @author ATailouloute */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; QuickScanner in = new QuickScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, QuickScanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); boolean[][] is = new boolean[n][n]; for (int i = 0; i < n; i++) { is[i][i] = true; } long[][] dp = new long[1 << n | 1][n]; for (int i = 0; i < m; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; is[u][v] = is[v][u] = true; dp[(1 << u) + (1 << v)][v] = 1; dp[(1 << u) + (1 << v)][u] = 1; } int k = 0; long res = 0; for (int mask = 1; mask < 1 << n; ++mask) { boolean f = true; for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0 && dp[mask][i] == 0) { if (f) { f = false; k = i; } else { for (int j = k + 1; j < n; j++) { if ((mask & (1 << j)) != 0 && is[i][j]) { dp[mask][i] += dp[mask - (1 << i)][j]; } } } if (is[k][i]) res += dp[mask][i]; } } } out.println(res >> 1); } } static class QuickScanner { BufferedReader br; StringTokenizer st; InputStream is; public QuickScanner(InputStream stream) { is = stream; br = new BufferedReader(new InputStreamReader(stream), 32768); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Scanner; public class Main implements Runnable { /** * @param args */ public static void main(String[] args) { new Thread(new Main()).start(); } public void run() { Locale.setDefault(Locale.US); try { run1(); } catch (IOException e) { throw new RuntimeException(); } } int nextInt(StreamTokenizer st) throws IOException { st.nextToken(); return (int) st.nval; } private List<Integer> kmp(String x, String a) { String s = a + "$" + x; int[] oppa = new int[s.length()]; oppa[0] = 0; int tmp = 0; List<Integer> res = new ArrayList<Integer>(); for (int i = 1; i < s.length(); i++) { while (tmp != 0 && s.charAt(tmp) != s.charAt(i)) { // System.out.println(i + " " + tmp); tmp = oppa[tmp - 1]; } if (s.charAt(tmp) == s.charAt(i)) tmp++; oppa[i] = tmp; if (tmp == a.length()) { res.add(i - a.length() - a.length()); } } return res; } double nextDouble(StreamTokenizer st) throws IOException { st.nextToken(); return st.nval; } String nextLine(StreamTokenizer st) throws IOException { st.nextToken(); return st.sval; } public void run1() throws IOException { Scanner sc = new Scanner(new InputStreamReader(System.in)); // Scanner sc = new Scanner(new FileReader("input.txt")); int n = sc.nextInt(); int m = sc.nextInt(); boolean[][] arr = new boolean[n][n]; for (int i = 0; i < m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); arr[a - 1][b - 1] = true; arr[b - 1][a - 1] = true; } long[][] res = new long[n][1 << n]; for (int mask = 1; mask < (1 << n); mask++) { int min = -1; for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) { if (min == -1) { min = i; if (mask == (1 << min)) res[min][mask] = 1; } for (int j = min + 1; j < n; j++) if ((mask & (1 << j)) == 0 && arr[i][j]) { res[j][mask | (1 << j)] += res[i][mask]; } } } } long r = 0; for (int mask = 1; mask < (1 << n); mask++) if (Integer.bitCount(mask) != 2) for (int j = 0; j < n; j++) { int i = 0; while ((mask & (1 << i)) == 0) i++; if (arr[i][j]) r += res[j][mask]; } System.out.println(r / 2); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; public class D { static boolean[][] adj; static int n; static int first; public static void main(String[] args) throws IOException { InputReader in = new InputReader(); n = in.nextInt(); // n = 19;? int m = in.nextInt(); adj = new boolean[n][n]; // for (int i = 0; i < n; i++) { // for (int j = 0; j < n; j++) { // adj[i][j] = true; // } // } dp = new long[1 << n][n]; for (int i = 0; i < m; i++) { int f = in.nextInt() - 1; int t = in.nextInt() - 1; adj[f][t] = adj[t][f] = true; } boolean[] v = new boolean[1 << n]; long res = 0; for (int f = 0; f < n; f++) { first = f; int cnt; for (int i = 0; i < 1 << n; i+=(1<<first)) if ((i & (1 << first)) == 0) for (int j = 0; j < n; j++) dp[i][j] = -1; for (int i = 0; i < 1 << n; i+= (1<<first)) { cnt = Integer.bitCount(i); if ((i & (1 << first)) == 0 && !v[i | (1 << first)] && cnt > 1) { v[i | (1 << first)] = true; res += solve(i, first, cnt); } } } System.out.println(res / 2); } static long[][] dp; public static long solve(int msk, int lst, int cnt) { if (cnt == 0) return (adj[lst][first]) ? 1 : 0; if (dp[msk][lst] != -1) return dp[msk][lst]; long res = 0; for (int i = 0; i < n; i++) if (adj[lst][i] && (msk & (1 << i)) > 0) res += solve(msk ^ (1 << i), i, cnt - 1); return dp[msk][lst] = res; } static class InputReader { BufferedReader in; StringTokenizer st; public InputReader() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(in.readLine()); } public String next() throws IOException { while (!st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
np
11_D. A Simple Task
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while ( sc.hasNextInt() ) { int n = sc.nextInt(); long m = sc.nextInt(); boolean edge[][] = new boolean[n][n]; long dp[][] = new long[1<<n][n]; for ( long i = 1 ; i<=m ; ++i ) { int u = sc.nextInt(); int v = sc.nextInt(); -- u; -- v; edge[u][v] = edge[v][u] = true; } for ( int i = 0 ; i<n ; ++i ) { dp[1<<i][i] = 1; } long res = 0; for ( int i = 1 ; i<(1<<n) ; ++i ) { int first = cal(i); for ( int j = 0 ; j<n ; ++j ) { if ( dp[i][j]==0 ) { continue; } for ( int k = first ; k<n ; ++k ) { if ( j==k || !edge[j][k] ) { continue; } if ( k==first && (i&(1<<k))!=0 ) { res += dp[i][j]; } if ( (i&(1<<k))==0 ) { dp[i|(1<<k)][k] += dp[i][j]; } } } } res -= m; System.out.println(res/2); } } public static int cal( int x ) { int ord = 0; while ( true ) { if ( (x&(1<<ord))!=0 ) { break; } ++ ord; } return ord; } public static boolean judge( int x ) { int cnt = 0; while ( x>=1 ) { if ( (x&1)==1 ) { ++ cnt; } x >>= 1; } return cnt >= 3; } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; /** * Created by Tejas on 18-10-2018. */ public class Main { static HashSet<Integer> adjList[]; public static void main(String[]args)throws IOException{ BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in)); StringBuilder stringBuilder=new StringBuilder(); String temp[]=bufferedReader.readLine().split(" "); int V=Integer.parseInt(temp[0]); int E=Integer.parseInt(temp[1]); adjList=new HashSet[V]; for(int i=0;i<V;i++) adjList[i]=new HashSet<>(); for(int i=0;i<E;i++){ temp=bufferedReader.readLine().split(" "); int x=Integer.parseInt(temp[0])-1; int y=Integer.parseInt(temp[1])-1; adjList[y].add(x); adjList[x].add(y); } stringBuilder.append(solve(V)+"\n"); System.out.println(stringBuilder); } private static long solve(int V) { long dp[][]=new long[(1<<V)][V]; for(int i=0;i<V;i++) dp[(1<<i)][i]=1; for(int mask=1;mask<(1<<V);mask++){ // HW starting at pos first and ending at j. int first = Integer.numberOfTrailingZeros(mask); for(int i=0;i<V;i++){ if((mask&(1<<i))==0 || first==i) continue; for (int j = 0; j < V; j++) if (adjList[i].contains(j) && (mask & (1<<j))!=0) dp[mask][i] += dp[mask ^ (1 << i)][j]; } } //Calculating simple cycles long count=0; for(int mask=1;mask<(1<<V);mask++) { int first = Integer.numberOfTrailingZeros(mask); if (Integer.bitCount(mask)>=3) for (int i = 0; i < V; i++) { if(adjList[first].contains(i)) count+=dp[mask][i]; } } return count/2; } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.text.*; import java.math.*; import java.util.*; public class Main { private StreamTokenizer in; private BufferedWriter out; public void solve() throws Exception { int n = nextInt(), m = nextInt(); int[] ss = new int[n]; for (int i=0; i<m; i++) { int a = nextInt(), b = nextInt(); a--;b--; ss[a]|=1<<b; ss[b]|=1<<a; } long[][] res = new long[n][1<<n]; int[] cnt = new int[1<<n], first = new int[1<<n]; for (int i=0; i<n; i++) { res[i][1<<i] = 1; first[1<<i] = i; cnt[1<<i] = 1; } long ans = 0; for (int mask = 0; mask<1<<n; mask++) { for (int last = first[mask]; last<n; last++) { if (res[last][mask]==0) continue; if (cnt[mask]>2) { if ((ss[last]&(1<<first[mask]))!=0) ans+=res[last][mask]; } int m2 = (~mask) & ss[last]; for (int next = first[mask]+1; next<n; next++) { if ((m2&(1<<next))==0) continue; int mask2 = mask|1<<next; res[next][mask2]+=res[last][mask]; cnt[mask2] = cnt[mask]+1; first[mask2] = first[mask]; } } } ans/=2; out.write(ans+"\n"); } public int nextInt() throws Exception { in.nextToken(); return (int)in.nval; } public void run() { try { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new BufferedWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { new Main().run(); } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Scanner; import static java.lang.Integer.bitCount; import static java.lang.Integer.numberOfTrailingZeros; import static java.lang.System.out; /** * 11D * * @author artyom */ public class ASimpleTask { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] d = new int[n][n]; for (int i = 0, m = sc.nextInt(); i < m; i++) { int a = sc.nextInt() - 1, b = sc.nextInt() - 1; d[a][b] = 1; d[b][a] = 1; } long[][] dp = new long[1 << n][n]; // SOLUTION BEGINS for (int mask = 1; mask < 1 << n; mask++) { int start = numberOfTrailingZeros(mask); // the starting vertex of a Hamiltonian walk if (bitCount(mask) == 1) { dp[mask][start] = 1; continue; } for (int i = 0; i < n; i++) { if ((mask & (1 << i)) > 0 && i != start) { int xmask = mask ^ (1 << i); // mask without vertex i for (int j = 0; j < n; j++) { if (d[j][i] > 0) { dp[mask][i] += dp[xmask][j]; } } } } } // SOLUTION ENDS long sum = 0; for (int mask = 1; mask < 1 << n; mask++) { if (bitCount(mask) >= 3) { // We need at least 3 vertices for a cycle for (int i = 0; i < n; i++) { if (d[numberOfTrailingZeros(mask)][i] > 0) { sum += dp[mask][i]; } } } } out.print(sum / 2); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.StringTokenizer; public class Main implements Runnable { int n; long[][] f; boolean[][] e; int bit(int value) { return (1<<value); } void solve() throws IOException { n = nextInt(); int m = nextInt(); f = new long[1<<n][n]; e = new boolean[n][n]; for (int i = 0; i < (1<<n); ++i) { for (int j = 0; j < n; ++j) { f[i][j] = -1; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { f[bit(i)|bit(j)][j] = 0; e[i][j] = false; } } for (int i = 0; i < m; ++i) { int u = nextInt()-1; int v = nextInt()-1; e[u][v] = true; e[v][u] = true; if (u < v) { f[bit(u)|bit(v)][v] = 1; } else { f[bit(v)|bit(u)][u] = 1; } } long answer = 0; for (int i = 1; i < (1<<n); ++i) { int start = 0; while (((1<<start)&i) == 0) { ++start; } int s = bit(start); for (int nxt = start+1; nxt < n; ++nxt) { int b = bit(nxt); if ((b&i) > 0 && (b|s) != i) { if (e[start][nxt]) { answer += clc(i, nxt); } } } } writer.print(answer>>1); } long clc(int maska, int last) { if (f[maska][last] == -1) { int first = 0; while (((1<<first)&maska) == 0) { ++first; } f[maska][last] = 0; for (int b = first+1; b < n; ++b) { if ((bit(b)&maska)>0) { if (e[b][last]) { f[maska][last] += clc(maska^bit(last), b); } } } } return f[maska][last]; } public static void main(String[] args) throws InterruptedException { new Thread(null, new Runnable() { public void run() { new Main().run(); } }, "1", 1 << 25).start(); } @Override public void run() { try { boolean fromStandart = true; reader = new BufferedReader(fromStandart ? new InputStreamReader(System.in) : new FileReader(INFILE)); writer = new PrintWriter(new BufferedWriter(fromStandart ? new OutputStreamWriter(System.out) : new FileWriter(OUTFILE))); tokenizer = null; solve(); writer.flush(); } catch (Exception error) { error.printStackTrace(); System.exit(1); } } static final String INFILE = "input.txt"; static final String OUTFILE = "output.txt"; BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextString() throws IOException { return reader.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class D11 { static HashMap<State, Integer> map; static long[][] ans; static boolean[][] connect; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); map = new HashMap<State, Integer>(); connect = new boolean[n][n]; ans = new long[n][1<<n]; for(int i = 0; i < n; i++) Arrays.fill(ans[i], -1); int m = Integer.parseInt(st.nextToken()); while(m-- > 0) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); a--; b--; connect[a][b] = connect[b][a] = true; } long ret = 0; int mask = 1 << n; mask--; for(int i = 0; i < n; i++) { for(int out = i+1; out < n; out++) { if(connect[i][out]) { ret += solve(mask - (1<<out), out, true); } } mask -= (1<<i); } System.out.println(ret/2); } public static long solve(int mask, int start, boolean a) { if(ans[start][mask] != -1) return ans[start][mask]; int end = 0; while((mask & (1<<end)) == 0) end++; long ret = 0; for(int out = 0; out < connect.length; out++) { if(connect[start][out] && (mask & (1 << out)) != 0) { if(out == end) { if(!a) ret++; } else ret += solve(mask - (1<<out), out, false); } } ans[start][mask] = ret; return ret; } static class State { public byte start, go; public int mask; public State(byte a, byte b, int c) { start = a; go = b; mask = c; } public int hashCode() { return 10007*mask + 43 * start + go; } public boolean equals(Object o) { State s = (State)o; return start == s.start && go == s.go && mask == s.mask; } } }
np
11_D. A Simple Task
CODEFORCES
import javafx.util.Pair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; public class ElongatedMatrix { private static int n; /** * if the rows are arranged in some permutation [p_1, p_2,...i,j,...p_n], * 1!=i!=j!=n, minCost[i][j] is the min k for any permutation with i&j adjacent **/ private static int[][] minCost; /** * minCostEndpoints[i][j] is the min k for any permutation such that * the rows are arranged in some permutation [i, p_2, ... p_{n-1}, j], **/ private static int[][] minCostEndpoints; /** * Max k of a path over a subset of all rows ending at a certain vertex * The first 16 bits of the key represent the subset. Node n is in the subset iff (x & (2 << n))!=0 * key/(1<<16) is the end vertex number */ private static HashMap<Integer, Integer> costs = new HashMap<>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int[] params = Arrays.stream(br.readLine().split(" ")) .mapToInt(x -> Integer.parseInt(x)).toArray(); n = params[0]; int m = params[1]; int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) { matrix[i] = Arrays.stream(br.readLine().split(" ")) .mapToInt(x -> Integer.parseInt(x)).toArray(); } minCost = new int[n][n]; minCostEndpoints = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i > j) { minCost[i][j] = Integer.MAX_VALUE; for (int k = 0; k < m; k++) { int diff = Math.abs(matrix[i][k] - matrix[j][k]); if (diff < minCost[i][j]) { minCost[i][j] = diff; } } minCost[j][i] = minCost[i][j]; } minCostEndpoints[i][j] = Integer.MAX_VALUE; for (int k = 0; k < m - 1; k++) { int diff = Math.abs(matrix[i][k + 1] - matrix[j][k]); if (diff < minCostEndpoints[i][j]) { minCostEndpoints[i][j] = diff; } } } } int maxCost = n == 1 ? minCostEndpoints[0][0] : 0; for (int i = 0; i < n; i++) { costs.clear(); for (int j = 0; j < n; j++) { if (i != j) { int bitmask = (1 << i) | (1 << j); int state = bitmask + (j << 16); costs.put(state, minCost[i][j]); } } for (int j = 0; j < n; j++) { if (i != j) { if (minCostEndpoints[i][j] <= maxCost) { continue; } else { int pathCost = Math.min(minCostEndpoints[i][j], findMaxCost(i, j, (1 << n) - 1)); maxCost = Math.max(maxCost, pathCost); } } } } System.out.println(maxCost); br.close(); } //find the minimum cost starting at st, ending at end, and using only the rows in set private static int findMaxCost(int st, int end, int set) { int state = set + (end << 16); if (costs.containsKey(state)) { return costs.get(state); } int maxCost = 0; for (int i = 0; i < n; i++) { if (i != st && i != end && (set & (1 << i)) != 0) { int setWithoutEnd = set - (1 << end); int pathCost = Math.min(findMaxCost(st, i, setWithoutEnd), minCost[i][end]); maxCost = Math.max(pathCost, maxCost); } } costs.put(state, maxCost); return maxCost; } }
np
1102_F. Elongated Matrix
CODEFORCES