藍橋杯-帶分數
標題:帶分數
100 可以表示為帶分數的形式:100 = 3 + 69258 / 714
還可以表示為:100 = 82 + 3546 / 197
注意特徵:帶分數中,數字1~9分別出現且只出現一次(不包含0)。
類似這樣的帶分數,100 有 11 種表示法。
題目要求:
從標準輸入讀入一個正整數N (N<1000*1000)
程式輸出該數字用數碼1~9不重複不遺漏地組成帶分數表示的全部種數。
注意:不要求輸出每個表示,只統計有多少表示法!
例如:
使用者輸入:
100
程式輸出:
11
再例如:
使用者輸入:
105
程式輸出:
6
資源約定:
峰值記憶體消耗 < 64M
CPU消耗< 3000ms
請嚴格按要求輸出,不要畫蛇添足地列印類似:“請您輸入...” 的多餘內容。
所有程式碼放在同一個原始檔中,除錯通過後,拷貝提交該原始碼。
注意: main函式需要返回0
注意: 只使用ANSI C/ANSI C++ 標準,不要呼叫依賴於編譯環境或作業系統的特殊函式。
注意: 所有依賴的函式必須明確地在原始檔中 #include <xxx>, 不能通過工程設定而省略常用標頭檔案。
提交時,注意選擇所期望的編譯器型別。
思路:全排列1-9,然後將1-9分割成兩部分,第一次用的也是這個思路,不過實現方法比較複雜。
#include<iostream> #include<string.h> #include<string> #include<algorithm> using namespace std; int main() { int m; cin >> m; char a[10] = {'1','2','3','4','5','6','7','8','9'}; int sum = 0; string s,s1,s2,s3; int n1,n2,n3; do { s = ""; for(int i=0; i<=8; i++) { s += a[i]; } //cout << s; //cout << endl; // 擷取的長度 for(int i=1; i<=7; i++) { for(int j=1; j<=8-i; j++) { s1 = s.substr(0, i); s2 = s.substr(i, j); s3 = s.substr(i+j, 9-i-j); n1 = atoi(s1.c_str()); n2 = atoi(s2.c_str()); n3 = atoi(s3.c_str()); // if(n1+1.0*n2/n3 == m) { sum++; //cout << n1 << "" << n2 << "" << n3 << endl; } } } } while(next_permutation(a, a+9)); cout << sum; }
AC程式碼:
#include<iostream> #include<string.h> #include<string> #include<algorithm> using namespace std; int main() { int m; cin >> m; int a[10] = {1,2,3,4,5,6,7,8,9}; int sum = 0; long long n1,n2,n3; do { for(int i=1; i<=7; i++) { for(int j=1; j<=8-i; j++) { // left -> i 位, up -> j 位, down, n1 = n2 = n3 = 0; int x; int q=0; for(x=0; x<i; x++) { n1 = n1*10 + a[q]; q++; } for(x=0; x<j; x++) { n2 = n2*10 + a[q]; q++; } for(x=0; x<=8-i-j; x++) { n3 = n3*10 + a[q]; q++; } //cout << n1 << " " << n2 << " " << n3 << endl; if(n1+1.0*n2/n3 == m) { sum++; } } } } while(next_permutation(a, a+9)); cout << sum; }