算法题解【传智杯】

A:

题解:

签到题。首先用 if语句判断 b 的符号,然后加在 a 的绝对值上即可。

  • 在函数里有个处理浮点数用的函数 copysign(a,b) 。当然浮点数要复杂得多,比如会有 Infinity、NaN这类奇怪的玩意,以及还有 −0这种特殊的东西。本题限定在了整数。
  • 题目的坑点:注意到,32 位有符号整型的范围是 −2^31∼(2^31—1),那么当 −2^31 取绝对值时就会超过 int的范围。可以特判/使用范围更大的数据类型。

JAVA版:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextLong(), b = scanner.nextLong();
        System.out.println((Math.abs(a) * (b > 0 ? 1 : -1)));
    }
}

B:

按照题目要求输入整数a,b,模拟这个奇怪的进位规则即可。

  • 出题的灵感?最近有一场CF就考到了第i位是i进制的题(当然并没有显式地告诉你算这东西的和,而是要证明一一个小结论) , 但是这题偏难了于是就改成了这样。
  • 题目的坑点?主要是细节部分。例如0+0= 0这个0也是有1的长度的,以及要考虑进位后总位数达到了max(n,m) + 1。

时间复杂度位 O(n+m)

 

JAVA版: 

import java.util.Scanner;

public class Main {

    public static int[] a = new int[200005];
    public static int[] b = new int[200005];
    public static int[] c = new int[200005];

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(), m = scanner.nextInt();
        int maxLength = Math.max(n, m);
        for (int i = (maxLength - n) + 1; i <= maxLength; ++i)
            a[i] = scanner.nextInt();
        for (int i = (maxLength - m) + 1; i <= maxLength; ++i)
            b[i] = scanner.nextInt();
        for (int i = maxLength, cnt = 2; i > 0; --i, ++cnt) {
            c[i] += a[i] + b[i];
            if (c[i] >= cnt) {
                c[i] -= cnt;
                c[i - 1] += 1;
            }
        }
        if (c[0] > 0) {
            System.out.printf("%d ", c[0]);
        }
        for (int i = 1; i <= maxLength; ++i) {
            System.out.printf("%d ", c[i]);
        }
        System.out.println();
    }
}

 


C:

 

暴风吸入输入数据里给定的所有字符,存到数组里,统计有多少个换行符,确定输入文件的总行数 m。由此计算出最后一个行号的长度 s=⌊lgm+1⌋

对于第 i 行,

  • 计算出 i 的长度 t=⌊lgi+1⌋。
  • 输出 s−t 个空格,再输出 i,然后输出 1 个空格。
  • 从第 i−1 个换行的位置开始,一直到第 i 个换行,把中间的字符全部输出。这样第 i 行就做完了。

时间复杂度为 O(∣S∣),其中 ∣S∣ 是输入的所有字符的个数。

JAVA代码:

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

public class Main {

    public static List list = new ArrayList<>();

    public static int getBit(int x) {
        int cnt = 0;
        while (x > 0) {
            x /= 10;
            ++cnt;
        }
        return cnt;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            list.add(scanner.nextLine());
        }
        int size = list.size();
        int len = getBit(size);
        for (int i = 0; i < size; ++i) {
            System.out.printf("%" + len + "d %s\n", i + 1, list.get(i));
        }
    }
}

 

你可能感兴趣的:(java,开发语言)