遞迴
P-1-1. 合成函數(1)
#include<bits/stdc++.h>
using namespace std;
int eval(){
string s;
cin >> s;
if(s[0]=='f'){
int x = eval();
return 2*x-1;
}else if(s[0]=='g'){
int x = eval();
int y = eval();
return x+2*y-3;
}else{
return stoi(s);
}
}
int main(){
cout << eval() << endl;
}
Q-1-2. 合成函數(2)
#include<bits/stdc++.h>
using namespace std;
int eval(){
string s;
cin >> s;
if(s[0]=='f'){
int x = eval();
return 2*x-3;
}else if(s[0]=='g'){
int x = eval();
int y = eval();
return 2*x+y-7;
}else if(s[0]=='h'){
int x = eval();
int y = eval();
int z = eval();
return 3*x-2*y+z;
}else{
return stoi(s);
}
}
int main(){
cout << eval() << endl;
}
P-1-3. 棍子中點切割
#include<bits/stdc++.h>
using namespace std;
pair<int,int> FIND(vector<int>&arr,int target){
int l = 0;
int r = arr.size()-1;
int m = l+(r-l)/2;
while(l<=r){
m = l+(r-l)/2;
if(arr[m]<target){
l=m+1;
}
if(arr[m]==target){
return {true,m};
}
if(arr[m]>target){
r=m-1;
}
}
return {false,l};
}
int cut(vector<int>&arr,int left,int right){
if (right-left<=1) return 0;
int m = FIND(arr,(arr[left]+arr[right])/2).second;
cout << m << endl;
return arr[right]-arr[left]+cut(arr,left,m)+cut(arr,m,right);
}
int main(){
int n,l;cin >> n >> l;
vector<int>v(n+2);
v[0]=0;
for(int i=1;i<=n;++i){
cin >> v[i];
}
v[n+1]=l;
cout << cut(v,0,n+1) << endl;
}
Last updated
Was this helpful?