PAT甲级半个月学习总结(Java)

声明:部分代码可能存在超时和错误,题目范围为1000~1074,分类的题目不是该类所有题目只是比较有代表性

体会:JAVA相比C++太容易超时了(即便算法相同)

降低时间的技巧

1.Bufferreader比Scanner可能用时稍短,且Scanner使用next容易出现问题

2.将String使用toCharArray转换成char数组,避免使用charAt

一些其他技巧

1.常见的导包:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.*;
import java.math.*;

想不起来具体的就用*

2.BigInteger比Long更适用

BigInteger常见操作:

      BigInteger bignum = new BigInteger(str);
      BigInteger multiply = bignum.multiply(new BigInteger("2"));

3.注意输出形式

System.out.println(String.format("%04d - %04d = %04d", bigger, smaller, n));

常见函数
1.判断是否对称
   public static boolean isPalindromic(String str){
      for (int i=0;i<str.length()/2;i++){
         if (str.charAt(i)!=str.charAt(str.length()-i-1)){
            return false;
         }
      }
      return true;
   }
2.判断是否是素数
   public static boolean isPrime(int number) {//判断素数
      // 小于2的数都不是素数
      if (number < 2) {
         return false;
      }
      for (int i=2;i*i<=number;i++){
         if (number%i==0) return false;
      }
      return true;
   }
3.转化为10进制
   public static int toDecimal(String num,int radix){
      int sum=0;
      for (int i=0;i<num.length();i++){
         if (Character.isDigit(num.charAt(i))){
            sum=sum*radix+(num.charAt(i)-'0');
         }
         else sum=sum*radix+(num.charAt(i)-'a'+10);
      }
      return sum;
   }
4.将r进制下的字符串n转化为10进制下的逆置后的数
   public static int translate(String n, int r) {//将r进制下的字符串n转化为10进制下的逆置后的数
      int sum = 0;
      for (int i = 0, unit = 1; i < n.length(); i++, unit *= r) {
         sum += unit * (n.charAt(i) - '0');
      }
      return sum;
   }
    public static int translate(String n,int r){
        int sum=0;
        for (int i=n.length()-1;i>=0;i--){
            sum=sum*r+(n.charAt(i)-'0');
        }
        return sum;
    }
5.进制转化
Integer.toString(int n,int r)//将10进制下的数n转成r进制

排序问题:

往往可以自定义类,然后继承implements Comparable<自定义的类>

再重写compareTo注意只能返回int

如果要比较的属性本来就是int型,可以用o.属性-this.属性

如果不是int,1070是一个例子

return o.each_price>this.each_price?1:-1;
1012.The Best Rank
import java.util.*;
public  class Main {
    static ArrayList<Integer> AList = new ArrayList<>();
    static ArrayList<Integer> CList = new ArrayList<>();
    static ArrayList<Integer> MList = new ArrayList<>();
    static ArrayList<Integer> EList = new ArrayList<>();
    static class Student {
        private int A ;
        private int M ;
        private int E ;
        private int C ;
        public Student(int C, int M, int E, int A) {
            this.A = A;
            this.M = M;
            this.C = C;
            this.E = E;
        }
    }


    public  static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n=scanner.nextInt();
        int m=scanner.nextInt();
        HashMap<Integer, Student> map = new HashMap<>();
        for (int i=0;i<n;i++){
            int num=scanner.nextInt();
            int C=scanner.nextInt();
            int M=scanner.nextInt();
            int E=scanner.nextInt();
            int A=(C+M+E)/3;
            AList.add(A);
            CList.add(C);
            MList.add(M);
            EList.add(E);
            map.put(num,new Student(C,M,E,A));
        }
        Collections.sort(AList);
        Collections.sort(CList);
        Collections.sort(MList);
        Collections.sort(EList);
        for (int i=0;i<m;i++){
            int key=scanner.nextInt();
            if (map.containsKey(key)){
                System.out.println(best_Rank(map.get(key)));
            }else {
                System.out.println("N/A");
            }
        }

}
    public static String best_Rank(Student student){
        int n=AList.size();//四个list的size都一样
        int best_rank=n-AList.lastIndexOf(student.A);
        String Grade="A";
        if (n-CList.lastIndexOf(student.C)<best_rank){
            best_rank=n-CList.lastIndexOf(student.C);
            Grade="C";
        }
        if (n-MList.lastIndexOf(student.M)<best_rank){
            best_rank=n-MList.lastIndexOf(student.M);
            Grade="M";
        }
        if (n-EList.lastIndexOf(student.E)<best_rank){
            best_rank=n-EList.lastIndexOf(student.E);
            Grade="E";
        }
        return best_rank+" "+Grade;
    }
}
1025.PAT Ranking
import java.util.*;

public class Main {
   static class testee implements Comparable<testee>{
      private String reg_num;
      private int score;
      private int location;
      private int localRank;
      private int finalRank;


      public testee(String reg_num, int score,int location) {
         this.reg_num = reg_num;
         this.score = score;
         this.location=location;
      }

      @Override
      public int compareTo(testee o) {//排序方法
         if (score == o.score) {
            return reg_num.compareTo(o.reg_num);
         } else if (score > o.score) {
            return -1;
         } else {
            return 1;
         }
      }
      @Override
      public String toString() {
         return reg_num + " " + finalRank + " " + (location+1) + " " + localRank;
      }

   }
   static ArrayList<ArrayList<testee>>arrayList=new ArrayList<>();
   static ArrayList<testee>totalList=new ArrayList<>();
   public static void main(String[] args) {
      Scanner scanner=new Scanner(System.in);
      int n=scanner.nextInt();
      for (int i=0;i<n;i++){
         int k=scanner.nextInt();
         ArrayList<testee>arrayList1=new ArrayList<>();//本地列表
         for (int j=0;j<k;j++){
               String reg_num=scanner.next();
               int score= scanner.nextInt();
               testee testee= new testee(reg_num,score,i);
               arrayList1.add(testee);
         }
         Collections.sort(arrayList1);
         arrayList.add(arrayList1);
      }
      for (int i=0;i< arrayList.size();i++){//本地列表排序完之后再进行并列的处理
         arrayList.get(i).get(0).localRank=1;
         totalList.add(arrayList.get(i).get(0));
         for (int j=1;j<arrayList.get(i).size();j++){
            if (arrayList.get(i).get(j).score==arrayList.get(i).get(j-1).score){
               arrayList.get(i).get(j).localRank=arrayList.get(i).get(j-1).localRank;
            }
            else arrayList.get(i).get(j).localRank=j+1;
            totalList.add(arrayList.get(i).get(j));//testee录入了localRank信息后再入totalList
         }
      }
      Collections.sort(totalList);
      totalList.get(0).finalRank=1;
      for (int i=1;i<totalList.size();i++){//总排名的并列处理
         if (totalList.get(i-1).score==totalList.get(i).score){
            totalList.get(i).finalRank=totalList.get(i-1).finalRank;
         }
         else totalList.get(i).finalRank=i+1;
      }
      System.out.println(totalList.size());
      for (int i=0;i<totalList.size();i++){
         testee t=totalList.get(i);
         System.out.println(t);
      }
}
}
1028.Listing Sorting
import java.util.*;

public class Main {
   static class Student {
      private String ID;
      private String Name;
      private int Grade;
      public Student(String ID, String name, int grade) {
         this.ID = ID;
         Name = name;
         Grade = grade;
      }

      @Override
      public String toString() {
         return ID+" "+Name+" "+Grade;
      }
   }

   static class Compare1 implements Comparator<Student> {
      @Override
      public int compare(Student o1, Student o2) {
         return o1.ID.compareTo(o2.ID);
      }
   }
   static class Compare2 implements Comparator<Student> {
      @Override
      public int compare(Student o1, Student o2) {
         if (!o1.Name.equals(o2.Name)) {
            return o1.Name.compareTo(o2.Name);
         } else {
            return o1.ID.compareTo(o2.ID);
         }
      }
   }
   static class Compare3 implements Comparator<Student> {
      @Override
      public int compare(Student o1, Student o2) {
         if (o1.Grade!=o2.Grade) {
            return o1.Grade-o2.Grade;
         } else {
            return o1.ID.compareTo(o2.ID);
         }
      }
   }

   static ArrayList<Student>arrayList=new ArrayList<>();
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      int n = scanner.nextInt();
      int c = scanner.nextInt();
      for (int i = 0; i < n; i++) {
         String ID = scanner.next();
         String Name = scanner.next();
         int Grade = scanner.nextInt();
         arrayList.add(new Student(ID, Name, Grade));
      }
      if (c == 1) {
         Collections.sort(arrayList, new Compare1());
      } else if (c == 2) {
         Collections.sort(arrayList, new Compare2());
      } else if (c == 3) {
         Collections.sort(arrayList, new Compare3());
      }
      for (int i=0;i<arrayList.size();i++){
         System.out.println(arrayList.get(i));
      }
   }

}
1052.Linked List Sorting
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;


public class Main {
    static class Node implements Comparable<Node>{
        private String address;
        private int key;
        private String next;

        public Node(String address, int key, String next) {
            this.address = address;
            this.key = key;
            this.next = next;
        }

        @Override
        public int compareTo(Node o) {
            return this.key-o.key;
        }

        @Override
        public String toString() {
            return address+" "+key+" "+next;
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
        String first[]=bufferedReader.readLine().split(" ");
        int n=Integer.parseInt(first[0]);
        ArrayList<Node>arrayList=new ArrayList<>();
        for (int i=0;i<n;i++){
            String strings[]=bufferedReader.readLine().split(" ");
            arrayList.add(new Node(strings[0],Integer.parseInt(strings[1]),strings[2]));
        }
        //根据key排序
        Collections.sort(arrayList);

        //修改next
        for (int i=0;i<n-1;i++){
            arrayList.get(i).next=arrayList.get(i+1).address;
        }
        arrayList.get(arrayList.size()-1).next="-1";

        System.out.println(n+" "+arrayList.get(0).address);
        for (Node node:arrayList){
            System.out.println(node);
        }
    }
}

多项式数组处理:

1002.A+B for Polynomials
import java.util.*;
public class Main {
   public static void main(String[] args) {
      Scanner scanner=new Scanner(System.in);
      double x1[]=new double[1001];
      double x2[]=new double[1001];
      int k1=scanner.nextInt();
      for (int i=0;i<k1;i++){
         int n1=scanner.nextInt();
         Double an1=scanner.nextDouble();
         x1[n1]+=an1;
      }
      int k2=scanner.nextInt();
      for (int i=0;i<k2;i++){
         int n2=scanner.nextInt();
         Double an2=scanner.nextDouble();
         x2[n2]+=an2;
      }
      for (int i=0;i<1001;i++){
         x1[i]=x1[i]+x2[i];
      }
      int count=0;
      String str="";
      for (int i=1000;i>=0;i--){
         if (x1[i]!=0){
            str=str+" "+i+" "+x1[i];
            count++;
         }
      }
      str=count+str;
      System.out.println(str);
   }
}
1009.Product of Polynomials
import java.util.*;
public class Main {
   public static void main(String[] args){
   Scanner scanner=new Scanner(System.in);
   double num1[]=new double[1001];
   double num2[]=new double[1001];
   double num3[]=new double[2001];
   int k1=scanner.nextInt();
   for (int i=0;i<k1;i++){
      int n1=scanner.nextInt();
      double an1=scanner.nextDouble();
      num1[n1]=an1;
   }
   int k2=scanner.nextInt();
   for (int i=0;i<k2;i++){
         int n2=scanner.nextInt();
         double an2=scanner.nextDouble();
         num2[n2]=an2;
   }
   for (int i=0;i<1001;i++){
         for (int j=0;j<1001;j++){
               num3[i+j]+=num1[i]*num2[j];
      }
   }
   int count=0;
   String str="";
   for (int i=2000;i>=0;i--){
      if (num3[i]!=0){
         str = str + " " + i + " " + String.format("%.1f", num3[i]);
         count++;
      }
   }
   System.out.println(count+str);
}
}

哈希表:

1039.Course List for Student
import java.util.*;


public class Main {
    public static void main(String[] args)  {
        Scanner scanner=new Scanner(System.in);
        int n =scanner.nextInt();
        int k=scanner.nextInt();
        HashMap<String, ArrayList<Integer>>hashMap=new HashMap<>();
        for (int i=0;i<k;i++){
            int courseID=scanner.nextInt();
            int stuNum=scanner.nextInt();
            for (int j=0;j<stuNum;j++){
                String name=scanner.next();
                if (!hashMap.containsKey(name)){
                    hashMap.put(name,new ArrayList<Integer>());
                }
                hashMap.get(name).add(courseID);
            }
        }
        for (int i=0;i<n;i++){
            String name=scanner.next();
            StringBuilder sb=new StringBuilder();
            sb.append(name);
            if (hashMap.containsKey(name)){
                ArrayList<Integer>arrayList=hashMap.get(name);
                Collections.sort(arrayList);
                sb.append(" ").append(arrayList.size());
                for (int j=0;j<arrayList.size();j++){
                    sb.append(" ").append(arrayList.get(j));
                }
                System.out.println(sb);
            }else {
                System.out.println(name+" 0");
            }
        }
}
}
  1041.Be Unique
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        LinkedHashMap<Integer, Integer> linkedHashMap = new LinkedHashMap<>();
        int n = scanner.nextInt();
        for (int i = 0; i < n; i++) {
            int key = scanner.nextInt();
            if (linkedHashMap.containsKey(key)) {
                int value = linkedHashMap.get(key);
                linkedHashMap.put(key, value + 1);
            } else {
                linkedHashMap.put(key, 1);
            }
        }
        for (Map.Entry<Integer, Integer> entry : linkedHashMap.entrySet()) {
            if (entry.getValue()==1){
                System.out.println(entry.getKey());
                return;
            }
        }
        System.out.println("None");
    }
}
   1054.The Dominant Color
import java.util.*;
public class Main {
    public static void main(String[] args)   {
        Scanner scanner=new Scanner(System.in);
        HashMap<Integer,Integer>hashMap=new HashMap<>();
        int m=scanner.nextInt();
        int n=scanner.nextInt();
        for (int i=0;i<n;i++){
            for (int j=0;j<m;j++){
                int key=scanner.nextInt();
                if (!hashMap.containsKey(key)){
                    hashMap.put(key,1);
                }
                else {
                    hashMap.put(key,hashMap.get(key)+1);
                }
            }
        }
        for(Map.Entry<Integer,Integer>entry:hashMap.entrySet()){
            if (entry.getValue()>m*n/2){
                System.out.println(entry.getKey());
            }
        }
        }
}
1071.Speech Patterns
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main{
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
        String input[]=bufferedReader.readLine().toLowerCase().replaceAll("[^a-z0-9]+", " ").split(" ");
        HashMap<String,Integer>wordmap=new HashMap<>();
        int cur_count=0,max_count=1;
        for (int i=0;i<input.length;i++){
            if (wordmap.containsKey(input[i])){
                cur_count=wordmap.get(input[i])+1;
                wordmap.put(input[i],cur_count);
                if (cur_count>max_count){
                    max_count=cur_count;
                }
            }else {
                wordmap.put(input[i],1);
            }
        }
        ArrayList<String>ans=new ArrayList<>();
        for (String str:wordmap.keySet()){
            if (wordmap.get(str)==max_count){
                ans.add(str);
            }
        }
        Collections.sort(ans);
        System.out.println(ans.get(0)+" "+max_count);
    }
}

栈:

1051.Pop Sequence
import java.util.*;

/*
  M (the maximum capacity of the stack),
  N (the length of push sequence),
  K (the number of pop sequences to be checked).
* */
public class Main {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int m=scanner.nextInt();
        int n=scanner.nextInt();
        int k=scanner.nextInt();
        for (int i=0;i<k;i++){
            int a[]=new int[n];
            for (int index = 0; index < n; index++) {
                a[index] = scanner.nextInt();
            }
            Stack<Integer>stack=new Stack<>();
            stack.clear();//下一次为stack赋值要将前一次的数据清除
            int index=0;
            int flag=1;
            for (int j=1;j<=n;j++){//注意从1开始
                stack.push(j);//stack每次输入顺序都一样,但不一定是一次输完
                if (stack.size()>m){//超过了最大容量
                    flag=0;
                    break;
                }
                while (!stack.isEmpty()&&stack.peek()==a[index]){
                    index++;
                    stack.pop();
                }
            }
            if (stack.isEmpty()&&flag==1){//全部能匹配且不超容量
                System.out.println("YES");
            }else {
                System.out.println("NO");
            }
        }
    }
}

进制转化:

1010.Radix
import java.util.*;
public class Main {
   public static void main(String[] args){
   Scanner scanner=new Scanner(System.in);
   String num1= scanner.next();
   String num2= scanner.next();
   int tag=scanner.nextInt();
   int radix=scanner.nextInt();
   int radixResult=-1;
   if (tag==1){
       int num=toDecimal(num1,radix);
       radixResult=findRadix(num2,num);
   }
   else {
       int num=toDecimal(num2,radix);
       radixResult=findRadix(num1,num);
   }
   if (radixResult!=-1){
      System.out.println(radixResult);
   }
   else System.out.println("Impossible");
}
   public static int findRadix(String num,int target){
      char maxDigit='0';
      for (char c:num.toCharArray()){
         if (c>maxDigit){
            maxDigit=c;
         }
      }
      int startRadix=0;
      if (Character.isDigit(maxDigit)){
         startRadix=maxDigit-'0'+1;
      }
      else {
         startRadix=maxDigit-'a'+11;
      }
      int i=startRadix;
      for (;toDecimal(num,i)<target;i++);
      if (toDecimal(num,i)==target)  {
         return i;
      }
      return -1;
   }
   public static int toDecimal(String num,int radix){
      int sum=0;
      for (int i=0;i<num.length();i++){
         if (Character.isDigit(num.charAt(i))){
            sum=sum*radix+(num.charAt(i)-'0');
         }
         else sum=sum*radix+(num.charAt(i)-'a'+10);
      }
      return sum;
   }
}
1015.Reversible Primes
import java.util.*;
public  class Main {
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      while (true) {
         int n = scanner.nextInt();
         if (n < 0) break;
         int m = scanner.nextInt();
         if (!isPrime(n)) {
            System.out.println("No");
         } else {
            String str = Integer.toString(n, m); //10->r
            int value = translate(str, m);
            if (isPrime(value)) {
               System.out.println("Yes");
            } else {
               System.out.println("No");
            }
         }
      }
   }
   public static int translate(String n, int r) {//将r进制下的字符串n转化为10进制下的逆置后的数
      int sum = 0;
      for (int i = 0, unit = 1; i < n.length(); i++, unit *= r) {
         sum += unit * (n.charAt(i) - '0');
      }
      return sum;
   }

   public static boolean isPrime(int number) {//判断素数
      // 小于2的数都不是素数
      if (number < 2) {
         return false;
      }
      for (int i=2;i*i<=number;i++){
         if (number%i==0) return false;
      }
      return true;
   }
}
1027.Colors in Mars
//20分
import java.util.*;
 
public class Main {
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      int red = scanner.nextInt();
      int green = scanner.nextInt();
      int blue = scanner.nextInt();
      String string = Integer.toString(red, 13).toUpperCase();
      String string2 = Integer.toString(green, 13).toUpperCase();
      String string3 = Integer.toString(blue, 13).toUpperCase();
      StringBuffer sb1 = new StringBuffer(string);
      StringBuffer sb2 = new StringBuffer(string2);
      StringBuffer sb3 = new StringBuffer(string3);
 
      if(string.length()==1) {
         sb1.insert(0, "0");
      }
      if(string2.length()==1) {
         sb2.insert(0, "0");
      }
      if(string3.length()==1) {
         sb3.insert(0, "0");
      }
      System.out.print("#"+sb1+sb2+sb3);
   }
}

排队问题:

1017.Queueing at Bank
import java.util.*;

public class Main {
   public final static int ET = 8*3600;
   public final static int LT = 17*3600;

   public static void main(String[] args){
      Scanner scanner=new Scanner(System.in);
      int n = scanner.nextInt();
      int k = scanner.nextInt();
      LinkedList<Customer> list = new LinkedList<>();
      int currentTime[] = new int[k];
      for(int i=0; i<n; i++) {
         String arriveTime=scanner.next();
         int processingTime=scanner.nextInt();
         Customer c = new Customer(arriveTime, processingTime);
         if(c.totalSecond <= LT)
            list.add(c);
      }
      for(int i=0; i<k; i++)
         currentTime[i] = ET;
      Collections.sort(list);
      int size = list.size();
      double totalWaitingTime = 0.0;
      while(!list.isEmpty()) {
         int index = 0;
         int minCurrentTime = Integer.MAX_VALUE;
         for(int i=0; i<k; i++) {
            if(minCurrentTime > currentTime[i]) {
               minCurrentTime = currentTime[i];
               index = i;
            }
         }
         Customer c = list.removeFirst();
         //从顾客的Arriving Time开始算起,要等一会儿才能服务
         if(c.totalSecond < currentTime[index]) {
            totalWaitingTime += currentTime[index] - c.totalSecond;
            currentTime[index] += c.processingTime;
         }
         //立马就能服务,不用等
         else
            currentTime[index] = c.totalSecond + c.processingTime;
      }
      System.out.printf("%.1f", totalWaitingTime/size/60);
   }
   static class Customer implements Comparable<Customer>{
      int totalSecond;
      int processingTime;
      String arrivetime;
      public Customer(String arrivetime, int processingTime) {
         this.arrivetime = arrivetime;
         String str[] = arrivetime.split(":");
         this.totalSecond = Integer.parseInt(str[0])*3600
                 + Integer.parseInt(str[1])*60 + Integer.parseInt(str[2]);
         this.processingTime = processingTime>60 ? 3600: processingTime * 60;
      }
      @Override
      public int compareTo(Customer c) {
         return this.totalSecond - c.totalSecond;
      }
   }
}

反转链表:

1074.Reversing Linked List
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;


public class Main {
    static class Node{
        private String address;
        private int data;
        private String next;

        public Node(String address, int data, String next) {
            this.address = address;
            this.data = data;
            this.next = next;
        }

        @Override
        public String toString() {
            return address+" "+data+" "+next;
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
        String input[]=bufferedReader.readLine().split(" ");
        HashMap<String,Node>hashMap=new HashMap<>();
        String head=input[0];
        int n=Integer.parseInt(input[1]);
        int k=Integer.parseInt(input[2]);
        for (int i=0;i<n;i++){
            String str=bufferedReader.readLine();
            hashMap.put(str.split(" ")[0],(new Node(str.split(" ")[0],Integer.parseInt(str.split(" ")[1]),str.split(" ")[2])));
        }
        Node curNode=hashMap.get(head);
        ArrayList<Node>arrayList=new ArrayList<>();
        while (!curNode.next.equals("-1")){
            arrayList.add(curNode);
            curNode=hashMap.get(curNode.next);
        }
        arrayList.add(curNode);
        for (int i=0;i<k/2;i++){
            Node temp=arrayList.get(i);
            arrayList.set(i,arrayList.get(k-i-1));
            arrayList.set(k-i-1,temp);
        }
        for (int i=0;i<n-1;i++){
            arrayList.get(i).next=arrayList.get(i+1).address;
        }
        arrayList.get(n-1).next="-1";
        for (int i=0;i<n;i++){
            System.out.println(arrayList.get(i));
        }
    }
}

科学计数法:

1073.Scientific Notation
import java.math.BigDecimal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String str = bufferedReader.readLine();
        BigDecimal num = new BigDecimal(str);
        System.out.println(num.toPlainString());
    }
}

子区间求和:

1007.Maximum Subsequence Sum
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
	public static void main(String[] args) throws IOException{
		BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(rd.readLine());
		String str[] = rd.readLine().split(" ");
		int sub_sum = 0, start = 0, end = n-1, index = 0, final_sum = Integer.MIN_VALUE;
		int val[] = new int[n];
		for(int i=0; i<n; i++) {
			val[i] = Integer.parseInt(str[i]);
			sub_sum += val[i];
			if(sub_sum >= 0) {
				if(sub_sum > final_sum) {
					final_sum = sub_sum;
					if(index != start)//从新的开始
						start = index; 
					end = i;
				}
			}
			else {//val[i]负的值比前面加起来的总和还大
				sub_sum = 0;
				index = i + 1;
			}
		}
		if(final_sum < 0) final_sum = 0;
		System.out.print(final_sum + " " + val[start] + " " + val[end]);
		
	}
}
//20分版
import java.util.*;
public class Main {
   public static void main(String[] args){
      Scanner scanner=new Scanner(System.in);
      int k=scanner.nextInt();
      int sub_sum = 0, start = 0, end = k-1, index = 0, final_sum = Integer.MIN_VALUE;
      int val[] = new int[k];
      for(int i=0; i<k; i++) {
         val[i] =scanner.nextInt();
         sub_sum += val[i];//从i开头 用子区间和作比较
         if(sub_sum >= 0) {
            if(sub_sum > final_sum) {//sub_sum > final_sum时,start和end才可能改变
               final_sum = sub_sum;
               if(index != start)//从新的开始
                  start = index;
               end = i;
            }
         }
         else {//val[i]负的值比前面加起来的总和还大
            sub_sum = 0;
            index = i + 1;
         }
      }
      if(final_sum < 0) final_sum = 0;
      System.out.print(final_sum + " " + val[start] + " " + val[end]);
   }
}
1046.Shortest Distance
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String[] first = reader.readLine().split(" ");
        int n = Integer.parseInt(first[0]);
        int[] dis = new int[n + 1];
        int[] sum = new int[n + 1];
        int circle = 0;

        for (int i = 1; i <= n; i++) {
            dis[i] = Integer.parseInt(first[i]);
            sum[i] = sum[i-1]+dis[i];
            circle += dis[i];

        }
        int m = Integer.parseInt(reader.readLine());
        for (int i = 0; i < m; i++) {
            String[] line = reader.readLine().split(" ");
            int start = Integer.parseInt(line[0]);
            int end = Integer.parseInt(line[1]);
            int low=Math.min(start,end);
            int high=Math.max(start,end);
            System.out.println(Math.min(sum[high - 1] - sum[low - 1], circle-(sum[high - 1] - sum[low - 1])));
        }
    }
}

深度优先遍历:

1013.Battle Over Cities
import java.util.*;
public  class Main {
    static int[][]map=new int[1001][1001];
    static boolean[]visit=new boolean[1001];
    static int n=0;
    //DFS
    static public void dfs(int start) {
        visit[start] = true;
        for (int i = 1; i <= n; i++) {
            if (visit[i] == false && map[start][i] == 1)//i没有被访问且start节点与i节点之间有连接,则以i为起点继续深度遍历
                dfs(i);//递归
        }
    }
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        n=scanner.nextInt();
        int m=scanner.nextInt();
        int k=scanner.nextInt();
        for(int i=0;i<m;i++){
            int x= scanner.nextInt();
            int y=scanner.nextInt();
            map[x][y]=map[y][x]=1;//稀疏矩阵存储
        }
        for(int i=0;i<k;i++){
            int num=0;//连通分量数
            int temp=scanner.nextInt();//缺失的城市号码
            Arrays.fill(visit,false);
            visit[temp]=true;//从temp找连通分量数
            for(int j=1;j<=n;j++){//从1开始,因为0不会被存储
                if (visit[j]==false){
                    dfs(j);
                    num++;//此时从j开始的深度遍历已经结束,为一个分量
                }
            }
            System.out.println(num-1);//输出num-1
        }
    }
}
1021.Deepest Root
import java.util.*;


public class Main{
    //邻接表,记录每个结点的邻居结点编号
    static ArrayList<ArrayList<Integer>> v = new ArrayList<>();
    //记录每个结点是否有被访问过
    static int []visited;
    //存储高度最高的根结点
    static ArrayList<Integer> farthest_point = new ArrayList<>();
    //记录最大高度
    static int maxdis = 0;

    static void dfs(int cur) {//判断有几个连通分量
        if(visited[cur] == 1) return ;
        visited[cur] = 1;
        for(int i:v.get(cur))
        {
            dfs(i);
        }
    }
    static void dfs2(int cur,int depth)
    {
        if(visited[cur] == 1) return ;
        visited[cur] = 1;
        if(depth > maxdis)
        {
            maxdis = depth;
            farthest_point.clear();
            if(!farthest_point.contains(cur))
            {
                farthest_point.add(cur);
            }
        }
        else if(depth == maxdis)
        {
            if(!farthest_point.contains(cur))
            {
                farthest_point.add(cur);
            }
        }
        for(int i : v.get(cur))
        {
            dfs2(i , depth + 1);
        }
    }

    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int n=scanner.nextInt();
        //因为编号从1开始,所以多创建一个
        visited = new int[n + 1];
        //创建对象
        for(int i = 0 ; i < n + 1 ;i ++)
        {
            ArrayList<Integer> arr = new ArrayList<>();
            v.add(arr);
        }
        for(int i = 1 ; i < n ;i++)
        {
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            v.get(x).add(y);
            v.get(y).add(x);
        }
        int count = 0;
        //先判断有几个连通分量
        for(int i = 1 ;i < n+1 ;i ++)
        {
            if(visited[i] == 0)
            {
                dfs(i);
                count ++;
            }
        }
        //不只有一个连通分量,一定不是树,一定有环,因为只给了n个结点,n-1条边
        if(count != 1)
        {
            System.out.println("Error: " + count + " components");
            return ;
        }
        //是树
        else
        {
            for(int i = 1 ; i <= n ; i ++)
            {
                for(int j = 1 ; j <= n ; j ++)
                {
                    visited[j] = 0;
                }
                dfs2(i,0);
            }
        }
        Collections.sort(farthest_point);
        for(int i : farthest_point)
        {
            System.out.println(i);
        }
    }
}

树的构造:

1020.Tree Traversals
import java.util.*;
class Main{
    static int[]postorder ;
    static int[]inorder;
    static int n;
    static Map<Integer,Integer> map = new HashMap<>();
    static int post_index;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        postorder = new int[n];
        inorder = new int[n];
        for(int i = 0 ; i < n ;i++)
        {
            postorder[i] = sc.nextInt();

        }
        for(int i = 0 ; i < n ;i++)
        {
            inorder[i] = sc.nextInt();
        }
        post_index = n - 1;
        int index = 0;
        for(int k :inorder)
        {
            map.put(inorder[index] , index++);
        }
        TreeNode root = BuilderTree(0,n-1);

        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        ArrayList<Integer> arr = new ArrayList<>();
        while(!q.isEmpty())
        {
            int n = q.size();
            for(int i = 0 ; i < n ;i++)
            {
                TreeNode temp = q.poll();
                arr.add(temp.val);
                if(temp.left != null) q.offer(temp.left);
                if(temp.right != null) q.offer(temp.right);
            }
        }
        for(int i = 0 ; i < arr.size() ;i++)
        {
            if(i == 0) System.out.print(arr.get(i));
            else System.out.print(" " + arr.get(i));
        }
    }

    private static TreeNode BuilderTree(int left, int right) {
        if(left > right) return null;
        int num = postorder[post_index];
        post_index --;
        TreeNode root = new TreeNode(num);
        int index = map.get(num);
        root.left = BuilderTree(left ,index - 1);
        root.right = BuilderTree(index + 1,right);
        return root;
    }
}
class TreeNode{
    int val;
    TreeNode left,right;
    public TreeNode()
    {

    }
    public TreeNode(int num)
    {
        this.val = num;
    }
}
1043.Is It a Binary Search Tree
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*
    先根据输入的前序遍历的第二个数字与第一个比较判断是否为 mirrorTree,
    如果是,在后面遍历的时候要把大的数据给右子树。
    遍历完树之后再通过bfs得出遍历的树的前序遍历。
    与输入的前序遍历进行比较,如果两者相等
    说明输入的数据是二叉搜索树或者其镜像,
    然后再通过dfs来输出 后序遍历
 */
public class Main {

    static class node{
        int val;
        node left;
        node right;
        public node(int val) {
            this.val = val;
        }
    }


    static node insertNode(node parent, int value){
        if(parent == null) {
            parent = new node(value);
            return parent;
        }
        if(value < parent.val){
            parent.left = insertNode(parent.left, value);
        }else{
            parent.right = insertNode(parent.right, value);
        }
        return parent;
    }

    static node insertMirrorNode(node parent, int value){
        if(parent == null) {
            parent = new node(value);
            return parent;
        }
        if(value < parent.val){
            parent.right = insertMirrorNode(parent.right, value);
        }else{
            parent.left = insertMirrorNode(parent.left, value);
        }
        return parent;
    }


    //  bfs用于前序遍历
    static void bfs(node node){
        sb.append(node.val).append(" ");
        if(node.left != null){
            bfs(node.left);
        }
        if(node.right != null){
            bfs(node.right);
        }
    }

    //  dfs用于后序遍历
    static void dfs(node node){
        if(node.left != null){
            dfs(node.left);
        }
        if(node.right != null){
            dfs(node.right);
        }
        res.append(node.val).append(" ");
    }

    static node root;
    static int[] preOrder;
    static boolean isMirror = false;
    static StringBuilder sb = new StringBuilder();//存放前序遍历后的节点,用于和输入的前序遍历进行比较
    static StringBuilder res = new StringBuilder();//存放后序遍历后的节点
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(bf.readLine());
        preOrder = new int[n];
        String line = bf.readLine().trim();
        String[] in = line.split(" ");
        for(int i = 0; i < n; i++){
            preOrder[i] = Integer.parseInt(in[i]);
        }
        if(preOrder.length == 1){
            System.out.println("YES");
            System.out.println(preOrder[0]);
            return;
        }

        //  判断是否为MirrorTree
        if(preOrder[0] <= preOrder[1])isMirror = true;//第一个小于等于第二个,只可能是右边镜像过来的
        if(!isMirror){
            for(int i = 0; i < preOrder.length; i++){
                root = insertNode(root, preOrder[i]);
            }
        }else{
            for(int i = 0; i < preOrder.length; i++){
                root = insertMirrorNode(root, preOrder[i]);
            }
        }
        bfs(root);
        if(sb.toString().trim().equals(line)){
            System.out.println("YES");
            dfs(root);
            System.out.println(res.toString().trim());
        }else{
            System.out.println("NO");
        }
    }
}
1064.Complete Binary Search Tree
import java.util.*;

public class Main {
    static void inorder(int i){
        if (i>n)return;
        inorder(i*2);
        arrayList.add(i);
        inorder(i*2+1);
    }
    static ArrayList<Integer>arrayList=new ArrayList<>();
    static int n;
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        n=scanner.nextInt();
        int a[]=new int[n+1];
        StringBuilder sb=new StringBuilder();
        for (int i=1;i<=n;i++){
            a[i]= scanner.nextInt();
        }
        Arrays.sort(a);
        inorder(1);
        int ans[]=new int[n+1];
        for (int i=0;i<n;i++){
            ans[arrayList.get(i)]=a[i+1];
        }
        for (int i=1;i<=n;i++){
            sb.append(ans[i]).append(" ");
        }
        System.out.println(sb.toString().trim());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值