【洛谷】P2036 [COCI 2008/2009 #2] PERKET 的题解
半年没打代码了,复健一下
题解
这是一题简单的 DFS,就是根据题意模拟就行。(甚至不用回溯)
要注意的是搜索的界限和要将 a n s ans ans 定义到正无穷,因为题目所需要的是酸度和苦度的绝对差最小。
剩下的看代码内的注释即可。
代码
#include <bits/stdc++.h>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {
inline int read() {
register int x = 0, f = 1;
register char c = getchar();
while (c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
inline void write(int x) {
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
}
using namespace fastIO;
int n, s[15], b[15], ans = 0x7f7f7f7f7f;
void dfs(int num, int x, int y) {
if(num > n) {
if(x == 1 && y == 0) return; // 判断水的情况
ans = min(abs(x - y), ans); // 计算 ans
return;
}
dfs(num + 1, x * s[num], y + b[num]);// 添加
dfs(num + 1, x, y);// 不添加
}
int main() {
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for(int i = 1; i <= n; i ++) {
cin >> s[i] >> b[i];
}
dfs(1, 1, 0);
cout << ans;
return 0;
}