1. 程式人生 > >洛谷P1118 [USACO06FEB]數字三角形 搜索

洛谷P1118 [USACO06FEB]數字三角形 搜索

col 但是 數字 turn pac ostream ios i++ nbsp

洛谷P1118 [USACO06FEB]數字三角形Backward Digit Su… 搜索

這題我們發現每一個位置的加權就是 楊輝三角 yh[ n ][ i ]
然後我們就可以求 n! 暴力 ,但是會 TLE 額 好像是會T 因為12! 已經 4億了
然後我們加一個強力剪枝 如果當前求出來的 s 已經大於 sum了,因為沒有負的加
權,也就是說這一路是沒有用了的,在繼續搜下去也不能更新答案了,那麽就直接退出 。

 1 #include <cstdio>
 2 #include <cmath>
 3 #include <cstdlib>
 4
#include <cstring> 5 #include <string> 6 #include <iostream> 7 #include <iomanip> 8 #include <algorithm> 9 using namespace std ; 10 11 int n,sum ; 12 int ans[13],yh[13][13] ; 13 bool finished ; 14 bool used[13] ; 15 16 inline void dfs(int p,int s) 17 { 18 if(p>n)
19 { 20 if(s==sum) 21 { 22 finished = 1 ; 23 for(int i=1;i<=n;i++) printf("%d ",ans[ i ]) ; 24 exit(0) ; 25 } 26 return ; 27 } 28 for(int i=1;i<=n;i++) 29 { 30 if(!used[ i ]) 31 { 32 if
(s+yh[n][p]*i>sum) continue ; //剪枝 即不能更新答案了 33 ans[ p ] = i ; 34 used[ i ] = 1 ; 35 dfs(p+1,s+yh[n][p]*i) ; 36 used[ i ] = 0 ; 37 } 38 } 39 } 40 41 int main() 42 { 43 scanf("%d%d",&n,&sum) ; 44 yh[1][1] = 1 ; 45 for(int i=2;i<=n;i++) 46 for(int j=1;j<=i;j++) 47 yh[ i ][ j ] = yh[ i-1 ][ j-1 ]+yh[ i-1 ][ j ] ; 48 49 dfs(1,0) ; 50 51 return 0 ; 52 }

洛谷P1118 [USACO06FEB]數字三角形 搜索