题解:P11568 「chaynOI R1 T1」一维数组
akcsps
·
·
题解
代码还是要特判 $n=1$ 或 $m=1$ 情况。
```cpp
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
bool isPalindrome(const std::string & num) {
std::string reversedStr = num;
std::reverse(reversedStr.begin(), reversedStr.end());
return num == reversedStr;
}
std::string multiply(const std::string & num1,
const std::string & num2) {
int len1 = num1.size();
int len2 = num2.size();
std::vector < int > result(len1 + len2, 0);
for (int i = len1 - 1; i >= 0; i--) {
for (int j = len2 - 1; j >= 0; j--) {
int mul = (num1[i] - '0') * (num2[j] - '0');
int p1 = i + j;
int p2 = i + j + 1;
int sum = mul + result[p2];
result[p2] = sum % 10;
result[p1] += sum / 10;
}
}
std::string strResult;
for (int digit: result) {
if (!(strResult.empty() && digit == 0)) {
strResult.push_back(digit + '0');
}
}
return strResult.empty() ? "0" : strResult;
}
int main() {
int n, m;
std::cin >> n >> m;if (m==1) {
for(int i=1; i<=n; i++) std::cout<<"1";std::cout<<" 1";
return 0;
}
std::string x_str(n, '0');
x_str[0] = '1';
std::string y_str(m, '0');
y_str[0] = '1';
bool found = false;
while (!found) {
for (int i = 0; i < 10; ++i) {
x_str[n - 1] = '0' + i;
for (int j = 0; j < 10; ++j) {
y_str[m - 1] = '0' + j;
std::string product_str = multiply(x_str, y_str);
if (isPalindrome(product_str)) {
std::cout << x_str << " " << y_str << std::endl;
found = true;
break;
}
}
if (found) {
break;
}
}
int carry = 1;
for (int k = m - 1; k >= 0 && carry; --k) {
int digit = y_str[k] - '0' + carry;
y_str[k] = '0' + (digit % 10);
carry = digit / 10;
}
if (carry) {
y_str.insert(y_str.begin(), '1');
}
}
return 0;
}
```
赛时代码没判 $n=1$,所以 $n=1$ 时可能可以 Hack 如上代码。大家见谅。