解題思路參考:https://www.cnblogs.com/jcwy/p/18003130
這裡給出DFS方法的程式碼。
100分程式碼:
#include <bits/stdc++.h>
using namespace std;
const int N = 15;
struct pl
{
int s; //酸度
int b; //苦度
} a[N];
int n;
int ans = 2e9;
int choice[N];
void dfs(int k)
{
if(k > n)
{
int S = 1, B = 0;
for(int i = 1; i <= n; i++)
{
if(choice[i] == 1)
{
S *= a[i].s;
B += a[i].b;
}
}
if(S != 1 || B != 0) ans = min(ans, abs(S - B));
return;
}
for(int i = 0; i <= 1; i++)
{
choice[k] = i;
dfs(k + 1);
}
}
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> a[i].s >> a[i].b;
}
dfs(1);
cout << ans;
return 0;
}