题目大意
算法思路
首先我们从小到大遍历区间内的每一个数,对于区间内的一个数t,我们将t迭代,同时用一个vector存下迭代的每一个数,同时进行标记,当t为1或者t在vector中重复出现时,停止遍历,如果t为1,则记录t的独立性(t是幸福数但t未必是特立独行的幸福数)。
遍历完数组后,我们只需要遍历之前记录过的幸福数即可,如果当前数没有依附于其他幸福数,也就是没有被数组标记过,也就是特立独行的幸福数,则输出
AC代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <string>
#include <cmath>
#include <queue>
#include <vector>
#include <map>
#include <sstream>
using namespace std;
const int N = 10010;
map<int, int> d;
int n, m;
bool st[N];
int f(int x)
{
int sum = 0;
while(x)
{
sum += (x % 10) * (x % 10);
x /= 10;
}
return sum;
}
bool prime(int x)
{
if(x == 1) return false;
for(int i = 2; i <= x / i; i++)
{
if(x % i == 0) return false;
}
return true;
}
int main(void)
{
cin >> n >> m;
for(int i = n; i <= m; i++)
{
int t = i;
vector<int> member;
while(t != 1)
{
t = f(t);
if(find(member.begin(), member.end(), t) != member.end()) break;
st[t] = true;
member.push_back(t);
}
if(t == 1)
{
if(prime(i)) d[i] = member.size() * 2;
else d[i] = member.size();
}
}
int cnt = 0;
for(auto i : d)
{
if(!st[i.first])
{
cout << i.first << ' ' << i.second << endl;
cnt++;
}
}
if(!cnt) puts("SAD");
return 0;
}