题目1214:丑数

本文介绍了一种高效算法来找出第N个只包含因子2、3和5的数(丑数),并通过优先队列实现。该算法适用于快速查找特定位置的丑数,适用于竞赛编程及算法挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。
习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

输入:

输入包括一个整数N(1<=N<=1500)。

输出:

可能有多组测试数据,对于每组数据,
输出第N个丑数。

样例输入:
3
样例输出:
3
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.lang.Comparable;
import java.util.ArrayList;
import java.util.PriorityQueue;

class Main
{
	public static final boolean DEBUG = false;
	public static ArrayList<Long> al = new ArrayList<Long>();
	
	static class Pair implements Comparable<Pair>
	{
		long first;
		int second;
		
		public Pair(long f, int s) 
		{
			first = f;
			second = s;
		}
		
		public int compareTo(Pair other) 
		{
			if (first != other.first) {
				if (first < other.first) return -1;
				else return 1;
			}
			
			return second - other.second;
		}
	}
	
	public static void init()
	{
		Pair p = new Pair(1, 2);
		PriorityQueue<Pair> pq = new PriorityQueue<Pair>();
		pq.add(p);
		
		for (int i = 0; i < 1501; i++) {
			Pair tmp = pq.poll();
			al.add(tmp.first);
			switch(tmp.second) {
			case 2:
				pq.add(new Pair(tmp.first * 2, 2));
			case 3:
				pq.add(new Pair(tmp.first * 3, 3));
			case 5:
				pq.add(new Pair(tmp.first * 5, 5));
			}
		}
	}
	
	public static void main(String[] args) throws IOException 
	{
		Scanner cin;
		int n;

		if (DEBUG) {
			cin = new Scanner(new FileReader("d:\\OJ\\uva_in.txt"));
		} else {
			cin = new Scanner(new InputStreamReader(System.in));
		}
		
		init();
		
		while (cin.hasNext()) {
			n = cin.nextInt();
			System.out.println(al.get(n - 1));
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值