2020刷题日记

因为要准备保研,所以想刷刷百练上面的题目,同时因为百练上面题目做的人比较少,大多数哦人又是使用c++做的,所以想在网上找到Java的百练答案又比较难,这篇博客即是我的刷题日记,也当作一个Java百练题解吧,想要搜索直接在本博客ctrl+f然后输入题号搜索即可


2020.1.18
我果然还是不甘心当一个five啊,今天开始刷百练的题目

有一说一之前刷过很多leetcode,做百练还是不难,但是百练不像leetcode,不能查看代码执行错误的用例,不能自定义测试用例,这点就很难受。

总结一下Java输入Scanner的几个常用API:

  • nextInt():跳过特殊字符获取下一个整数,但是获取之后cursor会停留在本行,不会跳到下一行
  • next():获取下一个字符串,会自动跳过空格,换行符等特殊字符,cursor可以移动到下一行
  • nextLine():从当前的cursor开始读到换行符,会将cursor放在下一行,如果没有换行符不可以获取字符串。
    2020刷题日记_第1张图片
    执行结果:
    2020刷题日记_第2张图片
    这是因为当读取12的时候,cursor到了12的后面换行符的前面,并没有跳到下一行,二nextLine()从当前cursor读取直到遇到换行符,所以读取了空

1001:Exponentiation

import java.math.BigDecimal;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        while(cin.hasNext()){
            BigDecimal R =  cin.nextBigDecimal();
            int n = cin.nextInt();
            BigDecimal ans = R.pow(n);
            //去掉末尾多余的0
            ans = ans.stripTrailingZeros();
            //不使用科学计数法
            String plain = ans.toPlainString();
            if (plain.startsWith("0.")){
                plain = plain.substring(1);
            }
            System.out.println(plain);
        }
    }
}


2020.1.19

1088:滑雪

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int m = cin.nextInt();
        int n = cin.nextInt();
        int[][] hights = new int[m][n];
        for (int i = 0;i < m;i++){
            for (int j = 0;j < n;j++){
                hights[i][j] = cin.nextInt();
            }
        }

        System.out.println(maxLength(hights,m,n));
    }

    static int maxLength(int[][] hights,int m,int n){
        int[][] lengths = new int[m][n];
        int max = 0;
        for (int i = 0;i < m;i++){
            for (int j = 0;j < n;j++){
                if (lengths[i][j] == 0){
                    lengths[i][j] = length(hights,lengths,i,j,m,n);
                    max = Math.max(max,lengths[i][j]);
                }
            }
        }
        return max;
    }

    static int length(int[][] hights,int[][] lengths,int i,int j,int m,int n){
        int length = 1;
        if (i > 0 && hights[i][j] > hights[i - 1][j]){
            if (lengths[i - 1][j] == 0){
                lengths[i - 1][j] = length(hights,lengths,i - 1,j,m,n);
            }
            length = Math.max(length,lengths[i - 1][j] + 1);
        }

        if (i < m - 1 && hights[i][j] > hights[i + 1][j]){
            if (lengths[i + 1][j] == 0){
                lengths[i + 1][j] = length(hights,lengths,i + 1,j,m,n);
            }
            length = Math.max(length,lengths[i + 1][j] + 1);
        }

        if (j > 0 && hights[i][j] > hights[i][j - 1]){
            if (lengths[i][j - 1] == 0){
                lengths[i][j - 1] = length(hights, lengths, i, j - 1, m, n);
            }
            length = Math.max(length,lengths[i][j - 1] + 1);
        }

        if (j < n - 1 && hights[i][j] > hights[i][j + 1]){
            if (lengths[i][j + 1] == 0){
                lengths[i][j + 1] = length(hights, lengths, i, j + 1, m, n);
            }
            length = Math.max(length,lengths[i][j + 1] + 1);
        }

        lengths[i][j] = length;
        return length;
    }


}

1007:DNA排序

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        int m = cin.nextInt();
        cin.nextLine();
        List<String> DNAs = new LinkedList<>();
        for (int i = 0;i < m;i++){
            DNAs.add(cin.nextLine());
        }

        Collections.sort(DNAs, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return nums(o1) - nums(o2);
            }
        });

        for (String DNA:DNAs){
            System.out.println(DNA);
        }
    }

    static int nums(String DNA){
        char[] chars = DNA.toCharArray();
        int numa = 0;
        int numc = 0;
        int numg = 0;
        int numt = 0;
        int len = DNA.length();
        for (char ch:chars){
            if (ch == 'A'){
                numa++;
            } else if (ch == 'C'){
                numc++;
            } else if (ch == 'G'){
                numg++;
            } else {
                numt++;
            }
        }

        int sum = 0;
        for(char ch:chars){
            if (ch == 'A'){
                numa--;
            } else if (ch == 'C'){
                numc--;
                sum += numa;
            } else if (ch == 'G'){
                numg--;
                sum += numa + numc;
            } else {
                numt--;
                sum += numa + numc + numg;
            }
        }

        return sum;
    }
}

4151:电影节

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        while (n != 0){
            Movie[] movies = new Movie[n];
            for (int i = 0;i < n;i++){
                int start = cin.nextInt();
                int end = cin.nextInt();
                Movie movie = new Movie(start,end);
                movies[i] = movie;
            }

            int index = 0;
            int count = 0;
            while (true){
                int minend = 2000;
                for (Movie movie:movies){
                    if (movie.getStartTime() >= index){
                        minend = Math.min(minend,movie.getEndTime());
                    }
                }
                if (minend == 2000){
                    break;
                } else {
                    count++;
                    index = minend;
                }
            }
            System.out.println(count);
            n = cin.nextInt();
        }
    }

    static class Movie{
        int startTime;
        int endTime;

        public Movie(int startTime, int endTime) {
            this.startTime = startTime;
            this.endTime = endTime;
        }

        public int getStartTime() {
            return startTime;
        }

        public int getEndTime() {
            return endTime;
        }
    }
}

写一个保留六位小数的程序:

DecimalFormat format = new DecimalFormat("0.000000");
System.out.println(1.2345567777);

返回的是个字符串


2020.1.20
这个百练真是把气笑了,有时候代码就是死活提交不上去,我又想念leetcode了。

4094:秘密会谈

import java.text.DecimalFormat;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        int s = cin.nextInt();
        int max = 0;
        for (int i = 0;i < n;i++){
            int start = cin.nextInt();
            int speed = cin.nextInt();
            int time = start + s / speed;
            max = Math.max(max,time);
        }
        System.out.println(max);
    }
}

4095:打字员

import java.text.DecimalFormat;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        for (int i = 0;i < n;i++){
            System.out.println(nums(cin.next()));
        }
    }

    //status 0:小写
    //1:大写
    static int nums(String str){
        int count = 0;
        int status = 0;
        char[] chars = str.toCharArray();
        for (char ch:chars){
            if ((ch >= 'a' && ch <= 'z' && status == 0) || (ch >= 'A' && ch <= 'Z' && status == 1)){
                count++;
            }else if (status == 0){
                status = 1;
                count += 2;
            } else {
                status = 0;
                count += 2;
            }
        }
        return count;
    }
}

4096:信号转换

import java.text.DecimalFormat;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        String str = cin.next();
        char[] chars = str.toCharArray();
        StringBuilder ans = new StringBuilder("");
        for (char ch : chars){
            if (ch == 'A'){
                ans.append(1);
            } else if (ch == 'B'){
                ans.append(2);
            } else if (ch == 'C'){
                ans.append('$');
            } else {
                ans.append("\n");
            }
        }
        System.out.println(ans.toString());
    }
}

4097:报站

import java.text.DecimalFormat;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        String[] stations = new String[n];
        for(int i = 0;i < n;i++){
            stations[i] = cin.next();
        }

        int m = cin.nextInt();
        for (int i = 0;i < m;i++){
            String start = cin.next();
            String end = cin.next();
            int startIndex = -1;
            int endIndex = -1;
            int j = 0;
            while(startIndex == -1 || endIndex == -1){
                if (stations[j].equals(start)){
                    startIndex = j;
                }
                if (stations[j].equals(end)){
                    endIndex = j;
                }
                j++;
            }
            if (startIndex <= endIndex){
                int k = startIndex;
                while (k != endIndex){
                    System.out.print(stations[k]+" ");
                    k++;
                }
                System.out.println(stations[endIndex]);
            } else {
                int k = startIndex;
                while (k != endIndex){
                    System.out.print(stations[k]+" ");
                    k--;
                }
                System.out.println(stations[endIndex]);
            }
        }
    }
}

4098:第二大价值

import java.text.DecimalFormat;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int m = cin.nextInt();
        for (int i = 0;i < m;i++){
            int n = cin.nextInt();
            Fruit max = new Fruit(0,0,0);
            Fruit second = new Fruit(0,0,0);
            for(int j = 0;j < n;j++){
                int id = cin.nextInt();
                int a = cin.nextInt();
                int b = cin.nextInt();
                Fruit fruit = new Fruit(a,b,id);
                if (a + b > max.getA() + max.getB()){
                    second = max;
                    max = fruit;
                } else if (a + b > second.getA() + second.getB()){
                    second = fruit;
                }
            }
            System.out.println(second.getId()+" "+second.getA()+" "+second.getB()+" "+(second.getA()+second.getB()));
        }

    }

    static class Fruit{
        private int a;
        private int b;
        private int id;

        public Fruit(int a, int b, int id) {
            this.a = a;
            this.b = b;
            this.id = id;
        }

        public int getA() {
            return a;
        }

        public int getB() {
            return b;
        }

        public int getId() {
            return id;
        }
    }

}

分享一个很坑爹的题:
4099:队列和栈
这个题坑爹之处在于你在输出error之后,还有继续处理完这次输入的余下内容

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int m = cin.nextInt();
        for (int i = 0;i < m;i++){
            int n = cin.nextInt();
            Stack<Integer> stack = new Stack<>();
            Queue<Integer> queue = new LinkedList<>();
            int j = 0;
            for (j = 0;j < n;j++){
                String opereation = cin.next();
                if (opereation.equals("push")){
                    int num = cin.nextInt();
                    stack.push(num);
                    queue.add(num);
                } else {
                    if (stack.empty()){
                        System.out.println("error");
                        System.out.println("error");
                        while(j < n){
                            cin.nextLine();
                            j++;
                        }
                        j = 0;
                        break;
                    } else {
                        stack.pop();
                        queue.poll();
                    }
                }
            }

            if (j == n){
                while (!queue.isEmpty()){
                    System.out.print(queue.poll()+" ");
                }
                System.out.print("\n");

                Stack<Integer> ans = new Stack<>();
                while(!stack.empty()){
                    ans.push(stack.pop());
                }
                while(!ans.empty()){
                    System.out.print(ans.pop()+" ");
                }
                System.out.print("\n");
            }
        }
    }
}


2020.1.21
4100:进程检测

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int m = cin.nextInt();
        for (int i = 0;i < m;i++){

            int n = cin.nextInt();
            int count = 0;
            Progress[] progresses = new Progress[n];
            for (int j = 0;j < n;j++){
                int start = cin.nextInt();
                int end = cin.nextInt();
                Progress progress = new Progress(start,end);
                progresses[j] = progress;
            }
            Arrays.sort(progresses, new Comparator<Progress>() {
                @Override
                public int compare(Progress o1, Progress o2) {
                    return o1.getStartTime() - o2.getStartTime();
                }
            });

            int left = 0;
            while(left < n){
                Progress progress = progresses[left];
                int right = left + 1;
                while (right < n){
                    Progress temp = progresses[right];
                    if (temp.getStartTime() > progress.getEndTime()){
                        break;
                    } else {
                        progress.setStartTime(temp.getStartTime());
                        progress.setEndTime(Math.min(progress.getEndTime(),temp.getEndTime()));
                    }
                    right++;
                }
                left = right;
                count++;
            }
            System.out.println(count);
        }
    }

    static class Progress{
        private int startTime;
        private int endTime;

        public Progress(int startTime, int endTime) {
            this.startTime = startTime;
            this.endTime = endTime;
        }

        public int getStartTime() {
            return startTime;
        }

        public int getEndTime() {
            return endTime;
        }

        public void setStartTime(int startTime) {
            this.startTime = startTime;
        }

        public void setEndTime(int endTime) {
            this.endTime = endTime;
        }
    }
}

4101:晶矿的个数

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int m = cin.nextInt();
        for (int i = 0;i < m;i++){

            int n = cin.nextInt();
            cin.nextLine();
            char[][] grouds = new char[n][n];
            for (int j = 0;j < n;j++){
                String str = cin.nextLine();
                grouds[j] = str.toCharArray();
            }

            int red = findRed(grouds,n);
            int black = findBlack(grouds,n);
            System.out.println(red+" "+black);
        }
    }

    static int findRed(char[][] grouds,int n){
        int count = 0;
        for (int i = 0;i < n;i++){
            for (int j = 0;j < n;j++){
                if (grouds[i][j] == 'r'){
                    count++;
                    DFS(grouds,i,j,n,'r');
                }
            }
        }
        return count;
    }

    static int findBlack(char[][] grouds,int n){
        int count = 0;
        for (int i = 0;i < n;i++){
            for(int j = 0;j < n;j++){
                if (grouds[i][j] == 'b'){
                    count++;
                    DFS(grouds,i,j,n,'b');
                }
            }
        }
        return count;
    }

    static void DFS(char[][] grouds,int i,int j,int n,char target){
        grouds[i][j] = '$';
        if (i > 0 && grouds[i - 1][j] == target){
            DFS(grouds,i - 1,j,n,target);
        }
        if (i < n - 1 && grouds[i + 1][j] == target){
            DFS(grouds,i + 1,j,n,target);
        }
        if (j > 0 && grouds[i][j - 1] == target){
            DFS(grouds, i, j - 1, n, target);
        }
        if (j < n - 1 && grouds[i][j + 1] == target){
            DFS(grouds, i, j + 1, n, target);
        }
    }

}

4103:踩方格
这一题要找规律

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int N = cin.nextInt();
        int y = 2;
        int ans = 3;
        for (int i = 1;i < N;i++){
            int temp = y;
            y = y + ans;
            ans = ans + 2 * temp;
        }
        System.out.println(ans);
    }

}

4104: 单词翻转

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        String input = cin.nextLine();
        char[] chars = input.toCharArray();
        int len = input.length();
        int left = 0;
        while (left < len){
            while (left < len && chars[left] == ' '){
                System.out.print(' ');
                left++;
            }
            int right = left;
            StringBuilder temp = new StringBuilder("");
            while (right < len && chars[right] != ' '){
                temp.append(chars[right]);
                right++;
            }
            left = right;
            System.out.print(temp.reverse());
        }
    }
}

4106:出现两次的字符-Characters Appearing twice

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        for (int i = 0;i < n;i++){
            Map<Character,Integer> count = new HashMap<>();
            String str = cin.next();
            char[] chars = str.toCharArray();
            for (char ch:chars){
                if (!count.containsKey(ch)){
                    count.put(ch,1);
                } else {
                    count.put(ch,count.get(ch) + 1);
                }
            }

            for (char ch:chars){
                if (count.get(ch) == 2){
                    System.out.println(ch);
                    break;
                }
            }
        }
    }
}

4139:不定方程求解

import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int a = cin.nextInt();
        int b = cin.nextInt();
        int c = cin.nextInt();
        int count = 0;
        for (int i = c / a;i >= 0;i--){
            if ((c - a * i) % b == 0){
                count++;
            }
        }
        System.out.println(count);
    }
}

4142:二分法求函数的零点

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        DecimalFormat format = new DecimalFormat("0.000000");
        System.out.println(format.format(root()));
    }

    static double root(){
        double left = 1.5;
        double right = 2.4;
        while (right - left > 0.000001){
            double med = (left + right) / 2;
            double val = Math.pow(med,5) - 15 * Math.pow(med,4) + 85 * Math.pow(med,3) - 225 * Math.pow(med,2) + 274 * med - 121;
            if (val > 0){
                left = med;
            } else {
                right = med;
            }
        }
        return right;
    }
}

4146:数字方格

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        int a1;
        int a2;
        int a3;
        int max = 0;
        for (a1 = n;a1 >= 0;a1 --){
            for (a2 = n;a2 >= 0;a2--){
                for(a3 = n;a3 >= 0;a3--){
                    if ((a1 + a2) % 2 == 0 && (a2 + a3) % 3 == 0 && (a1 + a2 + a3) % 5 == 0){
                        max = Math.max(max,a1 + a2 + a3);
                    }
                }
            }
        }
        System.out.println(max);
    }
}

4151:电影节

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        while (n != 0){
            Movie[] movies = new Movie[n];
            for (int i = 0;i < n;i++){
                int start = cin.nextInt();
                int end = cin.nextInt();
                Movie movie = new Movie(start,end);
                movies[i] = movie;
            }

            int index = 0;
            int count = 0;
            while (true){
                int minend = 2000;
                for (Movie movie:movies){
                    if (movie.getStartTime() >= index){
                        minend = Math.min(minend,movie.getEndTime());
                    }
                }
                if (minend == 2000){
                    break;
                } else {
                    count++;
                    index = minend;
                }
            }
            System.out.println(count);
            n = cin.nextInt();
        }
    }

    static class Movie{
        int startTime;
        int endTime;

        public Movie(int startTime, int endTime) {
            this.startTime = startTime;
            this.endTime = endTime;
        }

        public int getStartTime() {
            return startTime;
        }

        public int getEndTime() {
            return endTime;
        }
    }
}

4107:19岁生日礼物-Birthday Gift

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        for (int i = 0;i < n;i++){
            int x = cin.nextInt();
            String y = "" + x;
            if (x % 19 == 0 || y.contains("19")){
                System.out.println("Yes");
            } else {
                System.out.println("No");
            }
        }
    }
}


2020.1.22
4108:羚羊数量-Number Of Antelope
半夜做这个,脑子不清醒这么简单的一道题绕了半天

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        //i是第几年,nums[i]表示第i年有多少只
        int[] nums = new int[41];
        //i是的岁数,ages[i]是这个年龄的的个数
        int[] ages = new int[41];
        ages[0] = 1;
        for (int i = 0;i <= 40;i++){
            int sum = 0;
            //System.out.println("第"+i+"年-----------------------》");
            for (int count:ages){
                sum += count;
                //System.out.println(count);
            }
            nums[i] = sum;
            
            int born = 0;

            for (int j = 40;j > 0;j--){
                ages[j] = ages[j - 1];
            }

            for (int age = 3;age <= 40;age++){
                born += ages[age];
            }
            ages[0] = born;
        }
        
        int n = cin.nextInt();
        for (int i = 0;i < n;i++){
            int x = cin.nextInt();
            //key是羚羊的年龄,value是这个年龄的领养的数量
            System.out.println(nums[x]);
        }
    }
}

4109:公共朋友-Common Friends

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int c = cin.nextInt();
        for (int i = 0;i < c;i++){
            System.out.println("Case "+(i + 1)+":");
            int n = cin.nextInt();
            int m = cin.nextInt();
            int k = cin.nextInt();
            Map<Integer,Set<Integer>> friends = new HashMap<>();
            for (int j = 1;j <= n;j++){
                Set<Integer> friend = new HashSet<>();
                friends.put(j,friend);
            }
            for (int j = 0;j < m;j++){
                int f1 = cin.nextInt();
                int f2 = cin.nextInt();
                friends.get(f1).add(f2);
                friends.get(f2).add(f1);
            }

            for (int j = 0;j < k;j++){
                int f1 = cin.nextInt();
                int f2 = cin.nextInt();
                Set<Integer> friends1 = friends.get(f1);
                Set<Integer> friends2 = friends.get(f2);
                int count = 0;
                if (friends1.size() <= friends2.size()){
                    for (int friend:friends1){
                        if (friends2.contains(friend)){
                            count++;
                        }
                    }
                } else {
                    for (int friend:friends2){
                        if (friends1.contains(friend)){
                            count++;
                        }
                    }
                }
                System.out.println(count);
            }
        }
    }
}

4110:圣诞老人的礼物-Santa Clau’s Gifts

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        int weight = cin.nextInt();
        Candy[] candies = new Candy[n];
        for (int i = 0;i < n;i++){
            int v = cin.nextInt();
            int w = cin.nextInt();
            Candy candy = new Candy(w,v);
            candies[i] = candy;
        }
        Arrays.sort(candies, new Comparator<Candy>() {
            @Override
            public int compare(Candy o1, Candy o2) {
                double price1 = (double)o1.getValue() / o1.getWeight();
                double price2 = (double)o2.getValue() / o2.getWeight();
                if (price1 > price2){
                    return -1;
                } else if (price1 == price2){
                    return 0;
                } else {
                    return 1;
                }
            }
        });

        float sum = 0;
        int index = 0;
        while (weight > 0 && index < n){
            int min = Math.min(weight,candies[index].getWeight());
            float price = (float)candies[index].getValue() / candies[index].getWeight();
            sum += min * price;
            weight -= min;
            index++;
        }
        System.out.println(sum);
    }

    static class Candy{
        int weight;
        int value;

        public Candy(int weight, int value) {
            this.weight = weight;
            this.value = value;
        }

        public int getWeight() {
            return weight;
        }

        public int getValue() {
            return value;
        }
    }
}

4111:判断游戏胜者-Who Is the Winner

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        for (int i = 0;i < n;i++){
            String alice = cin.next();
            String bob = cin.next();
            compute(alice,bob);
        }
    }

    static void compute(String alice,String bob){
        int num1 = oneNum(alice);
        int num2 = oneNum(bob);
        if (num1 > num2){
            System.out.println("Alice");
        } else if (num1 < num2){
            System.out.println("Bob");
        } else {
            System.out.println("Tie");
        }
    }

    static String transfer(String str){
        int len = str.length();
        char[] chars = str.toCharArray();
        StringBuilder ans = new StringBuilder("");
        for (int i = 2;i < len;i++){
            char ch = chars[i];
            switch (ch){
                case '0':{
                    ans.append("0000");
                    break;
                }
                case '1':{
                    ans.append("0001");
                    break;
                }
                case '2':{
                    ans.append("0010");
                    break;
                }
                case '3':{
                    ans.append("0011");
                    break;
                }
                case '4':{
                    ans.append("0100");
                    break;
                }
                case '5':{
                    ans.append("0101");
                    break;
                }
                case '6':{
                    ans.append("0110");
                    break;
                }
                case '7':{
                    ans.append("0111");
                    break;
                }
                case '8':{
                    ans.append("1000");
                    break;
                }
                case '9':{
                    ans.append("1001");
                    break;
                }
                case 'a':{
                    ans.append("1010");
                    break;
                }
                case 'b':{
                    ans.append("1011");
                    break;
                }
                case 'c':{
                    ans.append("1100");
                    break;
                }
                case 'd':{
                    ans.append("1101");
                    break;
                }
                case 'e':{
                    ans.append("1110");
                    break;
                }
                case 'f':{
                    ans.append("1111");
                    break;
                }
            }
        }
        return ans.toString();
    }

    static int oneNum(String str){
        String str1 = transfer(str);
        char[] chars = str1.toCharArray();
        int len =  str1.length();
        int count = 0;
        int left = 0;
        while (left < len){
            while (left < len && chars[left] == '0'){
                left++;
            }
            if (left < len){
                count++;
            }
            int right = left + 1;
            while (right < len && chars[right] == '1'){
                right++;
            }
            left = right;
        }
        return count;
    }

}

4112:情报破译-Cryptanalysis

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        while (cin.hasNext()){
            String msg = cin.nextLine();
            int count = 0;
            char[] chars = msg.toCharArray();
            int len = msg.length();
            int left = 0;
            while (left < len){
                count++;
                while (left < len && !legal(chars[left])){
                    System.out.print(chars[left]);
                    left++;
                }
                StringBuilder word = new StringBuilder("");
                int right = left;
                while (right < len && legal(chars[right])){
                    word.append(chars[right]);
                    right++;
                }
                System.out.print(reverse(word.toString(),count));
                left = right;
            }
            System.out.print("\n");
        }
    }

    static String reverse(String string,int i){
        StringBuilder ans = new StringBuilder("");
        char[] chars = string.toCharArray();
        for (char ch:chars){
            char ch1;
            if (ch >= 'a' && ch <= 'z'){
                ch1 = (char)('a' + ((ch - 'a') - i + 26) % 26);
            } else {
                ch1 = (char)('A' + ((ch - 'A') - i + 26) % 26);
            }
            ans.append(ch1);
        }
        ans.reverse();
        return ans.toString();
    }

    static boolean legal(char ch){
        return (ch <= 'z' && ch >= 'a') || (ch >= 'A' && ch <= 'Z');
    }
}


2020.1.25
大年初一,希望今年平平安安,身体健康,万事如意

4117:简单的整数划分问题

这一题用到dp,new一个二维数组,dp[i][j]其中i表示我们要求的是加起来为i的结果,j表示开头第一个数是j
dp真的是需要积累的

import java.util.Scanner;

public class Main {

    private static int[][] dp = new int[51][51];

    static void initDp(){
        dp[0][0] = 1;
        dp[1][1] = 1;
        for (int i = 1;i <= 50;i++){
            for (int j = 1;j <= i;j++){
                int sum = 0;
                for (int k = 0;k <= j ;k++){
                    sum += dp[i - j][k];
                }
                dp[i][j] = sum;
            }
        }
    }

    public static void main(String[] args) {
        initDp();
        Scanner cin = new Scanner(System.in);
        while (cin.hasNext()){
            int input = cin.nextInt();
            int sum = 0;
            for (int i = 1;i <= input;i++){
                sum += dp[input][i];
            }
            System.out.println(sum);
        }
    }

}

4118:开餐馆
基础dp,用dp[i]表示最后一个选择第i个参观所带来的收益, 我不明白我的程序为什么会超时,我的时间复杂度明明是不会超时的,我感觉是测试用例有问题,这道题把我整放弃了,我还是回去做leetcode了,此博客暂时完结

import java.util.Scanner;

public class Main {
    
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int T = cin.nextInt();
        for (int i = 0;i < T;i++){
            int n = cin.nextInt();
            int distance = cin.nextInt();
            int[] dis = new int[n];
            int[] value = new int[n];
            for (int j = 0;j < n;j++){
                dis[j] = cin.nextInt();
            }
            for (int j = 0;j < n;j++){
                value[j] = cin.nextInt();
            }
            
            int max = 0;
            int[] dp = new int[n];
            for (int j = 0;j < n;j++){
                int temp = value[j];
                int index = 0;
                while(dis[j] - dis[index] > distance){
                    temp = Math.max(temp,value[j] + dp[index]);
                    index++;
                }
                dp[j] = temp;
                max = Math.max(max,dp[j]);
            }
            System.out.println(max);
        }
    }

}


2020.2.18
这瘟疫啥时候能过去。。。

4137:最小新整数:这个问题开始想难了,其实不难

import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int t = cin.nextInt();
        for (int i = 0;i < t;i++){
            String n = cin.next();
            int len = n.length();
            int k = cin.nextInt();
            int count = 0;
            Stack<Character> stack = new Stack<>();
            char[] chars = n.toCharArray();
            for (char ch:chars){
                while (!stack.empty() && ch < stack.peek() && count < k){
                    stack.pop();
                    count++;
                }
                stack.push(ch);
            }

            Stack<Character> temp = new Stack<>();
            while (!stack.empty()){
                temp.add(stack.pop());
            }
            StringBuilder stringBuilder = new StringBuilder("");
            for (int j = 0;j < len - k;j++){
                stringBuilder.append(temp.pop());
            }
            System.out.println(stringBuilder.toString());
        }
    }
}

签到题:
4138:质数的和与积

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        int left = n / 2;
        while(left > 1){
            int right = n - left;
            if (illegal(left) && illegal(right)){
                System.out.println(left * right);
                break;
            }
            left--;
        }
    }

    static boolean illegal(int x){
        int y = (int)Math.sqrt(x);
        for (int i = 2;i <= y;i++){
            if (x % i == 0){
                return false;
            }
        }
        return true;
    }
}

4147:汉诺塔问题(Hanoi)
老经典题了
汉诺塔问题的思路是这样的:
2020刷题日记_第3张图片
有n个大铁片子要从a借助b到达c,我们记为 F ( n , a , b , c ) F(n,a,b,c) F(n,a,b,c)
事实上,为了完成这个任务,我们必须要经过一个中间状态,那就是将前n-1个铁片放在b上,完了让第n个从a放在c上
那么问题变成这样:
要完成把n个铁片从a借助b到达c,需要分为三步:

  1. 把n-1个铁片从a借助c放到b上
  2. 把a上第n个铁片放在c上
  3. 把b上n-1个铁片借助a放在c上
    我们进行抽象:
    F ( n , a , b , c ) = F ( n − 1 , a , c , b ) − > 把 n 从 a 放 到 c 上 − > F ( n − 1 , b , a , c ) F(n,a,b,c)=F(n-1,a,c,b)->把n从a放到c上->F(n-1,b,a,c) F(n,a,b,c)=F(n1,a,c,b)>nac>F(n1,b,a,c)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        char a = cin.next().charAt(0);
        char b = cin.next().charAt(0);
        char c = cin.next().charAt(0);
        hanno(n,a,b,c);
    }

    static void hanno(int n,char a,char b,char c){
        if (n == 1){
            System.out.println(n + ":" + a + "->" + c);
        } else {
            hanno(n - 1,a,c,b);
            System.out.println(n + ":" + a + "->" + c);
            hanno(n - 1,b,a,c);
        }
    }
}


2020.2.19
做一个简单的一批的题目居然难住了:
836. 矩形重叠
如果连个矩阵 ( x 1 , y 1 , x 2 , y 2 ) , ( x 3 , y 3 , x 4 , y 4 ) (x1,y1,x2,y2),(x3,y3,x4,y4) (x1,y1,x2,y2),(x3,y3,x4,y4)要相交,那么他们俩相交的矩阵就是 ( m a x ( x 1 , x 3 ) , m a x ( y 1 , y 3 ) , m i n ( x 2 , x 4 ) , m i n ( y 2 , y 4 ) ) (max(x1,x3),max(y1,y3),min(x2,x4),min(y2,y4)) (max(x1,x3),max(y1,y3),min(x2,x4),min(y2,y4))
我们只需要判断这个能不能构成举行就可以了

    public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
        int x5 = Math.max(rec1[0],rec2[0]);
        int y5 = Math.max(rec1[1],rec2[1]);
        int x6 = Math.min(rec1[2],rec2[2]);
        int y6 = Math.min(rec1[3],rec2[3]);
        return x5 < x6 && y5 < y6;
    }

2020.2.20

4127:迷宫问题

啊这个问题有一点点意思的
BFS+DP
题目要求我们从左上角向右下角去找一条路,但是我们要反过来想,从右下角向左上角去找路,所以我们从右下角开始BFS,记录每个位置到右下角所需的最短路径,最后我们从左上角开始输出就可以了。

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[][] matrix = new int[5][5];
        int[][] length = new int[5][5];
        Scanner cin = new Scanner(System.in);
        for (int i = 0;i < 5;i++){
            for (int j = 0;j < 5;j++){
                matrix[i][j] = cin.nextInt();
                length[i][j] = Integer.MAX_VALUE;
            }
        }

        BFS(matrix,length);

        print(length,0,0);
    }

    static void print(int[][] length,int i,int j){
        System.out.println("(" + i + ", " + j + ")");
        int len = length[i][j];
        if (i > 0 && length[i - 1][j] == len - 1) {
            print(length, i - 1, j);
        }
        if (i < 4 && length[i + 1][j] == len - 1){
            print(length, i + 1, j);
        }
        if (j > 0 && length[i][j - 1] == len - 1) {
            print(length, i, j - 1);
        }
        if (j < 4 && length[i][j + 1] == len - 1) {
            print(length, i, j + 1);
        }
    }

    static void BFS(int [][] matrix,int[][] length){
        int count = 1;
        List<Point> points = new ArrayList<>();
        points.add(new Point(4,4));
        length[4][4] = 0;
        while (!points.isEmpty()){
            List<Point> points1 = new ArrayList<>();
            for (Point point:points){
                int x = point.x;
                int y = point.y;
                if (x > 0 && matrix[x - 1][y] == 0 && length[x - 1][y] == Integer.MAX_VALUE){
                    length[x - 1][y] = count;
                    points1.add(new Point(x - 1,y));
                }
                if (y > 0 && matrix[x][y - 1] == 0 && length[x][y - 1] == Integer.MAX_VALUE){
                    length[x][y - 1] = count;
                    points1.add(new Point(x,y - 1));
                }
                if (x < 4 && matrix[x + 1][y] == 0 && length[x + 1][y] == Integer.MAX_VALUE){
                    length[x + 1][y] = count;
                    points1.add(new Point(x + 1,y));
                }
                if (y < 4 && matrix[x][y + 1] == 0 && length[x][y + 1] == Integer.MAX_VALUE){
                    length[x][y + 1] = count;
                    points1.add(new Point(x,y + 1));
                }
            }
            count++;
            points = points1;
        }
    }


    static class Point{
        private int x;
        private int y;

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }
    }

}


4122:切割回文

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int T = cin.nextInt();
        for (int i = 0;i < T;i++){
            String string = cin.next();
            char[] chars = string.toCharArray();
            int len = string.length();
            System.out.println(getCount(chars,0,len - 1));
        }
    }

    static int getCount(char[] chars,int left,int right){
        if (left > right){
            return -1;
        }
        int index = left;
        while (!islegal(chars,index,right)){
            index++;
        }
        return 1 + getCount(chars, left, index - 1);
    }

    static boolean islegal(char[] chars,int left,int right){
        while (left < right){
            if(chars[left] != chars[right]){
                return false;
            } else {
                left++;
                right--;
            }
        }
        return true;
    }

}


2020.2.22
狗日的瘟疫

leetcode60:第k个排列

    public String getPermutation(int n, int k) {
        int t = n;
        k--;
        int[] nums = new int[n];
        boolean[] chosen = new boolean[n];
        StringBuilder stringBuilder = new StringBuilder("");

        for (int i = 1;i <= n;i++){
            nums[i - 1] = i;
        }

        while (t > 0){
            t--;
            int s = k / fx(t);
            int count = 0;
            int i = 0;

            for (;i < n;i++){
                if (!chosen[i]){
                    count++;
                }
                if (count > s){
                    break;
                }
            }

            stringBuilder.append(nums[i]);
            chosen[i] = true;
            k -= s * fx(t);
        }
        return stringBuilder.toString();
    }

    static int fx(int x){
        int ans = 1;
        for (int i = 2;i <= x;i++){
            ans *= i;
        }
        return ans;
    }

你可能感兴趣的:(人生,做题)