AOJ ITP1 5.Structured Program I
はい。なんか問題文を1行だけコピペするの意味ないことに気づいたので廃止します。
http://judge.u-aizu.ac.jp/onlinejudge/topic.jsp?cid=ITP1#problems/ITP1_5
A.Print a Rectangle
while 1: m,n=map(int, raw_input().split()) if n==m==0: break else: print (('#'*n+'\n')*m)
C++11
#include<bits/stdc++.h> #include<vector> #include<algorithm> using namespace std; int main(){ double pai=3.141592653589; int h,w; for(;;){ scanf("%d %d",&h,&w); if(h==0 && w==0) break; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ printf("#"); } printf("\n"); } printf("\n"); } return 0; }
文字列の出力の仕方が言語によってやや違ったりするけど特に大きく差がでない問題だと思う。あと一応はh,wのどちらかが0なだけで出力するものがなくなる、入力としてどちらかだけ0はあり得ない。なのでどちらでも好きな方を0と等しくないかだけみて終了条件のチェックが出来る。
B.Print a Frame
while 1: h,w=map(int,raw_input().split()) if h==0:exit() print'#'*w for i in range(h-2):print'#'+'.'*(w-2)+'#' print'#'*w print
C++11
#include<bits/stdc++.h> #include<vector> #include<algorithm> using namespace std; int main(){ int h,w; for(;;){ scanf("%d %d",&h,&w); if(h==0 && w==0) break; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(i==0 || i==h-1 || j==0 || j==w-1){ printf("#"); }else{ printf("."); } } printf("\n"); } printf("\n"); } return 0; }
これも同様にどちらか好きな方だけ0と等しくないか見れば終了判定できます。
C.Print a Chessboard
l='#.'*151 while 1: h,w=map(int,raw_input().split()) if h==0:break for i in range(h): if i%2:print l[1:w+1] else:print l[:w] print
C++11
#include<bits/stdc++.h> #include<vector> #include<algorithm> using namespace std; int main(){ double pai=3.141592653589; int h,w; for(;;){ scanf("%d %d",&h,&w); if(h==0 && w==0) break; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if((i+j)%2==0){ printf("#"); }else{ printf("."); } } printf("\n"); } printf("\n"); } return 0; }
これもまた終了条件はどちらかを見るだけでも。pythonでは予め#.が並んだものを用意しておいて始めと終わりの位置を指定する方法を使えたりもする。C++ではそういった方法が分からなかったので偶奇とかみて出力させた。
D.Structured Programming
n=int(raw_input()) ans='' for i in range(3,n+1): if i%3==0 or '3' in str(i): ans+=(' '+str(i)) print ans
C++11
#include<bits/stdc++.h> #include<vector> #include<algorithm> using namespace std; int main(){ double pai=3.141592653589; int n; scanf("%d",&n); for(int i=3;i<=n;i++){ int x=i; if(i%3==0){ printf(" %d",i); }else{ do{ if(x%10==3){ printf(" %d",i); break; } x/=10; } while(x); } } printf("\n"); return 0; }
そもそも何をしているのかの解読が非常に難儀しました。出力するものは3で割り切れるか桁の何処かに3を含むものを出力する。
x%10==3
でなければx/=10
するというのは1桁ずつ下げて下1桁が3になるかどうかチェックすることで桁の何処かに3を含むかを探している。pythonだとstrにキャストして文字列の3を含むかどうか1行で書けるけど、C++だと分からないのでひたすら割る方法になった。