DFS练习篇

收录一些遇到的DFS题目

P2089 烤鸡 (洛谷)

题目:猪猪Hanke特别喜欢吃烤鸡(本是同畜牲,相煎何太急!)Hanke吃鸡很特别,为什么特别呢?因为他有10种配料(芥末、孜然等),每种配料可以放1—3克,任意烤鸡的美味程度为所有配料质量之和
现在,Hanke想要知道,如果给你一个美味程度,请输出这10种配料的所有搭配方案

输入格式:一行,n<=5000

  • DFS(数据范围小,好像暴力循环也可以)
  • 分析:二维数组res记录每种方案对应的详情,一维数组ans记录在深搜过程中产生的方案。由于最多有 3 10 3^{10} 种情况,所以maxn定义成 60000 60000
  • 代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 60000;//3的十次方是59049
int n, kind;
int res[maxn][10], ans[10];
void dfs(int cou, int sum)
{
    if(cou == 10)
    {
        if(sum == n)
        {
            for(int i=0; i<10; i++)
                res[kind][i] = ans[i];
            kind++;
        }
    }
    else
    {
        for(int i=1; i<=3; i++)
        {
            ans[cou] = i;
            dfs(cou+1, sum+i);
        }
    }
}
int main()
{
    cin >> n;
    dfs(0, 0);
    cout << kind << endl;
    for(int i=0; i<kind; i++)
    {
        for(int j=0; j<10; j++)
        {
            cout << res[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

P1618 三连击(升级版)

题目:将1,2,…,9共9个数分成三组,分别组成三个三位数,且使这三个三位数的比例是A:B:C,试求出所有满足条件的三个三位数,若无解,输出“No!!!”。

输入格式:三个数,A B C。

  • DFS
  • 分析:和上一题挺像的,主要补充解释一下,像这里dfs走到cou==10时,里面不再有dfs(cou+1),所以就停下来了。
  • 代码
#include<bits/stdc++.h>
using namespace std;

int a, b, c, bl(0);
int vis[10], arr[10];
void dfs(int cou)
{
    if(cou == 10)
    {
        int n1 = arr[1]*100+arr[2]*10+arr[3];
        int n2 = arr[4]*100+arr[5]*10+arr[6];
        int n3 = arr[7]*100+arr[8]*10+arr[9];
        if(n1*b*c == n2*a*c && n1*b*c == n3*a*b)
        {
            cout << arr[1] << arr[2] << arr[3] << " "
                 << arr[4] << arr[5] << arr[6] << " "
                 << arr[7] << arr[8] << arr[9] << endl;
            bl = 1;
        }
    }
    else
    {
        for(int i=1; i<=9; i++)
        {
            if(vis[i] == 0)
            {
                arr[cou] = i;
                vis[i] = 1;
                dfs(cou+1);
                vis[i] = 0;
            }
        }
    }
}
int main()
{
    cin >> a >> b >> c;
    dfs(1);
    if(bl==0)
        cout << "No!!!\n";
    return 0;
}
发布了47 篇原创文章 · 获赞 4 · 访问量 1287

猜你喜欢

转载自blog.csdn.net/listenhhh/article/details/100797790