[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 }

猜你喜欢

转载自www.cnblogs.com/eternhope/p/10003863.html