# 靜心 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;
}
```