1053. Path of Equal Weight (30)

本文针对PAT-A 1053题提供了解题思路与代码实现,通过深度优先搜索算法寻找所有可能的路径组合,以解决特定数值目标的问题。

考察链表,排序,以及深度搜索

题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1053

#include<iostream>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stack>
#include <string>
#include <string.h>
#include <algorithm>
using namespace std;

int N, M, T;
typedef struct Node
{
	int key;
	vector<Node*> vNext;
}Node;
vector<int> possibleSolution;
bool cmp(Node* a, Node* b)
{
	return a->key > b->key;
}
void DFS(Node* curNode, int cur)
{
	cur += curNode->key;
	if (curNode->vNext.size() == 0)//leaf and find
	{
		if (cur == T)
		{
			for (int i = 0; i < possibleSolution.size(); ++i)
			{
				if(i != possibleSolution.size()-1)
					printf("%d ", possibleSolution[i]);
				else printf("%d\n", possibleSolution[i]);
			}
		}
		return;
	}
	else if (curNode->vNext.size() > 0)
	{
		if (cur > T)
			return;
		else
		{
			sort(curNode->vNext.begin(), curNode->vNext.end(), cmp);
			for (int i = 0; i < curNode->vNext.size(); ++i)
			{
				possibleSolution.push_back(curNode->vNext[i]->key);
				DFS(curNode->vNext[i], cur);
				possibleSolution.pop_back();
			}
		}
	}
}
int main()
{
	scanf("%d%d%d",&N,&M,&T);
	vector<int> weight(N);
	for (int i = 0; i < N; ++i)
		scanf("%d",&weight[i]);
	vector<Node*> nodeMap(N);
	//initial
	for (int i = 0; i < N; ++i)
	{
		nodeMap[i] = new Node;
		nodeMap[i]->key = weight[i];
	}
	//add child
	for (int i = 0; i < M; ++i)
	{
		int id; int C;
		scanf("%d%d",&id, &C);
		for (int j = 0; j < C; ++j)
		{
			int child;
			scanf("%d",&child);
			if (id >= 0 && id < N && child >= 0 && child < N)
				nodeMap[id]->vNext.push_back(nodeMap[child]);
		}
	}
	//dfs find all possible path and output
	possibleSolution.push_back(nodeMap[0]->key);
	int cur = 0;
	DFS(nodeMap[0], cur);
	//release memory
	for (int i = 0; i < N; ++i)
		delete nodeMap[i];

	return 0;
}


 

其他的文件创建完了,给我一下DeviceListNewViewController完整代码 import UIKit import SnapKit // MARK: - DeviceListNewViewController class DeviceListNewViewController: SurveillanceCommonTableController, SelectOrganizationViewDelegate { // MARK: - 属性 private lazy var titleView: NewTitleView = { let view = NewTitleView() view.titleText = "设备列表" view.didClickCallback = { [weak self] _ in guard let self = self else { return } let selectOrgView = self.selectOrganizationView let titleView = self.titleView if titleView.isAnimating { return } if !titleView.isInExpandStatus { titleView.isAnimating = true self.view.addSubview(selectOrgView) selectOrgView.show(animated: true) { titleView.isAnimating = false } } else { titleView.isAnimating = true self.hideLoadingView() selectOrgView.dismiss(animated: true) { titleView.isAnimating = false } } // 更新箭头状态 titleView.changeToStatus(expand: !titleView.isInExpandStatus) } return view }() private lazy var multiScreenButton: UIButton = { let btn = UIButton(type: .custom) btn.imgUri = "media_player_switch_multi_live" btn.setTitleColor(.blue, for: .normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: 16) btn.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) btn.addTarget(self, action: #selector(clickMultileLive), for: .touchUpInside) return btn }() var selectedTabType: DeviceListMasterSelectedType = .all { didSet { UserDefaults.standard.deviceListSelectedType = selectedTabType } } var selectedSiteInfo: TPSSVMSSubsiteInfo? { didSet { saveSelectedSiteInfo(selectedSiteInfo) } } private func saveSelectedSiteInfo(_ info: TPSSVMSSubsiteInfo?) { guard let siteInfo = info else { try? FileManager.default.removeItem(at: URL(fileURLWithPath: DeviceListMasterViewController.getDocumentsPath(path: DeviceListMasterViewController.kSelectedSiteFileName) ?? "")) return } do { let data = try NSKeyedArchiver.archivedData(withRootObject: siteInfo, requiringSecureCoding: true) try data.write(to: URL(fileURLWithPath: DeviceListMasterViewController.getDocumentsPath(path: DeviceListMasterViewController.kSelectedSiteFileName) ?? "")) } catch { print(error) } } private lazy var selectOrganizationView: SelectOrganizationView = { let view = SelectOrganizationView() view.rootViewController = self view.delegate = self view.frame = CGRect( x: 0, y: SelectOrganizationView.statusBarHeight + SelectOrganizationView.navigationBarHeight, width: screenWidth, height: screenHeight - SelectOrganizationView.statusBarHeight - SelectOrganizationView.navigationBarHeight ) return view }() // MARK: - 生命周期 override func viewDidLoad() { super.viewDidLoad() setNavigation() // 内容适配 tableView.contentInsetAdjustmentBehavior = .automatic reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: false) } // MARK: - 子视图与约束 override func tpbSetupSubviews() { super.tpbSetupSubviews() } override func tpbMakeConstraint() { tableView.snp.remakeConstraints { make in make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top) make.leading.trailing.equalToSuperview() make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom) } } // MARK: - 创建 UI 组件 private func setNavigation(){ // 设置自定义标题视图 navigationItem.titleView = titleView // 设置 titleView 最大宽度 let maxWidth: CGFloat = 200 titleView.snp.makeConstraints { make in make.width.lessThanOrEqualTo(maxWidth) make.height.equalTo(44) } // 添加按钮 let backButtonItem = self.tpbCreateLeftBarButtonItem(with: TPImageLiteral("common_light_back_nor"), andTarget: self, andAction: #selector(jumpToXXX)) let centralButtonItem = self.tpbCreateLeftBarButtonItem(with: TPImageLiteral("central_surveillance_button"), andTarget: self, andAction: #selector(centralButtonClicked)) let messageButtonItem = self.tpbCreateLeftBarButtonItem(with: TPImageLiteral("tabbar_message_nor"), andTarget: self, andAction: #selector(onMessageButtonTapped)) // 左侧按钮 navigationItem.leftBarButtonItems = [backButtonItem, centralButtonItem] // 右侧按钮 navigationItem.rightBarButtonItem = messageButtonItem } // MARK: - 创建组件:设备数量视图 private func createDeviceCountView() -> UIView { let containerView = UIView() containerView.backgroundColor = .tpbCard containerView.layer.cornerRadius = 4 containerView.clipsToBounds = true let labels = ["NVR", "4K", "2K", "HD"] var categoryViews: [UIView] = [] for text in labels { let categoryView = UIView() categoryView.backgroundColor = UIColor(white: 0.93, alpha: 1.0) categoryView.layer.cornerRadius = 8 categoryView.clipsToBounds = true let label = UILabel() label.text = text label.textColor = UIColor.tpbTextPrimary label.font = UIFont.systemFont(ofSize: 15, weight: .semibold) label.textAlignment = .center categoryView.addSubview(label) label.snp.makeConstraints { make in make.edges.equalToSuperview().inset(10) } containerView.addSubview(categoryView) categoryViews.append(categoryView) } for (index, view) in categoryViews.enumerated() { view.snp.makeConstraints { make in make.height.equalTo(60) make.centerY.equalTo(containerView) if index == 0 { make.leading.equalTo(containerView).offset(20) } else { make.leading.equalTo(categoryViews[index - 1].snp.trailing).offset(16) make.width.equalTo(categoryViews[0]) } if index == labels.count - 1 { make.trailing.equalTo(containerView).offset(-20) } } } return containerView } // MARK: - 创建组件:存储空间视图 private func createStorageUsageView() -> UIView { let containerView = UIView() containerView.backgroundColor = .tpbCard containerView.layer.cornerRadius = 8 containerView.clipsToBounds = true let titleLabel = UILabel() titleLabel.text = "存储空间" titleLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium) titleLabel.textColor = .tpbTextPrimary containerView.addSubview(titleLabel) let progressView = UIProgressView(progressViewStyle: .default) progressView.progressTintColor = UIColor.systemBlue progressView.trackTintColor = UIColor(white: 0.9, alpha: 1.0) containerView.addSubview(progressView) let detailLabel = UILabel() detailLabel.font = UIFont.systemFont(ofSize: 13, weight: .regular) detailLabel.textColor = .tpbTextPrimary detailLabel.textAlignment = .center containerView.addSubview(detailLabel) let used = 1.2 let total = 5.0 let percent = Float(used / total) progressView.setProgress(percent, animated: false) let percentage = Int(percent * 100) detailLabel.text = String(format: "%.1f TB / %.1f TB (%d%%)", used, total, percentage) titleLabel.snp.makeConstraints { make in make.top.leading.equalTo(containerView).offset(16) } progressView.snp.makeConstraints { make in make.centerX.centerY.equalTo(containerView) make.width.equalTo(200) make.height.equalTo(6) } detailLabel.snp.makeConstraints { make in make.top.equalTo(progressView.snp.bottom).offset(8) make.centerX.equalTo(progressView) } return containerView } // MARK: - 创建组件:仅返回设备列表的 Cell 模型数组 private func createDeviceListCells() -> [TPBBaseTableCellModel] { let itemCount = 10 let itemHeight: CGFloat = 130 let lineSpacing: CGFloat = 10 let totalHeight = itemHeight * CGFloat(itemCount) + lineSpacing * max(0, CGFloat(itemCount - 1)) let containerView = UIView() containerView.backgroundColor = .tpbCard let paddedView = UIView() paddedView.backgroundColor = .tpbCard paddedView.layer.cornerRadius = 3 paddedView.clipsToBounds = true let deviceListView = DeviceListView(itemCount: itemCount) containerView.addSubview(paddedView) paddedView.addSubview(deviceListView) paddedView.snp.makeConstraints { make in make.edges.equalTo(containerView).inset(UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)) } deviceListView.snp.makeConstraints { make in make.edges.equalTo(paddedView) make.height.equalTo(totalHeight) } let cellModel = TPBBaseTableCellModel.customContent(with: containerView) cellModel.height = TPBTableElementHeight.customHeight(totalHeight) return [cellModel] } // MARK: - 创建组件:多屏按钮作为 Header View private func createMultiScreenHeader() -> UIView { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 44)) headerView.backgroundColor = .clear let container = TPBBaseView() container.backgroundColor = .clear container.layer.cornerRadius = 3 container.clipsToBounds = true headerView.addSubview(container) container.snp.makeConstraints { make in make.trailing.equalTo(headerView).offset(-16) make.centerY.equalTo(headerView) make.size.equalTo(CGSize(width: 44, height: 44)) } // 确保按钮没有被重复添加 multiScreenButton.removeFromSuperview() container.addSubview(multiScreenButton) multiScreenButton.snp.makeConstraints { make in make.edges.equalToSuperview() } return headerView } // MARK: - 创建合并后的 Section(Header + Cell) private func createMergedDeviceSection() -> TPBTableSectionModel { let section = TPBTableSectionModel() section.customHeaderView = createMultiScreenHeader() section.sectionHeaderHeight = TPBTableElementHeight.customHeight(44) section.cellModelArray = createDeviceListCells() return section } // MARK: - 刷新数据 private func reloadData() { var tempSectionArray = [TPBTableSectionModel]() // Section 0: 设备数量 let section0 = TPBTableSectionModel() let deviceCountView = createDeviceCountView() let deviceCountCellModel = TPBBaseTableCellModel.customContent(with: deviceCountView) deviceCountCellModel.height = TPBTableElementHeight.customHeight(100) section0.cellModelArray = [deviceCountCellModel] tempSectionArray.append(section0) // Section 1: 存储空间 let section1 = TPBTableSectionModel() let storageView = createStorageUsageView() let storageCellModel = TPBBaseTableCellModel.customContent(with: storageView) storageCellModel.height = TPBTableElementHeight.customHeight(100) section1.cellModelArray = [storageCellModel] tempSectionArray.append(section1) // Section 2: 合并后的 Section let section2 = createMergedDeviceSection() tempSectionArray.append(section2) sectionArray = tempSectionArray tableView.reloadData() } // MARK: - Actions @objc private func clickMultileLive() { print("Multi-Screen 按钮被点击") } @objc private func jumpToXXX() { print("跳转到【待定】页面") } @objc private func centralButtonClicked() { print("跳转到【中心监控】页面") let centralJumpVC = CentralJumpViewController() let centralJumpNaviVC = BaseNavigationController(rootViewController: centralJumpVC) centralJumpNaviVC.view.frame = self.view.frame centralJumpNaviVC.view.backgroundColor = .clear centralJumpVC.currentSiteId = selectedTabType == .all ? nil : selectedSiteInfo?.siteId centralJumpVC.maskDidClickBlock = { centralJumpNaviVC.view.removeFromSuperview() } UIApplication.shared.keyWindow?.addSubview(centralJumpNaviVC.view) } @objc private func onMessageButtonTapped() { print("消息按钮被点击") } // MARK: - 加载视图控制 func hideLoadingView() { titleView.hideLoadingAnimation() } // MARK: - SelectOrganizationViewDelegate func didSelectOrganization(_ organization: OrganizationModel) { titleView.titleText = organization.name hideLoadingView() reloadData() } func didCancelSelectOrganization() { // 可选处理取消 } }
最新发布
12-06
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值