EOJ(排序)——1852. Ordered Fractions
阿新 • • 發佈:2019-01-11
1852. 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.
樣例
input
5
output
0/1
1/5
1/4
1/3
2/5
1/2
3/5
2/3
3/4
4/5
1/1
題目大意:
對分子,分母小於或等於N的分數集合進行排序,值相同的分數不計入最後的序列。
題目解析:
利用一個結構體儲存分數的分子、分母,用二重迴圈讀入各分數,最大公約數大於1的不儲存。排序時可以將兩分數通分,便於比較大小。
具體程式碼:
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int a;//分子
int b;//分母
}arr[100010];
bool cmp(node x,node y){
return x.a*y.b<y.a*x.b;
}
int measure(int x, int y)
{
int z = y;
while(x%y!=0)
{
z = x%y;
x = y;
y = z;
}
return z;
}
int main() {
freopen("data.in","r",stdin);
int n,k=0;
cin>>n;
cout<<"0/1"<<endl;
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
if(measure(i,j)<=1){
arr[k].a=i;
arr[k].b=j;
k++;
}
}
}
sort(arr,arr+k,cmp);
for(int i=0;i<k;i++)
cout<<arr[i].a<<"/"<<arr[i].b<<endl;
cout<<"1/1"<<endl;
return 0;
}