北大1047題

來源:互聯網
上載者:User

題目連結:http://acm.pku.edu.cn/JudgeOnline/problem?id=1047

 

這道題痛點:

1,帶前置0的大整數乘法,最終結果怎麼處理

2,如何判斷結果中的數字和原數中的數字是否相同

解決方案:

1,一個m位元和一個n位元相乘,結果最多為m+n位,最少位m+n-1位。根據本題的條件限制,假設帶前置0的op為m位,另一個乘數為1位或者2位且最大不超過60,所以結果可能的位元為m、m+1、m+2位,只要能確定m+1、m+2位不為0就知道結果為m位,如果能確定m+1、m+2位有一位不為0,就知道這個數一定不是迴圈數。

2,為了判定結果中的數字和原數中的數字是否相同用了兩個整型數組,統計兩個數中各個數字出現的頻率,然後調用標準庫演算法比較這兩個數組中的內容是否相等就可以判斷結果了。

 

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;

#define MAX 61

int main()
{
 freopen("in.txt","r",stdin);
 int in1[10],in2[10];
 char op1[MAX],op2[3],res[MAX+2];
 int i,j,k,len1,len2,len;
 stringstream ss;
 bool yes;
 while(cin >> op1)
 {
  yes = true;
  i = 0;
  memset(in1,0,sizeof(in1));
  while(op1[i] != '/0')
  {
   ++in1[op1[i] - '0'];
   ++i;
  }

  len1 =strlen(op1);
  reverse(op1,op1 + len1);

  for(i = 1;i <= len1;++i)
  {
   ss << i;
   ss >> op2;
   ss.clear();
   len2 = strlen(op2);
   reverse(op2,op2 + len2);
   memset(res,0,sizeof(res));

   for(j = 0;j < len1;++j)
   {
    for(k = 0;k < len2;++k)
    {
     res[j+k] += (op1[j] - '0') * (op2[k] - '0');
     if(res[j+k] > 9)
     {
      res[j+k+1] += res[j+k] / 10;
      res[j+k] %= 10;
     }
    }
   }

   
   if(res[len1] != 0 ||res[len1 + 1] != 0)
   {
    reverse(op1,op1 + len1);
    cout << op1 << " is not cyclic" << endl;
    yes = false;
    break;
   }
   else
    len = len1;
   
   memset(in2,0,sizeof(in2));
   for(j = 0;j < len;++j)
    ++in2[res[j]];
   
   if(!equal(in1,in1 + 10,in2))
   {
    reverse(op1,op1 + len1);
    cout << op1 << " is not cyclic" << endl;
    yes = false;
    break;
   }
  }

  if(yes)
  {
   reverse(op1,op1 + len1);
   cout << op1 << " is cyclic" << endl;
  }
 }
 return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.