Const_Lin
你从远方来, 我到远方去, 遥远的路程经过这里, 天空一无所有, 为何给我安慰。

题目描述:

如下数列,前5项分别是1/1,1/2,2/1,3/1,2/2……。输入n,输出第n项。
1/1 1/2 1/3 1/4 1/5
2/1 2/2 2/3 2/4
3/1 3/2 3/3
4/1 4/2
5/1
样例输入
3
14
7
12345
样例输出
2/1
2/4
1/4
59/99

代码如下:

#include<cstdio>
int main()
{
    int n;
    while(scanf("%d",&n) == 1)
    {
        int k = 1,s = 0;
        for(;;)
        {
            s += k;//s = 0 + 1 + 2 + 3 + ...//前k条斜线共有s个数
            if(s >= n)
            {
                if(k % 2 == 0) //要分奇偶条斜线两种情况
                    printf("%d/%d\n",k-s+n,s-n+1);
                else
                    printf("%d/%d\n",s-n+1,k-s+n);
                break;
            }
            k++;
        }
    }
    return 0;
}

/*更好的版本*/
#include<cstdio>
#include<cmath>
int main()
{
    int n;
    while(scanf("%d",&n) == 1)
    {//由n<=S(k) -> n<=1/2*k(k+1),得出k
        int k = (int)floor((sqrt(8.0 * n + 1) - 1) / 2 - le-9) + 1;
        int s = k * (k + 1) / 2;
        if(k % 2 == 0)
            printf("%d/%d",k-s+n,s-n+1);
        else
            printf("%d/%d",s-n+1,k-s+n);
    }
    return 0;
}

题目是出自刘汝佳老师的[算法竞赛入门经典]的一道题目,不过书上的代码好像错了。

Ps:Cantor是一个挺悲剧的一个人,唉,有兴趣的可以了解一下他。http://zh.wikipedia.org/wiki/%E6%A0%BC%E5%A5%A5%E5%B0%94%E6%A0%BC%C2%B7%E5%BA%B7%E6%89%98%E5%B0%94

参考地址:http://www.xuebuyuan.com/599354.html

posted on 2013-12-30 12:26  Const_Lin  阅读(369)  评论(0)    收藏  举报