问题解答2024年4月28日

本文介绍了一个Java程序,通过定义`District`类和`Solution`类,实现了一个服务接口,根据行政区ID查询并以树形结构返回包含当前行政区及其子区域的列表,使用了深度优先搜索算法(Stack实现)来遍历数据库数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;



//现有数据库里保存有行政区数据, 一个行政区是一行数据,包括行政区id,行政区名称,行政区父id。 比如:
//
//行政区ID,   行政区名称, 行政区父ID  
//1,             中国,            null
//2,             浙江省,         1
//3,                杭州市,         2
//4,                余杭区,            3
//
//
//要求编写一个服务接口,入参:行政区id,出参:树结构形式,包括当前行政区以及所有子行政区。
//
//比如入参是2,返回:
//浙江省
//-- 杭州市
//   -- 余杭区
//
//比如入参是1,返回:
//中国
//-- 浙江省
//  -- 杭州市
//     -- 余杭区
//
//比如入参是3,返回:
//杭州市
//-- 余杭区
public class Main {
    public static void main(String[] args) {
    	// 数据模拟
    	List<District> districtList = new ArrayList<District>();
    	districtList.add(new District("1", "中国", null));
    	
    	districtList.add(new District("2", "浙江省", "1"));
    	
    	districtList.add(new District("3", "杭州市", "2"));
    	districtList.add(new District("4", "湖州市", "2"));
    	districtList.add(new District("5", "嘉兴市", "2"));
    	districtList.add(new District("6", "绍兴市", "2"));
    	
    	districtList.add(new District("7", "余杭区", "3"));
    	districtList.add(new District("8", "上城区", "3"));
    	districtList.add(new District("9", "钱塘区", "3"));
    	districtList.add(new District("10", "滨江区", "3"));
    	Solution solution = new Solution(districtList);
    	
    	// 查询
    	String districtId = "2";
    	solution.getInfo(districtId);
    }
}

class Solution {
	private List<District> districtList;
	
	public Solution(List<District> districtList) {
		this.districtList = districtList;
	}
	
	public void getInfo(String districtId) {
		// 设计思路,按照行政区获取数据的方式,以深度优先搜索为主(用stack实现),优先显示子节点
		// 数据放在list中,通过遍历的方式查询,模拟数据库查询

		int level = 1;  // 每一层的缩进控制
		
		Stack<District> stack = new Stack<District>();
		District district = getDistrictsById(districtId);
		if (district != null) {
			district.setLevel(level);
			
			stack.push(district);
			while (!stack.isEmpty()) {
				
				District district2 = stack.pop();
//				System.out.println(district2.getLevel() + " " + district2.getDistrictName());
				System.out.println(String.format("%0" + district2.getLevel() + "d", 0).replace("0", " ") + " --" + district2.getDistrictName());
				
				List<District> childList = getDistrictsByParentId(district2.getDistrictId());
				
				level++;
				for (District district3 : childList) {
					district3.setLevel(level);
					stack.push(district3);
				}
			}
			
		}
	}
	
	// 根据id查找本级数据
	District getDistrictsById(String districtId) {
		for (int i = 0; i < districtList.size(); i++) {
			District district = districtList.get(i);
			if (district.getDistrictId() == districtId) {
				return district;
			}
		}
		return null;
	}
	// 相当于根据一个父节点,查出一层的数据
	List<District> getDistrictsByParentId(String parentId) {
		// 模拟数据库查询
		List<District> districtResult = new ArrayList<District>();
		for (int i = 0; i < districtList.size(); i++) {
			District district = districtList.get(i);
			if (district.getParentId() == parentId) {
				districtResult.add(district);
			}
		}
		return districtResult;
	}
}

// 行政区的类设计
class District {
	private String districtId;  // 行政区id
	private String districtName;  // 行政区名称
	private String parentId;   // 父id
	
	private int level;  // 临时控制每一层的缩进
	
	public District(String districtId, String districtName, String parentId) {
		this.districtId = districtId;
		this.districtName = districtName;
		this.parentId = parentId;
	}
	
	
	
	public String getDistrictId() {
		return districtId;
	}
	public void setDistrictId(String districtId) {
		this.districtId = districtId;
	}
	public String getDistrictName() {
		return districtName;
	}
	public void setDistrictName(String districtName) {
		this.districtName = districtName;
	}
	public String getParentId() {
		return parentId;
	}
	public void setParentId(String parentId) {
		this.parentId = parentId;
	}
	public int getLevel() {
		return level;
	}
	public void setLevel(int level) {
		this.level = level;
	}
}

### 蓝桥杯 Java 2024 比赛题目及解题思路 #### 比赛概述 蓝桥杯作为一项面向全国大学生的编程竞赛,其 Java B 组的比赛一直以来都注重基础知识的应用以及对实际问题解决能力的考查。根据参赛者的反馈,在2024的比赛中,试题整体偏向基础,涉及较少复杂的算法设计,而更加强调数学思维的应用[^1]。 #### 解题策略与注意事项 在比赛过程中,合理的时间管理至关重要。建议选手完成填空部分后快速浏览所有大题,优先处理简单题目以确保得分最大化。对于无法完全解答的大题,应尽早提交初步版本并逐步优化,利用 OI 赛制的优势争取更多分数[^2]。 #### 示例题目解析:黑色星期五 以下是具体的一道典型例题——“黑色星期五”的分析: ##### 题目描述 给定一个份(≥1998),统计该内有多少个月存在至少一次“黑色星期五”,即当月的13号恰好落在周五的情况。 ##### 解题方法 此问题本质上属于期运算范畴,需基于已知条件推导目标结论: - 已知初始状态为 **19981月1是周四**; - 判断某一各月份中的第十三天是否为周五,则可通过累加每增量来动态更新当前周几信息; - 特别需要注意的是闰规则的影响 —— 即每四增加一天至二月末位置处[^3]。 下面是实现上述逻辑的一种方式: ```java import java.util.Scanner; public class BlackFriday { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int year = scanner.nextInt(); // 输入待检测度 boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); // 计算是否为润 int daysInMonth[] = {31, (isLeapYear ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 各月天数数组初始化 int startDayOfWeek = getStartDayOfWeek(year); // 获取当对应星期编号(周一=1,..., 周=7) int fridayCount = countBlackFridays(daysInMonth, startDayOfWeek); // 主函数调用计数器返回最终结果 System.out.println(fridayCount); } private static int getStartDayOfWeek(int targetYear){ final int BASE_YEAR = 1998; final int START_DAY_1998_JANUARY_1ST = 4; // 星期四设为基准值4 int totalDaysPassedSinceBase = calculateTotalDaysBetween(BASE_YEAR, targetYear); return ((START_DAY_1998_JANUARY_1ST + totalDaysPassedSinceBase)%7)+1 ; } private static int calculateTotalDaysBetween(int baseYr,int tgtYr){ int sumOfYearsDifference = Math.abs(tgtYr-baseYr); int leapYearsWithinRange = (sumOfYearsDifference/4)-(sumOfYearsDifference/100)+(sumOfYearsDifference/400); return (sumOfYearsDifference*365)+leapYearsWithinRange; } private static int countBlackFridays(int[] monthLengthsArray, int initialWeekdayOffset){ int blackFrCounter=0; int cumulativeDaysSoFar=initialWeekdayOffset-1;//调整起始偏移量使得索引从零开始便于模操作 for(int i=0;i<monthLengthsArray.length;i++){ if((cumulativeDaysSoFar+13)%7==5){blackFrCounter++;}//如果累积后的第十三天正好位于第五位则满足条件 cumulativeDaysSoFar += monthLengthsArray[i]; } return blackFrCounter; } } ``` 以上代码片段展示了如何依据既定规则构建解决方案框架,并通过逐层分解任务简化复杂度。 #### 总结 通过对历真题的研究发现,掌握扎实的基础理论知识配合灵活运用技巧能够有效提升答题效率与准确性。希望每位参与者都能从中受益匪浅!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值