P2036 Perket

传送门

这道题由于n的数据过小,所以可以直接暴力,不过这道题的正解是dfs

#include
using namespace std;
const int maxn=15;
struct node{
	int x,y;
}s[maxn];
int n,sum=0x3f3f3f3f;
void dfs(int i,int x,int y){
	if(i==n){
		if(x==1&&y==0)return;
		sum=min(sum,abs(x-y));
		return;
	}
	dfs(i+1,x*s[i+1].x,y+s[i+1].y);
	dfs(i+1,x,y);
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	scanf("%d%d",&s[i].x,&s[i].y);
	dfs(0,1,0);
	printf("%d\n",sum);
	return 0;
}

暴力

#include
using namespace std;
typedef long long ll;
const int maxn=15;
struct node{
	ll x,y;
}s[maxn];
int n;
ll sum=0x3f3f3f3f;
int main(){
	scanf("%d",&n);
	node a;
	a.x=1;a.y=0;
	for(int i=1;i<=n;i++)
	scanf("%lld%lld",&s[i].x,&s[i].y);
	for(int i=1;i<=n;i++){
		a.x=s[i].x;a.y=s[i].y;
		sum=min(sum,abs(a.x-a.y));
		for(int j=1;j<=n;j++){
			if(i!=j){
			a.x*=s[j].x;a.y+=s[j].y;
			sum=min(sum,abs(a.x-a.y));				
			}
		}
	}
	printf("%lld\n",sum);
	return 0;
}

你可能感兴趣的:(搜索)