UVA-264-CountonCantor

来源:互联网 发布:电商童装行业数据分析 编辑:程序博客网 时间:2024/05/30 12:03
分析:这个题起初我直接是挨着遍历的,是的,很麻烦,也很费事费空间,还好这个题数据不是很大,没超时。
其实,它是有规律的

原始遍历代码
#include <stdio.h>
int main()
{
    int i,n,j,t1;
    while (scanf("%d",&n)!=EOF)
    {
        int t=1,x=0,y=0,f=1;
        for(i=2;i<10000;i++)
        {
            t+=i;
            f=t<=n;
            if (f==0) break;
            else
            {
                t1=i;
                if (t1%2!=0)
                {
                    y++;
                    for (j=0;j<t1-1;j++)
                    {
                        x++;
                        y--;
                    }
                }
                else if (t1%2==0)
                {
                    x++;
                    for (j=0;j<t1-1;j++)
                    {
                        x--;
                        y++;
                    }
                }
            }
        }
 
        int t2;
        t2=n-t+i;
        if (t2>0 && i%2==0)
        {
            x++;
            for (j=0;j<t2-1;j++)
            {
                x--;
                y++;
            }
        }
        else if (t2>0 && i%2!=0)
        {
            y++;
            for (j=0;j<t2-1;j++)
            {
                x++;
                y--;
            }
        }
        printf("%d/%d\n",y+1,x+1);
    }
    return 0;
 
}


规律代码

#include <cstdio>
int main()
{
    int n;
    while (scanf("%d",&n)!=EOF)
    {
        int f=1,s=0;
        while (1)
        {
            s+=f;
            if (s>=n)
            {
                printf("%d/%d\n",s-n+1,f+n-s);
                break;
            }
            f++;
        }
    }
    return 0;
}


之后在紫书给了一个更变态的做法

#include <cstdio>
#include <cmath>
int main()
{
    int n;
    while (scanf("%d",&n)!=EOF)
    {
        int k=(int)floor((sqrt(8.0*n+1)-1)/2-1e-9) +1;
        int s=k*(k+1)/2;
        printf("%d/%d\n",s-n+1,k+n-s);
    }
    return 0;
}
0 0