PAT (Advanced Level) Practice Problem 1001-1005 题解(Java 实现)

6 篇文章 0 订阅
4 篇文章 0 订阅

做题注意事项

  1. 类名必须为 Main
  2. 有关 Scanner 类的输入问题,Scanner.nextInt() 方法只能接收正整数,如输入负整数则会忽略掉掉负号,相当于对输入取 abs() ,要想解决这个 Bug,可以通过
int num1 = Integer.parseInt(scanner.next());

解决。

next() 和 nextLine() 都接收字符串;
next() 方法一定要接收到有效字符串才可以结束输入,对输入有效字符之前遇到的空格键、Tab 键或回车键等,next() 方法会自动将其去掉,只有在输入有效字符之后,next() 方法才将其后输入的空格键、Tab 键或回车键视为分隔符或结束符;
nextLine() 方法的结束符只是回车键,即 nextLine() 方法返回的是回车键的所有字符。

1001 A+B Format (20分)

Calculate a+b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

Input Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −10​6​​≤a,b≤10​6​​. The numbers are separated by a space.

Output Specification:

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input:

-1000000 9

Sample Output:

-999,991

Solution

import java.util.LinkedList;
import java.util.Scanner;

//CreateTime: 2019/3/21 23:21
//Author:     月小水长(https://github.com/inspurer/PAT)
/*
	类名:首字母大写,其他单词中首字母大写,其他小写
	方法名:首字母小写,其他单词中首字母大写,其他小写
	变量:与方法名规则同
	包名:全部小写
*/
public class Main {
	public static void main(String [] args){
		Scanner scanner = new Scanner(System.in);
		int num1 = Integer.parseInt(scanner.next());
		int num2 = Integer.parseInt(scanner.next());
		scanner.close();
		num1 += num2;
		int flag = num1>=0?1:0;
		num1 = num1>0?num1:-num1;
		if(String.valueOf(num1).length()<4) {
			if (flag == 0) {
				System.out.print(-num1);
			} else {
				System.out.print(num1);
			}
			return;
		}
		LinkedList<String> result = new LinkedList<String>();
		do{
			result.add(String.valueOf(num1%10));
			num1 /= 10;
			if((result.size()+1)%4==0&&num1>0){
				result.add(",");
			}
		}while (num1>0);
		if(flag==0){
			result.add("-");
		}
		for(int i = result.size()-1;i>=0;i--)
			System.out.print(result.get(i));
	}
}

1002 A+B for Polynomials (25 分)

This time, you are supposed to find A+B where A and B are two polynomials.

Input Specification:

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:

K N​1​​ a​N​1​​​​ N​2​​ a​N​2​​​​ … N​K​​ a​N​K​​​​

where K is the number of nonzero terms in the polynomial, N​i​​ and a​N​i​​​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤N​K​​<⋯<N​2​​<N​1​​≤1000.

Output Specification:

For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.

Sample Input:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:

3 2 1.5 1 2.9 0 3.2

Solution

import java.util.*;

//CreateTime: 2019/3/21 23:21
//Author:     月小水长(https://github.com/inspurer/PAT)
/*
	类名:首字母大写,其他单词中首字母大写,其他小写
	方法名:首字母小写,其他单词中首字母大写,其他小写
	变量:与方法名规则同
	包名:全部小写
*/
public class Main {
	public static void main(String [] args){
		Scanner sc = new Scanner(System.in);
		String aLine = null;
		String [] l = null;
		HashMap<Integer,Float> [] hm = new HashMap[2];
		for(int i = 0; i < 2; i++){
			aLine = sc.nextLine();
			l = aLine.split(" ");
			hm[i] = new HashMap<Integer, Float>(Integer.parseInt(l[0]));
			for(int j = 1; j < l.length; j += 2){
				hm[i].put(Integer.parseInt(l[j]),Float.parseFloat(l[j+1]));
			}
		}
		sc.close();
		HashSet<Integer> setKeys = new HashSet<>(hm[0].keySet());
		setKeys.addAll(hm[1].keySet());
		ArrayList<Integer> sumKeys = new ArrayList<>(setKeys);
		HashMap<Integer,Float> res = new HashMap<Integer,Float>();
		// 排除掉系数为 0
		for(int i = 0; i < sumKeys.size(); i++){
			int key = sumKeys.get(i);
			float value = hm[0].getOrDefault(key,0.0f)+hm[1].getOrDefault(key,0.0f);
			if(value == 0.0f)
				continue;
			res.put(key,value);
		}
		ArrayList resultKeys = new ArrayList(res.keySet());
		Collections.sort(resultKeys, new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				return o2 - o1;
			}
		});
		// 如果项数为0,只把0输出就可以了
		if(res.size() == 0) {
			System.out.print(0);
			return;
		}
		System.out.print(res.size());
		System.out.print(" ");
		for(int i = 0; i < resultKeys.size(); i++){
			int key = (int)resultKeys.get(i);
			System.out.print(key);
			System.out.print(" ");
			System.out.printf("%.1f",res.get(key));
			if(i == resultKeys.size() - 1)
				break;
			System.out.print(" ");
		}
	}
}
/*
	格式错误,要求跟输入一样,浮点数保留一位小数,最后不能有空格
	没有考虑到如果两个多项式相加,会出现系数为0的情况,此时不再记录(多虑的是demo分明有0输出了么,但是它是指数不是系数)
	数据的类型,一定尽量开始就合适
*/

1003 Emergency (25 分)

As an emergency rescue team leader of a city, you are given a special map of your country. The map shows several scattered cities connected by some roads. Amount of rescue teams in each city and the length of each road between any pair of cities are marked on the map. When there is an emergency call to you from some other city, your job is to lead your men to the place as quickly as possible, and at the mean time, call up as many hands on the way as possible.

Input Specification:

Each input file contains one test case. For each test case, the first line contains 4 positive integers: N (≤500) - the number of cities (and the cities are numbered from 0 to N−1), M - the number of roads, C​1​​ and C​2​​ - the cities that you are currently in and that you must save, respectively. The next line contains N integers, where the i-th integer is the number of rescue teams in the i-th city. Then M lines follow, each describes a road with three integers c​1​​, c​2​​ and L, which are the pair of cities connected by a road and the length of that road, respectively. It is guaranteed that there exists at least one path from C​1​​ to C​2​​.

Output Specification:

For each test case, print in one line two numbers: the number of different shortest paths between C​1​​ and C​2​​, and the maximum amount of rescue teams you can possibly gather. All the numbers in a line must be separated by exactly one space, and there is no extra space allowed at the end of a line.

Sample Input:

5 6 0 2
1 2 1 5 3
0 1 1
0 2 2
0 3 1
1 2 1
2 4 1
3 4 1

Sample Output:

2 4

Solution

import java.util.*;

//CreateTime: 2019/3/21 23:21
//Author:     月小水长(https://github.com/inspurer)
/*
	类名:首字母大写,其他单词中首字母大写,其他小写
	方法名:首字母小写,其他单词中首字母大写,其他小写
	变量:与方法名规则同
	包名:全部小写
*/
public class Main {
	public static void main(String [] args){
		int maxPathLength = 66666666;
		Scanner sc = new Scanner(System.in);
		int numOfCities = sc.nextInt();
		int numOfRoads = sc.nextInt();
		int C1 = sc.nextInt();
		int C2 = sc.nextInt();
		// 城市 i 的救援队数
		int [] numOfRescue = new int[numOfCities];
		int [][] roads = new int [numOfCities][numOfCities];
		for(int i = 0; i < numOfCities; i++){
			numOfRescue[i] = sc.nextInt();
		}
		//构建无向图
		for(int i = 0; i < numOfCities; i++)
			for(int j = 0; j < numOfCities; j++)
				roads[i][j] = maxPathLength;

		int start,stop,value;
		for(int i = 0; i < numOfRoads; i++){
			start = sc.nextInt();
			stop = sc.nextInt();
			value = sc.nextInt();
			roads[start][stop] = value;
			roads[stop][start] = value;
		}

		// 标记城市 i 是否被访问过
		Boolean [] visited = new Boolean[numOfCities];
		for(int i = 0; i < numOfCities; i++){
			visited[i] = false;
		}

		// 到城市 i 的最短路径长度
		int [] lengthOfShortestPath = new int[numOfCities];
		for(int i = 0; i < numOfCities; i++){
			lengthOfShortestPath[i] = maxPathLength;
		}

		// 到城市 i 的最短路径条数
		int [] numOfShortestPath = new int[numOfCities];
		for(int i = 0; i < numOfCities; i++){
			numOfShortestPath[i] = 0;
		}

		// 到城市 i 的总救援队数
		int [] numOfTotalRescue = new int[numOfCities];
		for(int i = 0; i < numOfCities; i++){
			numOfTotalRescue[i] = 0;
		}

//        visited[C1] = true;
		lengthOfShortestPath[C1] = 0;
		numOfShortestPath[C1] = 1;
		numOfTotalRescue[C1] = numOfRescue[C1];

		for(int i = 0; i < numOfCities; i++){
			int min = maxPathLength;
			int u = -1;
			for(int j = 0; j < numOfCities; j++){
				if(!visited[j]&&lengthOfShortestPath[j]<min){
					min = lengthOfShortestPath[j];
					u = j;
				}
			}
			if(u == -1){
				break;
			}
			visited[u] = true;
			for(int k = 0; k < numOfCities; k++){
				if(!visited[k]&&roads[u][k]!=maxPathLength){
					if(lengthOfShortestPath[k] > lengthOfShortestPath[u] + roads[u][k]){
						lengthOfShortestPath[k] = lengthOfShortestPath[u] + roads[u][k];
						numOfShortestPath[k] = numOfShortestPath[u];
						numOfTotalRescue[k] = numOfTotalRescue[u] + numOfRescue[k];
					}
					else if(lengthOfShortestPath[k] == lengthOfShortestPath[u] + roads[u][k]){
						numOfShortestPath[k] += numOfShortestPath[u];
						if(numOfTotalRescue[u] + numOfRescue[k] > numOfTotalRescue[k]){
							numOfTotalRescue[k] = numOfTotalRescue[u] + numOfRescue[k];
						}
					}
				}
			}
		}

		System.out.printf("%d %d",numOfShortestPath[C2],numOfTotalRescue[C2]);
	}
}

1004 Counting Leaves (30 分)

A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 0<N<100, the number of nodes in a tree, and M (<N), the number of non-leaf nodes. Then M lines follow, each in the format:

ID K ID[1] ID[2] … ID[K]

where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID’s of its children. For the sake of simplicity, let us fix the root ID to be 01.

The input ends with N being 0. That case must NOT be processed.

Output Specification:

For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.

The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output 0 1 in a line.

Sample Input:

2 1
01 1 02

Sample Output:

0 1

Solution

( 这个代码是借鉴前人的)

#include <vector>
#include<stdio.h>
#include <algorithm>
using namespace std;
vector<int> v[100];
int book[100], maxdepth = -1;
void dfs(int index, int depth) {
	if(v[index].size() == 0) {
		book[depth]++;
		maxdepth = max(maxdepth, depth);
		return ;
	}
	for(int i = 0; i < v[index].size(); i++)
		dfs(v[index][i], depth + 1);
}
int main() {
	int n, m, k, node, c;
	scanf("%d %d", &n, &m);
	for(int i = 0; i < m; i++) {
		scanf("%d %d",&node, &k);
		for(int j = 0; j < k; j++) {
			scanf("%d", &c);
			v[node].push_back(c);
		}
	}
	dfs(1, 0);
	printf("%d", book[0]);
	for(int i = 1; i <= maxdepth; i++)
		printf(" %d", book[i]);
	return 0;
}

1005 Spell It Right (20 分)

Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.

Input Specification:

Each input file contains one test case. Each case occupies one line which contains an N (≤10​100​​).

Output Specification:

For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.
Sample Input:

12345

Sample Output:

one five

Solution

import java.util.HashMap;
import java.util.Scanner;

//CreateTime: 2019/3/21 23:21
//Author:     月小水长(https://github.com/inspurer)
/*
	类名:首字母大写,其他单词中首字母大写,其他小写
	方法名:首字母小写,其他单词中首字母大写,其他小写
	变量:与方法名规则同
	包名:全部小写
*/
public class Main {
	public static void main(String [] args){
		Scanner scanner = new Scanner(System.in);
		String input = scanner.next();
		scanner.close();
		int count = 0;
		for(int i = 0; i < input.length(); i++){
			count += Integer.parseInt(input.substring(i,i+1));
		}
		HashMap<String,String> hm = new HashMap<String, String>();
		hm.put("0","zero");
		hm.put("1","one");
		hm.put("2","two");
		hm.put("3","three");
		hm.put("4","four");
		hm.put("5","five");
		hm.put("6","six");
		hm.put("7","seven");
		hm.put("8","eight");
		hm.put("9","nine");
		String res = String.valueOf(count);
		System.out.printf("%s",hm.get(res.substring(0,1)));
		for(int i = 1; i < res.length(); i++){
			System.out.printf(" %s",hm.get(res.substring(i,i+1))); 
		}
	}
}

做题反思

  1. 做了5题后,还是发现 Java 做 ACM 有蛮大局限性的,以后还是用 C++ 吧。我真是个菜鸡。
  2. 所有的代码在我的 Github PAT仓库 https://github.com/inspurer/PAT 欢迎围观。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

月小水长

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

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

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

打赏作者

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

抵扣说明:

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

余额充值