码迷,mamicode.com
首页 > 其他好文 > 详细

[2016-03-19][UVA][11549][Calculator Conundrum]

时间:2016-03-20 00:15:25      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

  • 时间:2016-03-19 21:27:43 星期六

  • 题目编号:[2016-03-19][UVA][11549][Calculator Conundrum]

  • 题目大意:给定数k每次取前n位不断平方,求出现的最大值是多少

  • 方法:

    • 方法1:模拟一遍过程,直到出现循环
    • 方法2:Floyd判断算法,定义两个k,每次k1走一次,k2走两次,知道k1,k2相同

方法1:STL超级暴力方法
方法2:小小优化版
方法3:Floyd判圈算法

方法1:STL超级暴力方法

  1. #include <set>
  2. #include <sstream>
  3. #include <string>
  4. #include <cstdio>
  5. using namespace std;
  6. typedef long long LL;
  7. int t,n,k,ans;
  8. int mnxt(){
  9. stringstream ss;
  10. ss<<(LL) k * k;
  11. string str = ss.str();
  12. if(str.length() > n) str = str.substr(0,n);
  13. int num = 0;
  14. stringstream ss2(str);
  15. ss2>>num;
  16. return num;
  17. }
  18. int main(){
  19. scanf("%d",&t);
  20. while(t--){
  21. scanf("%d%d",&n,&k);
  22. set<int> s;
  23. ans = k;
  24. while(!s.count(k)){
  25. s.insert(k);
  26. if(k > ans) ans = k;
  27. k = mnxt();
  28. }
  29. printf("%d\n",ans);
  30. }
  31. return 0;
  32. }

方法2:小小优化版

  1. #include <cstdio>
  2. #include <set>
  3. #include<algorithm>
  4. using namespace std;
  5. typedef long long LL;
  6. #define FOR(x,y,z) for(int (x)=(y);(x)<(z);++(x))
  7. int t,n,k,ans,buf[20];
  8. int mnxt(){
  9. if(!k) return 0;
  10. LL k2 = (LL)k*k;
  11. int cnt = 0;
  12. while (k2){
  13. buf[cnt++] = k2 % 10;
  14. k2 /= 10;
  15. }
  16. int tmpn = min(n,cnt);
  17. FOR(i,0,tmpn){
  18. k2 = k2 * 10 + buf[--cnt];
  19. }
  20. return k2;
  21. }
  22. int main(){
  23. scanf("%d",&t);
  24. while(t--){
  25. scanf("%d%d",&n,&k);
  26. set<int> s;
  27. ans = k;
  28. while(!s.count(k)){
  29. s.insert(k);
  30. if(k > ans) ans = k;
  31. k = mnxt();
  32. }
  33. printf("%d\n",ans);
  34. }
  35. return 0;
  36. }

方法3:Floyd判圈算法

  1. #include <cstdio>
  2. #include<algorithm>
  3. using namespace std;
  4. typedef long long LL;
  5. #define FOR(x,y,z) for(int (x)=(y);(x)<(z);++(x))
  6. int t,n,ans,buf[20],k1,k2;
  7. int mnxt(int k){
  8. if(!k) return 0;
  9. LL k2 = (LL)k*k;
  10. int cnt = 0;
  11. while (k2){
  12. buf[cnt++] = k2 % 10;
  13. k2 /= 10;
  14. }
  15. int tmpn = min(n,cnt);
  16. FOR(i,0,tmpn){
  17. k2 = k2 * 10 + buf[--cnt];
  18. }
  19. return k2;
  20. }
  21. int main(){
  22. scanf("%d",&t);
  23. while(t--){
  24. scanf("%d%d",&n,&k1);
  25. k2 = ans = k1;
  26. do{
  27. k1 = mnxt(k1);
  28. k2 = mnxt(k2); if(k2 > ans) ans = k2;
  29. k2 = mnxt(k2); if(k2 > ans) ans = k2;
  30. }
  31. while(k1 != k2);
  32. printf("%d\n",ans);
  33. }
  34. return 0;
  35. }




[2016-03-19][UVA][11549][Calculator Conundrum]

标签:

原文地址:http://www.cnblogs.com/qhy285571052/p/01b08802b544c5c4e3228e06ca8d5c5d.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!