Cabric Number Problem 堆(优先队列)版本

题:

Cabric Number Problem - POJ 1350 - Virtual Judge (vjudge.net)

1350 -- Cabric Number Problem (poj.org)

题面:

 

思路:

模拟一下就行,主要题目范围要求,不能小于四位也不能多于四位

代码:

#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <cmath>
using namespace std;

int up(int x) 
{
	priority_queue<int, vector<int>, less<int>>upper;  // 用堆来存
	while (x)
	{
		upper.push(x % 10);
		x /= 10;
	}
	int res = 0;
	double size = upper.size() - 1;// 为什么用 double, 因为不用的话 在oj上pow会报错
	double i = pow(10, size);  // 获取当前的最高位进位,为什么不用1000,因为会有小于四位的数
	while (!upper.empty())
	{
		res += upper.top() * i;
		i /= 10;
		upper.pop();
	}
	return res;
}

int lower(int x)
{
	priority_queue<int, vector<int>, greater<int>> low;
	while (x)
	{
		low.push(x % 10);
		x /= 10;
	}
	int res = 0;
	double size = low.size() - 1;
	double i = pow(10, size);
	while (!low.empty())
	{
		res += low.top() * i;
		i /= 10;
		low.pop();
	}
	return res;
}
int main()
{
	int n;
	while (cin >> n && n != -1)
	{
		cout << "N=" << n << ":\n";
		if (n % 1111 == 0 || n < 1000 || n > 9999) // 判断是否不符范围,可能小于4位也可能大于4位 不过到是不用考虑0001这样的
		{
			cout << "No!!\n";
			continue;
		}
		int t = n;
		int times = 0;
		while (t != 6174 && t != 0)
		{
			int u = up(t); // 获取最大
			int n = lower(t); // 获取最小
			cout << u << "-" << n << "=" << u - n << "\n";
			t = u - n;
			times++;
		}
		cout << "Ok!! " << times << " times" << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值