洛谷题单指南-搜索-P2036 [COCI 2008/2009 #2] PERKET

解题思路参考:https://www.cnblogs.com/jcwy/p/18003130

这里给出DFS方法的代码。

100分代码:

#include <bits/stdc++.h>
using namespace std;

int s[15], k[15], v[15], n;
int ans = INT_MAX;

void dfs(int x, int suan, int ku)
{
	if(x > n)
	{
		if(suan == 1 && ku == 0) return;
		else 
		{
			ans = min(ans, abs(suan - ku));
			return;
		}
	}
	dfs(x + 1, suan * s[x], ku + k[x]); //选第x个
	dfs(x + 1, suan, ku); //不选第x个
}

int main()
{
	cin >> n;
	for(int i = 1; i <= n; i++)
	{
		cin >> s[i] >> k[i];
	}
	dfs(1, 1, 0);
	cout << ans;
   
    return 0;
}

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;
}

 

posted @ 2024-03-06 09:18  五月江城  阅读(15)  评论(0编辑  收藏  举报