Java written test strong training Niuke.com selected programming questions 03

Single choice

Among the following options, the scheduling algorithm that satisfies short task priority (the task with the shortest execution time is executed first) and does not cause starvation is ().

  • A First come, first served
  • B High response ratio priority
  • C time slice rotation
  • D Non-preemptive short tasks are given priority

First come first serve (ECES, First Come First Serve)

The simplest scheduling algorithm, scheduling in order.

High response ratio priority (HRRN, Highest Response Ratio Next)

Taking into account the waiting time of the job/process and the time required for service, the response ratio of each job/process is first calculated during each scheduling, and the job/process with the highest response ratio is selected to serve it.

The high response ratio priority scheduling algorithm is a compromise algorithm between ECES (first come, first served algorithm) and SE (short job priority algorithm). It takes into account both job waiting time and job running time, and takes care of short jobs without using them . Improved scheduling performance when long jobs wait too long .

Response ratio = (waiting time + required service time) / required service time

Time slice round-robin scheduling (Round-Robin, RR)

Used for process scheduling in time-sharing systems. Each time it is scheduled, the head process of the ready queue is always selected and allowed to run on the CPU for a time slice preset by the system. Processes that have not completed running within a time slice are returned to the end of the thread queue and requeued, waiting for the next scheduling.

Shortest Job First (SJE, Shortest Job First)

SIE is a non-preemptive algorithm. The shortest job/process will be served first (the so-called "shortest" refers to the shortest required service time)

Once the system assigns the processor to the process with the highest priority in the ready queue, the process will continue to execute until it is completed. Easy to cause hunger.

Among the following options, the reasonable time to lower the process priority is ()

  • Process A's time slice runs out
  • Process B has just completed I/O and entered the ready queue.
  • C process is permanently in the ready queue
  • D process changes from ready state to running state

When using locks to ensure thread safety, liveness failures may occur. Liveness failures mainly include

  • A deadlock
  • B hungry
  • C livelock
  • D All of the above

The activity problem refers to a thread or process that cannot be occupied by the CPU for a long time.

A. Deadlock: Threads hold locks on each other and wait for each other to release resources. As a result, no one can execute.

B. Hungry: If a thread with a high priority is executed every time, a thread with a low priority may never be executed.

C. Livelock: Livelock means that the task or executor is not blocked. Because certain conditions are not met, attempts, failures, attempts, and failures are repeated.

The difference between livelock and deadlock is that the entity in livelock is constantly changing state, so-called "live", while the entity in deadlock behaves like waiting; livelock may unlock itself, but deadlock cannot.

Select the job with the longest waiting time among the queued jobs to be scheduled first. The scheduling algorithm is ().

  • A first come first served scheduling algorithm
  • B High response ratio priority scheduling algorithm
  • C priority scheduling algorithm
  • D Short job priority scheduling algorithm

High priority priority scheduling algorithm

It means that urgent jobs (high-priority tasks) can be processed with priority after entering the system.

For the description of processes and threads, the following is correct ()

  • A All threads in the parent process share the same address space, and all child processes of the parent process share the same address space.

  • B Changing the status of the main thread in the process will affect the behavior of other threads, and changing the status of the parent process will not affect other child processes.

  • C Multithreading will cause deadlock, but multiprocessing will not

  • D None of the above options are correct

A. The parent process and the child process have their own independent address spaces;

B. When the main thread and the sub-thread are in a parallel relationship, there is no dependency. Changing the status of the parent process, such as notifying the child process to exit when the parent process exits, can affect the state of the child process. If there is no notification, it will not affect the child process.

C. If multiple processes occupy the resources needed by each other and request each other's resources at the same time, and they will not release the resources they occupy before getting the request, then a deadlock will occur, that is, the processes cannot be synchronized.

Which of the following statements about running two threads on a processor is correct?

  • A One thread can change another thread's program counter (program counter)
    B One thread can neither read nor write another thread's stack
    C One thread can read and write another thread's register
    D None of the above

How to reduce page break errors?

  • A Process tends to occupy the CPU
    B Access locality (locality of reference) meets process requirements
    C Process tends to occupy I/O
    D Use a scheduling mechanism based on the shortest remaining time

Page Fault: Page Fault, which should actually be translated into page fault exception or page fault interrupt, is a concept after the introduction of virtual memory.

Virtual memory: After the operating system is started, it maintains a virtual address table in the memory, and the virtual addresses required by the process are recorded in the virtual address table. When a program is loaded and run, only a small part of it is loaded into memory, and the other part is loaded from disk when needed. When a certain instruction or data needs to be executed and it is found that they are not in the main memory, a page fault interrupt is generated, and the system transfers the page where the instruction or data is located from the auxiliary memory into the memory.

B: Good locality; the next thing you are looking for is not far before and after the current memory, and is likely to be on the same page, so there is no need to change pages frequently, and there are fewer page change errors.

AC is for improved performance. D also has nothing to do with reducing page feed errors

If there is insufficient memory in the system for the size required by the program, the program cannot be executed.

  • A wrong
    B right

The basic meaning of what is usually called "storage protection" is ().

  • A Prevent memory hardware from being damaged
    B Prevent programs from being lost in memory
    C Prevent mutual cross-border access between programs
    D Prevent programs from being peeked at

In a storage system using virtual storage technology, a multi-tasking operating system often transfers multiple different programs into the main memory for execution at the same time;

  1. First, you need to ensure that these programs do not overwrite each other.

  2. A program cannot access data of other programs and areas of main memory not allocated to it.

  3. An error in one program will not damage other user programs and system programs.

In order to meet the above conditions, the technology of protecting programs in main memory in a restricted manner is called storage protection . Storage area protection is mainly to prevent addresses from crossing boundaries .

In the following process scheduling algorithm, () there may be a situation where the process cannot be scheduled for a long time (starvation phenomenon).

  • A Non-preemptive static priority method
    B Preemptive static priority method
    C Time slice rotation scheduling algorithm
    D Non-preemptive dynamic priority method

Preemptive/preemptive
type When the current process is running, if an important or urgent high-priority process arrives (its status must be ready), the currently running process will be forced to give up the processor, and the system will immediately allocate the processor to Newly arrived processes.

Static priority is determined when a process is created
and remains unchanged throughout the lifetime of the process.

Dynamic priority:
The priority given when a process is created can change as the process progresses or as its waiting time increases , in order to obtain better scheduling performance. The priority will grow as the waiting time increases. .

A. Non-preemptive static priority method: The priority will not change. If there is a thread with the lowest priority waiting, then it will be the process' turn to execute after the process with the higher priority has finished executing.

B. Preemptive static priority method: Preemptive type means that those with high priority can seize the execution power of the CPU. If a low-priority process is executed and a high-priority process is in the ready state, the CPU will execute the high-priority process in a preemptive manner, and the low-priority process will be preempted and placed in the ready state. If a high-priority process is always ready, then a low-priority process may be waiting.

C. Time slice rotation scheduling algorithm: After the execution time slice is completed, the executed process will be placed at the end of the waiting queue for a loop. Since it is a loop, it will have a chance to take its turn.

D. Non-preemptive dynamic priority method: Non-preemptive, but if a process has been waiting, its priority will increase dynamically and it can obtain the execution right of the CPU.

If the current value of the semaphore is -4, it means that there are () processes waiting on the semaphore in the system.

  • A 4
    B 3
    C 5
    D 0

This is the P and V operation of the semaphore: The pv operation is also called wait and signal. It mainly controls the addition and subtraction of the amount of information controlled by the process during the operation process.

wait usage: wait(num) , num is the target parameter

  • The function of wait is to reduce the amount of information by one. If the amount of information >= 0, the process continues to execute; otherwise, the process is placed in the waiting state and placed in the waiting queue.

signal usage: signa1(num) , num is the target parameter

  • The function of signal is to increase the amount of information by one. If the amount of information is >0, the process continues to execute; otherwise, the first process waiting for the semaphore in the queue is released.

The semaphore represents the number of currently available resources . When the semaphore is negative, the process applying for resources can only wait. Therefore, the number of negative semaphores indicates how many processes have applied for resources but have no resources available and can only wait.

In base addressing mode, the effective address of the operand is ____.

  • A The content of the base register plus the formal address (displacement amount)
    B The content of the program counter plus the formal address
    C The content of the index register plus the formal address
    D The content of the register plus the formal address

Base addressing mode is mainly used to solve the problem of dynamic positioning of programs.

Base address addressing adds the contents of the base address register in the CPU to the formal address in the instruction format to form the effective address of the operand.

Essentially, we form a virtual address of memory through the base address register + formal address

If there are only user-level threads in the system, the processor scheduling unit is ().

  • A thread
    B process
    C program
    D job

If the system only has user-mode threads, the threads are invisible to the operating system, and the operating system can only schedule processes;
if there are kernel-mode threads in the system, the operating system can schedule by thread;

C: The program is a static executable file, and the process is dynamic. The content of the executable file is copied to the memory and occupies the CPU to run and becomes a process. D. Job: A job usually
includes several processes, and several processes work together to complete a task. , that is, homework.

An online server usually needs to read databases that store large amounts of data. In order to improve the server processing speed, it is usually necessary to add a cache. The following scenarios are not suitable for using cache.

  • A. Each piece of data in the database has an approximately equal probability of being accessed and is independent.
    B. A service that uses a multi-thread mechanism
    . C. The size of a single thread is too small.
    D. A service with a large number of accesses.

Because the probability of each piece of data being accessed in the database is approximately equal, and the cache space is generally small and it is impossible to store more data. For the data that needs to be queried for unidentified prediction, it is of little use to put the recently accessed data into the cache, so increasing the cache will not have a big effect. BCD can improve efficiency

In a system that supports multi-threading, several threads created by process P cannot share ().

  • A The code segment of process P
    B The file opened in process P
    C The global variable of process P
    D The stack pointer of a thread in process P

D is thread private

Which of the following is correct about the relationship between contention and deadlock in operating systems?

  • A Competition will definitely lead to deadlock
    B Deadlock will definitely be caused by competition
    C Competition may cause deadlock
    D Preventing deadlock can prevent competition

Four necessary conditions for deadlock:

  1. Mutually exclusive condition: A resource can only be used by one process at a time.
  1. Request and hold conditions: When a process is blocked due to requesting resources, it will hold on to the obtained resources.

  2. Non-deprivation condition: The resources that have been obtained by the process cannot be forcibly deprived before they are used up.

  3. Cyclic waiting condition: A head-to-tail cyclic waiting resource relationship is formed between several processes.

A. Competing for locks but not meeting the above conditions will not cause deadlock.

B. Thread A and thread B lock: Thread A gets the lock. But I forgot to unlock and wanted to lock again. As a result, both thread A and thread B fell into a deadlock state. There is no competing lock at this time

C. If competition meets the above four conditions for deadlock, it will cause deadlock, so it is possible

D. If there are multiple processes or threads operating on the same resource, then locking must be required, which means competition must be involved.

Concurrency is a different expression of parallelism, but the principles are the same.

  • A wrong
    B right

Concurrency: Multiple processes use time slice rotation scheduling under one CPU. Within a period of time, multiple processes can be advanced, which is called concurrency. The CPU sees them executing one by one, but it is invisible to the naked eye.

Parallelism: Multiple processes run simultaneously on multiple CPUs, which is called parallelism.

Thread switching will cause process switching.

  • A wrong
    B right

A process may also contain multiple threads. Switching between threads in the same process will not cause process switching; thread switching in different processes will cause process switching.

All programs of the operating system are resident in memory.

  • A is wrong
  • B right

For processes that are waiting for events, you can swap them to external memory (part or all) to free up more memory to load new processes so that CPU resources can be fully utilized.

The physical address of the logical address translation process is called ().

  • A Address allocation
    B Address mapping
    C Address protection
    D Address out of bounds

Logical address: A virtual address in memory. Physical address: the real address on the memory stick

A: When the process is created, memory is allocated

B: Address mapping: In order to ensure that the CPU can correctly access the storage unit when executing instructions, the logical address in the user program needs to be converted into a physical address directly addressed by the machine at runtime.

C: Between multiple processes, other people’s memory cannot be used.

D: Accessed the memory of other processes

In Unix systems, processes in the () state are easiest to execute.

  • A Auxiliary storage sleep
    B Memory sleep
    C Memory ready
    D Auxiliary storage ready

Insert image description here

The control information and description information of the process are stored in ().

  • A JCB
    B PCB
    C AFT
    D SFT

In order to describe the operation of the control process, the data structure that stores the management and control information of the process in the system is called the process control block (PCB Process ControlBlock). It is the most important data structure for process management and control. Each process has a PCB. , when the process is created, the PCB is established, which accompanies the entire process of running the process until it is canceled when the process is cancelled.

PCB generally includes:

  1. Program ID (PID, process handle): It is unique, and each process must correspond to a PID. PID is generally an integer number
  2. Characteristic information: generally divided into system processes, user processes, or kernel processes, etc.
  3. Process status: running, ready, blocked, indicating the current running status of the process
  4. Priority: Indicates the priority level for obtaining CPU control.
  5. Communication information: reflects the communication relationship between processes, because the operating system will provide communication channels
  6. On-site protection zone: used to protect blocked processes
  7. Resource requirements, allocation control information

In the case of (), the system deadlocks.

  • A Several processes are waiting endlessly for each other to release occupied resources due to competition for resources.
    B There are multiple blocked processes at the same time. C A
    major failure occurs in the computer system.
    D The number of resources is much less than the number of processes or the number of resources requested by processes at the same time greatly exceeds the resources. total

A deadlock occurs when two threads or threads are waiting for each other to release resources and refuse to give in to each other, resulting in a deadlock.

D: The process fails to compete for resources and is blocked.

When the system is thrashing, the effective measures that can be taken are ( ).
Ⅰ. Cancel part of the process Ⅱ. Increase the capacity of the disk swap area III. Increase the priority of user processes

  • A only Ⅰ
    B only Ⅱ
    C only Ⅲ
    D only Ⅰ, Ⅱ

In an operating system with a swap function, the external storage is usually divided into a file area and a swap area . The former is used to store files , and the latter is used to store processes swapped out from memory.

The thrashing phenomenon means that the page that has just been swapped out will be accessed again soon. For this reason, other pages must be swapped out
, and the page will be accessed soon. It is so troublesome to replace the page, so that most of the time is spent on page replacement.

Ⅰ: Undoing some processes can reduce the number of pages to be used and prevent jitter.

II and III: Swap area size and session priority have nothing to do with jitter. Pages are related to virtual memory,

Which of the following statements about threads is incorrect ()

  • A Use threads for time-consuming operations to improve program response
  • B Memory-consuming operations use threads to improve memory utilization.
  • C Multi-CPU systems use threads to improve CPU utilization
  • D Parallel operations use threads. For example, in the c/s architecture, the server program creates a thread to respond to each client request.

B: Threads are part of the process. It is wrong to say that improving memory utilization is wrong.

If the block size in a fixed block size file system is set larger, it will cause ().

  • A better disk throughput and worse disk space utilization
    B better disk throughput and better disk space utilization
    C worse disk throughput and better disk space utilization
    D worse disk Throughput and worse disk space utilization

Files are stored in blocks. If the block size is set larger, more data can be read at once, and the disk throughput is improved. However, the full file may not occupy the entire block, resulting in a decrease in utilization.

Among the following four characteristics of the process, the most basic characteristic is ().

  • A Concurrency
    B Dynamics
    C Independence
    D Asynchrony

A. Concurrency: refers to multiple process entities coexisting in memory and running simultaneously within a period of time. Concurrency is an important feature of processes and has also become an important feature of operating systems.

B. Dynamics: The essence of a process is an execution process of the process entity. Therefore, dynamics is the most basic feature of the process.

C. Independence: The process entity is a basic unit that runs independently, allocates resources independently, and accepts scheduling independently.

D. Asynchrony: refers to processes advancing sequentially at independent and unpredictable speeds, or entities running in an asynchronous manner.

Process scheduling is to select a process from () and put it into operation.

  • A ready queue
    B waiting queue
    C job backup queue
    D submission queue

B. Waiting queue: used to make threads wait for a specific event to occur without frequent polling. The process sleeps during waiting and is awakened by the kernel when something happens.

C. Job backup queue: The operating system first selects certain jobs from the backup queue in external storage and transfers them into the memory, creates processes for them, and allocates necessary resources. Then insert the newly created process into the ready queue and prepare for execution.

Which of the following statements about Cache is incorrect?

  • A The purpose of setting up Cache is to solve the speed matching problem between CPU and main memory
    B The theoretical basis for setting up Cache is the principle of locality of program access
    C Cache and main memory are uniformly addressed, and the address space of Cache is part of the main memory
    The functions of D Cache are implemented by hardware and are transparent to programmers.

A. The reason why Cache appears is to solve the speed matching problem between CPU and main memory. CPU speed > Cache speed > main memory speed.

B. The principle of locality of program access is that during a certain period of time when a program is running, most of the codes or data it accesses are concentrated in a certain area.

C. The address of Cache and the address of main memory are two different things. They are not uniformly addressed and have no affiliation.

D.cache is implemented by hardware.

What is memory thrashing (Thrashing) ( )

  • A Very frequent paging activity
    B Very high CPU execution activity
    C An extremely long execution process
    D An extremely large virtual memory

The concept of virtual management of memory, frequent replacement of pages , leads to a sharp decline in the efficiency of the entire system. This phenomenon is called memory jitter.
Jitter is generally caused by poor memory allocation algorithm , too small memory or poor program algorithm, which causes pages to be frequently transferred in and out of memory.

Among all non-preemptive CPU scheduling algorithms, the optimal system average response time is ( )

  • A Real-time scheduling algorithm
    B Short task priority algorithm
    C Time slice rotation algorithm
    D First come, first served algorithm

Response time is the time between the arrival of a task and the start of the task being processed (response). Turnaround time is the time between arrival and completion of processing.

A**.Real-time scheduling algorithm:** refers to the system's ability to provide the required level of service within a limited response time. If the system's time constraints are not met, system errors will occur.

B. Short task priority algorithm: Tasks with short execution time are executed first.

C. Time slice rotation algorithm: The system schedules the processes in the ready queue, each process is allocated a time slice, and the clock interrupt is used to perform periodic switching of processes.

D. First come, first served algorithm: Scheduling is done in first-come, first-served order.

Among the above scheduling algorithms, the time slice rotation algorithm is a preemptive scheduling algorithm;

When all processes arrive almost at the same time, the short task priority scheduling algorithm has the lowest average waiting time and average turnaround time.

Assume that in the following code, if the t1 thread has been started before the t2 thread is started. The output of the code is ()

public class TestDemo {
     
     
public static void main(String[]args)throws Exception {
     
     
final Object obj = new Object();
Thread t1 = new Thread() {
     
     
 public void run() {
     
     
     synchronized (obj) {
     
      // 1.
         try {
     
     
             obj.wait(); // 2. 释放对象锁,让当前线程等待(t1)
             // 6. t1 线程再申请 obj 锁, 申请成功,则继续往下地行
             System.out.println("Thread 1 wake up.");
         } catch (InterruptedException e) {
     
     
         }
     }
 }
};
t1.start();
Thread.sleep(1000);//We assume thread 1 must start up within 1 sec.
Thread t2 = new Thread() {
     
     
 public void run() {
     
     
     synchronized (obj) {
     
      // 3.
         obj.notifyAll(); // 4、通知 obj 对象 wait 等待的线程
         System.out.println("Thread 2 sent notify.");
     } // 5、这里释放锁 通知 obj
 }
};
t2.start();
}
}
  • A Thread 1 wake up Thread 2 sent notify.
    B Thread 2 sent notify. Thread 1 wake up
    CA and B are both possible.
    D The program has no output and is stuck.

Which of the following statements is correct?

  • A In page storage management, users should divide their programs into several equal pages
    B When all processes are suspended, the system will fall into a deadlock
    C Executing system calls can be interrupted
    D The process priority number is scheduled by the process Important basis, must be dynamically changed according to the running status of the process

A. The division of pages is done by the operating system .

B. The system must meet four conditions to enter a deadlock: mutual exclusion, loop and wait, no deprivation, request and hold; all processes are suspended, which does not mean that there is a relationship between resource calls and loop waiting between these processes. Some processes It may wake up automatically after the timer expires.

C: The user program calls a system function and can be interrupted by a process with a higher priority.

D. There is static priority scheduling.

Among the following methods, ____ cannot be used for program tuning?

  • A Improve data access methods to increase cache hit rate
    B Use multi-threading to improve the efficiency of I/O-intensive operations
    C Use database connection pools to replace direct database access
    D Use iteration to replace recursion
    E Combine multiple remote calls and send them in batches
    F Sharing Redundant data improves access efficiency

B If it is an I/O intensive application, it is ok.


Programming questions

Cut fabric strips

A piece of floral cloth with some patterns inside, and a small decorative strip that can be used directly, with some patterns inside. For a given strip of floral fabric and small decorative strips, calculate how many small decorative strips you can cut out of the strip of floral fabric?

Enter description:

输入包含多组数据。

每组数据包含两个字符串s,t,分别是成对出现的花布条和小饰条,其布条都是用可见ASCII字符表示的,可见的ASCII字符有多少个,布条的花纹也有多少种花样。花纹条和小饰条不会超过1000个字符长。

Output description:

对应每组输入,输出能从花纹布中剪出的最多小饰条个数,如果一块都没有,那就输出0,每个结果占一行。

enter

abcde a3
aaaaaa aa

output

0
3
import java.util.*;

public class Main {
    
    
    private static int cut(String s, String t) {
    
    
        int i = s.indexOf(t);
        if (i == -1) {
    
    
            return 0;
        }
        return 1 + cut(s.substring(i + t.length()), t);
    }
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
            String s = scanner.next();
            String t = scanner.next();
            System.out.println(cut(s, t));
        }
    }
}
import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
            String s = scanner.next();
            String t = scanner.next();
            int count = 0;
            while (s.contains(t)) {
    
    
                s = s.replaceFirst(t, ""); // replaceFirst 替换第一个
                count++;
            }
            System.out.println(count);
        }
    }
}

Guests come like clouds

NowCoder opened a breakfast shop. The customers of this shop have a strange habit: as long as they come to this shop for breakfast once, they will come here every day; and after eating breakfast in this shop for two days, everyone , and I will bring a new friend to taste it every day.
As a result, the number of customers in this store has grown from one person to hundreds or thousands of people: 1, 1, 2, 3, 5...
Now, NowCoder would like to ask you to help calculate the total number of customers he sold in a certain period of time. How many breakfasts to serve (assuming only one breakfast per guest).
Enter description:

测试数据包括多组。
每组数据包含两个整数from和to(1≤from≤to≤80),分别代表开店的第from天和第to天。

Output description:

对应每一组输入,输出从from到to这些天里(包含from和to两天),需要做多少份早餐。
import java.util.*;
import java.math.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        // 可以用 long[]
        // 1 1 2 3 5...
        BigDecimal[] bigDecimal = new BigDecimal[80];
        bigDecimal[0] = new BigDecimal("1");
        bigDecimal[1] = new BigDecimal("1");
        for (int i = 2; i < 80; i++) {
    
     // 数组 第 3 个下标为 2
            bigDecimal[i] = bigDecimal[i - 1].add(bigDecimal[i - 2]);
        }
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
            int from = scanner.nextInt();
            int to = scanner.nextInt();
            BigDecimal sum = new BigDecimal("0");
            for (int i = from - 1; i < to; i++) {
    
    
                sum = sum.add(bigDecimal[i]); // sum = 
            }
            System.out.println(sum);
        }
    }
}

Recipient list

NowCoder writes emails to many customers every day. As you know, if an email contains multiple recipients, the recipient names are separated by a comma and a space; if the recipient name also contains a space or a comma, the name needs to be enclosed in double quotes .
Now I give you a set of recipient names and ask you to help him generate the corresponding recipient list.
Enter description:

输入包含多组数据。

每组数据的第一行是一个整数n (1≤n≤128),表示后面有n个姓名。

紧接着n行,每一行包含一个收件人的姓名。姓名长度不超过16个字符。

Output description:

对应每一组输入,输出一行收件人列表。

enter

3
Joe
Quan, William
Letendre,Bruce
2
Leon
Kewell

output

Joe, "Quan, William", "Letendre,Bruce"
Leon, Kewell
import java.util.*;

public class Main {
    
    
    public static void main(String[]  args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
//            String ret = scanner.nextLine(); // n 读一行 防止换行作为了一个 s
//            int n = Integer.valueOf(ret);
            int n = scanner.nextInt();
            scanner.nextLine(); // 或者再读 line
            while (n-- != 0) {
    
    
                String s = scanner.nextLine();
                if (s.contains(",") || s.contains(" ")) {
    
    
                    if (n == 0) {
    
     // 最后一个没有逗号
                        System.out.print("\"" + s + "\"");
                    } else {
    
    
                        System.out.print("\"" + s + "\"" + ", ");
                    }
                } else {
    
    
                    if (n == 0) {
    
    
                        System.out.print(s);
                    } else {
    
    
                        System.out.print(s + ", ");
                    }
                }
            }
            System.out.println();
        }
    }
}

Raise rabbits

A mature rabbit can give birth to one litter per day. The maturity period of each bunny is one day. Someone adopts a little rabbit. How many rabbits will he get after the Nth day?

Enter description:

测试数据包括多组,每组一行,为整数n(1≤n≤90)。

Output description:

对应输出第n天有几只兔子(假设没有兔子死亡现象)。

enter

1<br/>2

output

1<br/>2
import java.util.*;
import java.math.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        // 可以用 long
        // 此题是 1 2 3 5...
        BigDecimal[] bigDecimal = new BigDecimal[90];
        BigDecimal b1 = new BigDecimal("1");
        BigDecimal b2 = new BigDecimal("1");
        BigDecimal b3 = b1;
        for (int i = 0; i < 90; i++) {
    
    
            bigDecimal[i] = b3;
            b1 = b2;
            b2 = b3;
            b3 = b1.add(b2);
        }
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
            int n = scanner.nextInt();
            System.out.println(bigDecimal[n - 1]);
        }
    }
}

An Xinqi fifth month rabbit

There is a pair of rabbits. They give birth to a pair of rabbits every month starting from the fifth month after birth. After the baby rabbit grows to the fifth month, they give birth to a pair of rabbits every month. If the rabbits do not die, ask the nth month. What is the number of pairs of rabbits.

对数: 1  1  1  1  2  3  4  5  7  10  14  19  26  36  50  69

增数: 0  0  0  0  1  1  1  1  2   3    4    5    7   10  14  19

Code:

public class TestDemo {
    
    
    private static int fib2(int n) {
    
    
        if (n == 1 || n == 2 || n == 3 || n == 4) {
    
    
            return 1;
        }
        return fib2(n - 1) + fib2(n - 4);
    }

    private static void fib(int n) {
    
    
        int[] array = new int[n];
        for (int i = 0; i < 4; i++) {
    
    
            array[i] = 1;
        }
        for (int i = 4; i < n; i++) {
    
    
            array[i] = array[i - 1] + array[i - 4];
        }
        System.out.println(Arrays.toString(array));
    }

    public static void main(String[] args) {
    
    
        fib(16); // [1, 1, 1, 1, 2, 3, 4, 5, 7, 10, 14, 19, 26, 36, 50, 69]
    }
}

Annual meeting lottery - wrong arrangement problem

The prizes at this year's company annual meeting are particularly impressive, but the rules for winning are very strange:
\1. First, all employees put a note with their name on it into the lottery box;
\2. After all the notes have been added, each The person takes a note from the box;
\3. If the note written is his or her name, then "Congratulations, you won the prize!"
Now tell you the number of people attending the party, please calculate the probability that there will be no Who won the award?
Enter description:

输入包含多组数据,每组数据包含一个正整数n(2≤n≤20)。

Output description:

对应每一组数据,以“xx.xx%”的格式输出发生无人获奖的概率。

enter

2

output

50.00%

[Problem-solving ideas]

Insert image description here

import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        long[] d = new long[21]; // 第 n 个人错排总数
        d[0] = 0;
        d[1] = 0;
        d[2] = 1;
        long[] f = new long[21]; // n 的阶乘
        f[0] = 1;
        f[1] = 1;
        f[2] = 2;
        for (int i = 3; i <= 20; i++) {
    
    
            d[i] = (i - 1) * (d[i - 1] + d[i - 2]);
            f[i] = f[i - 1] * i;
        }
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
    
    
            int n = scanner.nextInt();
            double ans = 100.0 * d[n] / f[n];
            System.out.printf("%.2f%%\n", ans);
        }
    }
}

CC list

NowCoder handles many emails every day, but he is not in the recipient list, sometimes he is just copied. He believes that the importance of these CC emails is lower than the emails he has in the recipient list, so he needs to filter out these secondary emails and prioritize the important emails.
Now you are given a list of CCs. Please determine whether the target user is in the CC list.
Enter description:

输入有多组数据,每组数据有两行。

第一行抄送列表,姓名之间用一个逗号隔开。如果姓名中包含空格或逗号,则姓名包含在双引号里。总长度不超过512个字符。

第二行只包含一个姓名,是待查找的用户的名字(姓名要完全匹配)。长度不超过16个字符。

Output description:

如果第二行的名字出现在收件人列表中,则输出“Ignore”,表示这封邮件不重要;否则,输出“Important!”,表示这封邮件需要被优先处理。

enter

Joe,Kewell,Leon
Joe
"Letendre, Bruce",Joe,"Quan, William"
William

output

Ignore
Important!
import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
            String s = scanner.nextLine();
            String name = scanner.nextLine();
            boolean flag = true;
            for (int i = 0; i < s.length(); i++) {
    
    
                StringBuilder sb = new StringBuilder();
                if (s.charAt(i) == '\"') {
    
     // 名字里有空格或逗号 找到另一个双引号
                    i++; // 跳过此双引号
                    while (i < s.length() && s.charAt(i) != '\"')
                        sb.append(s.charAt(i++));
                } else {
    
     // 普通名字 找到逗号为之
                    while (i < s.length() && s.charAt(i) != ',') {
    
    
                        sb.append(s.charAt(i++));
                    }
                }
                if (sb.toString().equals(name)) {
    
    
                    System.out.println("Ignore");
                    flag = false;
                    break;
                }
            }
            if (flag) {
    
    
                System.out.println("Important!");
            }
        }
    }
}

Rational Arithmetic (20)

For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference,
product and quotient.

Enter description:

Each input file contains one test case, which gives in one line the two rational numbers in the format "a1/b1 a2/b2". 
The numerators and the denominators are all in the range of long int. If there is a negative sign, it must appear only in 
front of the numerator. The denominators are guaranteed to be non-zero numbers.

Output description:

For each test case, print in 4 lines the sum, difference, product and quotient of the two rational numbers, respectively. The format of each 
line is "number1 operator number2 = result". Notice that all the rational numbers must be in their simplest form "k a/b", where k is 
the integer part, and a/b is the simplest fraction part. If the number is negative, it must be included in a pair of parentheses. If the 
denominator in the division is zero, output "Inf" as the result. It is guaranteed that all the output integers are in the range of long int.

enter

5/3 0/6

output

1 2/3 + 0 = 1 2/3<br/>1 2/3 - 0 = 1 2/3<br/>1 2/3 * 0 = 0<br/>1 2/3 / 0 = Inf

【Analysis】

1. The output should contain 4 lines: the addition, subtraction, multiplication and division of two fractions,
for example:
a+ b = c
a - b = ca * b = ca / ​​b = c

2. Each part of the result must be in the simplest form: 2/4
4===>1/2 cannot appear. The simplest form - just divide by the greatest common divisor

3. If it is a negative number, a negative sign must be output.

4. If the denominator is 0, output Inf

5. Both the numerator and denominator are within the range of long int.

Example: - a/b + c/d = (a*d + b*c)/(b*d) Add and subtract the common points to get
2/3 + 2/5 = (2*5 + 2*3) /(3*5)

——a/b - c/d = (a*d - b*c)/(b*d)
2/3 - 2/5 = (2*5 - 2*3)/(3*5)

——a/b * c/d = (a*c) / (b*d) numerator times numerator, denominator times denominator
2/3 * 2/5 = (2*2) / (3*5)

——a/b / c/d = (a*d) / (b*c) division is equivalent to multiplying the reciprocal
2/3 / 2/5 = (2*5) / (3*2) = 10/6 — >Simplify

import java.util.*;

class Rational {
    
    
    private long numerator; // 分子
    private long denominator; // 分母
    private long integer; // 带分数的整数部分
    private boolean negative; // 负数
    private boolean isZero; // 分母为 0
    private long totalNumerator; // 参与运算的分子:带分数的整数部分 + 原来分子

    // 截取 分子部分
    protected static long parseNumerator(String s) {
    
    
        return Long.parseLong(s.substring(0, s.indexOf('/')));
    }

    // 截取 分母部分
    protected static long parseDenominator(String s) {
    
    
        return Long.parseLong(s.substring(s.indexOf('/') + 1, s.length()));
    }

    // 判断化简 分子 分母
    protected Rational(long n, long d) {
    
    
        // 在输入的时候分母永远不可能为0,但是经过计算之后分母可能会为0
        if (0 == d) {
    
    
            isZero = true;
            return;
        }
        // If there is a negative sign, it must appear only in front of the numerator.
        if (n < 0) {
    
    
            negative = true;
        }
        // 在输入的时候,分母永远不可能小于0,但是经过计算之后分母也可能会小于0
        if (d < 0) {
    
    
            negative = !negative;
        }
        // 如果输入是假分数,需要将其调整为真分数 --> 5 / 3 --> 1 2/3
        integer =  n / d;
        numerator = n - integer * d;
        denominator = Math.abs(d);
        // 如果分数不是最简的形式,需要将其约分为最简的形式,比如:10 / 15
        // 在分子和分母的基础之上分别处以分子和分母的最大公约数
        if (numerator > 1 || numerator < -1) {
    
    
            long gcd = calcGCD(Math.abs(numerator), denominator); // 用整数
            if (gcd > 0) {
    
     // 有最大公约数
                numerator /= gcd;
                denominator /= gcd;
            }
        }
        // 用于计算的分子 如果是假分数,化成真分数计算
        totalNumerator = numerator + integer * denominator;
    }

    // 最大公约数 辗转相除法
    private long calcGCD(long n1, long n2) {
    
    
        if (n2 == 0) {
    
    
            return n1;
        }
        return calcGCD(n2, n1 % n2);
    }

    // 计算
    protected Rational Add(Rational r) {
    
     // 通分
        long n = totalNumerator * r.denominator + r.totalNumerator * denominator; // 分子
        long d = denominator * r.denominator; // 分母
        return new Rational(n, d); // 结果同样是最简加假分式
    }

    protected Rational Sub(Rational r) {
    
     // 通分
        long n = totalNumerator * r.denominator - r.totalNumerator * denominator;
        long d = denominator * r.denominator;
        return new Rational(n, d);
    }

    protected Rational Mul(Rational r) {
    
    
        long n = totalNumerator * r.totalNumerator;
        long d = denominator * r.denominator;
        return new Rational(n, d);
    }

    protected Rational Div(Rational r) {
    
    
        long n = totalNumerator * r.denominator;
        long d = denominator * r.totalNumerator;
        return new Rational(n, d);
    }

    // 判断输出形式
    public String toString() {
    
    
        if (isZero) {
    
     // 分母为 0 输出 Inf
            return "Inf";
        }
        if (integer == 0 && numerator == 0) {
    
     // 结果为 0
            return "0";
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (negative) {
    
     // 负数
            stringBuilder.append("(-");
        }
        // 输出 Rational:整数部分 + 分数部分
        // 整数部分
        if (0 != integer) {
    
    
            stringBuilder.append(Math.abs(integer));
            if (0 != numerator) {
    
     // 有分数 和整数之间有空格
                stringBuilder.append(" ");
            }
        }
        // 分数部分 可能没有
        if (0 != numerator) {
    
    
            stringBuilder.append(Math.abs(numerator) + "/" + denominator);
        }
        if (negative) {
    
    
            stringBuilder.append(")");
        }
        return new String(stringBuilder);
    }
}

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
            // 读取两个分数 分别截取出各自的 分子 和 分母
            String s = scanner.next(); //
            Rational r1 = new Rational(Rational.parseNumerator(s), Rational.parseDenominator(s));
            s = scanner.next(); //
            Rational r2 = new Rational(Rational.parseNumerator(s), Rational.parseDenominator(s));
            // 输出 两个分数 运算符 计算的结果
            // ——> 5/3   3/2
            // 1 2/3 + 1 1/2 = 3 1/6
            System.out.println(r1 + " + " + r2 + " = " + r1.Add(r2));
            System.out.println(r1 + " - " + r2 + " = " + r1.Sub(r2));
            System.out.println(r1 + " * " + r2 + " = " + r1.Mul(r2));
            System.out.println(r1 + " / " + r2 + " = " + r1.Div(r2));
        }
    }
}

Pre-Post

We are all familiar with pre-order, in-order and post-order traversals of binary trees. A common problem in data structure classes is to find the pre-order traversal of a binary tree when given the in-order and post-order traversals. Alternatively, you can find the post-order traversal when given the in-order and pre-order. However, in general you cannot determine the in-order traversal of a tree when given its pre-order and post-order traversals. Consider the four binary trees below:

img All of these trees have the same pre-order and post-order traversals. This phenomenon is not restricted to binary trees, but holds for general m-ary trees as well.

Enter description:

Input will consist of multiple problem instances. Each instance will consist of a line of the form m s1 s2, indicating that the trees are m-ary trees, s1 is the pre-order traversal and s2 is the post-order traversal.All traversal strings will consist of lowercase alphabetic characters. For all input instances, 1 <= m <= 20 and the length of s1 and s2 will be between 1 and 26 inclusive. If the length of s1 is k (which is the same as the length of s2, of course), the first k letters of the alphabet will be used in the strings. An input line of 0 will terminate the input.

Output description:

For each problem instance, you should output one line containing the number of possible trees which would result in the pre-order and post-order traversals for the instance. All output values will be within the range of a 32-bit signed integer. For each problem instance, you are guaranteed that there is at least one tree with the given pre-order and post-order traversals.

enter

2 abc cba
2 abc bca
10 abc bca
13 abejkcfghid jkebfghicda

output

4
1
45
207352860

【Analysis】

Each set of test cases: m s1s2
m means that the tree is an m-ary tree, s1 means the pre-order traversal result, s2 means the in-order traversal result, s1 and s2 have the same length and contain lowercase letters.

One test case occupies one line, and the line after the last test case outputs 0
: each use case inputs the number of all possible trees and outputs one line. The result must not exceed unsigned long

Insert image description here

**——分离根节点有多少颗子树:**

Insert image description here

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

// 保存子树的前序 后序 遍历结果
class SubTree {
    
    
    String pre;
    String post;
    public SubTree(String pre, String post) {
    
    
        this.pre = pre;
        this.post = post;
    }
}

public class Main {
    
    
    // 计算 n 的阶乘
    private static long fac(int n) {
    
    
        long f = 1;
        for (int i = 1; i <= n; i++) {
    
    
            f *= i;
        }
        return f;
    }

    // 计算组合
    private static long calcCom(int n, int m) {
    
    
        m = m < (n - m) ? m : (n - m); // C(n, m) = C(n, n-m)
        long r = 1;
        for (int i = n; i >= n - m + 1; i--) {
    
    
            r *= i;
        }
        return r / fac(m);
    }

    // 分离根节点有多少颗子树
    private static List<SubTree> calcSubTree(String pre, String post) {
    
    
        int subRootPreInx = 1; // 子树的根在前序遍历结果中的位置   根--->子树1--->子树2--->...--->子树n
        int postFirst = 0; // 后序遍历 : 子树1-->子树2-->...--->子树n-->根节点
        List<SubTree> list = new ArrayList<>();
        while (subRootPreInx < pre.length()) {
    
    
            char rootSub = pre.charAt(subRootPreInx); // 确认该颗子树的根节点 从前序遍历中找根
            int subRootPostInx = post.indexOf(rootSub); // 从后序遍历中找根的位置
            int subTreeNodeCount = subRootPostInx - postFirst + 1; // 该颗子树中总共有多少个节点
            SubTree subTree = new SubTree(
                    pre.substring(subRootPreInx, subRootPreInx + subTreeNodeCount),
                    post.substring(postFirst, postFirst + subTreeNodeCount)
            ); // 从前序遍历和后序遍历结果中分离出该棵子树的 前序和后序遍历结果
            list.add(subTree); // 保存 子树的 前序和后序遍历结果
            subRootPreInx += subTreeNodeCount; // 分离下一颗子树
            postFirst += subTreeNodeCount;
        }
        return list;
    }

    private static long calcPossibilitiesOfTree(int n, String pre, String post) {
    
    
        if (pre.isEmpty() || pre.length() == 1) {
    
     // 没有节点 或 只有一个节点
            return 1;
        }
        List<SubTree> subTree = calcSubTree(pre, post); // 分离根节点有多少颗子树
        long result = calcCom(n, subTree.size()); // 根节点子树 的可能性的 组合 结果
        for (SubTree e : subTree) {
    
     // 递归计算 根的子树 分别有多少种可能性
            result *= calcPossibilitiesOfTree(n, e.pre, e.post);
        }
        return result;
    }

    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
            int n = scanner.nextInt();
            if (n == 0) {
    
     // An input line of 0 will terminate the input.
                break;
            }
            String pre = scanner.next();
            String post = scanner.next();
            long ret = calcPossibilitiesOfTree(n, pre, post);
            System.out.println(ret);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_56884023/article/details/125114930
Recommended