1. 程式人生 > >[codevs1288] 埃及分數

[codevs1288] 埃及分數

題目傳送門

迭代深搜。

學了個騷氣的按需開陣列。

注意不能出現相等的情況。

要進行約分,否則會搜爆。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 
 6 int gcd(int x,int y)
 7 {
 8     return y?gcd(y,x%y):x;
 9 }
10 
11 void reduce(int &x,int &y)
12 {
13     int
g=gcd(x,y); 14 x/=g;y/=g; 15 } 16 17 int *buf,*ans; 18 int fl,dep=1; 19 20 void dfs(int a,int b,int d) 21 { 22 reduce(a,b); 23 if(d==1) 24 { 25 if(a==1&&b>buf[d+1]&&b<=ans[d]) 26 { 27 buf[d]=b; 28 fl=1; 29
for(int i=1;i<=sizeof(buf);i++) 30 ans[i]=buf[i]; 31 } 32 return; 33 } 34 for(int i=d*b/a;i>max(b/a,buf[d+1]);i--) 35 { 36 buf[d]=i; 37 int g=gcd(b,i); 38 dfs(i/g*a-b/g,b/g*i,d-1); 39 } 40 } 41 42 int main()
43 { 44 int a,b; 45 scanf("%d%d",&a,&b); 46 while(!fl) 47 { 48 dep++; 49 ans=new int[dep+5]; 50 buf=new int[dep+5]; 51 ans[1]=0x3f3f3f3f; 52 buf[dep+1]=0; 53 dfs(a,b,dep); 54 } 55 for(int i=dep;i>0;i--)printf("%d ",ans[i]); 56 return 0; 57 }