Ordered Fractions
2011-09-18 11:22
183 查看
Problem:
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:
Write a program that, given an integer N between 1 and 160 inclusive, prints the fractions in order of increasing magnitude.
———————————————————————————————————————————————————————————————————————
My Answer:
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.
PROGRAM NAME: frac1
INPUT FORMAT
One line with a single integer N.SAMPLE INPUT (file frac1.in)
5
OUTPUT FORMAT
One fraction per line, sorted in order of magnitude.SAMPLE OUTPUT (file frac1.out)
0/1
1/51/4
1/3
2/51/2
3/52/3
3/4
4/51/1
———————————————————————————————————————————————————————————————————————
My Answer:
/* ID:iby071 LANG:C++ TASK:frac1 */ #include<iostream> #include<fstream> using namespace std; struct frac { friend bool operator<(frac,frac); int a; int b; frac(int n1=0,int n2=0):a(n1),b(n2){} }; bool operator<(frac f1,frac f2) //定义分数大小的比较 { if(f1.a*f2.b<f1.b*f2.a) return true; else return false; } int divide(int low,int high,frac f[]) { frac k=f[low]; do { while(low<high && k<f[high]) --high; if(low<high) {f[low]=f[high];++low;} while(low<high && f[low]<k) ++low; if(low<high) {f[high]=f[low];--high;} }while(low!=high); f[low]=k; return low; } void quickSort(int low,int high,frac f[]) { if(low>=high) return; int mid=divide(low,high,f); quickSort(low,mid-1,f); quickSort(mid+1,high,f); } int gcd(int a,int b) //背下来:辗转相除法(by欧几里得)求最大公约数! { if(b==0) return a; else return gcd(b,a%b); } bool check(int a,int b) //判断是否最简分数 { if(gcd(a,b)==1) return true; else return false; } int main() { ifstream fin("frac1.in"); ofstream fout("frac1.out"); int n,size=0; frac *f; fin>>n; f=new frac[n*(n-1)/2+2]; f[0]=frac(0,1); //特别的:0/0 ++size; for(int b=n;b>1;--b) for(int a=1;a<b;++a) if(check(a,b)) {f[size]=frac(a,b);++size;} f[size]=frac(1,1); //特别的:1/1 ++size; quickSort(0,size-1,f); for(int i=0;i<size;++i) fout<<f[i].a<<'/'<<f[i].b<<endl; return 0; }
相关文章推荐
- USACO :Ordered Fractions解题报告
- USACO Ordered Fractions
- USACOTrainning.Ordered Fractions
- USACO-Ordered Fractions
- USACO2.1.2 Ordered Fractions (frac1)
- USACO Ordered Fractions(枚举)
- 顺序的分数 Ordered Fractions(枚举+排序)
- Ordered Fractions
- USACO 2.1 Ordered Fractions (frac1)
- USACO Section 2.1: Prob Ordered Fractions
- [题目] Section 2.1 OrderedFractions(USACO)
- USACO2.1.2 Ordered Fractions (frac1)
- USACO Section2.1 Ordered Fractions 解题报告
- USACO-Section2.1 Ordered Fractions(简单数据处理)
- USACO-Section 2.1 Ordered Fractions(排序)
- Ordered Fractions
- usaco Ordered Fractions
- 洛谷P1458 顺序的分数 Ordered Fractions
- USACO-Section2.1 Ordered Fractions[其他]
- Ordered Fractions