现在的位置: 首页 > 综合 > 正文

Q10.7

2018年04月29日 ⁄ 综合 ⁄ 共 718字 ⁄ 字号 评论关闭
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;

int findkth(int k)
{
	if (k == 1)
		return 0;
	if(k == 2)
		return 3;
	if(k == 3)
		return 5;
	if(k == 4)
		return 7;
	queue<int> a, b, c;
	a.push(3); a.push(5); a.push(7);
	b.push(3); b.push(5); b.push(7);
	c.push(3); c.push(5); c.push(7);
	
	int re, n = 4;
	while(n < k)
	{
		int t1 = a.front() * 3, t2 = b.front() * 5, t3 = c.front() * 7;
		
		if(t1 < t2)
		{
			if(t1 < t3)
			{
				a.pop();
				a.push(t1);
				re = t1;
			}
			else if(t1 == t3)
			{
				a.pop(); b.pop();
				a.push(t1);
				re = t1;
			}
			else
			{
				c.pop();
				c.push(t3);
				re = t3;
			}	
		}
		else if(t1 == t2)
		{
			a.pop(); b.pop();
			if(t1 == t3)
				c.pop();
			a.push(t1);
			re = t1;
		}
		else
		{
			if(t2 < t3)
			{
				b.pop();
				b.push(t2);
				re= t2;
			}
			else if(t2 == t3)
			{
				b.pop(); c.pop();
				b.push(t2);
				re = t2;
			}
			else
			{
				c.pop();
				c.push(t3);
				re = t3;
			}
		}
		n++;
	}
	if(n == k)
		return re;
}

int main(void)
{
	int k = 7;
	cout << findkth(k) << endl;
	
	return 0;
}

抱歉!评论已关闭.