您的位置:首页 > 其它

Ordered Fractions

2013-02-05 17:24 162 查看
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


啥也不说了上代码。。

/*
ID: des_jas1
PROG: frac1
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <cmath>
#include <algorithm>
//#define fin cin
//#define fout cout
using namespace std;

const int M=13000;
int N,num=0,exnum=0;
bool a[165][165];
const char ch='/';
ofstream fout("frac1.out");
ifstream fin("frac1.in");
typedef struct frac
{
int a;
int b;
int index;
float f;
void init(int u,int q,int r,float i)
{
a=u;
b=q;
index=r;
f=i;
}
void p()
{
fout<<a<<ch<<b<<endl;
}
}fraction;

fraction frac[M];

void graph()
{

}

void mark(int f,int b)
{
int i=2,j=2,ff,bb;
while(b*i<=N)
{
ff=f*j;
bb=b*i;
a[ff][bb]=true;
i++;
j++;
}
}

void initial()
{
int i,j;
frac[0].init(0,1,0,0);
num++;
for(i=2;i<=N;i++)
for(j=i-1;j>=1;j--)
{
if(a[j][i])
continue;
a[j][i]=true;
mark(j,i);
frac[num].init(j,i,num,j*0.1/i);//*0.1!!!
num++;
}
frac[num].init(1,1,num,1);
num++;
}

void Swap(int a,int b)
{
fraction temp;
temp=frac[a];
frac[a]=frac[b];
frac[b]=temp;
}

void compare()
{
int i,j,flag,k,kk=num-1;
for(i=1;i<num-1;i++)
{
flag=0;
k=kk;
for(j=1;j<k;j++)
{
if((frac[j].f-frac[j+1].f)>1e-6)
{
Swap(j,j+1);
flag=1;
kk=j;
}
}
if(!flag)
break;
}
}

int main()
{
memset(a,0,sizeof(a));
fin>>N;
initial();
compare();
int i;
for(i=0;i<num;i++)
frac[i].p();
fout.close();
fin.close();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: