usaco2.1.2——frac1

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/5
1/4
1/3
2/5
1/2
3/5
2/3
3/4
4/5
1/1

描述

输入一个自然数N,请写一个程序来增序输出分母小于等于N的最简(原文:“既约”)真分数

格式

PROGRAM NAME: frac1

INPUT FORMAT:

(file frac1.in)

单独的一行 一个自然数N(1..160)

OUTPUT FORMAT:

(file frac1.out)

每个分数单独占一行,按照大小次序排列

SAMPLE INPUT

5

SAMPLE OUTPUT

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

USER: di zhang [codeway3]
TASK: frac1
LANG: PASCAL

Compiling...
Compile: OK

Executing...
   Test 1: TEST OK [0.000 secs, 276 KB]
   Test 2: TEST OK [0.000 secs, 276 KB]
   Test 3: TEST OK [0.000 secs, 276 KB]
   Test 4: TEST OK [0.000 secs, 276 KB]
   Test 5: TEST OK [0.000 secs, 276 KB]
   Test 6: TEST OK [0.000 secs, 276 KB]
   Test 7: TEST OK [0.000 secs, 276 KB]
   Test 8: TEST OK [0.000 secs, 276 KB]
   Test 9: TEST OK [0.000 secs, 276 KB]
   Test 10: TEST OK [0.000 secs, 276 KB]
   Test 11: TEST OK [0.000 secs, 276 KB]

All tests OK.

YOUR PROGRAM ('frac1') WORKED FIRST TIME! That's fantastic -- and a rare thing. Please accept these special automated congratulations.

这道题的做法实在是太多了。。。
枚举+快排什么的
我这次用的是比较nb的数学方法,
叫什么也不知道。。。
如下所示
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
递归调用即可得解
{
ID: codeway3
PROG: frac1
LANG: PASCAL
}
program frac1;
  var
    i,j,n,m,k,l:longint;
  procedure doing(a,b,c,d:longint);
    var
      i,j:longint;
    begin
      if (b>n)or(d>n) then exit;
      doing(a,b,a+c,b+d);
      if b+d<=n then writeln(a+c,'/',b+d);
      doing(a+c,b+d,c,d);
    end;
  begin
    assign(input,'frac1.in');
    reset(input);
    assign(output,'frac1.out');
    rewrite(output);
    readln(n);
    writeln('0/1');
    doing(0,1,1,1);
    writeln('1/1');
    close(input);
    close(output);
  end.

posted on 2012-02-19 10:16  codeway3  阅读(298)  评论(0编辑  收藏  举报

导航