PAT (Advanced Level) Practice Problem 1001-1005 solution to a problem (Java implementation)

Do questions Notes

  1. The class name must to Main
  2. Enter questions about Scanner class, Scanner.nextInt () method can only receive a positive integer, such as negative integer input will be ignored out of a negative number, which is equivalent to the input taken abs (), in order to solve this Bug, by
int num1 = Integer.parseInt(scanner.next());

solve.

next () and nextLine () receives string;
next () method must be a valid character string can only be received by an input end of the spacebar encountered before entering a valid character, Tab key or the enter key, next () the method will automatically be removed only after you enter a valid character, spacebar next () method before the subsequent input, Tab or enter key as a separator or terminator;
terminator nextLine () method simply return car key, nextLine () method returns all the characters enter key.

1001 A + B Format (20 minutes)

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

(This code is learn from our predecessors)

#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))); 
		}
	}
}

Do question reflection

  1. After doing five questions, or find ACM Java do have quite a big limitations, or after it in C ++. I was a chicken dish.
  2. All code in my Github PAT warehouse https://github.com/inspurer/PAT welcome onlookers.
Published 84 original articles · won praise 250 · Views 150,000 +

Guess you like

Origin blog.csdn.net/ygdxt/article/details/89150460