zoukankan      html  css  js  c++  java
  • 动态规划的引入 P2196 挖地雷【DFS求路径最大节点参数和】

    题目

    https://www.luogu.com.cn/problem/P2196

    题目分析

    其实是与使用DFS求解最短路径的方法是差不多的,只不过这里的visited数组不用重新置0

    对图中的每个节点都要进行DFS,选择最大的节点参数和作为结果(注意在进行遍历执行DFS的时候要对visited数组进行重新初始化,而path数组不用,可以在上一步的基础上直接更新)

    在DFS函数中,我们寻找以该节点出发能获得的最大的节点参数和,并将最后结束的节点记录下来用于之后路径的输出

    代码

    #include<iostream>
    #include<cstdio>
    #include<stack>
    #include<cstring>
    #include<string>
    using namespace std;
    int edges[25][25];
    int maxx = 0, maxi = 0;
    int list[25];
    int visited[25];
    int path[25];
    stack<int>output;
    void DFS(int s, int n, int temp)
    {
        visited[s] = 1;
        if (temp > maxx) { maxx = temp; maxi = s; }
        for (int i = 1; i <= n; i++)
        {
            if (!visited[i] && edges[s][i] == 1)
            {
                DFS(i, n, temp + list[i]);
                path[i] = s;
            }
        }
    }
    int main()
    {
        int n;
        scanf("%d", &n);
        for (int i = 1; i <= n; i++)
            scanf("%d", &list[i]);
        for (int i = n - 1; i >= 1; i--)
        {
            for (int j = n - i + 1; j <= n; j++)
            {
                scanf("%d", &edges[n - i][j]);
            }
        }
        int aa = 0;
        int tt = 0;
        for (int i = 1; i <= n; i++)
        {
            
            memset(visited, 0, sizeof(visited));
            DFS(i, n, list[i]);
            if (maxx > tt) { tt=maxx; aa = i; }
        }
        memset(visited, 0, sizeof(visited));
        DFS(aa, n, list[aa]);
        output.push(maxi);
        int temp = path[maxi];
        while (temp != 0)
        {
            output.push(temp);
            temp = path[temp];
        }
        int space = 0;
        while (!output.empty())
        {
            int t = output.top(); output.pop();
            if (space == 0) { printf("%d", t); space++; }
            else printf(" %d", t);
        }
        printf("
    %d", tt);
    
    }
  • 相关阅读:
    Spring Bean Scope 有状态的Bean 无状态的Bean
    管理Mysql常用指令
    mysql处理特殊字符
    linux下memcached安装 和redis安装,jdk,tomcat,mysql 安装
    Jenkins
    tomcat站点配置
    tomcat配置jdbc
    spring 深入reading
    JAVA随机数之多种方法从给定范围内随机N个不重复数
    Intellij IDEA 快捷键整理
  • 原文地址:https://www.cnblogs.com/Jason66661010/p/13109840.html
Copyright © 2011-2022 走看看