豎式問題
找出所有形如abc*de(三位數乘以兩位數)的算式,使得在完整的豎式中,所有數字都屬于一個特定的數字集合。輸入數字集合(相鄰數字之間沒有空格),輸出所有豎式。每個豎式前應有編号,之後應有一個空行。最後輸出解的總數。具體格式見樣例輸出(為了便于觀察,豎式中的空格改用小數點顯示,但你的程式應該輸出空格,而非小數點)。
樣例輸入:2357
樣例輸出:
<1>
..775
X..33
-----
.2325
2325.
-----
25575
The number of solutions = 1
分析
題目大意是:找出所有三位數abc*de(兩位數),在乘法算式中
的所有的數字都必須屬于給定的集合,乘法算式中間結果包括abc
*(de/10)和abc*(de%10),最終結果是abc*de,我們隻需枚舉
所有三位數和兩位數,檢測所有的數字是否屬于給定集合就可以了
代碼
#include<bits/stdc++.h>
using namespace std;
int main() {
string s;
char buff[20];
int count = 0;
cin >> s;
for (int abc = 100; abc < 1000; abc++) {
for (int de = 10; de < 100; de++) {
int x = abc * (de % 10), y = abc * (de / 10), z = abc * de;
sprintf(buff, "%d%d%d%d%d", abc, de, x, y, z);
int ok = 1;
for (int i = 0; i < strlen(buff); i++) {
if (s.find(buff[i]) == s.npos)
ok = 0;
}
if (ok == 1) {
printf("<%d>\n", ++count);
printf("%5d\nX%4d\n-----\n%5d\n%-5d\n-----\n%5d\n", abc, de, x, y, z);
}
}
}
printf("The number of solutions = %d", count);
return 0;
}
這是算法競賽入門經典的代碼,不過abc和de的枚舉值範圍我修改了,還有字元數組被我換成了string,從這個代碼中學到的是int快速轉char*,使用sprintf将幾個int寫入字元數組buffer中,友善快捷;還有string的find函數查找失敗的傳回值是npos(no position)