首页 > 其他分享 >回溯大合集+主元素+DFS图

回溯大合集+主元素+DFS图

时间:2024-07-07 10:19:44浏览次数:8  
标签:return scanner int DFS ++ static 回溯 new 合集

子集和问题

import java.util.Scanner;
​
public class Main {
    static int n; // 元素个数
    static int tarsum; // 目标和
    static int remainSum = 0; // 当前元素加到最后一个元素的总和,剩余元素和
    static int sesum = 0; // 已选元素之和
    static int[] arr; // 原数组
    static int[] choose; // 判断元素选不选
​
    static boolean backtrack(int index) {
        if (sesum == tarsum) return true; // 已选和等于目标和,找到
        if (index >= n) return false; // 没有更多元素可以处理,没找到
​
        remainSum -= arr[index]; // 先减去当前元素
​
        if (sesum + arr[index] <= tarsum) { // 如果当前和加上该元素小于等于目标和,可以选
            choose[index] = 1; // 选择该元素
            sesum += arr[index]; // 更新当前和
            if (backtrack(index + 1)) return true; // 如果找到则返回true
            sesum -= arr[index]; // 否则减回去
        }
​
        if (sesum + remainSum >= tarsum) { // 即使不选择当前元素,加上剩余元素总和也足以达到或超过目标和
            choose[index] = 0; // 不选当前元素
            if (backtrack(index + 1)) return true; // 如果找到则返回true
        }
​
        remainSum += arr[index]; // 加回去当前元素
        return false; // 未找到
    }
​
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt(); // 读取元素个数
        tarsum = scanner.nextInt(); // 读取目标和
        arr = new int[n]; // 初始化数组
        choose = new int[n]; // 初始化选择数组
​
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt(); // 读取每个元素
            remainSum += arr[i]; // 计算总和
        }
​
        if (!backtrack(0)) {
            System.out.println("No Solution!"); // 如果找不到,输出无解
        } else {
            for (int i = 0; i < n; i++) {
                if (choose[i] == 1) {
                    System.out.print(arr[i] + " "); // 输出选中的元素
                }
            }
        }
    }
}
​

最大子矩和

import java.util.Scanner;
​
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // 创建扫描器对象读取输入
        
        while (scanner.hasNext()) { // 检查是否有更多的输入
            int rows = scanner.nextInt(); // 读取矩阵行数
            int cols = scanner.nextInt(); // 读取矩阵列数
            
            int[][] matrix = new int[rows][cols]; // 初始化矩阵
            for (int i = 0; i < rows; i++) { // 遍历每一行
                for (int j = 0; j < cols; j++) { // 遍历每一列
                    matrix[i][j] = scanner.nextInt(); // 读取矩阵元素
                }
            }
            
            System.out.println(findMaxSubmatrixSum(matrix, rows, cols)); // 计算并输出最大子矩阵和
        }
        
        scanner.close(); // 关闭扫描器
    }
    
    private static int findMaxSubmatrixSum(int[][] matrix, int rows, int cols) {
        //构建一个前缀和矩阵prefixSum为了计算方便,我们将前缀和矩阵多加一行一列作为边界
        int[][] prefixSum = new int[rows + 1][cols + 1]; // 初始化前缀和数组
        
        // 计算前缀和
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= cols; j++) {
                //前缀和矩阵的i,j = 原矩阵对应点 + 前缀和矩阵左边一个 + 右边一个 - 左上角一个。
                prefixSum[i][j] = matrix[i - 1][j - 1] + prefixSum[i - 1][j] + prefixSum[i][j - 1] - prefixSum[i - 1][j - 1];
            }
        }
        
        int maxSum = Integer.MIN_VALUE; // 初始化最大子矩阵和为最小值
​
        //计算最大子矩阵和,遍历每行每列
        // 固定上边界
        for (int top = 0; top < rows; top++) {
            // 固定下边界
            for (int bottom = top; bottom < rows; bottom++) {
                int currentSum = 0; // 当前子矩阵和
                // 遍历每一列
                for (int col = 0; col < cols; col++) {
                    int submatrixSum = getSubmatrixSum(prefixSum, top, col, bottom, col); // 计算当前列在top和bottom之间的和
                    // 如果当前和大于0,累加,为什么?如果和都是负数了说明必不可能是最大子矩和,我们只要把所有正的累加即可
                    if (currentSum > 0) {
                        currentSum += submatrixSum; 
                    // 如果当前和小于等于0,重置为当前列和
                    } else {
                        currentSum = submatrixSum; 
                    }
                    //currentSum = (currentSum > 0) ? currentSum + submatrixSum : submatrixSum;
                    maxSum = Math.max(maxSum, currentSum); // 更新最大子矩阵和
                }
            }
        }
        return maxSum; // 返回最大子矩阵和
    }
    
    // 要计算子矩阵和,使用已经算出来的前缀和矩阵达到快速计算。
   private static int getSubmatrixSum(int[][] prefixSum,int topRow, int leftCol, int bottomRow, int rightCol) {
        //右下角 - 左下角 - 右上角 + 左上角,因为pre是比martix多一位的,所以遇到右边界,下边界都要+1
        return prefixSum[bottomRow + 1][rightCol + 1] - prefixSum[bottomRow + 1][leftCol] -
                prefixSum[topRow][rightCol + 1] + prefixSum[topRow][leftCol];
    }
}

N皇后

import java.util.Scanner;
​
public class Main {
    static final int MAX = 22; // 棋盘的最大尺寸
    static int[][] chessboard = new int[MAX][MAX]; // 棋盘,用于存储皇后的位置
​
    // 检查在 (row, col) 放置皇后是否安全
    static boolean isSafe(int row, int col, int n) {
        // 检查同一列
        for (int i = 0; i < row; i++) {
            if (chessboard[i][col] == 1) {
                return false;
            }
        }
​
        // 检查左上对角线
        for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
            if (chessboard[i][j] == 1) {
                return false;
            }
        }
​
        // 检查右上对角线
        for (int i = row, j = col; i >= 0 && j < n; i--, j++) {
            if (chessboard[i][j] == 1) {
                return false;
            }
        }
​
        return true; // 如果没有冲突,返回 true
    }
​
    // 递归函数,尝试在第 row 行放置皇后
    static boolean solveUtil(int row, int n) {
        // 如果所有皇后都成功放置,返回 true
        if (row == n) {
            return true;
        }
​
        // 尝试在当前行的每一列放置皇后
        for (int col = 0; col < n; col++) {
            if (isSafe(row, col, n)) { // 检查当前位置是否安全
                chessboard[row][col] = 1; // 放置皇后
​
                // 递归尝试在下一行放置皇后
                if (solveUtil(row + 1, n)) {
                    return true;
                }
​
                chessboard[row][col] = 0; // 回溯:移除皇后
            }
        }
​
        return false; // 如果在当前行的所有列都不能放置皇后,返回 false
    }
​
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // 创建扫描器对象
        int n = scanner.nextInt(); // 读取用户输入的棋盘大小
​
        // 初始化棋盘
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                chessboard[i][j] = 0;
            }
        }
​
        // 求解 N 皇后问题
        if (!solveUtil(0, n)) { // 如果没有找到解决方案,输出提示信息
            System.out.println("No solution found");
        } else {
            // 打印解决方案,每行输出一个皇后所在的列
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (chessboard[i][j] == 1) {
                        System.out.print((j + 1) + " "); // 输出皇后所在的列
                        break;
                    }
                }
            }
        }
​
        scanner.close(); // 关闭扫描器
    }
}
​

主元素

主元素:
​
import java.util.Scanner;
​
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt(); // 读取测试用例的数量
​
        while (T-- > 0) {
            int n = sc.nextInt(); // 读取集合的元素数量
            int[] arr = new int[n];
            for (int i = 0; i < n; i++) {
                arr[i] = sc.nextInt(); // 读取集合中的元素
            }
            // 调用方法找到主元素
            String result = findMajorityElement(arr, n);
            // 输出结果
            System.out.println(result);
        }
        sc.close();
    }
​
    // 方法:使用摩尔投票算法找到主元素
    private static String findMajorityElement(int[] arr, int n) {
        int count = 0;
        int condidate = -1;
        
        for(int num : arr){
            if(count == 0){
                count = 1;
                condidate = num;
            }else if(num == condidate){
                count++;
            }else{
                count--;
            }
            
        }
        
        count = 0;
        for(int num : arr){
            if( num == condidate){
                count++;
            }
        }
        if(count  > n/2){
            return String.valueOf(condidate);
            
        }else{
            return "no";
        }
    }
}
​

用DFS计算pre和post

import java.util.*;
​
public class Main {
    private static int time;
    private static int[] pre;
    private static int[] post;
    private static List<List<Integer>> graph;
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // 读取输入
        int n = scanner.nextInt(); // 顶点数
        int e = scanner.nextInt(); // 边数
        
        pre = new int[n + 1]; // 初始化 pre 数组
        post = new int[n + 1]; // 初始化 post 数组
        graph = new ArrayList<>(); // 初始化邻接表
        
        for (int i = 0; i <= n; i++) {
            graph.add(new ArrayList<>()); // 创建每个顶点的邻接表
        }
        
        for (int i = 0; i < e; i++) {
            int a = scanner.nextInt(); // 读取边的起点
            int b = scanner.nextInt(); // 读取边的终点
            graph.get(a).add(b); // 添加边到邻接表
        }
        
        for (int i = 1; i <= n; i++) {
            Collections.sort(graph.get(i)); // 按顶点编号从小到大排序邻接表
        }
        
        time = 1; // 时钟从 1 开始
        boolean[] visited = new boolean[n + 1]; // 初始化访问标记数组
        
        dfs(1, visited); // 从 1 号顶点开始 DFS
        
        // 输出 pre 数组
        for (int i = 1; i <= n; i++) {
            System.out.print(pre[i] + " ");
        }
        System.out.println();
        
        // 输出 post 数组
        for (int i = 1; i <= n; i++) {
            System.out.print(post[i] + " ");
        }
        System.out.println();
        
        scanner.close(); // 关闭扫描器
    }
    
    private static void dfs(int v, boolean[] visited) {
        visited[v] = true; // 标记顶点 v 为已访问
        pre[v] = time++; // 记录 pre 值并增加时间
        
        for (int neighbor : graph.get(v)) { // 遍历邻接顶点
            if (!visited[neighbor]) { // 如果邻接顶点未被访问
                dfs(neighbor, visited); // 递归调用 DFS
            }
        }
        
        post[v] = time++; // 记录 post 值并增加时间
    }
}
​

标签:return,scanner,int,DFS,++,static,回溯,new,合集
From: https://www.cnblogs.com/hanlinyuan/p/18288247

相关文章

  • 背包问题大合集
    dp背包3步曲1.确定dp[i][v]的含义(一维的话是dp[v]):在0…i的物品中,体积为v的背包中,能够拿到的最大价值为dp[i][v]。2.求关系式不拿物品:(物品数量减少)一维:dp[v]二维:dp[i][v]=dp[i-1][v]拿:(物品数量减少,背包体积减物品体积)一维:dp......
  • 力扣第22题:括号生成 深度优先搜索(DFS)和它的优化(C++)
    数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。示例:输入:n=3输出:["((()))","(()())","(())()","()(())","()()()"]思路递出去,再归回来,是为递归。DFS算法是利用递归思想的一种搜索算法。想象一个矿井,从地面到井底有多层......
  • 【AcWing】842. 排列数字(DFS)
    DFS是树形结构,深度优先搜索。dfs可以算作递归。横线上填和前面不一样的数字。每一次向下探索都一条路走到黑,直到不能走再回溯。#include<iostream>usingnamespacestd;constintN=10;intn;intpath[N];//存放走过的路径boolst[N];//存放1~n哪个数用过了,全局b......
  • leetcode77组合——经典回溯算法
    本文主要讲解组合的要点与细节,以及回溯算法的解题步骤,按照步骤思考更方便理解 c++和java代码如下,末尾给定两个整数 n 和 k,返回范围 [1,n] 中所有可能的 k 个数的组合。你可以按 任何顺序 返回答案。 具体要点:1.首先,这道题的暴力解法是k层for循环,遍历所有的......
  • 回溯算法套路①子集型回溯 - 灵神视频总结
    我回来了,前两天模型出了问题,忙于工作。加上回溯有点想不清楚,查了查资料。汗颜。这节课主要讲回溯的基本概念和回溯的基本套路。首先各位思考一个问题:如果生成一个长度为2的字符串,该怎么操作?我们通常的想法是用两层循环拼接就好,如果用两层循环,如果我要生成长为2或者3......
  • 【专题】2024年6月数字化行业报告合集汇总PDF分享(附原数据表)
    原文链接:https://tecdat.cn/?p=36658原文出处:拓端数据部落公众号随着科技的飞速发展和全球数字化进程的加速推进,我们正处在一个充满变革与机遇的时代。从人工智能的深入应用到工业互联网的蓬勃发展,从智慧医疗的兴起到新能源汽车的普及,每一个领域都在经历着前所未有的转型与升级......
  • C#实现DFS和BFS
    以图示为例:Noderoot=newNode("A",newNode("B",newNode("C"),newNode("D")),newNode("E",newNode("F"),newNode("......
  • LeetCode-刷题记录-滑动窗口合集(本篇blog会持续更新哦~)
    一、滑动窗口概述滑动窗口(SlidingWindow)是一种用于解决数组(或字符串)中子数组(或子串)问题的有效算法。SlidingWindow核心思想:滑动窗口技术的基本思想是维护一个窗口(一般是一个子数组或子串),该窗口在数组上滑动,并在滑动过程中更新窗口的内容。通过滑动窗口,可以在(O(......
  • Codeforces 19xx 合集
    CF1974A.PhoneDesktop每个手机只能填两个大的,先把大的填完,然后剩下的地方用小的补上,最后小的不够用了再拿新的手机。B.SymmetricEncoding直接模拟吧。C.BeautifulTriplePairs一个比较好写的做法,是先不管那个不同的,把所有存在两个相同的都加上,最后减去三遍三个......
  • 软件开发资料合集(开发&实施&运维&安全&交付)
        前言:在软件项目管理中,每个阶段都有其特定的目标和活动,确保项目的顺利进行和最终的成功交付。以下是软件项目管理各个阶段的详细资料:软件项目管理部分文档清单: 工作安排任务书,可行性分析报告,立项申请审批表,产品需求规格说明书,需求调研计划,用户需求调查单,用户需求说......