P1135
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 10010;
int n, A, B;
int evlt[N];
int res = 1e9;
bool st[N]; //存每层楼走没走过
//当前在x楼, 当前按了cnt次按钮
void dfs(int x, int cnt) {
if(cnt >= res) return ;
if(x < 0 || x > n) return ;
if(x == B) {
res = min(res, cnt);
return ;
}
//上
if(x + evlt[x] <= n && !st[x + evlt[x]]) {
st[x + evlt[x]] = true;
dfs(x + evlt[x], cnt + 1);
st[x + evlt[x]] = false; // 恢复现场
}
//下
if(x - evlt[x] > 0 && !st[x - evlt[x]]) {
st[x - evlt[x]] = true;
dfs(x - evlt[x], cnt + 1);
st[x - evlt[x]] = false;
}
}
int main() {
scanf("%d%d%d", &n, &A, &B);
for(int i = 1; i <= n; i ++) {
scanf("%d", &evlt[i]);
}
dfs(A, 0);
if(res == 1e9) {
printf("-1\n");
return 0;
}
printf("%d\n", res);
return 0;
}
P2036
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 20;
int s[N];//酸
int b[N];//苦
int st[N];
int n;
int ans = 1e9;
void dfs(int x)//目前位置
{
if (x > n)
{
bool xuanle = false;
int sum1 = 1;//酸
int sum2 = 0;//苦
for (int i = 1; i <= n; i++)
{
if (st[i] == 1)
{
xuanle = true;
sum1 *= s[i];
sum2 += b[i];
}
}
if (xuanle)
{
ans = min(ans, abs(sum1 - sum2));
}
return;
}
st[x] = 1;//选
dfs(x + 1);
st[x] = 0;
st[x] = 2;//不选
dfs(x + 1);
st[x] = 0;
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> s[i] >> b[i];
}
dfs(1);
cout << ans;
return 0;
}