问题
https://vjudge.net/problem/UVA-11549
分析
使用set或者unordered_set进行查重,如果重复就跳出循环,注意数据的类型,防止溢出
使用unorder_set查重,比set更快。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_set>
using namespace std;
typedef long long LL;
const int maxn=20+5;
int n,k,kase=0;
LL buf[maxn];
//数字k的下一个数字x
int next(int k){
LL t=(LL)k*k;
int x=0,p=0,t2;
while(t){
buf[p]=t%10;
t/=10;
++p;
}
for(int i=p-1,j=0;i>=0 && j<n;--i,++j){
x=10*x+buf[i];
}
return x;
}
int main(void){
scanf("%d",&kase);
while(kase--){
int ans=0;
scanf("%d%d",&n,&k);
unordered_set<int> s;
while(!s.count(k)){
s.insert(k);
ans=max(ans,k);
k=next(k);
}
printf("%d\n",ans);
}
}
使用Floyd判圈算法查找重复
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
typedef long long LL;
const int maxn=20+5;
int n,k,kase=0;
LL buf[maxn];
//数字k的下一个数字x
int next(int k){
LL t=(LL)k*k;
int x=0,p=0,t2;
while(t){
buf[p]=t%10;
t/=10;
++p;
}
for(int i=p-1,j=0;i>=0 && j<n;--i,++j){
x=10*x+buf[i];
}
return x;
}
int main(void){
scanf("%d",&kase);
while(kase--){
scanf("%d%d",&n,&k);
int ans=0,k1=k,k2=k;
ans=max(ans,k);
do{
k1=next(k1);
ans=max(ans,k1);
k2=next(k2);
ans=max(ans,k2);
k2=next(k2);
ans=max(ans,k2);
}while(k1!=k2);
printf("%d\n",ans);
}
}