Q:吃桃子
int n;
int f(int x) {
if (x == n) return 1;
return (f(x + 1) + 1) * 2;
}//7 3 1 4 1 10 4 1
int main() {
cin >> n;
cout << f(1) << '\n';
return 0;
}
Q:斐波那契
#include<iostream>
using namespace std;
int n, a, b, p;
int ans[2005];
bool vis[2005]; //!!!默认是false
int f(int n) {
if (vis[n])
return ans[n];
vis[n] = true;
if (n == 1 || n == 2)
return ans[n] = 1 % p; //!!如果p是1,return就是0
else
return ans[n] = ((a * f(n - 1)) % p + (b * f(n - 2)) % p) % p;
}
int main() {
cin >> n >> a >> b >> p;
cout << f(n) << '\n';
return 0;
}
Q:快速幂
#include<iostream>
using namespace std;
long long f(long long x, long long y, long long p) {
if (y == 0)
return 1 % p; //!!!会坑人
else if (y % 2 == 0) {
long long temp = f(x, y / 2, p);
return temp * temp % p;
}
else {
long long temp = f(x, y / 2, p);
return temp * temp % p * x % p;
}
}
int main() {
long long x, y, p;
int t;
cin >> t;
while (t--) {
cin >> x >> y >> p;
cout << f(x, y, p) << '\n';
}
return 0;
}
Q:弹簧版
#include<iostream>
#include<math.h>
using namespace std;
int n;
int a[203];
int b[203];
bool vis[203];
int ans[203];
int f(int x) { //表示最小次数
if (x > n) //离开弹簧,不需要再来一次
return 0;
if (vis[x])
return ans[x];
vis[x] = true;
//本次弹跳+下一位置的最小次数
return ans[x] = min(f(x + a[x]), f(x + b[x])) + 1;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {
cin >> b[i];
}
cout << f(1);
return 0;
}
Q:最大公约数
int f(int x, int y) {
if (y == 0)
return x;
if (x == 0)
return y;
return f(y, x % y);
}
int main() {
int t;
cin >> t;
int x, y;
for (int i = 0; i < t; i++) {
cin >> x >> y;
cout << f(x, y) << '\n';
}
return 0;
}
Q:括号匹配
#include<iostream>
#include<stack>
#include<string>
using namespace std;
stack<char> ch;
int a[50005];
int main() {
string s;
cin >> s;
int len = s.length();
int flag = 0;
char temp;
bool b = true;
for (int i = 0; i < len; i++) {
temp = s[i];
if (temp == '(') { //!!压入栈的不一定是(也可以是编号)
ch.push(i+1);
}
else {
if ( !ch.empty() ) {
a[i+1] = ch.top();
ch.pop();
}
else {
cout << "No" << '\n';
b = false;
break;
}
}
}
if (!ch.empty())
b = false;
if (b) {
cout << "Yes" << endl;
for (int i = 1; i <= len; i++) {
if(a[i])
cout << a[i] << " " << i << '\n';
}
}
else
cout << "No" << endl;
return 0;
}
Q:网页跳转
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main() {
int n;
cin >> n;
string flag, html;
stack<string> s;
stack<string> temp;
for (int i = 0; i < n; i++) {
cin >> flag;
if (flag == "VISIT") {
cin >> html;
s.push(html);
while (!temp.empty())
temp.pop(); //!!打开新的网址之后不会再有前进操作啦!!
cout << html << '\n';
}
else if (flag == "BACK") {
if (s.empty())
cout << "Ignore" << '\n';
else {
temp.push(s.top());
s.pop();
if (s.empty()) {
cout << "Ignore" << '\n';
s.push(temp.top());
temp.pop();
}
else
cout << s.top() << endl;
}
}
else {
if (temp.empty())
cout << "Ignore" << endl;
else {
cout << temp.top() << endl;
s.push(temp.top());
temp.pop();
}
}
}
return 0;
}