团体程序设计天梯赛 L2-029 特立独行的幸福 (25分)

题目链接:

L2-029 特立独行的幸福 (25分)

今天除夕夜,Yuhan在这里给大家拜个(早)年~
祝大家新年快乐,在新的一年里有[特立独行的幸福]~
(^ω^)

思路:

我们可以在O(n)O(\sqrt{n})的时间内判断一个数是否为素数;
其次迭代计算下一个平方和时需要计算这个数之前是否出现过,以保证不会进入死循环,同时也判断该数是不是一个幸福数;
在处理区间所有数的过程中,我们应该记录依赖于每个数的数,这些数就不是特立独行的;
最后将符合条件的数输出即可~

代码:

#include<bits/stdc++.h>

using namespace std;

inline bool isPrime(int & x) {
	for(int i = 2; i * i <= x; i++) {
		if(x % i == 0) return false;
	}
	return x > 1;
}
inline int nxt(int x) {
	int ans = 0;
	while(x) ans += (x % 10) * (x % 10), x /= 10;
	return ans;
}
bool flag, spec[10005];
inline int get(int x) {
	map<int, bool> vst;
	int ans = 0, mul = isPrime(x) ? 2 : 1;
	for(; x != 1; ++ans) {
		if(vst[x] == true) return 0;
		vst[x] = true;
		spec[x = nxt(x)] = false;
	}
	return ans * mul;
}
typedef pair<int, int> P;
int main() {
#ifdef MyTest
	freopen("Sakura.txt", "r", stdin);
#endif
	int a, b;
	cin >> a >> b;
	vector<P> res;
	for(int i = a; i <= b; i++) spec[i] = true;
	for(int i = a; i <= b; i++) res.push_back(P{i, get(i)});
	for(P & p : res) if(p.second && spec[p.first]) {
		cout << p.first << ' ' << p.second << '\n';
		flag = true;
	}
	if(!flag) cout << "SAD";
	return 0;
}
posted @ 2020-01-24 20:54  YuhanのBlog  阅读(404)  评论(0编辑  收藏  举报