日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

TZOJ--3560: Ordered Fractions (枚举)

發布時間:2025/6/17 编程问答 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 TZOJ--3560: Ordered Fractions (枚举) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

3560: Ordered Fractions?

描述

Consider the set of all reduced fractions between 0 and 1 inclusive with denominators less than or equal to N.

Here is the set when N = 5:

0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1

Write a program that, given an integer N between 1 and 160 inclusive, prints the fractions in order of increasing magnitude.

輸入

One line with a single integer N.

輸出

One fraction per line, sorted in order of magnitude.

樣例輸入

?5

樣例輸出

0/1
1/5
1/4
1/3
2/5
1/2
3/5
2/3
3/4
4/5
1/1

題目來源

USACO

?

題目鏈接:http://tzcoder.cn/acmhome/problemdetail.do?&method=showdetail&id=3560

?

題目大意:輸出所有分母小于N,且分數值在0-1之間的所有分數

兩重循環枚舉以0-n為分子,1-n為分母的所有分數,然后去除重復的排序輸出

我們可以考慮優化一下這個暴力,我們發現重復的 1/2 = 2/4 = 3/6,后面這些重復的都不是最簡分數,所以我們只需要存在所有的最簡分數,這樣就不需要去重。

?

優化前:

#include<iostream> #include<algorithm> #include<string.h> using namespace std; struct A {int z;//分子 int m;//分母 double a;//分數的值,因為數字很小,可以直接double比較是否相等 }; int gcd(int x, int y) {if (x % y)return gcd(y , x % y);return y; } bool cmp(A x,A y) //按照 分數的值 進行排序從小到大輸出 {return x.a<y.a; } A symp[12882],temp; int main(void) {int n,i,j,j_m,i_z,g,x;scanf("%d",&n);x=1;symp[0].a=0;for(j=1; j<=n; j++){for(i=1; i<=j; i++){//分子大于分母就大于1,可以不用遍歷枚舉g=gcd(j,i); j_m=j/g;i_z=i/g;symp[x].a=i_z*1.0/j_m;symp[x].z=i_z;symp[x].m=j_m;x++;}} sort(symp,symp+x,cmp);cout<<"0/1"<<endl;for(i=1; i<x; i++) {if(symp[i].a==symp[i-1].a)continue;//和前一項相等的,表示重復了,可以不用輸出 elseprintf("%d/%d\n",symp[i].z,symp[i].m);}return 0; }

  

優化后的代碼:(我隊友寫的)

#include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> using namespace std; struct shu {int fenzi;int fenmu; }a[165*165]; int gcd(int x,int y) {return y==0?x:gcd(y,x%y); } bool cmp(shu x,shu y)//分數通分后比較分子 {int z=gcd(x.fenmu,y.fenmu);z=x.fenmu*y.fenmu/z;return x.fenzi*(z/x.fenmu)<y.fenzi*(z/y.fenmu); } int main() {int i,j,n,k;while(~scanf("%d",&n)){k=0;for(i=2;i<=n;i++){for(j=1;j<i;j++){if(gcd(i,j)!=1)continue;//判斷是否是最簡分數a[k].fenzi=j;a[k++].fenmu=i;}}sort(a,a+k,cmp);printf("0/1\n");for(i=0;i<k;i++){printf("%d/%d\n",a[i].fenzi,a[i].fenmu);}printf("1/1\n");// 1/1 的gcd等于1會出現多次,所以特判輸出} }

  

?

轉載于:https://www.cnblogs.com/Anidlebrain/p/10081195.html

總結

以上是生活随笔為你收集整理的TZOJ--3560: Ordered Fractions (枚举)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。