http://ace.delos.com/usacoprob2?a=natOyh2BvAP&S=frac1

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

Here's a super fast solution from Russ:

We notice that we can start with 0/1 and 1/1 as our endpoints'' and recursively generate the middle points by adding numerators and denominators.

0/1                                                              1/1
1/2
1/3                      2/3
1/4              2/5         3/5                 3/4
1/5      2/7     3/8    3/7   4/7   5/8       5/7         4/5


Each fraction is created from the one up to its right and the one up to its left. This idea lends itself easily to a recursion that we cut off when we go too deep.

View Code
/*
ID:liuweiv2
PROG:frac1
LANG:C++
*/

#include <iostream>
#include<algorithm>
#include<vector>
#include<fstream>

using namespace std;

ifstream infile;
ofstream outfile;

int n;

struct Num {

int zi;
int mu;

bool operator < (const Num &a) const{
return zi*a.mu < mu * a.zi;
}

};
void yueFun(Num & num){
int tempZi = num.zi;
int tempMu = num.mu;
int last = tempMu % tempZi;
while(last){
tempMu = tempZi;
tempZi = last;
last = tempMu % tempZi;
}
num.zi/=tempZi;
num.mu/=tempZi;

};

void print(Num num){
outfile<<num.zi<<"/"<<num.mu<<endl;
}

vector<Num>nums;

int main(int argc, const char * argv[])
{

infile.open("frac1.in");
outfile.open("frac1.out");
infile>>n;
Num num;
num.zi = 0;num.mu = 1;nums.push_back(num);
num.zi = 1;num.mu = 1;nums.push_back(num);

for(int i=2;i<=n;i++)
for(int j=1;j<i;j++){
num.zi = j;
num.mu = i;
yueFun(num);
nums.push_back(num);
}
sort(nums.begin(),nums.end());

int a = -1,b = -1;
for(int i=0;i<nums.size();i++){
if(a == nums[i].zi && b == nums[i].mu)
continue;
else{
a = nums[i].zi;
b = nums[i].mu;
print(nums[i]);
}
}

return 0;

}

posted on 2012-06-07 12:02  geeker  阅读(610)  评论(0编辑  收藏  举报