挑战编程PC/UVa Stern-Brocot代数系统

/*
Stern-Brocot代数系统

Stern-Brocot树是一种生成所有非负的最简分数m/n的美妙方式。
其基本方式是从(0/1, 1/0)这两个分数开始, 根据需要反复执行如下操作:
在相邻的分数  m/n 和 m1/n1之间插入  (m+m1)/(n+n1)

例如,可以将它看成是无限延伸的二叉树   
           0         1         1
		  ---       ---       ---
		   1         1         0
                    /           
                   /             
                 1        2
			    ---      ---
				 2        1
			    /       /  
               /       /   
		      1     2  3     3
		     ---   --- ---  ---
			  3     3  2     1
            ....   ...   .......
用字母 L 和 R 分别表示从树根开始的一步 往左走 和 往右走,
则一个L和R组成的序列唯一确定了树中的一个位置。

唯一例外的是 1/1. 
*/


#include<iostream>
#include<string>
#include<vector>
using namespace std;

typedef struct Point
{
	int x;
	int y;	
	const Point& operator+=(const Point& pt)
	{
		x+=pt.x;
		y+=pt.y;
		return *this;
	}
}LP,RP;

void getStr(LP leftP, RP rightP, Point pt, const Point P, string& str)
{
	if(pt.x == P.x && pt.y==P.y)
	{
		return;
	}
	double tmp = pt.x*1.0/pt.y;
	double tmp1 = leftP.x*1.0/leftP.y;
	double tmp2 = P.x*1.0/P.y;
	double tmp3;
	if(rightP.y==0)
	{
		tmp3 = INT_MAX*0.1;
	}
	else
	{
		tmp3 = rightP.x*1.0/rightP.y;
	}
	if(tmp2<tmp&&tmp2>tmp1)
	{
		rightP = pt;
		pt+=leftP;

		str+='L';
		getStr(leftP, rightP, pt, P, str);
	}
	if(tmp2>tmp&&tmp2<tmp3)
	{
		leftP = pt;
		pt+=rightP;

		str+='R';
		getStr(leftP, rightP, pt, P, str);
	}
}

int main()
{
	int M, N;
	vector<string> svec;
	string str;

	Point leftP, rightP, Pt, P;
	while(cin>>M>>N)
	{
		if(1==M&&1==N)
			break;
		str.clear();
		P.x = M;
		P.y = N;
		leftP.x = 0;
		leftP.y = 1;
		rightP.x = 1;
		rightP.y = 0;
		Pt.x = 1;
		Pt.y = 1;
		getStr(leftP, rightP, Pt, P, str);
		svec.push_back(str);
	}

	for (int i=0; i<svec.size(); i++)
	{
		cout<<svec[i]<<endl;
	}

	return 0;
}


/*
5 7
878 323
1 1

*/

  

原文地址:https://www.cnblogs.com/aituming/p/4471606.html