PAT甲级1053 Path of Equal Weight (JAVA版)

31 篇文章 0 订阅

本题考查

树的深度优先遍历

思路

利用迭代方式实现DFS,并通过函数参数传递路径与路径权值的变化情况。
因为题目要求结果需要排序,将结果存入ArrayList中,并编写一个比较器进行排序。
最开始的一般我直接用String的排序方法,结果有一个用例没通过,分析得知是因为String的排序方法有一些漏洞比如说:“123”、“99”进行比较时,后者要大于前者,因为String是按照字符进行比较的。所以要想进行比较需要将代表顺序的字符串转化为整数进行比较。所以需要自己编写一个比较器。

AC代码

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
	
	static String[] weight;
	static ArrayList<Integer>[] tree;
	static int sum;
	static ArrayList<String> result = new ArrayList<>();
	
	static void dfs() {
		DFS(0,"",0);
	}
	
	static void DFS(int start ,String path,int total) {
		if(total >  sum);
		else {
			ArrayList<Integer> current = tree[start];
			path += String.valueOf(weight[start]) + " ";
			total += Integer.parseInt(weight[start]);
			if(current == null) {
				if(total == sum)
					result.add(path.trim());
			}
			else {
				for(int i = 0 ; i < current.size() ; i++) {
					DFS(current.get(i),path,total);
				}
			}
		}
	}
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		Scanner scaner = new Scanner(System.in);
		int totalNodeNum = scaner.nextInt();
		int nonLeafNodeNum = scaner.nextInt();
		sum = scaner.nextInt();
		scaner.nextLine();
		tree = new ArrayList[totalNodeNum];
		weight = scaner.nextLine().split(" ");
		for(int i = 0 ; i < nonLeafNodeNum ; i++) {
			int index = scaner.nextInt();
			int num = scaner.nextInt();
			ArrayList<Integer> temp = tree[index] = new ArrayList<>();
			for(int j = 0 ; j < num ; j++) {
				temp.add(scaner.nextInt());
			}
		}
		scaner.close();
		dfs();
		Comparator<String> cmp = new newcmp();
		Collections.sort(result,cmp);
		for(String s : result)
			System.out.println(s);		
	}
}

class newcmp implements Comparator<String> {
	@Override
	public int compare(String o1, String o2) {
		String[] temp1 = o1.split(" ");
		String[] temp2 = o2.split(" ");
		int edge = Math.min(temp1.length, temp2.length);
		for(int i = 1 ; i < edge ; i++) {
			if(temp1[i].equals(temp2[i]));
			else {
				int int1 = Integer.parseInt(temp1[i]);
				int int2 = Integer.parseInt(temp2[i]);
				if(int1 > int2) {
					return -1;
				}
				else
					return 1;
			}
		}
		return 0;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值