藍橋杯 2014本科C++ B組 奇怪的分式 暴力枚舉

來源:互聯網
上載者:User

標籤:

藍橋杯 枚舉 奇怪的分式

標題:奇怪的分式

 

    上小學的時候,小明經常自己發明新演算法。一次,老師出的題目是:

 

    1/4 乘以 8/5

 

    小明居然把分子拼接在一起,分母拼接在一起,答案是:18/45 (參見圖1.png)

 

    老師剛想批評他,轉念一想,這個答案湊巧也對啊,真是見鬼!

 

    對於分子、分母都是 1~9 中的一位元的情況,還有哪些算式可以這樣計算呢?

 

    請寫出所有不同算式的個數(包括題中舉例的)。

 

    顯然,交換分子分母后,例如:4/1 乘以 5/8 是滿足要求的,這算做不同的算式。

 

    但對於分子分母相同的情況,2/2 乘以 3/3 這樣的類型太多了,不在計數之列!

 

注意:答案是個整數(考慮對稱性,肯定是偶數)。請通過瀏覽器提交。不要書寫多餘的內容。

挺簡單的,要是暴力枚舉也沒問題,用一個DFS的深搜代碼看上去簡單點,另外熟悉GCD,將兩個分數的最大公約數求出,相除公約數,再去判斷這兩個分數是否相同。

答案:14

代碼如下

 

 1 #include<iostream> 2 #include<cstdio> 3 #define MAXN 5 4 using namespace std; 5 int num[MAXN],s1,s2,r1,r2; 6 int count=0; 7 int gcd(int a,int b) 8 { 9     int s;10     while(b)11     {12         s=a%b;13         a=b;14         b=s;15     }16     return a;17  } 18 void dfs(int m)19 {20     int i,j,a,b,t,ss1,ss2,rr1,rr2;21     if(m==5)22     {23         if(num[1]!=num[2]&&num[3]!=num[4])24         {25             s1=num[1]*10+num[3];26             s2=num[2]*10+num[4];27             r1=num[1]*num[3];28             r2=num[2]*num[4];29             if(r1<r2)30             {31                 a=r2;32                 b=r1;33                 t=gcd(a,b);34             }35             else36             {37                 a=r1;38                 b=r2;39                 t=gcd(a,b); 40             }41             rr1=r1/t;42             rr2=r2/t;43             if(s1<s2)44             {45                 a=s2;46                 b=s1;47                 t=gcd(a,b);48             }49             else50             {51                 a=s1;52                 b=s2;53                 t=gcd(a,b); 54             }    55             ss1=s1/t;56             ss2=s2/t;57             if(rr1==ss1&&rr2==ss2)58             {59                 cout<<num[1]<<"/"<<num[2]<<" * "<<num[3]<<"/"<<num[4]<<" = "<<num[1]<<num[3]<<"/"<<num[2]<<num[4]<<endl;60                 count++;61             }62         }63     }64     else65     {66         for(i=1;i<=9;i++)67         {68             num[m]=i;69             dfs(m+1);70         }71     }72  } 73  int main()74  {75      dfs(1);76      cout<<count<<endl;77      return 0;78  }

 

藍橋杯 2014本科C++ B組 奇怪的分式 暴力枚舉

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.