Count on Canton Time Limit:1000MS Memory Limit:30000KB 64bit IO Format:%I64d & %I64u Submit Status
Description
One of the famous proofs of modern mathematics is Georg Cantor's demonstration that the set of rational numbers is enumerable. The proof works by using an explicit enumeration of rational numbers as shown in the diagram below.
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
In the above diagram, the first term is 1/1, the second term is 1/2, the third term is 2/1, the fourth term is 3/1, the fifth term is 2/2, and so on.
Input
The input list contains a single number per line and will be terminated by endof-file.
Output
You are to write a program that will read a list of numbers in the range from 1 to 10^7 and will print for each number the corresponding term in Cantor's enumeration as given below.
Sample Input
3
14
7
Sample Output
TERM 3 IS 2/1
TERM 14 IS 2/4
TERM 7 IS 1/4
题意: 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
蛇形排列,第一个数是1/1,第二个数是1/2,第三个数是2/1,第四个数3/1,第五个数是2/2。。。。。。如此排列,问第多少个数是多少。
解题思路:
按照图中的排列,第一列有1个数,第二列有2个数,第n列有n个数,这是一个公差为1的等差数列,利用二分查找,找到要询问数所在列(即区间)的最大值,可知,当处于第i列的时候,分子分母和为i+1,由此可知规律:
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
long long cun[5000];
int rfen(int l,int r,int n)
{
int mad,bj = -1;
while(l <= r)
{
mad = (l + r)/2;
if(cun[mad] < n)
l = mad + 1;
else
{
bj = mad;
r = mad - 1;
}
}
return bj;
}
int main()
{
int i,j,k;
int right,cha;
long long n;
cun[1] = 1;
for(i = 2; i < 4472; i++)
{
cun[i] = i + cun[i-1];
}
while(scanf("%lld",&n)!= EOF)
{
right = rfen(1,4472,n);
cha = cun[right] - n;
if(right % 2 == 0)
printf("TERM %lld IS %d/%d\n",n,right - cha,cha + 1);
else
{
printf("TERM %lld IS %d/%d\n",n,cha + 1,right - cha);
}
}
return 0;
}