遞迴
f(n){ f(n-1) }
遞迴
/*
* AP325
* P-1-1. 合成函數(1)
*/
#include<bits/stdc++.h>
using namespace std;
int solve(){
string s;
cin >> s;
if(s[0]=='f'){
int x = solve();
return 2*x-1;
}else if(s[0]=='g'){
int x = solve();
int y = solve();
return x+2*y-3;
}else{
int sum = 0;
for(int i=0;i<s.size();++i){
sum+=s[i]-'0';
sum*=10;
}
return sum/10;
}
}
int main(){
cout << solve() << endl;
}
河內塔
/*
* TIOJ
* 1355. 河內之塔-蘿莉塔
*/
#include<bits/stdc++.h>
using namespace std;
int cnt = 0;
void f(int n, int from, int temp, int to) {
if (n == 1) {
cnt += 1;
printf("#%d : move the dish from #%d to #%d\n", cnt, from, to);
return;
}
f(n - 1, from, to, temp);
cnt += 1;
printf("#%d : move the dish from #%d to #%d\n", cnt, from, to);
f(n - 1, temp, from, to);
}
int main() {
int n;
cin >> n;
f(n, 1, 2, 3);
}
Last updated
Was this helpful?