# 陣列練習的題解 --- # 數字出現次數 - 想法 : 利用一個變數儲存出現次數即可 - 題解 : ``` cpp= #include<bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(0); cin.tie(0); int n,k,arr[10005],i,x=0; cin >>n;//n個數字 for(i=0;i<n;i++) cin >>arr[i]; cin >>k;//查詢k出現的次數 for(i=0;i<n;i++){ if(arr[i]==k) x++; } cout<<x<<'\n'; } ``` ---- # AB數字密碼 - 想法 : 巢狀迴圈分別檢查,設立兩個變數a和b儲存幾A幾B,利用字串儲存比較方便 - 題解 : ``` cpp= #include<bits/stdc++.h> using namespace std; int main(){ string s1,s2; int a=0,b=0,i,j; cin >>s1>>s2; for(i=0;i<4;i++) for(j=0;j<4;j++){ if(s1[i]==s2[j] && i==j)a++; if(s1[i]==s2[j] && i!=j)b++; } cout<<a<<"A"<<b<<"B"<<'\n'; } ``` ---- # 保險箱~簡單版 - 想法:直接設立一個陣列儲存有多少錢,接下來跟著輸入進行操作即可 - 數字可能極大,請記得使用long long - 題解: ``` cpp= #include<bits/stdc++.h> #define ll long long using namespace std; int main(){ ios::sync_with_stdio(0),cin.tie(0); int n,k,t,a,b; while(cin >>n>>k>>t){ ll safe[10005]={0}; if(n==-1)break; //輸入原本多少錢 for(int i=1;i<=n;++i){ cin >>safe[i]; } for(int i=1;i<=k;++i){ cin >>a>>b; //在保險箱a中存b元 safe[a]+=b; //不能有負數 if(safe[a]<0)safe[a]=0; } //查詢 while(t--){ cin >>a; cout<<safe[a]<<" "; } cout<<'\n'; } } ``` ---- # 踩地雷~困難版 - 簡單版的太過於簡單,直接給困難版的題解 - 想法:利用二維陣列儲存有地雷的座標 - 要注意是否在邊緣,陣列多開兩格,將外圈設為零,這樣加起來就不會有問題 - 開另一個小陣列用來檢查座標 - 題解: ``` cpp= #include<bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(0),cin.tie(0); int n,m,k,t,a,b; int pos[9][2]={{1,1},{1,0},{0,1},{1,-1},{-1,1},{-1,-1},{0,-1},{-1,0}}; while(cin >>n>>m>>k>>t){ int arr[105][105]={0}; for(int i=0;i<k;++i){ cin >>a>>b; arr[a][b]=1; } for(int i=0;i<t;++i){ cin >>a>>b; int tmp=0; if(arr[a][b]==1)cout<<"bomb "; else{ for(int j=0;j<8;++j) if(arr[a+pos[j][0]][b+pos[j][1]])++tmp; cout<<tmp<<" "; } } cout<<'\n'; } } ``` ###### tags: `題解` *2022/1/2 WXDai*