您的位置:首页 > 其它

UVA-264-CountonCantor

2015-12-10 20:31 411 查看
分析:这个题起初我直接是挨着遍历的,是的,很麻烦,也很费事费空间,还好这个题数据不是很大,没超时。

其实,它是有规律的

原始遍历代码

#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: