题外话:本学期开设课程算法分析与设计,我会记录一些Sicily上的作业题目,附上自己粗浅的理解和总结。有不正确的地方欢迎大家批评指正。
1020. Big Integer
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
Long long ago, there was a super computer that could deal with VeryLongIntegers(no VeryLongInteger will be negative). Do you know how this computer stores the VeryLongIntegers? This computer has a set of n positive integers: b1,b2,…,bn, which is called a basis for the computer.
The basis satisfies two properties:
- 1 < bi <= 1000 (1 <= i <= n),
- gcd(bi,bj) = 1 (1 <= i,j <= n, i ≠ j).
Let M = b1b2…*bn
Given an integer x, which is nonegative and less than M, the ordered n-tuples (x mod b1, x mod b2, …, x mod bn), which is called the representation of x, will be put into the computer.
Input
The input consists of T test cases. The number of test cases (T) is given in the first line of the input.
Each test case contains three lines.
The first line contains an integer n(<=100).
The second line contains n integers: b1,b2,…,bn, which is the basis of the computer.
The third line contains a single VeryLongInteger x.
Each VeryLongInteger will be 400 or fewer characters in length, and will only contain digits (no VeryLongInteger will be negative).
Output
For each test case, print exactly one line – the representation of x.
The output format is:(r1,r2,…,rn)
Sample Input
2
3
2 3 5
10
4
2 3 5 7
13
Sample Output
(0,1,0)
(1,1,3,6)
一. 题意理解
输入一个大数(字符串表示)以及一组基(多个数,任意两数之间没有公共因子),要求输出大数对每个基数求模的结果。
二. 设计思路
既然是大数,就不能直接用%运算。我们可以参考竖式除法的过程,将求模运算分解成一步一步的:
上图即为1234/7的结果,商176余2。12%7得到5,5*10+3得到53,再继续对7求模,这样就可以用循环来表达了。
三. 代码实现
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main() {
int t;
cin >> t;
for (int i = 0; i < t; i++) {
int n, base;
vector<int> Base;
string num;
cin >> n;
for (int j = 0; j < n; j++) {
cin >> base;
Base.push_back(base);
}
cin >> num;
for (int j = 0; j < n; j++) {
int i = 0;
int rem = 0;
while (i < num.size()) {
rem *= 10;
int temp = num[i] - '0';
rem += temp;
rem %= Base[j];
i++;
}
if (j == 0)
cout << "(";
cout << rem;
if (j != n - 1) cout << ",";
else cout << ")" << endl;
}
}
return 0;
}
四. 时间复杂度分析
时间复杂度O(n*m)。