阮柏燁
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    1
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 靜心 C++ ## 模擬考時作參考解答 ### 1. 中位數 (unsorted) ```C++== #include <iostream> #include <algorithm> using namespace std; int main() { int n; cin >> n; int nums[n]; for (int i = 0; i < n; i++) { cin >> nums[i]; } sort(nums, nums + n); int m; if (n % 2 == 0) { m = (nums[n/2 - 1] + nums[n/2]) / 2; } else { m = nums[n/2]; } cout << m << endl; return 0; } ``` ### 2. 排序 ```C++= #include<iostream> // 包含標準輸入輸出流的標頭文件 #include<algorithm> // 包含STL算法的標頭文件,例如排序 using namespace std; int main() { int n; cin >> n; // 讀取數據的個數 int a[n]; // 定義一個整數型陣列 // 使用迴圈讀取所有數據到陣列a中 for(int i = 0; i < n; i++) { cin >> a[i]; } sort(a, a+n); // 使用標準模板庫中的sort函數對陣列進行排序 // 迴圈輸出排序後的陣列 for(int i = 0; i < n; i++) { cout << a[i] << " "; } } ``` ### 3. 鬆餅 ```C++= #include<iostream> using namespace std; int main(){ int day = 0; int n; cin >> n; // 當n大於0時執行迴圈 while(n > 0){ day++; // 每次迴圈迭代,天數增加1 n -= day; // 從n中扣除當前天數的值 } cout << day; } ``` ### 4. 圍欄總和 ```C++= #include<iostream> using namespace std; int main(){ int n, m; cin >> n >> m; int k; int ans = 0; for(int i=0;i<n;i++){ // 外層迴圈,控制行數,從0到n-1 for(int j=0;j<m;j++){ // 內層迴圈,控制列數,從0到m-1 cin >> k; // 讀入矩陣中的元素至變數k // 判斷當前元素是否在矩陣的邊緣(第一行、最後一行、第一列、最後一列) if(i == 0 || i == n-1 || j == 0 || j == m-1){ ans += k; // 如果元素位於邊緣,則將其值加到答案變數ans中 } } } cout << ans; } ``` ### 5. 字串重組與比較 ```C++= #include<iostream> using namespace std; int main(){ string s, s2 = ""; cin >> s; 串s int len = s.size(); // 獲取字符串s的長度並儲存到變量len中 // 建立新的字符串s2 for(int i=0; i<=len/2-1; i++){ // 迴圈從0遍歷到字符串長度的一半減1 s2 += s[i]; // 向s2中加入s的第i個字符 s2 += s[len-1-i]; // 向s2中加入s從後向前的第i個字符 } int ans = 0; for(int i=0; i<len; i++){ if(s[i] == s2[i]){ ans++; } cout << ans; // 輸出最後的計數結果ans } ``` ### 5-1. 字串重組與比較 ```C++= #include<iostream> using namespace std; int main(){ string s, s2 = ""; // 定義兩個字符串s和s2,s2初始化為空字符串 cin >> s; // 從標準輸入讀取字符串s int len = s.size(); // 獲取字符串s的長度並儲存到變量len中 // 建立新的字符串s2 for(int i = 0; i < len / 2; i++){ // 迴圈從0遍歷到字符串長度的一半 s2 += s[i]; // 向s2中加入s的第i個字符 s2 += s[len - 1 - i]; // 向s2中加入s從後向前的第i個字符 } // 如果字符串長度為奇數,補上中間的字符 if (len % 2 != 0) { s2 += s[len / 2]; } int ans = 0; for(int i = 0; i < len; i++){ if(s[i] == s2[i]){ // 比較s和s2在同一位置的字符是否相同 ans++; // 如果相同,ans計數器加1 } } cout << ans << endl; // 輸出最後的計數結果ans return 0; // 返回0表示程式正常結束 } ``` ### 分隔 ```C++= #include <iostream> #include <string> using namespace std; int main(){ int n; cin >> n; for(int i=0; i<n; i++){ for(int j=0; j<n-1-i; j++){ cout << " "; } for(int j=1; j<=i+1; j++){ cout << j; } for(int j=i; j>0; j--){ cout << j; } cout << endl; } for(int i=0; i<n; i++){ for(int j=0; j<=i; j++){ cout << " "; } for(int j=1; j<n-i; j++){ cout << j; } for(int j=n-i-2; j>0; j--){ cout << j; } cout << endl; } } ``` ```C++= #include <iostream> using namespace std; int main(){ char arr[5] = "abcd"; for(int i=0; i<4; i++){ if(i!=0) for(int j=0; j<4; j++){ if(j!=1 && j!=i) for(int k=0; k<4; k++){ if(k!=2 && k!=i && k!= j) for(int l=0; l<4; l++){ if(l!=3 && l!=i && l!=j && l!=k) cout << arr[i] << arr[j] << arr[k] << arr[l] << endl; } } } } } ``` ```C++= #include <iostream> using namespace std; int main(){ for(int i=1; i<5; i++){ for(int j=1; j<5; j++){ if(j != i) for(int k=1; k<5; k++){ if(k!=i && k!=j){ cout << i <<" "<< j <<" "<< k << endl; } } } } } ``` ```C++= #include <iostream> using namespace std; int main(){ int n; cin >> n; int ans[3]{0}; int k; for(int i=0; i<n; i++){ cin >> k; ans[k%3]++; } for(int i=0; i<3; i++) cout << ans[i] << " "; } ``` ```C++= #include <bits/stdc++.h> using namespace std; int main(){ int a[30]{0}; int n; cin >> n; for (int i = 0; i < 3; i++){ int m; cin >> m; a[m] = 1; } for (int i = n; i > 0; i--){ if (!a[i]) cout << i << "\n"; } } ``` ```C++= #include <iostream> using namespace std; int main(){ int n; cin >> n; int k, total = 0; for(int i=0; i<n; i++){ total = 0; cin >> k; for(int j=1; j<k; j++){ if(k % j == 0){ total += j; } } if(total == k){ cout << k; break; } } return 0; } ``` ```C++= #include <iostream> using namespace std; int main() { int n; cin >> n; int costs[n], pro[n]; for(int i=0; i<n; i++){ cin >> costs[i]; } for(int i=0; i<n; i++){ cin >> pro[i]; } int total = 0; for(int i=0; i<n; i++){ total += pro[i]; if(total >= costs[i]){ cout << ":D" << endl; total -= costs[i]; }else{ cout << ":(" << endl; } } return 0; } ``` ```C++= #include <iostream> using namespace std; int main() { int n; // 讀取整數 n,表示接下來要輸入的數字個數 cin >> n; // 初始化 minValue 為一個很大的值,maxValue 為一個很小的值 int minValue = 10001, maxValue = -1; // 循環 n 次來讀取每一個數字 for (int i = 0; i < n; ++i) { int value; // 讀取一個數字 cin >> value; // 如果讀取的數字大於目前的最大值,更新最大值 if (value > maxValue) { maxValue = value; } // 如果讀取的數字小於目前的最小值,更新最小值 if (value < minValue) { minValue = value; } } // 輸出最大值和最小值之差的兩倍 cout << (maxValue - minValue) * 2 << endl; return 0; } ``` ```c++= #include<iostream> #include<algorithm> using namespace std; int main(){ int n; cin >> n; int h[n]; for(int i=0;i<n;i++){ cin >> h[i]; } cout << h+n - max_element(h, h+n) - 1; return 0; } ``` ```c++= #include <iostream> #include <algorithm> // for max_element, min_element #include <cmath> // for abs using namespace std; int main() { int n; cin >> n; int h[n]; for(int i = 0; i < n; i++){ cin >> h[i]; } cout << abs(max_element(h, h + n) - min_element(h, h + n)) - 1; } ``` ```c++= #include <iostream> #include <algorithm> using namespace std; int main() { int n; cin >> n; int nums[100]; // 假設 n 的最大值為 100 for (int i = 0; i < n; i++) { cin >> nums[i]; } sort(nums, nums + n); int median; if (n % 2 == 0) { median = (nums[n/2 - 1] + nums[n/2]) / 2; } else { median = nums[n/2]; } cout << median << endl; return 0; } ``` ```C++= #include<iostream> using namespace std; bool checkID(string &s){ //自訂函式 if(s.length()!=10) //長度為10 return false; if(s[0] < 'A' or s[0] > 'Z') //第一個字母為大寫英文 return false; if(s[1] != '1' and s[1] != '2') //第二個字為數字0或1 return false; for(int i=2;i<10;i++){ //2~8個字為純數字 if(s[i] < '0' or s[i] > '9') return false; } return true; } int main() { string s; cin >> s; if(checkID(s) == 1){ cout << "True"; }else{ cout << "False"; } return 0; } ``` ``` 第 0 行:1, 2 第 1 行:3, 4 第 2 行:5, 0 第 3 行:7, 8 第 4 行:9, 10 ``` ```C++= #include <iostream> using namespace std; int main() { // 宣告一個 3x4 的整數型二維陣列 int array[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; // 輸出陣列的每一個元素 for (int i = 0; i < 3; i++) { // 迴圈遍歷每一行 for (int j = 0; j < 4; j++) { // 迴圈遍歷每一列 cout << "Element at [" << i << "][" << j << "]: " << array[i][j] << endl; } } return 0; } ``` ```C++= #include <iostream> #include <cstring> using namespace std; int main(){ int n; cin >> n; char arr[100]; cin >> arr; int len = strlen(arr); for(int i=0; i<len; i++){ if(arr[i] == 'l'){ arr[i] = 'L'; } } cout << arr; return 0; } ``` 找因數 ```C++= #include <iostream> using namespace std; int main() { int number; cout << "Enter a positive integer: "; cin >> number; cout << "Factors of " << number << " are: "; for(int i = 1; i <= number; ++i) { if(number % i == 0) { cout << i << " "; } } cout << endl; return 0; } ``` ```C++= #include <iostream> // 匯入 iostream 標準庫,用於輸入輸出功能 using namespace std; // 使用標準命名空間 std int main() { int n; // 宣告一個整數變數 n cin >> n; // 從標準輸入讀取一個值到 n int total = 0, total2 = 0; // 宣告兩個整數變數 total 和 total2 並初始化為 0 for(int i = 1; i < n; i++){ // 從 1 遍歷到 n-1 if(n % i == 0){ // 如果 n 可以被 i 整除 (i 是 n 的因數) total += i; // 將 i 加到 total } } if(total == n){ // 如果 total(n 的所有真因數之和)等於 n cout << "True"; // 打印 "True"(表示 n 是一個完全數) } else { for(int i = 1; i < total; i++){ // 否則,再次遍歷從 1 到 total-1 if(total % i == 0){ // 如果 total 可以被 i 整除 total2 += i; // 將 i 加到 total2 } } if(total2 == n){ // 如果 total2(total 的所有真因數之和)等於 n cout << total; // 打印 total(表示 n 和 total 是友好數) }else{ cout << "False"; // 否則,打印 "False" } } return 0; // 程式結束,返回 0 } ``` ## 陣列 正確宣告方式 ```C++= type arrayName[size]; int numbers[10]; // 宣告陣列大小數量與設值相同 int day[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; ``` 列表初始化(list initialization)是C++11引入的一種新特性,它提供了一種更簡潔、更清晰的方式來初始化對象,包括陣列。這種初始化方式使用大括號{}來包圍初始化列表,並且可以用於各種情況。以下兩種方式皆正確。 ```C++= int array[] = {1, 2, 3, 4, 5}; int array[]{1, 2, 3, 4, 5}; ``` 特殊情境 ```C++= // 不足的會補上零 int data[5] = {100}; ``` 錯誤的陣列宣告示例 ```C++= // 陣列大小不是非負整數 int numbers[-10]; // 陣列元素的資料型別不同 int numbers[10] = {1, 2.5, 3}; // 陣列名稱與其他變數名稱相同 int numbers[10]; int numbers[20]; // 塞太多元素 too many initialize int data[2] = {100,200,300}; ``` `string arr[] vs char arr[]` ```C++= string arr[] = {"apple", "banana", "cherry"}; // 初始化字串陣列 char arr1[] = "hello"; // 初始化字元陣列 char arr2[] = {'w', 'o', 'r', 'l', 'd', '\0'}; // 另一種初始化方式,最後要加 \0 ``` ## 數學運算 ```C++= #include <iostream> #include <cmath> using namespace std; int main() { double x = 3.14; int y = floor(x); // 無條件捨去 int z = ceil(x); // 無條件進位 int k = round(x); // 四捨五入 cout << y << endl; return 0; } ``` 樹的距離 ```C++= #include <iostream> using namespace std; int main() { int n; cin >> n; int x[n]; for(int i=0;i<n;i++){ cin >> x[i]; } for(int i=0;i<n;i++){ if(i == 0){ cout << x[1] - x[0] << " "; }else if(i == n-1){ cout << x[n-1] - x[n-2] << " "; }else{ int l, r; l = x[i] - x[i-1]; r = x[i+1] - x[i]; if(l < r){ cout << l << " "; }else{ cout << r << " "; } } } return 0; } ``` 對獎 ```C++= #include<iostream> using namespace std; int main(){ int k, n; cin >> k >> n; bool a[101]; int p[n], t[n]; for(int i=0;i<101;i++){ a[i] = 0; } for(int i=0, num;i<k;i++){ cin >> num; a[num] = 1; } for(int i=0;i<n;i++){ cin >> p[i]; } for(int i=0;i<n;i++){ cin >> t[i]; } int ans = 0; for(int i=0;i<n;i++){ if(a[p[i]] == 1){ ans += t[i]; } } cout << ans << " "; } ``` 機械鼠 ```c++= #include <iostream> using namespace std; int main() { int x,n; int right = 0, left = 0; int l = -101, r = 101; cin >> x >> n; int h[n]; for(int i=0;i<n;i++){ cin >> h[i]; } for(int i=0;i<n;i++){ if(h[i] > x){ right++; l = max(l,h[i]); }else { left++; r = min(r,h[i]); } } if(left>right){ cout << left << " " << r; }else{ cout << right << " " << l; } return 0; } ``` 程式考試 ```c++= #include <iostream> using namespace std; int main() { // 初始化變數 int submit, highest_score = -1, first_highest_time = 0, error_time = 0; // 讀取提交次數 cin >> submit; for (int i = 0; i < submit; i++) { int time, score; // 讀取每次提交的時間和分數 cin >> time >> score; // 如果分數為-1,代表有錯誤,錯誤次數加一 if (score == -1) { error_time++; } // 如果當前分數高於已記錄的最高分,更新最高分和首次獲得最高分的時間 if (score > highest_score) { highest_score = score; first_highest_time = time; } } // 計算最終得分:最高分減去提交次數和錯誤次數的兩倍 int endScore = highest_score - submit - error_time * 2; // 如果最終得分為負數,調整為0 if (endScore < 0) { endScore = 0; } // 輸出最終得分和首次獲得最高分的時間 cout << endScore << " " << first_highest_time << endl; return 0; } ``` 數字遊戲 ```c++= #include <iostream> #include <algorithm> // 引入算法庫,主要用於使用max函數 using namespace std; int main() { int a, b, c; cin >> a >> b >> c; // 讀取三個整數 int counts[10] = {0}; // 建立一個數組來存儲數字1到9的出現次數 // 增加每個數字的計數 counts[a]++; counts[b]++; counts[c]++; // 找出三個數字中出現最多次的次數 int maxCount = max({counts[a], counts[b], counts[c]}); cout << maxCount; // 輸出出現次數最多的數字的次數 // 從9開始遍歷到1,輸出出現的數字 for (int i = 9; i >= 1; i--) { if (counts[i] > 0) { cout << ' ' << i; } } cout << '\n'; // 輸出換行符 return 0; } ``` 程式交易 ```c++= #include <iostream> using namespace std; int main() { int time, rangePrice; cin >> time >> rangePrice; const int MAX_SIZE = 100; int prices[MAX_SIZE]; for (int i = 0; i < time; ++i) { cin >> prices[i]; } int BuyPrice = prices[0]; bool Have = true; int profit = 0; for (int i = 1; i < time; ++i) { // 如果目前持股,且股票價格超過了買入價格加上波動範圍,就賣出 if (Have && prices[i] >= BuyPrice + rangePrice) { profit += (prices[i] - BuyPrice); // 計算獲利 BuyPrice = prices[i]; // 設定新的買入價格為目前的股票價格 Have = false; } // 如果目前沒有持股,且股票價格低於買入價格減去波動範圍,就買進 if (!Have && prices[i] <= BuyPrice - rangePrice) { BuyPrice = prices[i]; // 設定新的買入價格為目前的股票價格 Have = true; } } cout << profit << endl; return 0; } ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully