裸题
Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 20 Accepted Submission(s) : 5
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
Here is no naked girl nor naked runners, but a naked problem: you are to find the K-th smallest element in the set of all irreducible fractions p/q,with 0<p<q<=N.
Input
The first line of input is an integer T(T<=1000), indicating there are T cases.
For each cases, there is one line with two positive integers N and K(1<=K<N<=100000).
For each cases, there is one line with two positive integers N and K(1<=K<N<=100000).
Output
For each case, output one line containing the answer.
Sample Input
4 5 1 5 2 5 3 5 4
Sample Output
1/5 1/4 1/3 2/5
//题意是求分子分母都小于N的第k小的分数。由1/n<1/(n-1) ,2/n>1/(n-1) ,k1/n1>(k1+k2)/(n1+n2) (n1>n2,k1>k2) 得出
所以通过这个构建子树,从 1/2开始先向左扩张,找到最小的(即 1/n),然后回退找到父亲那里就是次小的,然后搜右子树,。。
下面用栈来模拟查找这个过程。
#include<cstdio>
const int size=100000; //栈的最大深度
int pa[size],qa[size],pb[size],qb[size]; //栈中当前两个分数的分子分母
int s[size]; //栈的当前状态
int main()
{
int t,n,k,p,q;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
pa[0]=s[0]=0; //初始化分数和状态
qa[0]=pb[0]=qb[0]=1;
int i=0; //栈的深度
while(1) //循环求解
{
p=pa[i]+pb[i];
q=qa[i]+qb[i]; //依栈顶的两个分数计算出来的子节点的分数
if(q>n) i--; //分母超出n的范围 退栈
else if(s[i]==0) //把当前子节点分数当作右分数
{
pa[i+1]=pa[i];//当前左分数压栈
qa[i+1]=qa[i];
pb[i+1]=p; //当前右分数压栈
qb[i+1]=q; //进入下一步
s[i]++; //新的栈顶元素初始化状态
s[i+1]=0; //栈的深度加1
i++;
}
else
{ //把当前子节点分数当作左分数
k--; //找到一个最小分数
if(k==0) break;
pa[i]=p;
qa[i]=q;
s[i]=0;
}
}
printf("%d/%d\n",p,q);
}
return 0;
}