PAT

PAT


1.A+B Format

格式化输出A+B的结果

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

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
	    int a = scanner.nextInt();
	    int b = scanner.nextInt();
	    scanner.close();
      
    int c,d = 0;
        c = a + b;
       
        if(c<0){
            c = -c;
            System.out.print("-");
        }
        String c1 = String.valueOf(c);
        int count = 0;
        String sum = "";
        for(int i=c1.length()-1;i>=0;i--){
            sum = c1.charAt(i) + sum;
            count++;
            if(count%3==0&&i!=0){
                sum = "," + sum;
            }
        }
        System.out.println(sum);
       
    }
}

字符串的拼接是依次的,因此在sum=s[i]+sum; //i递减时// 可以保证sum与原s[]相同

import java.util.Scanner;
 
public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
	    int a = scanner.nextInt();
	    int b = scanner.nextInt();
	    scanner.close();
	    int sum = a + b;
	    if(sum < 0) {
	    	System.out.print("-");
	    	sum = 0 - sum;
	    }
	    if(sum >= 1000000) {
	    	System.out.printf("%d,%03d,%03d",sum/1000000,sum%1000000/1000,sum%1000);
	    }else if(sum >= 1000) {
	    	System.out.printf("%d,%03d", sum/1000,sum%1000);
	    }else {
	    	System.out.println(sum);
	    }
	}
}

格式化输出:"%xd"中x即为要保留的位数

`if(sum >= 1000000) {
	    	System.out.printf("%d,%03d,%03d",sum/1000000,sum%1000000/1000,sum%1000);
	    }else if(sum >= 1000) {
	    	System.out.printf("%d,%03d", sum/1000,sum%1000);
	    }else {
	    	System.out.println(sum);
	    }`

注意取余用法

import java.util.Scanner;
 
public class Main {
	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
	    int a = scanner.nextInt();
	    int b = scanner.nextInt();
	    scanner.close();
	    int sum = a + b;
	    if(sum < 0) {
	    	System.out.print("-");
	    	sum = 0 - sum;
	    }
	    String sumStr = String.valueOf(sum);
	    int length = sumStr.length();
	    StringBuffer stringBuffer;
	    if(length <= 3) {
	    	System.out.println(sumStr);
	    } else if(length <= 6) {
	    	stringBuffer = new StringBuffer(sumStr);
	    	stringBuffer.insert(length - 3, ",");
	    	System.out.println(stringBuffer.toString());
	    } else {
	    	stringBuffer = new StringBuffer(sumStr);
	    	stringBuffer.insert(length - 3, ",");
	    	stringBuffer.insert(length - 6, ",");
	    	System.out.println(stringBuffer.toString());
	    }
	}
}

StringBuffer:线程安全的可变字符序列。StringBuffer 上的主要操作是 append 和 insert 方法。可变使其内容、长度可以容易改变。
StringBuilder:线程不安全。

2.A+B for Polynomials

将两个降序排列的多项式(指数只能是整数)相加
在这里插入图片描述

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    String[] A = s.nextLine().trim().split(" ");
    String[] B = s.nextLine().trim().split(" ");
    s.close();
    Map<Integer, Double> map = new HashMap<>();

    int k1 =Integer.parseInt(A[0]);  
    int k2 =Integer.parseInt(B[0]);

    for(int i=1; i<k1*2+1; i +=2)
      map.put(Integer.valueOf(A[i]), Double.valueOf(A[i+1]));

    for (int i = 1; i < k2 * 2 + 1; i += 2) {
      int key = Integer.valueOf(B[i]);
      double value = Double.valueOf(B[i + 1]);

      if (map.containsKey(key)) {
        value += map.get(key);
        if (Math.abs(value) <= 0.00001) {
          map.remove(key);
        } else {
          value = Math.round(value * 10) / 10.0;
          map.put(key, value);
        }
      } else {
        value = Math.round(value * 10) / 10.0;
        map.put(key, value);
      }
    }
    Set<Integer> set = map.keySet();
    List<Integer> list = new ArrayList<Integer>();
    for(int i : set) list.add(i);
    Collections.sort(list);
    Collections.reverse(list);
    System.out.print(list.size());
    for(int i=0; i<list.size(); i++) {
      int j = list.get(i);
      System.out.print(" " + j + " " + map.get(j));
    }
  }
}

Map相关:
Map< keytype, valuetype> map = new HashMap<>();
map.put(key,value);
valuetype value=map.get(key);
boolean b=map.containsKey(key);
map.remove(key);
Set< valuetype > set=map.keySet();

List相关:
List< valuetype > list=new ArrayList<>();
list.add(value);
Collections.sort(list);
Collections.reverse(list);
list.get(position);

保留一位小数:value=Math.round(value*10)/10.0;
浮点数之间/与0之间不能直接判断是否相等,可以作差与误差比较,如
if (Math.abs(float1-float2)<error);//其中error=Math.pow(10, -8);

#define err 1e-7
#include <math.h>
#include <stdio.h>
int main() {
    double a[1001] = {0.0};
    int count = 0, max = 0, min = 0;
    int k;
    double tempA;
    int tempN;
    
    // 读入第一个多项式并存储
    scanf("%d", &k);
    for(int i = 0; i < k; i++){
        scanf("%d %lf", &tempN, &tempA);
        if(i == 0) max = tempN;
        if(i == k - 1) min = tempN;
        a[tempN] = tempA;
    }
    // 一开始有k项
    count = k;
    
    // 读入第二个多项式的同时直接计算
    scanf("%d", &k);
    for(int i = 0; i < k; i++){
        scanf("%d %lf", &tempN, &tempA);
        // 原来没有这一项,增加后就会多一项
        if(fabs(a[tempN]) < err){
            count++;
            if(tempN > max) max = tempN;
            else if(tempN < min) min = tempN;
        }
        a[tempN] += tempA;
        
        // 计算结果趋近于0,减少一项
        if(fabs(a[tempN]) < err){
            count--;
        }
    }
    
    // 输出K
    printf("%d", count);
    
    // 输出N和an
    for(int i = max; i >= min; i--){
        if(fabs(a[i]) > err){
            printf(" %d %.1f", i, a[i]);
        }
    }
    return 0;
}

3.Emergency

找图中两点间最短路径的个数,以及最短路径中最大顶点权值和
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

import java.util.*;    
public class Main{    
    static int n = 0;
    static int m = 0;
    static int c1 = 0;
    static int c2 = 0;
    static int[][] map = new int[505][505];
    static int[] weight = new int[505];
    static int[] dist = new int[505];
    static boolean[] visit = new boolean[505];
    static int[] num = new int[505];
    static int[] w = new int[505];
    static final int inf = 9999999;
    public static void main(String[] args){  
        Arrays.fill(dist, inf);
        int i = 0, j = 0, k = 0;
        for(i=0;i<505;i++) {
            Arrays.fill(map[i], inf);
        }
        Scanner cin = new Scanner(System.in);
        n = cin.nextInt();
        m = cin.nextInt();
        c1 = cin.nextInt();
        c2 = cin.nextInt();
        for(i=0;i<n;i++) {
            weight[i] = cin.nextInt();
        }
        for(i=0;i<m;i++) {
            int x = cin.nextInt();
            int y = cin.nextInt();
            int z = cin.nextInt();
            map[x][y] = map[y][x] = z;
        }
        dist[c1] = 0;
        w[c1] = weight[c1];
        num[c1] = 1;
        while(true) {
            int index = -1, min = inf;
            for(j=0;j<n;j++) {
                if(visit[j] == false && dist[j] < min) {
                    min = dist[j];
                    index = j;
                }
            }
            if(index == -1) break;
            visit[index] = true;
            for(k=0;k<n;k++) {
                if(visit[k] == false && map[index][k] != inf) {
                    if(dist[index] + map[index][k] < dist[k]) {
                        dist[k] = dist[index] + map[index][k];
                        num[k] = num[index];
                        w[k] = w[index] + weight[k];
                    }
                    else if(dist[index] + map[index][k] == dist[k]) {
                        num[k] = num[k] + num[index];
                        if(w[index] + weight[k] > w[k]) {
                            w[k] = w[index] + weight[k];
                        }
                    }
                }
            }
        }
        System.out.printf("%d %d",num[c2], w[c2]);
    }  
} 

用图的思想,但不一定要用到图类,既然只有一个图对象,那么不创建类而直接使用图中的变量更为方便。
要理解迪杰斯特拉算法,其中的dist[k]以及本代码中的num[k]和w[k]都是累加而来的。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值