标签:
题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1002
题解:求给出图的生成树数目
关于生成树数目的计算:http://www.cnblogs.com/shjwudp/articles/4339068.html
这题有很坑,答案会爆longlong,用了java写的
1 /* 2 * Problem: BZOJ 1002 3 * Author: SHJWUDP 4 * Created Time: 2015/4/15 星期三 19:24:14 5 * File Name: Main.java 6 * State: Accepted 7 * Memo: Matrix-Tree 8 */ 9 import java.util.*; 10 import java.io.*; 11 import java.math.*; 12 13 public class Main { 14 public static void main(String args[]) throws IOException { 15 InputStream inputStream = System.in; 16 OutputStream outputStream = System.out; 17 InputReader in = new InputReader(inputStream); 18 PrintWriter out = new PrintWriter(outputStream); 19 20 TaskA solver = new TaskA(); 21 solver.solve(in, out); 22 out.close(); 23 } 24 } 25 26 class TaskA { 27 public void solve(InputReader in, PrintWriter out) { 28 int n=in.nextInt(); 29 if(n<=1) { 30 out.print(1+"\n"); 31 return ; 32 } 33 int[][] D=new int[n+1][n+1]; 34 int[][] A=new int[n+1][n+1]; 35 D[n][n]=n; 36 for(int i=0; i<n; i++) D[i][i]=3; 37 for(int i=0; i<n; i++) { 38 A[i][n]=A[n][i]=1; 39 int r=(i+1)%n; 40 A[i][r]=A[r][i]=1; 41 } 42 43 BigInteger[][] C=new BigInteger[n+1][n+1]; 44 for(int i=0; i<=n; i++) { 45 for(int j=0; j<=n; j++) { 46 C[i][j]=BigInteger.valueOf(D[i][j]-A[i][j]); 47 } 48 } 49 50 //计算C的m-1阶行列式 (m=n+1) 51 BigInteger ans=BigInteger.ONE; 52 for(int i=0; i<n; i++) { 53 for(int j=i+1; j<n; j++) while(C[j][i]!=BigInteger.ZERO) { 54 BigInteger t=C[i][i].divide(C[j][i]); 55 for(int k=i; k<n; k++) { 56 C[i][k]=C[i][k].subtract(C[j][k].multiply(t)); 57 } 58 for(int k=i; k<n; k++) { 59 BigInteger tmp=C[i][k]; 60 C[i][k]=C[j][k]; 61 C[j][k]=tmp; 62 } 63 ans=ans.negate(); 64 } 65 ans=ans.multiply(C[i][i]); 66 } 67 if(ans.compareTo(BigInteger.ZERO)<0) ans=ans.negate(); 68 out.print(ans+"\n"); 69 } 70 } 71 72 class InputReader { 73 public BufferedReader reader; 74 public StringTokenizer tokenizer; 75 76 public InputReader(InputStream stream) { 77 reader = new BufferedReader(new InputStreamReader(stream), 32768); 78 tokenizer = null; 79 } 80 81 public String next() { 82 while(tokenizer == null || !tokenizer.hasMoreTokens()) { 83 try { 84 tokenizer = new StringTokenizer(reader.readLine()); 85 } catch (IOException e) { 86 throw new RuntimeException(e); 87 } 88 } 89 return tokenizer.nextToken(); 90 } 91 92 public int nextInt() { 93 return Integer.parseInt(next()); 94 } 95 96 public BigInteger nextBigInt() { 97 return new BigInteger(next()); 98 } 99 }
标签:
原文地址:http://www.cnblogs.com/shjwudp/p/4430021.html