#include <stdio.h>
#define DEBUG 1
#define TESTCASES 9
int max;
typedef struct Fraction{
int numerator;
int denominator;
}Fraction;
Fraction FractionArray[25600];
int numOfFractions;
//判断a,b是否互质
int relativePrime(int a, int b){
int r = a % b;
while (r != 0){
a = b;
b = r;
r = a % b;
}
return (b == 1);
}
//两个分数的比较
int FractionCompare(Fraction one, Fraction another){
return one.numerator * another.denominator - one.denominator * another.numerator;
}
int partition(int first, int last){
Fraction pivotFraction = FractionArray[first];
while (first < last){
while (first < last && FractionCompare(FractionArray[last], pivotFraction) >= 0)
last--;
FractionArray[first] = FractionArray[last];
while (first < last && FractionCompare(FractionArray[first], pivotFraction) <= 0)
first++;
FractionArray[last] = FractionArray[first];
}
FractionArray[first] = pivotFraction;
return first;
}
void quickSortFractions(int first, int last){
while (first < last){
int pivot = partition(first, last);
quickSortFractions(first, pivot - 1);
first = pivot + 1;
}
}
int main(){
#if DEBUG
int testCase;
for (testCase = 1; testCase <= TESTCASES; testCase++){
char inputFileName[20] = "inputx.txt";
inputFileName[5] = '1' + (testCase - 1);
freopen(inputFileName, "r", stdin);
printf("\n#%d\n", testCase);
#endif
scanf("%d", &max);
numOfFractions = 0;
int denominator, numerator;
for (denominator = 1; denominator <= max; denominator++)
for (numerator = 0; numerator <= denominator; numerator++)
if (relativePrime(numerator, denominator)){
FractionArray[numOfFractions].numerator = numerator;
FractionArray[numOfFractions].denominator = denominator;
numOfFractions++;
}
quickSortFractions(0, numOfFractions - 1);
int FractionIndex;
for (FractionIndex = 0; FractionIndex < numOfFractions; FractionIndex++)
printf("%d/%d\n", FractionArray[FractionIndex].numerator, FractionArray[FractionIndex].denominator);
#if DEBUG
}
#endif
return 0;
}
USACO 2.1 Ordered Fractions
最新推荐文章于 2017-03-07 16:59:40 发布