PTA甲級—數學
- 2021 年 3 月 5 日
- 筆記
1.簡單數學
1008 Elevator (20分)
模擬題


#include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <iostream> #include <map> #include <cmath> #define ll long long #define inf 0x3f3f3f using namespace std; const int maxn = 1e4+100; int n, sum, now, tmp; int main(){ scanf("%d", &n); for(int i = 1; i <= n; i++){ scanf("%d", &tmp); int num = tmp-now; sum += num > 0 ? num*6 : num*(-4); now = tmp; } sum += 5*n; printf("%d", sum); }
View Code
1049 Counting Ones (30 分)
1的個數等於各個位出現1的次數的累加和,因此我們計算各個位上對答案的貢獻即可。
那麼關鍵的問題就在如何計算某一位上的貢獻,當然就是求這一位為1時數的個數,如下:
(具體為什麼是這樣可以在腦子或者紙上演算一下)
我一開始的思路是對的,但是那會想不出來具體的做法,考試時暴力騙個分還是可以的。另外上機指南中提到可以對程式進行邊界測試,確實應當如此,以後多使用幾種方法來測試自己的程式碼


#include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <iostream> #include <vector> #include <set> #include <map> #include <queue> #define ll long long #define inf 0x3f3f3f3f #define pb push_back #define pii pair<int,int> using namespace std; const int maxn = 2e6+100; int n, res; int main(){ scanf("%d", &n); int left = n, right, a = 1, now; while(left){ now = left%10, right = n-left*a, left /= 10; if(now==0) res += left*a; else if(now==1) res += left*a+right+1; else res += (left+1)*a; a *= 10; } printf("%d", res); }
View Code
Reference:
//blog.csdn.net/CV_Jason/article/details/85112495
1069 The Black Hole of Numbers (20 分)
按照題目要求模擬即可,不過要注意要考慮全面:
1.所有輸出都要求4位數
2.考慮特殊樣例如6174、2222、1情況下的處理。如輸入為1的時候要補充前導0;輸入為6174的時候要輸出一行而不能直接退出


#include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <iostream> #include <vector> #include <set> #include <map> #include <queue> #define ll long long #define inf 0x3f3f3f3f #define pb push_back #define pii pair<int,int> using namespace std; const int maxn = 1e5+100; string a, b, c, last, s; int tmp; int main(){ cin >> c; while(1){ for(int i = 0; i < 4-c.length(); i++) s += "0"; s += c, a = b = s, last = c; sort(a.begin(), a.end()), sort(b.rbegin(), b.rend()); c = to_string(stoi(b) - stoi(a)), s.clear(); printf("%04d - %04d = %04d\n", stoi(b), stoi(a), stoi(c)); if(c=="6174"||c=="0") break; } }
View Code