公式
B - Pawn on a Grid 解説
by
B - Pawn on a Grid 解説
by
mechanicalpenciI
問題を入力の形式に従って読み変えると、「\(W\) 文字の文字列が \(H\) 個与えられます。各文字列に現れる #
の数の合計を求めてください。 」という問題になります。これは for 文と if 文またはcount関数を用いて実装する事ができます。
c++による実装例(if 文) :
#include <bits/stdc++.h>
using namespace std;
int main() {
int h,w,ans=0;
string s;
cin >> h >> w;
for(int i=0;i<h;i++){
cin>>s;
for(int j=0;j<w;j++){
if(s[j]=='#')ans++;
}
}
cout << ans <<endl;
return 0;
}
Pythonによる実装例(if 文) :
h,w = map(int, input().split())
ans=0
for i in range(h):
s=input()
for j in range(w):
if s[j]=='#':
ans += 1
print(ans)
c++による実装例(count 関数) :
#include <bits/stdc++.h>
using namespace std;
int main() {
int h,w,ans=0;
string s;
cin >> h >> w;
for(int i=0;i<h;i++){
cin>>s;
ans += count(s.begin(), s.end(), '#'); //if文の場合と, この行だけ異なる
}
cout << ans <<endl;
return 0;
}
Pythonによる実装例(count 関数) :
h,w = map(int, input().split())
ans=0
for i in range(h):
ans += input().count('#')
print(ans)
投稿日時:
最終更新: